diff --git a/AUTHORS b/AUTHORS index 93a5671e..8cc54cc 100644 --- a/AUTHORS +++ b/AUTHORS
@@ -682,6 +682,7 @@ Tim Ansell <mithro@mithis.com> Tim Niederhausen <tim@rnc-ag.de> Timo Reimann <ttr314@googlemail.com> +Tom Callaway <tcallawa@redhat.com> Tom Harwood <tfh@skip.org> Torsten Kurbad <google@tk-webart.de> Tomas Popela <tomas.popela@gmail.com>
diff --git a/BUILD.gn b/BUILD.gn index f589a3a..c3f83c0 100644 --- a/BUILD.gn +++ b/BUILD.gn
@@ -18,6 +18,7 @@ import("//remoting/remoting_enable.gni") import("//third_party/openh264/openh264_args.gni") import("//tools/ipc_fuzzer/ipc_fuzzer.gni") +import("//ui/ozone/ozone.gni") import("//v8/gni/v8.gni") import("//v8/snapshot_toolchain.gni") @@ -373,7 +374,7 @@ ] } - if (use_x11) { + if (use_x11 || ozone_platform_x11) { deps += [ "//tools/xdisplaycheck" ] } @@ -910,16 +911,31 @@ testonly = true deps = [ - "//content/shell:content_shell", + ":webkit_layout_tests", "//third_party/WebKit/public:all_blink", + ] + } + + # Layout tests runner + # third_party/WebKit/Tools/Scripts/run-webkit-tests + group("run_webkit_tests") { + testonly = true + deps = [ + ":webkit_layout_tests", + ] + } + + # https://www.chromium.org/developers/testing/webkit-layout-tests + group("webkit_layout_tests") { + testonly = true + + data_deps = [ + "//content/shell:content_shell", "//tools/imagediff", ] - # NOTE: The following deps are needed to run the layout tests - # (run-webkit-tests) but there is no GN target for the layout tests, - # so we need to specify the dependencies here instead. if (is_android) { - deps += [ + data_deps += [ "//breakpad:breakpad_unittests", "//breakpad:dump_syms", "//breakpad:microdump_stackwalk", @@ -931,24 +947,28 @@ } if (is_win) { - deps += [ "//content/shell:content_shell_crash_service" ] + data_deps += [ "//content/shell:content_shell_crash_service" ] } if (!is_win && !is_android) { - deps += [ "//breakpad:minidump_stackwalk($host_toolchain)" ] + data_deps += [ "//breakpad:minidump_stackwalk($host_toolchain)" ] } if (is_mac) { - deps += [ "//breakpad:dump_syms($host_toolchain)" ] + data_deps += [ "//breakpad:dump_syms($host_toolchain)" ] } if (is_linux) { - deps += [ "//breakpad:dump_syms($host_toolchain)" ] + data_deps += [ "//breakpad:dump_syms($host_toolchain)" ] } data = [ + "//testing/scripts/common.py", + "//testing/xvfb.py", + "//testing/scripts/run_telemetry_as_googletest.py", "//third_party/WebKit/LayoutTests/", "//third_party/WebKit/Tools/Scripts/", + "$root_build_dir/resources/inspector/", ] } } @@ -988,7 +1008,7 @@ if (is_win) { data_deps += [ "//chrome/installer/mini_installer:mini_installer", - "//third_party/angle/src/tests:angle_perftests", + "//chrome/test:angle_perftests", ] } else { data_deps += [ "//breakpad:minidump_stackwalk($host_toolchain)" ]
diff --git a/DEPS b/DEPS index af17348..b7c7914 100644 --- a/DEPS +++ b/DEPS
@@ -40,11 +40,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Skia # and whatever else without interference from each other. - 'skia_revision': 'bde64e438ae24f9f1c90fff5e1a12e71db5742de', + 'skia_revision': '2ad208dbd599a6ff54efd6070e82bc95f704d88b', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. - 'v8_revision': 'a8fcdeb75e4b6ad3fa43015707f4fac8dbcc094d', + 'v8_revision': '2f829181b72df1fe0d48696307651516d1adce10', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling swarming_client # and whatever else without interference from each other. @@ -52,7 +52,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. - 'angle_revision': 'd7490967e1e7f66ebb84ce5fafff3513100fc71a', + 'angle_revision': '9863a3ef180edb17307665e0cc65a16603222103', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling build tools # and whatever else without interference from each other. @@ -64,7 +64,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. - 'pdfium_revision': '27e66753c8bd6e664f26d05c1a468dc68be01913', + 'pdfium_revision': '3439802410dc2c4aeb49397c987bf5ca0ddfad8b', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling openmax_dl # and whatever else without interference from each other. @@ -72,7 +72,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling BoringSSL # and whatever else without interference from each other. - 'boringssl_revision': '11a7b3c2d902ddb039e42fe19933e2a942f585f0', + 'boringssl_revision': 'b8d74f5b6a7ba628a937034f8a9ac1b9a36d9ad0', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling google-toolbox-for-mac # and whatever else without interference from each other. @@ -88,7 +88,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling NaCl # and whatever else without interference from each other. - 'nacl_revision': '3d513f39fafc2f24b10a98d2ceee7dd0599474a5', + 'nacl_revision': '163dfeb43e76995b4265ecd4e78670f7dd432e44', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling freetype-android # and whatever else without interference from each other. @@ -96,7 +96,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling catapult # and whatever else without interference from each other. - 'catapult_revision': '8ad018587279114b0cd368e9a0d4a8cecef03c08', + 'catapult_revision': '18bfc9b4cd624ca55e7589b5f7043867b9ee5b40', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -188,7 +188,7 @@ Var('chromium_git') + '/external/bidichecker/lib.git' + '@' + '97f2aa645b74c28c57eca56992235c79850fa9e0', 'src/third_party/webgl/src': - Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + 'bc2b06dfadf741437dbfdb0ec41c9557770b71e8', + Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + '130f5c1846618224127385428f2b189868f7cb9b', 'src/third_party/webdriver/pylib': Var('chromium_git') + '/external/selenium/py.git' + '@' + '5fd78261a75fe08d27ca4835fb6c5ce4b42275bd', @@ -487,7 +487,7 @@ Var('chromium_git') + '/external/github.com/kennethreitz/requests.git' + '@' + 'f172b30356d821d180fa4ecfa3e71c7274a32de4', 'src/third_party/custom_tabs_client/src': - Var('chromium_git') + '/external/github.com/GoogleChrome/custom-tabs-client.git' + '@' + 'c51efbddc4f976c88d15c730a79feba65ca857af', + Var('chromium_git') + '/external/github.com/GoogleChrome/custom-tabs-client.git' + '@' + 'e2b6730dad438de70d88b6ae5d33aa0995ba77d1', 'src/third_party/gvr-android-sdk/src': Var('chromium_git') + '/external/github.com/googlevr/gvr-android-sdk.git' + '@' + '25e7e14413229d4644a66be77e8f8ddeb3f91fe7',
diff --git a/android_webview/BUILD.gn b/android_webview/BUILD.gn index f5d8c73..a0e40238 100644 --- a/android_webview/BUILD.gn +++ b/android_webview/BUILD.gn
@@ -2,13 +2,14 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import("//android_webview/system_webview_apk_tmpl.gni") +import("//android_webview/webview_repack_locales.gni") import("//build/config/android/config.gni") import("//build/config/android/rules.gni") import("//build/config/locales.gni") +import("//components/spellcheck/spellcheck_build_features.gni") import("//tools/grit/repack.gni") import("//tools/resources/generate_resource_whitelist.gni") -import("system_webview_apk_tmpl.gni") -import("webview_repack_locales.gni") declare_args() { # Package name of the system_webview_apk target. @@ -488,6 +489,7 @@ "//components/printing/browser", "//components/printing/common", "//components/printing/renderer", + "//components/spellcheck:build_features", "//components/supervised_user_error_page", "//components/supervised_user_error_page:gin", "//components/version_info",
diff --git a/android_webview/DEPS b/android_webview/DEPS index 63f5faa..75ca256 100644 --- a/android_webview/DEPS +++ b/android_webview/DEPS
@@ -10,6 +10,9 @@ "+components/metrics", "+components/prefs", "+components/version_info", + # Only allow this header in spellchecking since allowing all of spellchecking + # would include both browser and renderer components. + "+components/spellcheck/spellcheck_build_features.h", "+components/supervised_user_error_page", "+components/web_restrictions", "+content/public/common",
diff --git a/android_webview/browser/aw_content_browser_client.cc b/android_webview/browser/aw_content_browser_client.cc index 021681d..5f695ea 100644 --- a/android_webview/browser/aw_content_browser_client.cc +++ b/android_webview/browser/aw_content_browser_client.cc
@@ -36,6 +36,7 @@ #include "components/cdm/browser/cdm_message_filter_android.h" #include "components/crash/content/browser/crash_micro_dump_manager_android.h" #include "components/navigation_interception/intercept_navigation_delegate.h" +#include "components/spellcheck/spellcheck_build_features.h" #include "content/public/browser/browser_message_filter.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_security_policy.h" @@ -59,7 +60,7 @@ #include "ui/base/resource/resource_bundle_android.h" #include "ui/resources/grit/ui_resources.h" -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) #include "components/spellcheck/browser/spellcheck_message_filter_platform.h" #include "components/spellcheck/common/spellcheck_switches.h" #endif @@ -219,7 +220,7 @@ host->AddFilter(new cdm::CdmMessageFilterAndroid()); host->AddFilter(new AwPrintingMessageFilter(host->GetID())); -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) host->AddFilter(new SpellCheckMessageFilterPlatform(host->GetID())); #endif }
diff --git a/android_webview/native/BUILD.gn b/android_webview/native/BUILD.gn index 86b568c..6eaba42 100644 --- a/android_webview/native/BUILD.gn +++ b/android_webview/native/BUILD.gn
@@ -4,6 +4,7 @@ import("//build/config/android/config.gni") import("//build/config/android/rules.gni") +import("//components/spellcheck/spellcheck_build_features.gni") source_set("native") { deps = [ @@ -13,6 +14,7 @@ "//base/third_party/dynamic_annotations:dynamic_annotations", "//cc:cc", "//components/autofill/content/browser:browser", + "//components/spellcheck:build_features", "//components/strings", "//components/web_contents_delegate_android:web_contents_delegate_android", "//content/public/common",
diff --git a/android_webview/native/android_webview_jni_registrar.cc b/android_webview/native/android_webview_jni_registrar.cc index f3b20ea..7697aa14 100644 --- a/android_webview/native/android_webview_jni_registrar.cc +++ b/android_webview/native/android_webview_jni_registrar.cc
@@ -25,8 +25,9 @@ #include "base/android/jni_android.h" #include "base/android/jni_registrar.h" #include "base/trace_event/trace_event.h" +#include "components/spellcheck/spellcheck_build_features.h" -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) #include "components/spellcheck/browser/android/component_jni_registrar.h" #endif @@ -52,7 +53,7 @@ { "AwWebContentsDelegate", RegisterAwWebContentsDelegate }, { "CookieManager", RegisterCookieManager }, { "AwGLFunctor", RegisterAwGLFunctor }, -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) {"SpellCheckerSessionBridge", spellcheck::android::RegisterSpellcheckJni}, #endif };
diff --git a/android_webview/renderer/aw_content_renderer_client.cc b/android_webview/renderer/aw_content_renderer_client.cc index 20754a7..97148169 100644 --- a/android_webview/renderer/aw_content_renderer_client.cc +++ b/android_webview/renderer/aw_content_renderer_client.cc
@@ -26,6 +26,7 @@ #include "components/autofill/content/renderer/autofill_agent.h" #include "components/autofill/content/renderer/password_autofill_agent.h" #include "components/printing/renderer/print_web_view_helper.h" +#include "components/spellcheck/spellcheck_build_features.h" #include "components/supervised_user_error_page/gin_wrapper.h" #include "components/supervised_user_error_page/supervised_user_error_page_android.h" #include "components/visitedlink/renderer/visitedlink_slave.h" @@ -52,7 +53,7 @@ #include "url/gurl.h" #include "url/url_constants.h" -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) #include "components/spellcheck/renderer/spellcheck.h" #include "components/spellcheck/renderer/spellcheck_provider.h" #endif @@ -81,7 +82,7 @@ base::ASCIIToUTF16(android_webview::kAndroidWebViewVideoPosterScheme)); blink::WebSecurityPolicy::registerURLSchemeAsSecure(aw_scheme); -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) if (!spellcheck_) { spellcheck_ = base::MakeUnique<SpellCheck>(); thread->AddObserver(spellcheck_.get()); @@ -176,7 +177,7 @@ render_view, std::unique_ptr<printing::PrintWebViewHelper::Delegate>( new AwPrintWebViewHelperDelegate())); -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) new SpellCheckProvider(render_view, spellcheck_.get()); #endif }
diff --git a/android_webview/renderer/aw_content_renderer_client.h b/android_webview/renderer/aw_content_renderer_client.h index ac0312c..578a2e3 100644 --- a/android_webview/renderer/aw_content_renderer_client.h +++ b/android_webview/renderer/aw_content_renderer_client.h
@@ -11,10 +11,11 @@ #include "android_webview/renderer/aw_render_thread_observer.h" #include "base/compiler_specific.h" #include "base/memory/weak_ptr.h" +#include "components/spellcheck/spellcheck_build_features.h" #include "components/web_restrictions/interfaces/web_restrictions.mojom.h" #include "content/public/renderer/content_renderer_client.h" -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) class SpellCheck; class SpellCheckProvider; #endif @@ -62,7 +63,7 @@ std::unique_ptr<visitedlink::VisitedLinkSlave> visited_link_slave_; web_restrictions::mojom::WebRestrictionsPtr web_restrictions_service_; -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) std::unique_ptr<SpellCheck> spellcheck_; #endif
diff --git a/android_webview/tools/system_webview_shell/test/data/webexposed/global-interface-listing-expected.txt b/android_webview/tools/system_webview_shell/test/data/webexposed/global-interface-listing-expected.txt index 1d23f86b..2681df8 100644 --- a/android_webview/tools/system_webview_shell/test/data/webexposed/global-interface-listing-expected.txt +++ b/android_webview/tools/system_webview_shell/test/data/webexposed/global-interface-listing-expected.txt
@@ -4359,7 +4359,6 @@ attribute SVG_ZOOMANDPAN_UNKNOWN getter preserveAspectRatio getter viewBox - getter viewTarget getter zoomAndPan method constructor setter zoomAndPan
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index 3fe326a..6de7e50a 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -187,6 +187,8 @@ "common/shelf/wm_shelf_util.cc", "common/shelf/wm_shelf_util.h", "common/shell_delegate.h", + "common/shutdown_controller.cc", + "common/shutdown_controller.h", "common/system/accessibility_observer.h", "common/system/brightness_control_delegate.h", "common/system/chromeos/audio/audio_detailed_view.cc", @@ -307,7 +309,6 @@ "common/system/chromeos/session/tray_session_length_limit.h", "common/system/chromeos/settings/tray_settings.cc", "common/system/chromeos/settings/tray_settings.h", - "common/system/chromeos/shutdown_policy_observer.h", "common/system/chromeos/supervised/custodian_info_tray_observer.h", "common/system/chromeos/supervised/tray_supervised_user.cc", "common/system/chromeos/supervised/tray_supervised_user.h", @@ -810,8 +811,6 @@ "wm/session_state_animator.h", "wm/session_state_animator_impl.cc", "wm/session_state_animator_impl.h", - "wm/shutdown_client_proxy.cc", - "wm/shutdown_client_proxy.h", "wm/stacking_controller.cc", "wm/stacking_controller.h", "wm/system_gesture_event_filter.cc",
diff --git a/ash/accelerators/accelerator_controller_unittest.cc b/ash/accelerators/accelerator_controller_unittest.cc index 93bc0b5..cb99f26 100644 --- a/ash/accelerators/accelerator_controller_unittest.cc +++ b/ash/accelerators/accelerator_controller_unittest.cc
@@ -941,8 +941,8 @@ // NOTE: Accelerators that do not work on the lock screen need to be // tested before the sequence below is invoked because it causes a side // effect of locking the screen. - EXPECT_TRUE(ProcessInController( - ui::Accelerator(ui::VKEY_L, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN))); + EXPECT_TRUE( + ProcessInController(ui::Accelerator(ui::VKEY_L, ui::EF_COMMAND_DOWN))); #endif }
diff --git a/ash/ash_chromeos_strings.grdp b/ash/ash_chromeos_strings.grdp index 77e71e6..1e9be1e 100644 --- a/ash/ash_chromeos_strings.grdp +++ b/ash/ash_chromeos_strings.grdp
@@ -613,4 +613,10 @@ desc="Notification message to tell users about the deprecation of Shift+Alt shortcut to switch to the next input method."> The shortcut to switch to the next input method has changed. Please use <ph name="NEW_SHORTCUT">$1<ex>Ctrl+Shift+Space</ex></ph> instead of <ph name="OLD_SHORTCUT">$2<ex>Shift+Alt</ex></ph>. </message> + + <!-- Notification that an accelerator was pressed, so the user knows how to toggle it back --> + <message name="IDS_HIGH_CONTRAST_ACCEL_MSG" + desc="Notification message to tell users that they just pressed the Search+Shift+H shortcut to toggle High Contrast Mode, and that pressing it again will toggle it off."> + High Contrast Mode enabled. Press Search+Shift+H again to toggle it off. + </message> </grit-part>
diff --git a/ash/ash_touch_exploration_manager_chromeos.cc b/ash/ash_touch_exploration_manager_chromeos.cc index 8eda21ee..363f6df6 100644 --- a/ash/ash_touch_exploration_manager_chromeos.cc +++ b/ash/ash_touch_exploration_manager_chromeos.cc
@@ -102,6 +102,17 @@ UpdateTouchExplorationState(); } +void AshTouchExplorationManager::PlaySpokenFeedbackToggleCountdown( + int tick_count) { + WmShell::Get()->accessibility_delegate()->PlaySpokenFeedbackToggleCountdown( + tick_count); +} + +void AshTouchExplorationManager::ToggleSpokenFeedback() { + WmShell::Get()->accessibility_delegate()->ToggleSpokenFeedback( + ash::A11Y_NOTIFICATION_SHOW); +} + void AshTouchExplorationManager::OnWindowActivated( aura::client::ActivationChangeObserver::ActivationReason reason, aura::Window* gained_active, @@ -129,11 +140,18 @@ const bool spoken_feedback_enabled = WmShell::Get()->accessibility_delegate()->IsSpokenFeedbackEnabled(); + if (!touch_accessibility_enabler_) { + // Always enable gesture to toggle spoken feedback. + touch_accessibility_enabler_.reset(new ui::TouchAccessibilityEnabler( + root_window_controller_->GetRootWindow(), this)); + } + if (spoken_feedback_enabled) { if (!touch_exploration_controller_.get()) { touch_exploration_controller_ = base::MakeUnique<ui::TouchExplorationController>( - root_window_controller_->GetRootWindow(), this); + root_window_controller_->GetRootWindow(), this, + touch_accessibility_enabler_.get()); } if (pass_through_surface) { const gfx::Rect& work_area =
diff --git a/ash/ash_touch_exploration_manager_chromeos.h b/ash/ash_touch_exploration_manager_chromeos.h index 9377059..8b2aa00 100644 --- a/ash/ash_touch_exploration_manager_chromeos.h +++ b/ash/ash_touch_exploration_manager_chromeos.h
@@ -10,6 +10,7 @@ #include "ash/ash_export.h" #include "ash/common/system/accessibility_observer.h" #include "base/macros.h" +#include "ui/chromeos/touch_accessibility_enabler.h" #include "ui/chromeos/touch_exploration_controller.h" #include "ui/display/display_observer.h" #include "ui/wm/public/activation_change_observer.h" @@ -28,6 +29,7 @@ class ASH_EXPORT AshTouchExplorationManager : public AccessibilityObserver, public ui::TouchExplorationControllerDelegate, + public ui::TouchAccessibilityEnablerDelegate, public display::DisplayObserver, public aura::client::ActivationChangeObserver { public: @@ -52,6 +54,10 @@ void OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) override; + // TouchAccessibilityEnablerDelegate overrides: + void PlaySpokenFeedbackToggleCountdown(int tick_count) override; + void ToggleSpokenFeedback() override; + // aura::client::ActivationChangeObserver overrides: void OnWindowActivated( aura::client::ActivationChangeObserver::ActivationReason reason, @@ -67,6 +73,7 @@ bool VolumeAdjustSoundEnabled(); std::unique_ptr<ui::TouchExplorationController> touch_exploration_controller_; + std::unique_ptr<ui::TouchAccessibilityEnabler> touch_accessibility_enabler_; RootWindowController* root_window_controller_; chromeos::CrasAudioHandler* audio_handler_;
diff --git a/ash/common/accelerators/accelerator_controller.cc b/ash/common/accelerators/accelerator_controller.cc index d706493..8f9503b 100644 --- a/ash/common/accelerators/accelerator_controller.cc +++ b/ash/common/accelerators/accelerator_controller.cc
@@ -47,12 +47,18 @@ #include "ash/common/system/chromeos/palette/palette_tray.h" #include "ash/common/system/chromeos/palette/palette_utils.h" #include "ash/common/system/status_area_widget.h" +#include "ash/common/system/system_notifier.h" #include "ash/common/wm_root_window_controller.h" #include "ash/common/wm_window.h" +#include "ash/resources/vector_icons/vector_icons.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/power_manager_client.h" +#include "grit/ash_strings.h" #include "ui/base/ime/chromeos/ime_keyboard.h" #include "ui/base/ime/chromeos/input_method_manager.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/gfx/paint_vector_icon.h" +#include "ui/message_center/message_center.h" #endif // defined(OS_CHROMEOS) namespace ash { @@ -339,6 +345,13 @@ } #if defined(OS_CHROMEOS) + +using message_center::Notification; + +// Identifier for the high contrast toggle accelerator notification. +const char kHighContrastToggleAccelNotificationId[] = + "chrome://settings/accessibility/highcontrast"; + void HandleShowImeMenuBubble() { base::RecordAction(UserMetricsAction("Accel_Show_Ime_Menu_Bubble")); @@ -466,6 +479,27 @@ keyboard->SetCapsLockEnabled(!keyboard->CapsLockIsEnabled()); } +void HandleToggleHighContrast() { + base::RecordAction(UserMetricsAction("Accel_Toggle_High_Contrast")); + + // Show a notification so the user knows that this accelerator toggled + // high contrast mode, and that they can press it again to toggle back. + // The message center automatically only shows this once per session. + std::unique_ptr<Notification> notification(new Notification( + message_center::NOTIFICATION_TYPE_SIMPLE, + kHighContrastToggleAccelNotificationId, base::string16() /* title */, + l10n_util::GetStringUTF16(IDS_HIGH_CONTRAST_ACCEL_MSG), + gfx::Image(CreateVectorIcon(kSystemMenuAccessibilityIcon, SK_ColorBLACK)), + base::string16() /* display source */, GURL(), + message_center::NotifierId(message_center::NotifierId::SYSTEM_COMPONENT, + system_notifier::kNotifierAccessibility), + message_center::RichNotificationData(), nullptr)); + message_center::MessageCenter::Get()->AddNotification( + std::move(notification)); + + WmShell::Get()->accessibility_delegate()->ToggleHighContrast(); +} + void HandleToggleSpokenFeedback() { base::RecordAction(UserMetricsAction("Accel_Toggle_Spoken_Feedback")); @@ -832,6 +866,7 @@ case OPEN_GET_HELP: case SHOW_IME_MENU_BUBBLE: case SUSPEND: + case TOGGLE_HIGH_CONTRAST: case TOGGLE_SPOKEN_FEEDBACK: case TOGGLE_WIFI: case VOLUME_DOWN: @@ -1049,6 +1084,9 @@ case TOGGLE_CAPS_LOCK: HandleToggleCapsLock(); break; + case TOGGLE_HIGH_CONTRAST: + HandleToggleHighContrast(); + break; case TOGGLE_SPOKEN_FEEDBACK: HandleToggleSpokenFeedback(); break;
diff --git a/ash/common/accelerators/accelerator_table.cc b/ash/common/accelerators/accelerator_table.cc index 9d81119..4181c1dc 100644 --- a/ash/common/accelerators/accelerator_table.cc +++ b/ash/common/accelerators/accelerator_table.cc
@@ -72,9 +72,8 @@ TOUCH_HUD_CLEAR}, {true, ui::VKEY_P, ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN, TOUCH_HUD_PROJECTION_TOGGLE}, - // Accessibility: Spoken feedback shortcuts. The first one is to toggle - // spoken feedback on or off. The others are only valid when - // spoken feedback is enabled. + {false, ui::VKEY_H, ui::EF_COMMAND_DOWN | ui::EF_SHIFT_DOWN, + TOGGLE_HIGH_CONTRAST}, {true, ui::VKEY_Z, ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN, TOGGLE_SPOKEN_FEEDBACK}, {true, ui::VKEY_OEM_COMMA, ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN, @@ -215,9 +214,12 @@ const size_t kDeprecatedAcceleratorsLength = arraysize(kDeprecatedAccelerators); const DeprecatedAcceleratorData kDeprecatedAcceleratorsData[] = { - {LOCK_SCREEN, "Ash.Accelerators.Deprecated.LockScreen", - IDS_DEPRECATED_LOCK_SCREEN_MSG, IDS_SHORTCUT_LOCK_SCREEN_OLD, - IDS_SHORTCUT_LOCK_SCREEN_NEW, true}, + { + LOCK_SCREEN, "Ash.Accelerators.Deprecated.LockScreen", + IDS_DEPRECATED_LOCK_SCREEN_MSG, IDS_SHORTCUT_LOCK_SCREEN_OLD, + IDS_SHORTCUT_LOCK_SCREEN_NEW, + false // Old accelerator was disabled in M56. + }, {SHOW_TASK_MANAGER, "Ash.Accelerators.Deprecated.ShowTaskManager", IDS_DEPRECATED_SHOW_TASK_MANAGER_MSG, IDS_SHORTCUT_TASK_MANAGER_OLD, IDS_SHORTCUT_TASK_MANAGER_NEW, true}, @@ -340,6 +342,7 @@ KEYBOARD_BRIGHTNESS_DOWN, KEYBOARD_BRIGHTNESS_UP, TOGGLE_CAPS_LOCK, + TOGGLE_HIGH_CONTRAST, TOGGLE_SPOKEN_FEEDBACK, TOGGLE_MIRROR_MODE, TOGGLE_WIFI, @@ -403,6 +406,7 @@ SUSPEND, SWAP_PRIMARY_DISPLAY, TOGGLE_CAPS_LOCK, + TOGGLE_HIGH_CONTRAST, TOGGLE_MIRROR_MODE, TOGGLE_SPOKEN_FEEDBACK, TOGGLE_WIFI, @@ -465,6 +469,7 @@ POWER_RELEASED, SWAP_PRIMARY_DISPLAY, TOGGLE_CAPS_LOCK, + TOGGLE_HIGH_CONTRAST, TOGGLE_MIRROR_MODE, TOGGLE_SPOKEN_FEEDBACK, TOGGLE_WIFI, @@ -528,6 +533,7 @@ KEYBOARD_BRIGHTNESS_UP, TOGGLE_APP_LIST, TOGGLE_CAPS_LOCK, + TOGGLE_HIGH_CONTRAST, TOGGLE_SPOKEN_FEEDBACK, TOGGLE_WIFI, VOLUME_DOWN,
diff --git a/ash/common/accelerators/accelerator_table.h b/ash/common/accelerators/accelerator_table.h index e64d879..960cbbb3 100644 --- a/ash/common/accelerators/accelerator_table.h +++ b/ash/common/accelerators/accelerator_table.h
@@ -138,6 +138,7 @@ SWITCH_TO_NEXT_USER, SWITCH_TO_PREVIOUS_USER, TOGGLE_CAPS_LOCK, + TOGGLE_HIGH_CONTRAST, TOGGLE_MIRROR_MODE, TOGGLE_SPOKEN_FEEDBACK, TOGGLE_WIFI,
diff --git a/ash/common/accessibility_delegate.h b/ash/common/accessibility_delegate.h index 36ea7080..f3dcccb 100644 --- a/ash/common/accessibility_delegate.h +++ b/ash/common/accessibility_delegate.h
@@ -121,6 +121,9 @@ // Gets the last accessibility alert that was triggered. virtual AccessibilityAlert GetLastAccessibilityAlert() = 0; + // Play tick sound indicating spoken feedback will be toggled after countdown. + virtual void PlaySpokenFeedbackToggleCountdown(int tick_count) = 0; + // Plays an earcon. Earcons are brief and distinctive sounds that indicate // when their mapped event has occurred. The sound key enums can be found in // chromeos/audio/chromeos_sounds.h.
diff --git a/ash/common/default_accessibility_delegate.cc b/ash/common/default_accessibility_delegate.cc index a4ebb23..559db9e6 100644 --- a/ash/common/default_accessibility_delegate.cc +++ b/ash/common/default_accessibility_delegate.cc
@@ -146,6 +146,9 @@ return accessibility_alert_; } +void DefaultAccessibilityDelegate::PlaySpokenFeedbackToggleCountdown( + int tick_count) {} + void DefaultAccessibilityDelegate::PlayEarcon(int sound_key) {} base::TimeDelta DefaultAccessibilityDelegate::PlayShutdownSound() const {
diff --git a/ash/common/default_accessibility_delegate.h b/ash/common/default_accessibility_delegate.h index 07bd8b66..68b471f 100644 --- a/ash/common/default_accessibility_delegate.h +++ b/ash/common/default_accessibility_delegate.h
@@ -52,6 +52,7 @@ double GetSavedScreenMagnifierScale() override; void TriggerAccessibilityAlert(AccessibilityAlert alert) override; AccessibilityAlert GetLastAccessibilityAlert() override; + void PlaySpokenFeedbackToggleCountdown(int tick_count) override; void PlayEarcon(int sound_key) override; base::TimeDelta PlayShutdownSound() const override; void HandleAccessibilityGesture(ui::AXGesture gesture) override;
diff --git a/ash/common/mojo_interface_factory.cc b/ash/common/mojo_interface_factory.cc index d6a38b9..1eef497 100644 --- a/ash/common/mojo_interface_factory.cc +++ b/ash/common/mojo_interface_factory.cc
@@ -7,6 +7,7 @@ #include <utility> #include "ash/common/shelf/shelf_controller.h" +#include "ash/common/shutdown_controller.h" #include "ash/common/system/locale/locale_notification_controller.h" #include "ash/common/system/tray/system_tray_controller.h" #include "ash/common/wallpaper/wallpaper_controller.h" @@ -28,6 +29,11 @@ WmShell::Get()->shelf_controller()->BindRequest(std::move(request)); } +void BindShutdownControllerRequestOnMainThread( + mojom::ShutdownControllerRequest request) { + WmShell::Get()->shutdown_controller()->BindRequest(std::move(request)); +} + void BindSystemTrayRequestOnMainThread(mojom::SystemTrayRequest request) { WmShell::Get()->system_tray_controller()->BindRequest(std::move(request)); } @@ -49,6 +55,8 @@ main_thread_task_runner); registry->AddInterface(base::Bind(&BindShelfRequestOnMainThread), main_thread_task_runner); + registry->AddInterface(base::Bind(&BindShutdownControllerRequestOnMainThread), + main_thread_task_runner); registry->AddInterface(base::Bind(&BindSystemTrayRequestOnMainThread), main_thread_task_runner); registry->AddInterface(base::Bind(&BindWallpaperRequestOnMainThread),
diff --git a/ash/common/shelf/overflow_button.cc b/ash/common/shelf/overflow_button.cc index 607d07a..4f3489e4 100644 --- a/ash/common/shelf/overflow_button.cc +++ b/ash/common/shelf/overflow_button.cc
@@ -84,7 +84,11 @@ } std::unique_ptr<views::InkDrop> OverflowButton::CreateInkDrop() { - return CreateDefaultFloodFillInkDropImpl(); + std::unique_ptr<views::InkDropImpl> ink_drop = + CreateDefaultFloodFillInkDropImpl(); + ink_drop->SetShowHighlightOnHover(false); + ink_drop->SetAutoHighlightMode(views::InkDropImpl::AutoHighlightMode::NONE); + return std::move(ink_drop); } std::unique_ptr<views::InkDropRipple> OverflowButton::CreateInkDropRipple()
diff --git a/ash/common/shutdown_controller.cc b/ash/common/shutdown_controller.cc new file mode 100644 index 0000000..7342eb2 --- /dev/null +++ b/ash/common/shutdown_controller.cc
@@ -0,0 +1,47 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ash/common/shutdown_controller.h" + +#include "ash/common/shell_delegate.h" +#include "ash/common/wm_shell.h" + +#if defined(OS_CHROMEOS) +#include "base/sys_info.h" +#include "chromeos/dbus/dbus_thread_manager.h" +#include "chromeos/dbus/power_manager_client.h" +#endif + +namespace ash { + +ShutdownController::ShutdownController() {} + +ShutdownController::~ShutdownController() {} + +void ShutdownController::ShutDownOrReboot() { +#if defined(OS_CHROMEOS) + if (base::SysInfo::IsRunningOnChromeOS()) { + // Power manager handles shutdown on Chrome OS hardware. + using chromeos::DBusThreadManager; + if (reboot_on_shutdown_) + DBusThreadManager::Get()->GetPowerManagerClient()->RequestRestart(); + else + DBusThreadManager::Get()->GetPowerManagerClient()->RequestShutdown(); + return; + } +#endif // defined(OS_CHROMEOS) + + // On Windows and on Linux desktop just exit. + WmShell::Get()->delegate()->Exit(); +} + +void ShutdownController::SetRebootOnShutdown(bool reboot_on_shutdown) { + reboot_on_shutdown_ = reboot_on_shutdown; +} + +void ShutdownController::BindRequest(mojom::ShutdownControllerRequest request) { + bindings_.AddBinding(this, std::move(request)); +} + +} // namespace ash
diff --git a/ash/common/shutdown_controller.h b/ash/common/shutdown_controller.h new file mode 100644 index 0000000..266af11 --- /dev/null +++ b/ash/common/shutdown_controller.h
@@ -0,0 +1,49 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef ASH_COMMON_SHUTDOWN_CONTROLLER_H_ +#define ASH_COMMON_SHUTDOWN_CONTROLLER_H_ + +#include "ash/ash_export.h" +#include "ash/public/interfaces/shutdown.mojom.h" +#include "base/compiler_specific.h" +#include "base/macros.h" +#include "mojo/public/cpp/bindings/binding_set.h" + +namespace ash { + +// Handles actual device shutdown by making requests to powerd over D-Bus. +// Caches the DeviceRebootOnShutdown device policy sent from Chrome over mojo. +class ASH_EXPORT ShutdownController + : NON_EXPORTED_BASE(public mojom::ShutdownController) { + public: + ShutdownController(); + ~ShutdownController() override; + + bool reboot_on_shutdown() const { return reboot_on_shutdown_; } + + // Shuts down or reboots based on the current DeviceRebootOnShutdown policy. + // Does not trigger the shutdown fade-out animation. For animated shutdown + // use WmShell::RequestShutdown(). Virtual for testing. + virtual void ShutDownOrReboot(); + + // Binds the mojom::ShutdownController interface request to this object. + void BindRequest(mojom::ShutdownControllerRequest request); + + private: + // mojom::ShutdownController: + void SetRebootOnShutdown(bool reboot_on_shutdown) override; + + // Cached copy of the DeviceRebootOnShutdown policy from chrome. + bool reboot_on_shutdown_ = false; + + // Bindings for the ShutdownController interface. + mojo::BindingSet<mojom::ShutdownController> bindings_; + + DISALLOW_COPY_AND_ASSIGN(ShutdownController); +}; + +} // namespace ash + +#endif // ASH_COMMON_SHUTDOWN_CONTROLLER_H_
diff --git a/ash/common/system/chromeos/bluetooth/tray_bluetooth.cc b/ash/common/system/chromeos/bluetooth/tray_bluetooth.cc index 0cee381..e93332e 100644 --- a/ash/common/system/chromeos/bluetooth/tray_bluetooth.cc +++ b/ash/common/system/chromeos/bluetooth/tray_bluetooth.cc
@@ -74,9 +74,11 @@ } } -// Returns corresponding device type icons for given Bluetooth device types. +// Returns corresponding device type icons for given Bluetooth device types and +// connection states. const gfx::VectorIcon& GetBluetoothDeviceIcon( - device::BluetoothDeviceType device_type) { + device::BluetoothDeviceType device_type, + bool connected) { switch (device_type) { case device::BluetoothDeviceType::COMPUTER: return ash::kSystemMenuComputerIcon; @@ -104,7 +106,8 @@ LOG(WARNING) << "Unknown device type icon for Bluetooth was requested."; break; } - return ash::kSystemMenuBluetoothIcon; + return connected ? ash::kSystemMenuBluetoothConnectedIcon + : ash::kSystemMenuBluetoothIcon; } const int kDisabledPanelLabelBaselineY = 20; @@ -335,7 +338,8 @@ HoverHighlightView* container = nullptr; if (UseMd()) { gfx::ImageSkia icon_image = CreateVectorIcon( - GetBluetoothDeviceIcon(list[i].device_type), kMenuIconColor); + GetBluetoothDeviceIcon(list[i].device_type, list[i].connected), + kMenuIconColor); container = AddScrollListItemWithIcon(list[i].display_name, highlight, checked, enabled, icon_image);
diff --git a/ash/common/system/chromeos/ime_menu/ime_list_view.cc b/ash/common/system/chromeos/ime_menu/ime_list_view.cc index 4bf2189..cf6d111 100644 --- a/ash/common/system/chromeos/ime_menu/ime_list_view.cc +++ b/ash/common/system/chromeos/ime_menu/ime_list_view.cc
@@ -4,7 +4,6 @@ #include "ash/common/system/chromeos/ime_menu/ime_list_view.h" -#include "ash/common/ash_view_ids.h" #include "ash/common/material_design/material_design_controller.h" #include "ash/common/system/tray/hover_highlight_view.h" #include "ash/common/system/tray/ime_info.h" @@ -203,8 +202,8 @@ private: void Init() { + TrayPopupUtils::ConfigureAsStickyHeader(this); SetLayoutManager(new views::FillLayout); - set_background(views::Background::CreateSolidBackground(kBackgroundColor)); TriView* tri_view = TrayPopupUtils::CreateDefaultRowView(); AddChildView(tri_view); @@ -229,8 +228,6 @@ ui::ResourceBundle::GetSharedInstance().GetLocalizedString( IDS_ASH_STATUS_TRAY_ACCESSIBILITY_VIRTUAL_KEYBOARD)); tri_view->AddView(TriView::Container::END, toggle_); - - set_id(VIEW_ID_STICKY_HEADER); } // Updates the style of |label_| based on the current native theme.
diff --git a/ash/common/system/chromeos/network/network_list_md.cc b/ash/common/system/chromeos/network/network_list_md.cc index 0f6c381..df2ddad1 100644 --- a/ash/common/system/chromeos/network/network_list_md.cc +++ b/ash/common/system/chromeos/network/network_list_md.cc
@@ -6,12 +6,12 @@ #include <stddef.h> -#include "ash/common/ash_view_ids.h" #include "ash/common/system/chromeos/network/network_icon.h" #include "ash/common/system/chromeos/network/network_icon_animation.h" #include "ash/common/system/chromeos/network/network_list_delegate.h" #include "ash/common/system/tray/system_menu_button.h" #include "ash/common/system/tray/tray_constants.h" +#include "ash/common/system/tray/tray_popup_utils.h" #include "base/memory/ptr_util.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/power_manager/power_supply_properties.pb.h" @@ -29,7 +29,6 @@ #include "ui/gfx/font.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/gfx/vector_icons_public.h" -#include "ui/views/background.h" #include "ui/views/border.h" #include "ui/views/controls/button/toggle_button.h" #include "ui/views/controls/label.h" @@ -136,8 +135,7 @@ // TODO(mohsen): Consider using TriView class and adding a utility function // to TrayPopupUtils to simplify creation of the following layout. See // https://crbug.com/614453. - set_id(VIEW_ID_STICKY_HEADER); - set_background(views::Background::CreateSolidBackground(kBackgroundColor)); + TrayPopupUtils::ConfigureAsStickyHeader(this); container_ = new views::View; container_->SetBorder(views::CreateEmptyBorder( 0, kSectionHeaderRowLeftInset, 0, kSectionHeaderRowRightInset));
diff --git a/ash/common/system/chromeos/network/vpn_list_view.cc b/ash/common/system/chromeos/network/vpn_list_view.cc index ff8ee0a..1ad1629 100644 --- a/ash/common/system/chromeos/network/vpn_list_view.cc +++ b/ash/common/system/chromeos/network/vpn_list_view.cc
@@ -296,8 +296,10 @@ provider_view_key_map_.clear(); network_view_service_path_map_.clear(); list_empty_ = true; - container()->SetLayoutManager( - new views::BoxLayout(views::BoxLayout::kVertical, 0, 0, 0)); + if (!UseMd()) { + container()->SetLayoutManager( + new views::BoxLayout(views::BoxLayout::kVertical, 0, 0, 0)); + } // Get the list of available VPN networks, in shill's priority order. chromeos::NetworkStateHandler::NetworkStateList networks;
diff --git a/ash/common/system/chromeos/shutdown_policy_observer.h b/ash/common/system/chromeos/shutdown_policy_observer.h deleted file mode 100644 index cb15296a..0000000 --- a/ash/common/system/chromeos/shutdown_policy_observer.h +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright 2014 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 ASH_COMMON_SYSTEM_CHROMEOS_SHUTDOWN_POLICY_OBSERVER_H_ -#define ASH_COMMON_SYSTEM_CHROMEOS_SHUTDOWN_POLICY_OBSERVER_H_ - -#include "ash/ash_export.h" - -namespace ash { - -// Registered with SystemTrayDelegate to observe the |kRebootOnShutdown| policy. -class ASH_EXPORT ShutdownPolicyObserver { - public: - // Called when the value of the |kRebootOnShutdown| policy is changed. - virtual void OnShutdownPolicyChanged(bool reboot_on_shutdown) = 0; - - protected: - virtual ~ShutdownPolicyObserver() {} -}; - -} // namespace ash - -#endif // ASH_COMMON_SYSTEM_CHROMEOS_SHUTDOWN_POLICY_OBSERVER_H_
diff --git a/ash/common/system/date/date_default_view.cc b/ash/common/system/date/date_default_view.cc index 8eedc08..c27ed1a 100644 --- a/ash/common/system/date/date_default_view.cc +++ b/ash/common/system/date/date_default_view.cc
@@ -6,11 +6,11 @@ #include "ash/common/metrics/user_metrics_action.h" #include "ash/common/session/session_state_delegate.h" +#include "ash/common/shutdown_controller.h" #include "ash/common/system/date/date_view.h" #include "ash/common/system/tray/special_popup_row.h" #include "ash/common/system/tray/system_tray.h" #include "ash/common/system/tray/system_tray_controller.h" -#include "ash/common/system/tray/system_tray_delegate.h" #include "ash/common/system/tray/tray_constants.h" #include "ash/common/system/tray/tray_popup_header_button.h" #include "ash/common/wm_shell.h" @@ -44,8 +44,7 @@ : help_button_(nullptr), shutdown_button_(nullptr), lock_button_(nullptr), - date_view_(nullptr), - weak_factory_(this) { + date_view_(nullptr) { SetLayoutManager(new views::FillLayout); date_view_ = new tray::DateView(owner); @@ -90,6 +89,11 @@ shutdown_button_->SetTooltipText( l10n_util::GetStringUTF16(IDS_ASH_STATUS_TRAY_SHUTDOWN)); view->AddViewToRowNonMd(shutdown_button_, true); + // This object is recreated every time the menu opens. Don't bother updating + // the tooltip if the shutdown policy changes while the menu is open. + bool reboot = WmShell::Get()->shutdown_controller()->reboot_on_shutdown(); + shutdown_button_->SetTooltipText(l10n_util::GetStringUTF16( + reboot ? IDS_ASH_STATUS_TRAY_REBOOT : IDS_ASH_STATUS_TRAY_SHUTDOWN)); } if (shell->GetSessionStateDelegate()->CanLockScreen()) { @@ -101,20 +105,10 @@ l10n_util::GetStringUTF16(IDS_ASH_STATUS_TRAY_LOCK)); view->AddViewToRowNonMd(lock_button_, true); } - SystemTrayDelegate* system_tray_delegate = shell->system_tray_delegate(); - system_tray_delegate->AddShutdownPolicyObserver(this); - system_tray_delegate->ShouldRebootOnShutdown(base::Bind( - &DateDefaultView::OnShutdownPolicyChanged, weak_factory_.GetWeakPtr())); #endif // !defined(OS_WIN) } -DateDefaultView::~DateDefaultView() { - // We need the check as on shell destruction, the delegate is destroyed first. - SystemTrayDelegate* system_tray_delegate = - WmShell::Get()->system_tray_delegate(); - if (system_tray_delegate) - system_tray_delegate->RemoveShutdownPolicyObserver(this); -} +DateDefaultView::~DateDefaultView() {} views::View* DateDefaultView::GetHelpButtonView() { return help_button_; @@ -154,13 +148,4 @@ date_view_->CloseSystemBubble(); } -void DateDefaultView::OnShutdownPolicyChanged(bool reboot_on_shutdown) { - if (!shutdown_button_) - return; - - shutdown_button_->SetTooltipText(l10n_util::GetStringUTF16( - reboot_on_shutdown ? IDS_ASH_STATUS_TRAY_REBOOT - : IDS_ASH_STATUS_TRAY_SHUTDOWN)); -} - } // namespace ash
diff --git a/ash/common/system/date/date_default_view.h b/ash/common/system/date/date_default_view.h index 4e49032..6adaee0 100644 --- a/ash/common/system/date/date_default_view.h +++ b/ash/common/system/date/date_default_view.h
@@ -7,9 +7,7 @@ #include "ash/ash_export.h" #include "ash/common/login_status.h" -#include "ash/common/system/chromeos/shutdown_policy_observer.h" #include "base/macros.h" -#include "base/memory/weak_ptr.h" #include "ui/views/controls/button/button.h" #include "ui/views/view.h" @@ -26,8 +24,7 @@ // TODO(tdanderson): Remove this class once material design is enabled by // default. See crbug.com/614453. class ASH_EXPORT DateDefaultView : public views::View, - public views::ButtonListener, - public ShutdownPolicyObserver { + public views::ButtonListener { public: DateDefaultView(SystemTrayItem* owner, LoginStatus login); @@ -39,9 +36,6 @@ tray::DateView* GetDateView(); const tray::DateView* GetDateView() const; - // ash::ShutdownPolicyObserver: - void OnShutdownPolicyChanged(bool reboot_on_shutdown) override; - private: // Overridden from views::ButtonListener. void ButtonPressed(views::Button* sender, const ui::Event& event) override; @@ -51,8 +45,6 @@ TrayPopupHeaderButton* lock_button_; tray::DateView* date_view_; - base::WeakPtrFactory<DateDefaultView> weak_factory_; - DISALLOW_COPY_AND_ASSIGN(DateDefaultView); };
diff --git a/ash/common/system/system_notifier.cc b/ash/common/system/system_notifier.cc index d7704b0f..f014d80 100644 --- a/ash/common/system/system_notifier.cc +++ b/ash/common/system/system_notifier.cc
@@ -18,8 +18,8 @@ // which can appear regardless of the situation, such like login screen or lock // screen. const char* kAlwaysShownSystemNotifierIds[] = { - kNotifierDeprecatedAccelerator, kNotifierBattery, kNotifierDisplay, - kNotifierDisplayError, + kNotifierAccessibility, kNotifierDeprecatedAccelerator, kNotifierBattery, + kNotifierDisplay, kNotifierDisplayError, #if defined(OS_CHROMEOS) kNotifierNetworkError, #endif @@ -60,6 +60,7 @@ } // namespace +const char kNotifierAccessibility[] = "ash.accessibility"; const char kNotifierBattery[] = "ash.battery"; const char kNotifierBluetooth[] = "ash.bluetooth"; const char kNotifierDeprecatedAccelerator[] = "ash.accelerator-controller";
diff --git a/ash/common/system/system_notifier.h b/ash/common/system/system_notifier.h index e8bbb30..08cc4773 100644 --- a/ash/common/system/system_notifier.h +++ b/ash/common/system/system_notifier.h
@@ -14,6 +14,7 @@ namespace system_notifier { // The list of ash system notifier IDs. Alphabetical order. +ASH_EXPORT extern const char kNotifierAccessibility[]; ASH_EXPORT extern const char kNotifierBattery[]; ASH_EXPORT extern const char kNotifierBluetooth[]; ASH_EXPORT extern const char kNotifierDeprecatedAccelerator[];
diff --git a/ash/common/system/tiles/tiles_default_view.cc b/ash/common/system/tiles/tiles_default_view.cc index 92a0e60e..26b9e01 100644 --- a/ash/common/system/tiles/tiles_default_view.cc +++ b/ash/common/system/tiles/tiles_default_view.cc
@@ -6,6 +6,7 @@ #include "ash/common/metrics/user_metrics_action.h" #include "ash/common/session/session_state_delegate.h" +#include "ash/common/shutdown_controller.h" #include "ash/common/system/tray/system_menu_button.h" #include "ash/common/system/tray/system_tray.h" #include "ash/common/system/tray/system_tray_controller.h" @@ -44,18 +45,9 @@ settings_button_(nullptr), help_button_(nullptr), lock_button_(nullptr), - power_button_(nullptr), - weak_factory_(this) {} + power_button_(nullptr) {} -TilesDefaultView::~TilesDefaultView() { - SystemTrayDelegate* system_tray_delegate = - WmShell::Get()->system_tray_delegate(); - - // Perform this check since the delegate is destroyed first upon shell - // destruction. - if (system_tray_delegate) - system_tray_delegate->RemoveShutdownPolicyObserver(this); -} +TilesDefaultView::~TilesDefaultView() {} void TilesDefaultView::Init() { WmShell* shell = WmShell::Get(); @@ -109,10 +101,11 @@ new SystemMenuButton(this, SystemMenuButton::InkDropStyle::FLOOD_FILL, kSystemMenuPowerIcon, IDS_ASH_STATUS_TRAY_SHUTDOWN); AddChildView(power_button_); - SystemTrayDelegate* system_tray_delegate = shell->system_tray_delegate(); - system_tray_delegate->AddShutdownPolicyObserver(this); - system_tray_delegate->ShouldRebootOnShutdown(base::Bind( - &TilesDefaultView::OnShutdownPolicyChanged, weak_factory_.GetWeakPtr())); + // This object is recreated every time the menu opens. Don't bother updating + // the tooltip if the shutdown policy changes while the menu is open. + bool reboot = WmShell::Get()->shutdown_controller()->reboot_on_shutdown(); + power_button_->SetTooltipText(l10n_util::GetStringUTF16( + reboot ? IDS_ASH_STATUS_TRAY_REBOOT : IDS_ASH_STATUS_TRAY_SHUTDOWN)); #endif // !defined(OS_WIN) } @@ -141,15 +134,6 @@ owner_->system_tray()->CloseSystemBubble(); } -void TilesDefaultView::OnShutdownPolicyChanged(bool reboot_on_shutdown) { - if (!power_button_) - return; - - power_button_->SetTooltipText(l10n_util::GetStringUTF16( - reboot_on_shutdown ? IDS_ASH_STATUS_TRAY_REBOOT - : IDS_ASH_STATUS_TRAY_SHUTDOWN)); -} - views::View* TilesDefaultView::GetHelpButtonView() const { return help_button_; }
diff --git a/ash/common/system/tiles/tiles_default_view.h b/ash/common/system/tiles/tiles_default_view.h index 19140c85..fd59a2c 100644 --- a/ash/common/system/tiles/tiles_default_view.h +++ b/ash/common/system/tiles/tiles_default_view.h
@@ -7,9 +7,7 @@ #include "ash/ash_export.h" #include "ash/common/login_status.h" -#include "ash/common/system/chromeos/shutdown_policy_observer.h" #include "base/macros.h" -#include "base/memory/weak_ptr.h" #include "ui/views/controls/button/button.h" #include "ui/views/view.h" @@ -24,8 +22,7 @@ // The container view for the tiles in the bottom row of the system menu // (settings, help, lock, and power). class ASH_EXPORT TilesDefaultView : public views::View, - public views::ButtonListener, - public ShutdownPolicyObserver { + public views::ButtonListener { public: TilesDefaultView(SystemTrayItem* owner, LoginStatus login); ~TilesDefaultView() override; @@ -38,9 +35,6 @@ // views::ButtonListener: void ButtonPressed(views::Button* sender, const ui::Event& event) override; - // ShutdownPolicyObserver: - void OnShutdownPolicyChanged(bool reboot_on_shutdown) override; - // Accessor needed to obtain the help button view for the first-run flow. views::View* GetHelpButtonView() const; @@ -60,8 +54,6 @@ views::CustomButton* lock_button_; views::CustomButton* power_button_; - base::WeakPtrFactory<TilesDefaultView> weak_factory_; - DISALLOW_COPY_AND_ASSIGN(TilesDefaultView); };
diff --git a/ash/common/system/tiles/tray_tiles.cc b/ash/common/system/tiles/tray_tiles.cc index 9c68db2f..227a4c9 100644 --- a/ash/common/system/tiles/tray_tiles.cc +++ b/ash/common/system/tiles/tray_tiles.cc
@@ -22,6 +22,10 @@ return default_view_->GetHelpButtonView(); } +TilesDefaultView* TrayTiles::GetDefaultViewForTesting() const { + return default_view_; +} + views::View* TrayTiles::CreateDefaultViewForTesting(LoginStatus status) { return CreateDefaultView(status); }
diff --git a/ash/common/system/tiles/tray_tiles.h b/ash/common/system/tiles/tray_tiles.h index 92d61d2..be8bc8b 100644 --- a/ash/common/system/tiles/tray_tiles.h +++ b/ash/common/system/tiles/tray_tiles.h
@@ -24,6 +24,7 @@ // Accessor needed to obtain the help button view for the first-run flow. views::View* GetHelpButtonView() const; + TilesDefaultView* GetDefaultViewForTesting() const; views::View* CreateDefaultViewForTesting(LoginStatus status); private:
diff --git a/ash/common/system/tray/default_system_tray_delegate.cc b/ash/common/system/tray/default_system_tray_delegate.cc index f58c214..7c14054 100644 --- a/ash/common/system/tray/default_system_tray_delegate.cc +++ b/ash/common/system/tray/default_system_tray_delegate.cc
@@ -39,7 +39,11 @@ info->factory_reset_required = false; } -bool DefaultSystemTrayDelegate::ShouldShowSettings() { +bool DefaultSystemTrayDelegate::ShouldShowSettings() const { + return true; +} + +bool DefaultSystemTrayDelegate::ShouldShowNotificationTray() const { return true; } @@ -47,7 +51,7 @@ bluetooth_enabled_ = !bluetooth_enabled_; } -bool DefaultSystemTrayDelegate::IsBluetoothDiscovering() { +bool DefaultSystemTrayDelegate::IsBluetoothDiscovering() const { return false; }
diff --git a/ash/common/system/tray/default_system_tray_delegate.h b/ash/common/system/tray/default_system_tray_delegate.h index a4550ff..81a9821 100644 --- a/ash/common/system/tray/default_system_tray_delegate.h +++ b/ash/common/system/tray/default_system_tray_delegate.h
@@ -21,9 +21,10 @@ std::string GetSupervisedUserManager() const override; bool IsUserSupervised() const override; void GetSystemUpdateInfo(UpdateInfo* info) const override; - bool ShouldShowSettings() override; + bool ShouldShowSettings() const override; + bool ShouldShowNotificationTray() const override; void ToggleBluetooth() override; - bool IsBluetoothDiscovering() override; + bool IsBluetoothDiscovering() const override; bool GetBluetoothAvailable() override; bool GetBluetoothEnabled() override; bool GetBluetoothDiscovering() override;
diff --git a/ash/common/system/tray/system_tray_delegate.cc b/ash/common/system/tray/system_tray_delegate.cc index d30bc104..13e56db 100644 --- a/ash/common/system/tray/system_tray_delegate.cc +++ b/ash/common/system/tray/system_tray_delegate.cc
@@ -72,7 +72,11 @@ info->factory_reset_required = false; } -bool SystemTrayDelegate::ShouldShowSettings() { +bool SystemTrayDelegate::ShouldShowSettings() const { + return false; +} + +bool SystemTrayDelegate::ShouldShowNotificationTray() const { return false; } @@ -107,7 +111,7 @@ void SystemTrayDelegate::ToggleBluetooth() {} -bool SystemTrayDelegate::IsBluetoothDiscovering() { +bool SystemTrayDelegate::IsBluetoothDiscovering() const { return false; } @@ -158,15 +162,6 @@ void SystemTrayDelegate::RemoveCustodianInfoTrayObserver( CustodianInfoTrayObserver* observer) {} -void SystemTrayDelegate::AddShutdownPolicyObserver( - ShutdownPolicyObserver* observer) {} - -void SystemTrayDelegate::RemoveShutdownPolicyObserver( - ShutdownPolicyObserver* observer) {} - -void SystemTrayDelegate::ShouldRebootOnShutdown( - const RebootOnShutdownCallback& callback) {} - VPNDelegate* SystemTrayDelegate::GetVPNDelegate() const { return nullptr; }
diff --git a/ash/common/system/tray/system_tray_delegate.h b/ash/common/system/tray/system_tray_delegate.h index 61ff9b64..75cadb8 100644 --- a/ash/common/system/tray/system_tray_delegate.h +++ b/ash/common/system/tray/system_tray_delegate.h
@@ -32,7 +32,6 @@ struct IMEPropertyInfo; class CustodianInfoTrayObserver; -class ShutdownPolicyObserver; class SystemTray; class SystemTrayItem; @@ -76,8 +75,6 @@ class NetworkingConfigDelegate; class VPNDelegate; -using RebootOnShutdownCallback = base::Callback<void(bool)>; - // SystemTrayDelegate is intended for delegating tasks in the System Tray to the // application (e.g. Chrome). These tasks should be limited to application // (browser) specific tasks. For non application specific tasks, where possible, @@ -134,7 +131,10 @@ virtual void GetSystemUpdateInfo(UpdateInfo* info) const; // Returns true if settings menu item should appear. - virtual bool ShouldShowSettings(); + virtual bool ShouldShowSettings() const; + + // Returns true if notification tray should appear. + virtual bool ShouldShowNotificationTray() const; // Shows information about enterprise enrolled devices. virtual void ShowEnterpriseInfo(); @@ -161,7 +161,7 @@ virtual void ConnectToBluetoothDevice(const std::string& address); // Returns true if bluetooth adapter is discovering bluetooth devices. - virtual bool IsBluetoothDiscovering(); + virtual bool IsBluetoothDiscovering() const; // Returns the currently selected IME. virtual void GetCurrentIME(IMEInfo* info); @@ -223,18 +223,6 @@ virtual void RemoveCustodianInfoTrayObserver( CustodianInfoTrayObserver* observer); - // Adds an observer whose |OnShutdownPolicyChanged| function is called when - // the |DeviceRebootOnShutdown| policy changes. If this policy is set to - // true, a device cannot be shut down anymore but only rebooted. - virtual void AddShutdownPolicyObserver(ShutdownPolicyObserver* observer); - - virtual void RemoveShutdownPolicyObserver(ShutdownPolicyObserver* observer); - - // Determines whether the device is automatically rebooted when shut down as - // specified by the device policy |DeviceRebootOnShutdown|. This function - // asynchronously calls |callback| once a trusted policy becomes available. - virtual void ShouldRebootOnShutdown(const RebootOnShutdownCallback& callback); - // Returns VPNDelegate. May return nullptr. virtual VPNDelegate* GetVPNDelegate() const;
diff --git a/ash/common/system/tray/tray_background_view.cc b/ash/common/system/tray/tray_background_view.cc index cf52b947..b2ad7299 100644 --- a/ash/common/system/tray/tray_background_view.cc +++ b/ash/common/system/tray/tray_background_view.cc
@@ -35,6 +35,7 @@ #include "ui/gfx/transform.h" #include "ui/views/animation/flood_fill_ink_drop_ripple.h" #include "ui/views/animation/ink_drop_highlight.h" +#include "ui/views/animation/ink_drop_mask.h" #include "ui/views/background.h" #include "ui/views/layout/box_layout.h" #include "ui/wm/core/window_animations.h" @@ -572,6 +573,14 @@ SchedulePaint(); } +std::unique_ptr<views::InkDropMask> TrayBackgroundView::CreateInkDropMask() + const { + return base::MakeUnique<views::RoundRectInkDropMask>( + GetLocalBounds(), + GetBackgroundBounds(GetContentsBounds(), shelf_alignment_), + kTrayRoundedBorderRadius); +} + bool TrayBackgroundView::ShouldEnterPushedState(const ui::Event& event) { if (is_active_) return false;
diff --git a/ash/common/system/tray/tray_background_view.h b/ash/common/system/tray/tray_background_view.h index 4197403..5b6a5a20 100644 --- a/ash/common/system/tray/tray_background_view.h +++ b/ash/common/system/tray/tray_background_view.h
@@ -139,6 +139,7 @@ protected: // ActionableView: + std::unique_ptr<views::InkDropMask> CreateInkDropMask() const override; bool ShouldEnterPushedState(const ui::Event& event) override; bool PerformAction(const ui::Event& event) override; void HandlePerformActionResult(bool action_performed,
diff --git a/ash/common/system/tray/tray_details_view.cc b/ash/common/system/tray/tray_details_view.cc index 9ca7faf..d6c6ea5 100644 --- a/ash/common/system/tray/tray_details_view.cc +++ b/ash/common/system/tray/tray_details_view.cc
@@ -43,12 +43,14 @@ class ScrollContentsView : public views::View, public views::ViewTargeterDelegate { public: - ScrollContentsView() { + ScrollContentsView() + : box_layout_(new views::BoxLayout( + views::BoxLayout::kVertical, + 0, + 0, + UseMd() ? 0 : kContentsBetweenChildSpacingNonMd)) { SetEventTargeter(base::MakeUnique<views::ViewTargeter>(this)); - SetLayoutManager( - new views::BoxLayout(views::BoxLayout::kVertical, 0, - UseMd() ? kContentsVerticalSpacingMd : 0, - UseMd() ? 0 : kContentsBetweenChildSpacingNonMd)); + SetLayoutManager(box_layout_); } ~ScrollContentsView() override {} @@ -90,6 +92,18 @@ return header.view == details.child; }), headers_.end()); + } else if (details.is_add && details.parent == this && + details.child == child_at(0)) { + // We always want padding on the bottom of the scroll contents. + // We only want padding on the top of the scroll contents if the first + // child is not a header (in that case, the padding is built into the + // header). + DCHECK_EQ(box_layout_, GetLayoutManager()); + box_layout_->set_inside_border_insets( + gfx::Insets(details.child->id() == VIEW_ID_STICKY_HEADER + ? 0 + : kMenuSeparatorVerticalPadding, + 0, kMenuSeparatorVerticalPadding, 0)); } } @@ -111,7 +125,6 @@ const SkColor kSeparatorColor = SkColorSetA(SK_ColorBLACK, 0x1F); const int kShadowOffsetY = 2; const int kShadowBlur = 2; - const int kContentsVerticalSpacingMd = 4; // TODO(fukino): Remove this constant once we stop maintaining pre-MD design. // crbug.com/614453. const int kContentsBetweenChildSpacingNonMd = 1; @@ -197,6 +210,8 @@ canvas->DrawRect(rect, paint); } + views::BoxLayout* box_layout_; + // Header child views that stick to the top of visible viewport when scrolled. std::vector<Header> headers_;
diff --git a/ash/common/system/tray/tray_popup_utils.cc b/ash/common/system/tray/tray_popup_utils.cc index 69050a7..60f36e27 100644 --- a/ash/common/system/tray/tray_popup_utils.cc +++ b/ash/common/system/tray/tray_popup_utils.cc
@@ -5,6 +5,7 @@ #include "ash/common/system/tray/tray_popup_utils.h" #include "ash/common/ash_constants.h" +#include "ash/common/ash_view_ids.h" #include "ash/common/material_design/material_design_controller.h" #include "ash/common/session/session_state_delegate.h" #include "ash/common/system/tray/fixed_sized_image_view.h" @@ -14,6 +15,7 @@ #include "ash/common/system/tray/tray_popup_label_button_border.h" #include "ash/common/wm_shell.h" #include "ui/views/animation/ink_drop_impl.h" +#include "ui/views/background.h" #include "ui/views/border.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/button/label_button.h" @@ -220,6 +222,14 @@ return slider; } +void TrayPopupUtils::ConfigureAsStickyHeader(views::View* view) { + view->set_id(VIEW_ID_STICKY_HEADER); + view->set_background( + views::Background::CreateSolidBackground(kBackgroundColor)); + view->SetBorder( + views::CreateEmptyBorder(gfx::Insets(kMenuSeparatorVerticalPadding, 0))); +} + void TrayPopupUtils::ConfigureContainer(TriView::Container container, views::View* container_view) { container_view->SetLayoutManager(
diff --git a/ash/common/system/tray/tray_popup_utils.h b/ash/common/system/tray/tray_popup_utils.h index a48cc78..2936cae 100644 --- a/ash/common/system/tray/tray_popup_utils.h +++ b/ash/common/system/tray/tray_popup_utils.h
@@ -85,6 +85,9 @@ // with a FillLayout. static views::Slider* CreateSlider(views::SliderListener* listener); + // Sets up |view| to be a sticky header in a tray detail scroll view. + static void ConfigureAsStickyHeader(views::View* view); + // Configures |container_view| just like CreateDefaultRowView() would // configure |container| on its returned TriView. To be used when mutliple // targetable areas are required within a single row.
diff --git a/ash/common/system/user/button_from_view.cc b/ash/common/system/user/button_from_view.cc index b1a632e..fc7d7e9 100644 --- a/ash/common/system/user/button_from_view.cc +++ b/ash/common/system/user/button_from_view.cc
@@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <vector> + #include "ash/common/system/user/button_from_view.h" #include "ash/common/ash_constants.h" @@ -12,12 +14,17 @@ #include "base/strings/utf_string_conversions.h" #include "ui/accessibility/ax_node_data.h" #include "ui/gfx/canvas.h" +#include "ui/views/animation/flood_fill_ink_drop_ripple.h" +#include "ui/views/animation/ink_drop.h" +#include "ui/views/animation/ink_drop_highlight.h" +#include "ui/views/animation/ink_drop_impl.h" #include "ui/views/background.h" #include "ui/views/border.h" #include "ui/views/layout/box_layout.h" #include "ui/views/layout/fill_layout.h" namespace ash { +namespace tray { namespace { @@ -26,8 +33,6 @@ } // namespace -namespace tray { - ButtonFromView::ButtonFromView(views::View* content, views::ButtonListener* listener, bool highlight_on_hover, @@ -37,10 +42,15 @@ highlight_on_hover_(highlight_on_hover), button_hovered_(false), show_border_(false), - tab_frame_inset_(tab_frame_inset) { + tab_frame_inset_(tab_frame_inset), + ink_drop_container_(nullptr) { + set_has_ink_drop_action_on_click(true); set_notify_enter_exit_on_child(true); if (MaterialDesignController::IsSystemTrayMenuMaterial()) { + ink_drop_container_ = new views::InkDropContainerView(); + AddChildView(ink_drop_container_); SetLayoutManager(new views::FillLayout()); + SetInkDropMode(InkDropHostView::InkDropMode::ON); } else { SetLayoutManager( new views::BoxLayout(views::BoxLayout::kHorizontal, 1, 1, 0)); @@ -100,6 +110,45 @@ node_data->SetName(base::JoinString(labels, base::ASCIIToUTF16(" "))); } +void ButtonFromView::Layout() { + CustomButton::Layout(); + if (ink_drop_container_) + ink_drop_container_->SetBoundsRect(GetLocalBounds()); +} + +void ButtonFromView::AddInkDropLayer(ui::Layer* ink_drop_layer) { + ink_drop_container_->AddInkDropLayer(ink_drop_layer); +} + +void ButtonFromView::RemoveInkDropLayer(ui::Layer* ink_drop_layer) { + ink_drop_container_->RemoveInkDropLayer(ink_drop_layer); +} + +std::unique_ptr<views::InkDrop> ButtonFromView::CreateInkDrop() { + std::unique_ptr<views::InkDropImpl> ink_drop = + CreateDefaultFloodFillInkDropImpl(); + ink_drop->SetShowHighlightOnHover(false); + return std::move(ink_drop); +} + +std::unique_ptr<views::InkDropRipple> ButtonFromView::CreateInkDropRipple() + const { + return base::MakeUnique<views::FloodFillInkDropRipple>( + GetInkDropBounds(), GetInkDropCenterBasedOnLastEvent(), + kTrayPopupInkDropBaseColor, kTrayPopupInkDropRippleOpacity); +} + +std::unique_ptr<views::InkDropHighlight> +ButtonFromView::CreateInkDropHighlight() const { + const gfx::Rect bounds = GetInkDropBounds(); + std::unique_ptr<views::InkDropHighlight> highlight( + new views::InkDropHighlight(bounds.size(), 0, + gfx::RectF(bounds).CenterPoint(), + kTrayPopupInkDropBaseColor)); + highlight->set_visible_opacity(kTrayPopupInkDropHighlightOpacity); + return highlight; +} + void ButtonFromView::ShowActive() { if (MaterialDesignController::IsSystemTrayMenuMaterial()) return; @@ -117,5 +166,11 @@ SchedulePaint(); } +gfx::Rect ButtonFromView::GetInkDropBounds() const { + gfx::Rect bounds = GetLocalBounds(); + bounds.Inset(ink_drop_insets_); + return bounds; +} + } // namespace tray } // namespace ash
diff --git a/ash/common/system/user/button_from_view.h b/ash/common/system/user/button_from_view.h index 646d69a2..ea5190a 100644 --- a/ash/common/system/user/button_from_view.h +++ b/ash/common/system/user/button_from_view.h
@@ -5,10 +5,16 @@ #ifndef ASH_COMMON_SYSTEM_USER_BUTTON_FROM_VIEW_H_ #define ASH_COMMON_SYSTEM_USER_BUTTON_FROM_VIEW_H_ +#include <memory> + #include "base/macros.h" #include "ui/gfx/geometry/insets.h" #include "ui/views/controls/button/custom_button.h" +namespace views { +class InkDropContainerView; +} // namespace views + namespace ash { namespace tray { @@ -31,21 +37,39 @@ // Called when the border should remain even in the non highlighted state. void ForceBorderVisible(bool show); - // Overridden from views::View + // views::View: void OnMouseEntered(const ui::MouseEvent& event) override; void OnMouseExited(const ui::MouseEvent& event) override; void OnPaint(gfx::Canvas* canvas) override; void OnFocus() override; void OnBlur() override; void GetAccessibleNodeData(ui::AXNodeData* node_data) override; + void Layout() override; // Check if the item is hovered. bool is_hovered_for_test() { return button_hovered_; } + void set_ink_drop_insets(const gfx::Insets& insets) { + ink_drop_insets_ = insets; + } + + protected: + // views::CustomButton: + void AddInkDropLayer(ui::Layer* ink_drop_layer) override; + void RemoveInkDropLayer(ui::Layer* ink_drop_layer) override; + std::unique_ptr<views::InkDrop> CreateInkDrop() override; + std::unique_ptr<views::InkDropRipple> CreateInkDropRipple() const override; + std::unique_ptr<views::InkDropHighlight> CreateInkDropHighlight() + const override; + private: // Change the hover/active state of the "button" when the status changes. void ShowActive(); + // Returns the bounds that the ink drop ripple and highlight should be created + // with. + gfx::Rect GetInkDropBounds() const; + // Content of button. views::View* content_; @@ -61,6 +85,14 @@ // The insets which get used for the drawn accessibility (tab) frame. gfx::Insets tab_frame_inset_; + // A separate view is necessary to hold the ink drop layer so that |this| can + // host labels with subpixel anti-aliasing enabled. Only used for material + // design. + views::InkDropContainerView* ink_drop_container_; + + // Used to inset the ink drop. + gfx::Insets ink_drop_insets_; + DISALLOW_COPY_AND_ASSIGN(ButtonFromView); };
diff --git a/ash/common/system/user/user_view.cc b/ash/common/system/user/user_view.cc index 63e331fc..8290fb1 100644 --- a/ash/common/system/user/user_view.cc +++ b/ash/common/system/user/user_view.cc
@@ -35,6 +35,7 @@ #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/canvas.h" +#include "ui/gfx/geometry/insets.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/label.h" @@ -250,23 +251,29 @@ // The logout button must be added before the user card so that the user card // can correctly calculate the remaining available width. // Note that only the current multiprofile user gets a button. - if (!user_index_) + if (IsActiveUser()) AddLogoutButton(login); AddUserCard(login); if (UseMd()) { - auto layout = new views::BoxLayout(views::BoxLayout::kHorizontal, - kMenuExtraMarginFromLeftEdge, 0, 0); + auto* layout = new views::BoxLayout(views::BoxLayout::kHorizontal, 0, 0, 0); + if (IsActiveUser()) { + layout->set_inside_border_insets(gfx::Insets( + 0, kMenuExtraMarginFromLeftEdge, 0, kMenuExtraMarginFromLeftEdge)); + } + SetLayoutManager(layout); layout->set_cross_axis_alignment( views::BoxLayout::CROSS_AXIS_ALIGNMENT_CENTER); layout->SetFlexForView(user_card_view_, 1); - int separator_width = user_index_ == 0 ? kSeparatorWidth : 0; - SetBorder(views::CreatePaddedBorder( - views::CreateSolidSidedBorder(0, 0, separator_width, 0, - kSeparatorColor), - gfx::Insets(kMenuSeparatorVerticalPadding, 0, - kMenuSeparatorVerticalPadding - separator_width, 0))); + + if (IsActiveUser()) { + SetBorder(views::CreatePaddedBorder( + views::CreateSolidSidedBorder(0, 0, kSeparatorWidth, 0, + kSeparatorColor), + gfx::Insets(kMenuSeparatorVerticalPadding, 0, + kMenuSeparatorVerticalPadding - kSeparatorWidth, 0))); + } } } @@ -297,6 +304,10 @@ return user_card_view_->GetBoundsInScreen(); } +bool UserView::IsActiveUser() const { + return user_index_ == 0; +} + gfx::Size UserView::GetPreferredSize() const { // MD uses a layout manager. if (UseMd()) @@ -307,7 +318,7 @@ if (logout_button_) size.SetToMax(logout_button_->GetPreferredSize()); // Only the active user panel will be forced to a certain height. - if (!user_index_) { + if (IsActiveUser()) { size.set_height(std::max( size.height(), GetTrayConstant(TRAY_POPUP_ITEM_MIN_HEIGHT) + GetInsets().height())); @@ -373,7 +384,7 @@ WmShell::Get()->system_tray_delegate()->SignOut(); } else if (sender == user_card_view_ && IsMultiProfileSupportedAndUserActive()) { - if (!user_index_) { + if (IsActiveUser()) { ToggleAddUserMenuOption(); } else { RemoveAddUserMenuOption(); @@ -457,7 +468,7 @@ if (clickable) { // To allow the border to start before the icon, reduce the size before and // add an inset to the icon to get the spacing. - if (!user_index_) { + if (IsActiveUser()) { SetBorder(views::CreateEmptyBorder( kTrayPopupUserCardVerticalPadding, kSidePadding - kTrayUserTileHoverBorderInset, @@ -467,7 +478,7 @@ } gfx::Insets insets = gfx::Insets(1, 1, 1, 1); views::View* contents_view = user_card_view_; - if (user_index_) { + if (!IsActiveUser()) { // Since the activation border needs to be drawn around the tile, we // have to put the tile into another view which fills the menu panel, // but keeping the offsets of the content. @@ -480,8 +491,8 @@ contents_view->AddChildView(user_card_view_); insets = gfx::Insets(1, 1, 1, 3); } - bool highlight = !UseMd() && user_index_ == 0; - auto* button = new ButtonFromView(contents_view, this, highlight, insets); + auto* button = + new ButtonFromView(contents_view, this, IsActiveUser(), insets); user_card_view_ = button; is_user_card_button_ = true; } @@ -502,6 +513,8 @@ views::View* contents_view = user_card_view_; auto* button = new ButtonFromView(contents_view, this, false, gfx::Insets()); + if (IsActiveUser()) + button->set_ink_drop_insets(gfx::Insets(kTrayPopupInkDropInset)); user_card_view_ = button; is_user_card_button_ = true; } @@ -552,6 +565,8 @@ ButtonFromView* button = new ButtonFromView( add_user_view, add_user_enabled_ ? this : nullptr, !UseMd() && add_user_enabled_, gfx::Insets(UseMd() ? 0 : 1)); + if (UseMd()) + button->set_ink_drop_insets(gfx::Insets(kTrayPopupInkDropInset)); button->SetAccessibleName( l10n_util::GetStringUTF16(IDS_ASH_STATUS_TRAY_SIGN_IN_ANOTHER_ACCOUNT)); button->ForceBorderVisible(true);
diff --git a/ash/common/system/user/user_view.h b/ash/common/system/user/user_view.h index d1b01c8..6d0e845 100644 --- a/ash/common/system/user/user_view.h +++ b/ash/common/system/user/user_view.h
@@ -52,6 +52,9 @@ views::View* user_card_view_for_test() const { return user_card_view_; } private: + // Retruns true if |this| view is for the currently active user, i.e. top row. + bool IsActiveUser() const; + // Overridden from views::View. gfx::Size GetPreferredSize() const override; int GetHeightForWidth(int width) const override;
diff --git a/ash/common/system/web_notification/web_notification_tray.cc b/ash/common/system/web_notification/web_notification_tray.cc index 4ca0327f..034e1d4e 100644 --- a/ash/common/system/web_notification/web_notification_tray.cc +++ b/ash/common/system/web_notification/web_notification_tray.cc
@@ -423,7 +423,8 @@ // Private methods. bool WebNotificationTray::ShouldShowMessageCenter() { - return !system_tray_->HasNotificationBubble(); + return WmShell::Get()->system_tray_delegate()->ShouldShowNotificationTray() && + !system_tray_->HasNotificationBubble(); } bool WebNotificationTray::ShouldBlockShelfAutoHide() const {
diff --git a/ash/common/wm_shell.cc b/ash/common/wm_shell.cc index ea70a16..98cd1ce 100644 --- a/ash/common/wm_shell.cc +++ b/ash/common/wm_shell.cc
@@ -21,6 +21,7 @@ #include "ash/common/shelf/shelf_model.h" #include "ash/common/shelf/shelf_window_watcher.h" #include "ash/common/shell_delegate.h" +#include "ash/common/shutdown_controller.h" #include "ash/common/system/brightness_control_delegate.h" #include "ash/common/system/keyboard_brightness_control_delegate.h" #include "ash/common/system/locale/locale_notification_controller.h" @@ -248,6 +249,7 @@ new_window_client_(base::MakeUnique<NewWindowClientProxy>( delegate_->GetShellConnector())), shelf_controller_(base::MakeUnique<ShelfController>()), + shutdown_controller_(base::MakeUnique<ShutdownController>()), system_tray_controller_(base::MakeUnique<SystemTrayController>( delegate_->GetShellConnector())), system_tray_notifier_(base::MakeUnique<SystemTrayNotifier>()),
diff --git a/ash/common/wm_shell.h b/ash/common/wm_shell.h index da548cf..2c7a154 100644 --- a/ash/common/wm_shell.h +++ b/ash/common/wm_shell.h
@@ -62,6 +62,7 @@ class ShelfWindowWatcher; class ShellDelegate; class ShellObserver; +class ShutdownController; class SystemTrayDelegate; class SystemTrayController; class SystemTrayNotifier; @@ -157,6 +158,10 @@ ShelfModel* shelf_model(); + ShutdownController* shutdown_controller() { + return shutdown_controller_.get(); + } + SystemTrayController* system_tray_controller() { return system_tray_controller_.get(); } @@ -485,6 +490,7 @@ std::unique_ptr<ShelfController> shelf_controller_; std::unique_ptr<ShelfDelegate> shelf_delegate_; std::unique_ptr<ShelfWindowWatcher> shelf_window_watcher_; + std::unique_ptr<ShutdownController> shutdown_controller_; std::unique_ptr<SystemTrayController> system_tray_controller_; std::unique_ptr<SystemTrayNotifier> system_tray_notifier_; std::unique_ptr<SystemTrayDelegate> system_tray_delegate_;
diff --git a/ash/mus/accelerators/accelerator_controller_unittest.cc b/ash/mus/accelerators/accelerator_controller_unittest.cc index 7e08b15..d5f27ca0 100644 --- a/ash/mus/accelerators/accelerator_controller_unittest.cc +++ b/ash/mus/accelerators/accelerator_controller_unittest.cc
@@ -916,8 +916,8 @@ // NOTE: Accelerators that do not work on the lock screen need to be // tested before the sequence below is invoked because it causes a side // effect of locking the screen. - EXPECT_TRUE(ProcessInController( - ui::Accelerator(ui::VKEY_L, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN))); + EXPECT_TRUE( + ProcessInController(ui::Accelerator(ui::VKEY_L, ui::EF_COMMAND_DOWN))); #endif }
diff --git a/ash/mus/manifest.json b/ash/mus/manifest.json index ee82302..706b4b8 100644 --- a/ash/mus/manifest.json +++ b/ash/mus/manifest.json
@@ -7,6 +7,7 @@ "ash": [ "ash::mojom::LocaleNotificationController", "ash::mojom::ShelfController", + "ash::mojom::ShutdownController", "ash::mojom::SystemTray", "ash::mojom::WallpaperController" ],
diff --git a/ash/public/interfaces/shutdown.mojom b/ash/public/interfaces/shutdown.mojom index e0060fb..4785e773 100644 --- a/ash/public/interfaces/shutdown.mojom +++ b/ash/public/interfaces/shutdown.mojom
@@ -4,13 +4,11 @@ module ash.mojom; -// Interface implemented by service:content_browser to activate shutdown. -// -// TODO(erg): Eventually, when CrosSettings is moved out of chrome into its -// own process, this client should go away. The code which actually calls -// shutdown should be moved into ash/, and ash should subscribe to changes -// in CrosSettings. crbug.com/628792 -interface ShutdownClient { - // Requests that the system shuts down. - RequestShutdown(); +// Interface implemented by ash and used by chrome to provide shutdown policy +// information. Exists because device policy is owned by chrome, not ash. +interface ShutdownController { + // Sets a boolean pref that indicates whether the device automatically reboots + // when the user initiates a shutdown via an UI element. Used in enterprise + // environments for devices that should not be shut down. + SetRebootOnShutdown(bool reboot_on_shutdown); };
diff --git a/ash/resources/vector_icons/BUILD.gn b/ash/resources/vector_icons/BUILD.gn index c6728a16..d618616 100644 --- a/ash/resources/vector_icons/BUILD.gn +++ b/ash/resources/vector_icons/BUILD.gn
@@ -90,6 +90,8 @@ "system_menu_arrow_right.icon", "system_menu_bluetooth.1x.icon", "system_menu_bluetooth.icon", + "system_menu_bluetooth_connected.1x.icon", + "system_menu_bluetooth_connected.icon", "system_menu_bluetooth_disabled.1x.icon", "system_menu_bluetooth_disabled.icon", "system_menu_brightness.1x.icon",
diff --git a/ash/resources/vector_icons/system_menu_bluetooth_connected.1x.icon b/ash/resources/vector_icons/system_menu_bluetooth_connected.1x.icon new file mode 100644 index 0000000..81682cc --- /dev/null +++ b/ash/resources/vector_icons/system_menu_bluetooth_connected.1x.icon
@@ -0,0 +1,44 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +CANVAS_DIMENSIONS, 20, +MOVE_TO, 10.5f, 1.5f, +R_H_LINE_TO, -1, +V_LINE_TO, 8, +LINE_TO, 5.69f, 4.17f, +LINE_TO, 4.5f, 5.34f, +LINE_TO, 9.5f, 10, +R_LINE_TO, -5, 4.66f, +R_LINE_TO, 1.19f, 1.09f, +LINE_TO, 9.5f, 12, +R_V_LINE_TO, 6.5f, +R_H_LINE_TO, 1, +R_LINE_TO, 4.5f, -5, +R_LINE_TO, -3.5f, -3.5f, +LINE_TO, 15, 6.5f, +R_LINE_TO, -4.5f, -5, +CLOSE, +MOVE_TO, 15, 10, +R_LINE_TO, 2, -2, +R_LINE_TO, 2, 2, +R_LINE_TO, -2, 2, +R_LINE_TO, -2, -2, +CLOSE, +MOVE_TO, 2, 10, +R_LINE_TO, 2, -2, +R_LINE_TO, 2, 2, +R_LINE_TO, -2, 2, +R_LINE_TO, -2, -2, +CLOSE, +R_MOVE_TO, 9.27f, -5.14f, +R_LINE_TO, 1.59f, 1.57f, +R_LINE_TO, -1.59f, 1.57f, +V_LINE_TO, 4.86f, +CLOSE, +R_MOVE_TO, 0, 10.28f, +R_V_LINE_TO, -3.13f, +R_LINE_TO, 1.59f, 1.57f, +R_LINE_TO, -1.59f, 1.57f, +CLOSE, +END
diff --git a/ash/resources/vector_icons/system_menu_bluetooth_connected.icon b/ash/resources/vector_icons/system_menu_bluetooth_connected.icon new file mode 100644 index 0000000..5287568 --- /dev/null +++ b/ash/resources/vector_icons/system_menu_bluetooth_connected.icon
@@ -0,0 +1,44 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +CANVAS_DIMENSIONS, 40, +MOVE_TO, 21, 3, +R_H_LINE_TO, -2, +R_V_LINE_TO, 13, +R_LINE_TO, -7.61f, -7.67f, +LINE_TO, 9, 10.68f, +LINE_TO, 19, 20, +LINE_TO, 9, 29.32f, +R_LINE_TO, 2.39f, 2.18f, +LINE_TO, 19, 24, +R_V_LINE_TO, 13, +R_H_LINE_TO, 2, +R_LINE_TO, 9, -10, +R_LINE_TO, -7, -7, +R_LINE_TO, 7, -7, +R_LINE_TO, -9, -10, +CLOSE, +R_MOVE_TO, 1.55f, 6.72f, +R_LINE_TO, 3.18f, 3.13f, +R_LINE_TO, -3.18f, 3.13f, +V_LINE_TO, 9.72f, +CLOSE, +R_MOVE_TO, 0, 20.57f, +R_V_LINE_TO, -6.27f, +R_LINE_TO, 3.18f, 3.13f, +R_LINE_TO, -3.18f, 3.13f, +CLOSE, +MOVE_TO, 29, 20, +R_LINE_TO, 3, -3, +R_LINE_TO, 3, 3, +R_LINE_TO, -3, 3, +R_LINE_TO, -3, -3, +CLOSE, +MOVE_TO, 6, 20, +R_LINE_TO, 3, -3, +R_LINE_TO, 3, 3, +R_LINE_TO, -3, 3, +R_LINE_TO, -3, -3, +CLOSE, +END
diff --git a/ash/shelf/shelf_view_unittest.cc b/ash/shelf/shelf_view_unittest.cc index 99a69020..0bc25fdf 100644 --- a/ash/shelf/shelf_view_unittest.cc +++ b/ash/shelf/shelf_view_unittest.cc
@@ -1986,6 +1986,9 @@ } // views::InkDrop: + void HostSizeChanged(const gfx::Size& new_size) override { + ink_drop_->HostSizeChanged(new_size); + } views::InkDropState GetTargetInkDropState() const override { return ink_drop_->GetTargetInkDropState(); } @@ -2140,8 +2143,9 @@ void InitAppListButtonInkDrop() { app_list_button_ = shelf_view_->GetAppListButton(); - auto app_list_button_ink_drop = base::MakeUnique<InkDropSpy>( - base::MakeUnique<views::InkDropImpl>(app_list_button_)); + auto app_list_button_ink_drop = + base::MakeUnique<InkDropSpy>(base::MakeUnique<views::InkDropImpl>( + app_list_button_, app_list_button_->size())); app_list_button_ink_drop_ = app_list_button_ink_drop.get(); views::test::InkDropHostViewTestApi(app_list_button_) .SetInkDrop(std::move(app_list_button_ink_drop), false); @@ -2150,8 +2154,9 @@ void InitBrowserButtonInkDrop() { browser_button_ = test_api_->GetButton(browser_index_); - auto browser_button_ink_drop = base::MakeUnique<InkDropSpy>( - base::MakeUnique<views::InkDropImpl>(browser_button_)); + auto browser_button_ink_drop = + base::MakeUnique<InkDropSpy>(base::MakeUnique<views::InkDropImpl>( + browser_button_, browser_button_->size())); browser_button_ink_drop_ = browser_button_ink_drop.get(); views::test::InkDropHostViewTestApi(browser_button_) .SetInkDrop(std::move(browser_button_ink_drop)); @@ -2652,8 +2657,9 @@ overflow_button_ = test_api_->overflow_button(); - auto overflow_button_ink_drop = base::MakeUnique<InkDropSpy>( - base::MakeUnique<views::InkDropImpl>(overflow_button_)); + auto overflow_button_ink_drop = + base::MakeUnique<InkDropSpy>(base::MakeUnique<views::InkDropImpl>( + overflow_button_, overflow_button_->size())); overflow_button_ink_drop_ = overflow_button_ink_drop.get(); views::test::InkDropHostViewTestApi(overflow_button_) .SetInkDrop(std::move(overflow_button_ink_drop));
diff --git a/ash/shell.cc b/ash/shell.cc index 9c211fc..a539468 100644 --- a/ash/shell.cc +++ b/ash/shell.cc
@@ -724,8 +724,8 @@ screen_pinning_controller_.reset( new ScreenPinningController(window_tree_host_manager_.get())); - lock_state_controller_ = base::MakeUnique<LockStateController>( - wm_shell_->delegate()->GetShellConnector()); + lock_state_controller_ = + base::MakeUnique<LockStateController>(wm_shell_->shutdown_controller()); power_button_controller_.reset( new PowerButtonController(lock_state_controller_.get())); #if defined(OS_CHROMEOS)
diff --git a/ash/test/BUILD.gn b/ash/test/BUILD.gn index 787ef5d..7cc551bf 100644 --- a/ash/test/BUILD.gn +++ b/ash/test/BUILD.gn
@@ -113,8 +113,6 @@ "test_session_state_animator.h", "test_shell_delegate.cc", "test_shell_delegate.h", - "test_shutdown_client.cc", - "test_shutdown_client.h", "test_suite.cc", "test_suite.h", "test_suite_init.h",
diff --git a/ash/test/lock_state_controller_test_api.cc b/ash/test/lock_state_controller_test_api.cc index b173468..bab5468d 100644 --- a/ash/test/lock_state_controller_test_api.cc +++ b/ash/test/lock_state_controller_test_api.cc
@@ -20,10 +20,5 @@ LockStateControllerTestApi::~LockStateControllerTestApi() {} -void LockStateControllerTestApi::SetShutdownClient( - std::unique_ptr<mojom::ShutdownClient> client) { - controller_->shutdown_client_ = std::move(client); -} - } // namespace test } // namespace ash
diff --git a/ash/test/lock_state_controller_test_api.h b/ash/test/lock_state_controller_test_api.h index 31ca2112..3dcb390f 100644 --- a/ash/test/lock_state_controller_test_api.h +++ b/ash/test/lock_state_controller_test_api.h
@@ -25,7 +25,9 @@ explicit LockStateControllerTestApi(LockStateController* controller); ~LockStateControllerTestApi(); - void SetShutdownClient(std::unique_ptr<mojom::ShutdownClient> client); + void set_shutdown_controller(ShutdownController* shutdown_controller) { + controller_->shutdown_controller_ = shutdown_controller; + } bool lock_fail_timer_is_running() const { return controller_->lock_fail_timer_.IsRunning();
diff --git a/ash/test/test_shutdown_client.cc b/ash/test/test_shutdown_client.cc deleted file mode 100644 index 0767d99a..0000000 --- a/ash/test/test_shutdown_client.cc +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ash/test/test_shutdown_client.h" - -namespace ash { -namespace test { - -TestShutdownClient::TestShutdownClient() : num_shutdown_requests_(0) {} - -TestShutdownClient::~TestShutdownClient() {} - -void TestShutdownClient::RequestShutdown() { - ++num_shutdown_requests_; -} - -} // namespace test -} // namespace ash
diff --git a/ash/test/test_shutdown_client.h b/ash/test/test_shutdown_client.h deleted file mode 100644 index 55c7415..0000000 --- a/ash/test/test_shutdown_client.h +++ /dev/null
@@ -1,35 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef ASH_TEST_TEST_SHUTDOWN_CLIENT_H_ -#define ASH_TEST_TEST_SHUTDOWN_CLIENT_H_ - -#include "ash/public/interfaces/shutdown.mojom.h" -#include "base/macros.h" - -namespace ash { -namespace test { - -// Fake implementation of ShutdownClient that just logs requests to lock the -// screen and shut down the device. -class TestShutdownClient : public mojom::ShutdownClient { - public: - TestShutdownClient(); - ~TestShutdownClient() override; - - int num_shutdown_requests() const { return num_shutdown_requests_; } - - // LockStateControllerDelegate implementation. - void RequestShutdown() override; - - private: - int num_shutdown_requests_; - - DISALLOW_COPY_AND_ASSIGN(TestShutdownClient); -}; - -} // namespace test -} // namespace ash - -#endif // ASH_TEST_TEST_SHUTDOWN_CLIENT_H_
diff --git a/ash/wm/lock_state_controller.cc b/ash/wm/lock_state_controller.cc index d2d8da6..5842f17 100644 --- a/ash/wm/lock_state_controller.cc +++ b/ash/wm/lock_state_controller.cc
@@ -11,13 +11,13 @@ #include "ash/cancel_mode.h" #include "ash/common/accessibility_delegate.h" #include "ash/common/shell_delegate.h" +#include "ash/common/shutdown_controller.h" #include "ash/common/wm_shell.h" #include "ash/public/cpp/shell_window_ids.h" #include "ash/public/interfaces/shutdown.mojom.h" #include "ash/shell.h" #include "ash/wm/session_state_animator.h" #include "ash/wm/session_state_animator_impl.h" -#include "ash/wm/shutdown_client_proxy.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" @@ -72,7 +72,8 @@ const int LockStateController::kLockToShutdownTimeoutMs = 150; const int LockStateController::kShutdownRequestDelayMs = 50; -LockStateController::LockStateController(service_manager::Connector* connector) +LockStateController::LockStateController( + ShutdownController* shutdown_controller) : animator_(new SessionStateAnimatorImpl()), login_status_(LoginStatus::NOT_LOGGED_IN), system_is_locked_(false), @@ -80,8 +81,9 @@ shutdown_after_lock_(false), animating_lock_(false), can_cancel_lock_animation_(false), - shutdown_client_(base::MakeUnique<ShutdownClientProxy>(connector)), + shutdown_controller_(shutdown_controller), weak_ptr_factory_(this) { + DCHECK(shutdown_controller_); Shell::GetPrimaryRootWindow()->GetHost()->AddObserver(this); } @@ -308,25 +310,9 @@ void LockStateController::OnRealPowerTimeout() { VLOG(1) << "OnRealPowerTimeout"; DCHECK(shutting_down_); -#if defined(OS_CHROMEOS) - if (!base::SysInfo::IsRunningOnChromeOS()) { - ShellDelegate* delegate = WmShell::Get()->delegate(); - if (delegate) { - delegate->Exit(); - return; - } - } -#endif WmShell::Get()->RecordUserMetricsAction(UMA_ACCEL_SHUT_DOWN_POWER_BUTTON); - - // Connect to the browser to tell it to shutdown the computer. It will either - // shut down or restart the computer based on the device settings. - // - // TODO(erg): Once CrosSettings has been moved out of chrome/, - // LockStateController should become a preference observer of it, and we - // should move the current content_browser implementation here. - // crbug.com/628792 - shutdown_client_->RequestShutdown(); + // Shut down or reboot based on device policy. + shutdown_controller_->ShutDownOrReboot(); } void LockStateController::StartCancellableShutdownAnimation() {
diff --git a/ash/wm/lock_state_controller.h b/ash/wm/lock_state_controller.h index 388558d..73877ed 100644 --- a/ash/wm/lock_state_controller.h +++ b/ash/wm/lock_state_controller.h
@@ -22,19 +22,13 @@ class Size; } -namespace service_manager { -class Connector; -} - namespace ui { class Layer; } namespace ash { -namespace mojom { -class ShutdownClient; -} +class ShutdownController; namespace test { class LockStateControllerTest; @@ -89,7 +83,7 @@ // the animation time to finish. static const int kShutdownRequestDelayMs; - explicit LockStateController(service_manager::Connector* connector); + explicit LockStateController(ShutdownController* shutdown_controller); ~LockStateController() override; // Starts locking (with slow animation) that can be cancelled. @@ -247,8 +241,8 @@ // How long has it been since the request to lock the screen? std::unique_ptr<base::ElapsedTimer> lock_duration_timer_; - // The client that we request to shut down the machine. - std::unique_ptr<mojom::ShutdownClient> shutdown_client_; + // Controller used to trigger the actual shutdown. + ShutdownController* shutdown_controller_; // Started when we request that the screen be locked. When it fires, we // assume that our request got dropped.
diff --git a/ash/wm/lock_state_controller_unittest.cc b/ash/wm/lock_state_controller_unittest.cc index 2647952..5a9f1bfb 100644 --- a/ash/wm/lock_state_controller_unittest.cc +++ b/ash/wm/lock_state_controller_unittest.cc
@@ -8,6 +8,7 @@ #include <utility> #include "ash/common/session/session_state_delegate.h" +#include "ash/common/shutdown_controller.h" #include "ash/common/test/test_session_state_delegate.h" #include "ash/common/wm/maximize_mode/maximize_mode_controller.h" #include "ash/common/wm_shell.h" @@ -17,7 +18,6 @@ #include "ash/test/test_screenshot_delegate.h" #include "ash/test/test_session_state_animator.h" #include "ash/test/test_shell_delegate.h" -#include "ash/test/test_shutdown_client.h" #include "ash/wm/power_button_controller.h" #include "ash/wm/session_state_animator.h" #include "base/memory/scoped_vector.h" @@ -43,6 +43,23 @@ (*flag) = true; } +// ShutdownController that tracks how many shutdown requests have been made. +class TestShutdownController : public ShutdownController { + public: + TestShutdownController() {} + ~TestShutdownController() override {} + + int num_shutdown_requests() const { return num_shutdown_requests_; } + + private: + // ShutdownController: + void ShutDownOrReboot() override { num_shutdown_requests_++; } + + int num_shutdown_requests_ = 0; + + DISALLOW_COPY_AND_ASSIGN(TestShutdownController); +}; + } // namespace class LockStateControllerTest : public AshTestBase { @@ -50,7 +67,6 @@ LockStateControllerTest() : power_button_controller_(nullptr), lock_state_controller_(nullptr), - shutdown_client_(nullptr), session_manager_client_(nullptr), test_animator_(nullptr) {} ~LockStateControllerTest() override {} @@ -61,16 +77,13 @@ base::WrapUnique(session_manager_client_)); AshTestBase::SetUp(); - shutdown_client_ = new TestShutdownClient; - std::unique_ptr<TestShutdownClient> shutdown_client(shutdown_client_); - test_animator_ = new TestSessionStateAnimator; lock_state_controller_ = Shell::GetInstance()->lock_state_controller(); lock_state_controller_->set_animator_for_test(test_animator_); test_api_.reset(new LockStateControllerTestApi(lock_state_controller_)); - test_api_->SetShutdownClient(std::move(shutdown_client)); + test_api_->set_shutdown_controller(&test_shutdown_controller_); power_button_controller_ = Shell::GetInstance()->power_button_controller(); @@ -90,7 +103,7 @@ } int NumShutdownRequests() { - return shutdown_client_->num_shutdown_requests() + + return test_shutdown_controller_.num_shutdown_requests() + shell_delegate_->num_exit_requests(); } @@ -327,7 +340,7 @@ PowerButtonController* power_button_controller_; // not owned LockStateController* lock_state_controller_; // not owned - TestShutdownClient* shutdown_client_; // not owned + TestShutdownController test_shutdown_controller_; // Ownership is passed on to chromeos::DBusThreadManager. chromeos::FakeSessionManagerClient* session_manager_client_; TestSessionStateAnimator* test_animator_; // not owned
diff --git a/ash/wm/shutdown_client_proxy.cc b/ash/wm/shutdown_client_proxy.cc deleted file mode 100644 index 316df3a4..0000000 --- a/ash/wm/shutdown_client_proxy.cc +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ash/wm/shutdown_client_proxy.h" - -#include "ash/public/interfaces/shutdown.mojom.h" -#include "services/service_manager/public/cpp/connector.h" - -namespace ash { - -ShutdownClientProxy::ShutdownClientProxy(service_manager::Connector* connector) - : connector_(connector) {} - -ShutdownClientProxy::~ShutdownClientProxy() {} - -void ShutdownClientProxy::RequestShutdown() { - mojom::ShutdownClientPtr client; - connector_->ConnectToInterface("service:content_browser", &client); - client->RequestShutdown(); -} - -} // namespace ash
diff --git a/ash/wm/shutdown_client_proxy.h b/ash/wm/shutdown_client_proxy.h deleted file mode 100644 index df5148a..0000000 --- a/ash/wm/shutdown_client_proxy.h +++ /dev/null
@@ -1,37 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef ASH_WM_SHUTDOWN_CLIENT_PROXY_H_ -#define ASH_WM_SHUTDOWN_CLIENT_PROXY_H_ - -#include "ash/public/interfaces/shutdown.mojom.h" -#include "base/macros.h" - -namespace service_manager { -class Connector; -} - -namespace ash { - -// A ShutdownClientProxy which lazily connects to an exported -// mojom::ShutdownClient in "service:content_browser" on each use. This exists -// so we can replace an instance of this class with a TestShutdownClient in -// tests. -class ShutdownClientProxy : public mojom::ShutdownClient { - public: - explicit ShutdownClientProxy(service_manager::Connector* connector); - ~ShutdownClientProxy() override; - - // mojom::ShutdownClient: - void RequestShutdown() override; - - private: - service_manager::Connector* connector_; - - DISALLOW_COPY_AND_ASSIGN(ShutdownClientProxy); -}; - -} // namespace ash - -#endif // ASH_WM_SHUTDOWN_CLIENT_PROXY_H_
diff --git a/base/BUILD.gn b/base/BUILD.gn index 47ee8fa..f92612d 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -544,6 +544,8 @@ "metrics/histogram_delta_serialization.cc", "metrics/histogram_delta_serialization.h", "metrics/histogram_flattener.h", + "metrics/histogram_functions.cc", + "metrics/histogram_functions.h", "metrics/histogram_macros.h", "metrics/histogram_samples.cc", "metrics/histogram_samples.h", @@ -1870,6 +1872,7 @@ "metrics/field_trial_unittest.cc", "metrics/histogram_base_unittest.cc", "metrics/histogram_delta_serialization_unittest.cc", + "metrics/histogram_functions_unittest.cc", "metrics/histogram_macros_unittest.cc", "metrics/histogram_snapshot_manager_unittest.cc", "metrics/histogram_unittest.cc",
diff --git a/base/allocator/README.md b/base/allocator/README.md index 164df51a..a211732 100644 --- a/base/allocator/README.md +++ b/base/allocator/README.md
@@ -189,8 +189,8 @@ - [Unified allocator shim doc - Feb 2016][url-allocator-shim] - [Allocator cleanup doc - Jan 2016][url-allocator-cleanup] - [Proposal to use PartitionAlloc as default allocator](https://crbug.com/339604) -- [Memory-Infra: Tools to profile memory usage in Chrome](components/tracing/docs/memory_infra.md) +- [Memory-Infra: Tools to profile memory usage in Chrome](/docs/memory-infra/README.md) [url-allocator-cleanup]: https://docs.google.com/document/d/1V77Kgp_4tfaaWPEZVxNevoD02wXiatnAv7Ssgr0hmjg/edit?usp=sharing -[url-memory-infra-heap-profiler]: components/tracing/docs/heap_profiler.md +[url-memory-infra-heap-profiler]: /docs/memory-infra/heap_profiler.md [url-allocator-shim]: https://docs.google.com/document/d/1yKlO1AO4XjpDad9rjcBOI15EKdAGsuGO_IeZy0g0kxo/edit?usp=sharing
diff --git a/base/files/file_path_watcher.cc b/base/files/file_path_watcher.cc index e370fcb1..245bd8e 100644 --- a/base/files/file_path_watcher.cc +++ b/base/files/file_path_watcher.cc
@@ -8,12 +8,12 @@ #include "base/files/file_path_watcher.h" #include "base/logging.h" -#include "base/message_loop/message_loop.h" #include "build/build_config.h" namespace base { FilePathWatcher::~FilePathWatcher() { + DCHECK(sequence_checker_.CalledOnValidSequence()); impl_->Cancel(); } @@ -38,6 +38,7 @@ bool FilePathWatcher::Watch(const FilePath& path, bool recursive, const Callback& callback) { + DCHECK(sequence_checker_.CalledOnValidSequence()); DCHECK(path.IsAbsolute()); return impl_->Watch(path, recursive, callback); }
diff --git a/base/files/file_path_watcher.h b/base/files/file_path_watcher.h index 7b1483a..267c03ae 100644 --- a/base/files/file_path_watcher.h +++ b/base/files/file_path_watcher.h
@@ -12,6 +12,7 @@ #include "base/files/file_path.h" #include "base/macros.h" #include "base/memory/ref_counted.h" +#include "base/sequence_checker.h" #include "base/single_thread_task_runner.h" namespace base { @@ -25,6 +26,8 @@ // detect the creation and deletion of files in a watched directory, but will // not detect modifications to those files. See file_path_watcher_kqueue.cc for // details. +// +// Must be destroyed on the sequence that invokes Watch(). class BASE_EXPORT FilePathWatcher { public: // Callback type for Watch(). |path| points to the file that was updated, @@ -76,7 +79,7 @@ }; FilePathWatcher(); - virtual ~FilePathWatcher(); + ~FilePathWatcher(); // A callback that always cleans up the PlatformDelegate, either when executed // or when deleted without having been executed at all, as can happen during @@ -98,6 +101,8 @@ private: scoped_refptr<PlatformDelegate> impl_; + SequenceChecker sequence_checker_; + DISALLOW_COPY_AND_ASSIGN(FilePathWatcher); };
diff --git a/base/files/file_path_watcher_linux.cc b/base/files/file_path_watcher_linux.cc index 958e60c..3b0ff6236 100644 --- a/base/files/file_path_watcher_linux.cc +++ b/base/files/file_path_watcher_linux.cc
@@ -657,6 +657,7 @@ } // namespace FilePathWatcher::FilePathWatcher() { + sequence_checker_.DetachFromSequence(); impl_ = new FilePathWatcherImpl(); }
diff --git a/base/files/file_path_watcher_mac.cc b/base/files/file_path_watcher_mac.cc index b65591a2..d59ca215 100644 --- a/base/files/file_path_watcher_mac.cc +++ b/base/files/file_path_watcher_mac.cc
@@ -49,6 +49,7 @@ } // namespace FilePathWatcher::FilePathWatcher() { + sequence_checker_.DetachFromSequence(); impl_ = new FilePathWatcherImpl(); }
diff --git a/base/files/file_path_watcher_stub.cc b/base/files/file_path_watcher_stub.cc index c637e3c..c224e37 100644 --- a/base/files/file_path_watcher_stub.cc +++ b/base/files/file_path_watcher_stub.cc
@@ -28,6 +28,7 @@ } // namespace FilePathWatcher::FilePathWatcher() { + sequence_checker_.DetachFromSequence(); impl_ = new FilePathWatcherImpl(); }
diff --git a/base/files/file_path_watcher_unittest.cc b/base/files/file_path_watcher_unittest.cc index fc6f5a8..d2ec37b 100644 --- a/base/files/file_path_watcher_unittest.cc +++ b/base/files/file_path_watcher_unittest.cc
@@ -28,7 +28,6 @@ #include "base/synchronization/waitable_event.h" #include "base/test/test_file_util.h" #include "base/test/test_timeouts.h" -#include "base/threading/thread.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" @@ -37,6 +36,10 @@ #include "base/android/path_utils.h" #endif // defined(OS_ANDROID) +#if defined(OS_POSIX) +#include "base/files/file_descriptor_watcher_posix.h" +#endif // defined(OS_POSIX) + namespace base { namespace { @@ -131,30 +134,19 @@ DISALLOW_COPY_AND_ASSIGN(TestDelegate); }; -void SetupWatchCallback(const FilePath& target, - FilePathWatcher* watcher, - TestDelegateBase* delegate, - bool recursive_watch, - bool* result, - base::WaitableEvent* completion) { - *result = watcher->Watch(target, recursive_watch, - base::Bind(&TestDelegateBase::OnFileChanged, - delegate->AsWeakPtr())); - completion->Signal(); -} - class FilePathWatcherTest : public testing::Test { public: FilePathWatcherTest() - : file_thread_("FilePathWatcherTest") {} +#if defined(OS_POSIX) + : file_descriptor_watcher_(&loop_) +#endif + { + } ~FilePathWatcherTest() override {} protected: void SetUp() override { - // Create a separate file thread in order to test proper thread usage. - base::Thread::Options options(MessageLoop::TYPE_IO, 0); - ASSERT_TRUE(file_thread_.StartWithOptions(options)); #if defined(OS_ANDROID) // Watching files is only permitted when all parent directories are // accessible, which is not the case for the default temp directory @@ -171,10 +163,6 @@ void TearDown() override { RunLoop().RunUntilIdle(); } - void DeleteDelegateOnFileThread(TestDelegate* delegate) { - file_thread_.task_runner()->DeleteSoon(FROM_HERE, delegate); - } - FilePath test_file() { return temp_dir_.GetPath().AppendASCII("FilePathWatcherTest"); } @@ -196,18 +184,23 @@ bool WaitForEvents() WARN_UNUSED_RESULT { collector_->Reset(); + + RunLoop run_loop; // Make sure we timeout if we don't get notified. - loop_.task_runner()->PostDelayedTask(FROM_HERE, - MessageLoop::QuitWhenIdleClosure(), - TestTimeouts::action_timeout()); - RunLoop().Run(); + ThreadTaskRunnerHandle::Get()->PostDelayedTask( + FROM_HERE, run_loop.QuitWhenIdleClosure(), + TestTimeouts::action_timeout()); + run_loop.Run(); return collector_->Success(); } NotificationCollector* collector() { return collector_.get(); } - MessageLoop loop_; - base::Thread file_thread_; + MessageLoopForIO loop_; +#if defined(OS_POSIX) + FileDescriptorWatcher file_descriptor_watcher_; +#endif + ScopedTempDir temp_dir_; scoped_refptr<NotificationCollector> collector_; @@ -219,14 +212,9 @@ FilePathWatcher* watcher, TestDelegateBase* delegate, bool recursive_watch) { - base::WaitableEvent completion(WaitableEvent::ResetPolicy::AUTOMATIC, - WaitableEvent::InitialState::NOT_SIGNALED); - bool result; - file_thread_.task_runner()->PostTask( - FROM_HERE, base::Bind(SetupWatchCallback, target, watcher, delegate, - recursive_watch, &result, &completion)); - completion.Wait(); - return result; + return watcher->Watch( + target, recursive_watch, + base::Bind(&TestDelegateBase::OnFileChanged, delegate->AsWeakPtr())); } // Basic test: Create the file and verify that we notice. @@ -237,7 +225,6 @@ ASSERT_TRUE(WriteFile(test_file(), "content")); ASSERT_TRUE(WaitForEvents()); - DeleteDelegateOnFileThread(delegate.release()); } // Verify that modifying the file is caught. @@ -251,7 +238,6 @@ // Now make sure we get notified if the file is modified. ASSERT_TRUE(WriteFile(test_file(), "new content")); ASSERT_TRUE(WaitForEvents()); - DeleteDelegateOnFileThread(delegate.release()); } // Verify that moving the file into place is caught. @@ -266,7 +252,6 @@ // Now make sure we get notified if the file is modified. ASSERT_TRUE(base::Move(source_file, test_file())); ASSERT_TRUE(WaitForEvents()); - DeleteDelegateOnFileThread(delegate.release()); } TEST_F(FilePathWatcherTest, DeletedFile) { @@ -279,7 +264,6 @@ // Now make sure we get notified if the file is deleted. base::DeleteFile(test_file(), false); ASSERT_TRUE(WaitForEvents()); - DeleteDelegateOnFileThread(delegate.release()); } // Used by the DeleteDuringNotify test below. @@ -327,11 +311,9 @@ // Flaky on MacOS (and ARM linux): http://crbug.com/85930 TEST_F(FilePathWatcherTest, DISABLED_DestroyWithPendingNotification) { std::unique_ptr<TestDelegate> delegate(new TestDelegate(collector())); - FilePathWatcher* watcher = new FilePathWatcher; - ASSERT_TRUE(SetupWatch(test_file(), watcher, delegate.get(), false)); + FilePathWatcher watcher; + ASSERT_TRUE(SetupWatch(test_file(), &watcher, delegate.get(), false)); ASSERT_TRUE(WriteFile(test_file(), "content")); - file_thread_.task_runner()->DeleteSoon(FROM_HERE, watcher); - DeleteDelegateOnFileThread(delegate.release()); } TEST_F(FilePathWatcherTest, MultipleWatchersSingleFile) { @@ -343,8 +325,6 @@ ASSERT_TRUE(WriteFile(test_file(), "content")); ASSERT_TRUE(WaitForEvents()); - DeleteDelegateOnFileThread(delegate1.release()); - DeleteDelegateOnFileThread(delegate2.release()); } // Verify that watching a file whose parent directory doesn't exist yet works if @@ -370,7 +350,6 @@ ASSERT_TRUE(base::DeleteFile(file, false)); VLOG(1) << "Waiting for file deletion"; ASSERT_TRUE(WaitForEvents()); - DeleteDelegateOnFileThread(delegate.release()); } // Exercises watch reconfiguration for the case that directories on the path @@ -403,7 +382,6 @@ ASSERT_TRUE(WriteFile(file, "content v2")); VLOG(1) << "Waiting for file modification"; ASSERT_TRUE(WaitForEvents()); - DeleteDelegateOnFileThread(delegate.release()); } #if defined(OS_MACOSX) @@ -421,7 +399,6 @@ ASSERT_TRUE(base::DeleteFile(dir, true)); ASSERT_TRUE(WaitForEvents()); - DeleteDelegateOnFileThread(delegate.release()); } // Tests that a file that is deleted and reappears is tracked correctly. @@ -438,7 +415,6 @@ ASSERT_TRUE(WriteFile(test_file(), "content")); VLOG(1) << "Waiting for file creation"; ASSERT_TRUE(WaitForEvents()); - DeleteDelegateOnFileThread(delegate.release()); } TEST_F(FilePathWatcherTest, WatchDirectory) { @@ -471,7 +447,6 @@ ASSERT_TRUE(WriteFile(file2, "content")); VLOG(1) << "Waiting for file2 creation"; ASSERT_TRUE(WaitForEvents()); - DeleteDelegateOnFileThread(delegate.release()); } TEST_F(FilePathWatcherTest, MoveParent) { @@ -497,8 +472,6 @@ base::Move(dir, dest); VLOG(1) << "Waiting for directory move"; ASSERT_TRUE(WaitForEvents()); - DeleteDelegateOnFileThread(file_delegate.release()); - DeleteDelegateOnFileThread(subdir_delegate.release()); } TEST_F(FilePathWatcherTest, RecursiveWatch) { @@ -508,7 +481,6 @@ bool setup_result = SetupWatch(dir, &watcher, delegate.get(), true); if (!FilePathWatcher::RecursiveWatchAvailable()) { ASSERT_FALSE(setup_result); - DeleteDelegateOnFileThread(delegate.release()); return; } ASSERT_TRUE(setup_result); @@ -564,7 +536,6 @@ // Delete "$dir/subdir/subdir_child_dir/child_dir_file1". ASSERT_TRUE(base::DeleteFile(child_dir_file1, false)); ASSERT_TRUE(WaitForEvents()); - DeleteDelegateOnFileThread(delegate.release()); } #if defined(OS_POSIX) @@ -612,8 +583,6 @@ FilePath target2_file(target2.AppendASCII("file")); ASSERT_TRUE(WriteFile(target2_file, "content")); ASSERT_TRUE(WaitForEvents()); - - DeleteDelegateOnFileThread(delegate.release()); } #endif // OS_POSIX @@ -640,8 +609,6 @@ // Move the directory into place, s.t. the watched file appears. ASSERT_TRUE(base::Move(source_dir, dest_dir)); ASSERT_TRUE(WaitForEvents()); - DeleteDelegateOnFileThread(file_delegate.release()); - DeleteDelegateOnFileThread(subdir_delegate.release()); } // Verify that changing attributes on a file is caught @@ -662,7 +629,6 @@ // Now make sure we get notified if the file is modified. ASSERT_TRUE(base::MakeFileUnreadable(test_file())); ASSERT_TRUE(WaitForEvents()); - DeleteDelegateOnFileThread(delegate.release()); } #if defined(OS_LINUX) @@ -678,7 +644,6 @@ // Note that test_file() doesn't have to exist. ASSERT_TRUE(CreateSymbolicLink(test_file(), test_link())); ASSERT_TRUE(WaitForEvents()); - DeleteDelegateOnFileThread(delegate.release()); } // Verify that deleting a symlink is caught. @@ -694,7 +659,6 @@ // Now make sure we get notified if the link is deleted. ASSERT_TRUE(base::DeleteFile(test_link(), false)); ASSERT_TRUE(WaitForEvents()); - DeleteDelegateOnFileThread(delegate.release()); } // Verify that modifying a target file that a link is pointing to @@ -710,7 +674,6 @@ // Now make sure we get notified if the file is modified. ASSERT_TRUE(WriteFile(test_file(), "new content")); ASSERT_TRUE(WaitForEvents()); - DeleteDelegateOnFileThread(delegate.release()); } // Verify that creating a target file that a link is pointing to @@ -725,7 +688,6 @@ // Now make sure we get notified if the target file is created. ASSERT_TRUE(WriteFile(test_file(), "content")); ASSERT_TRUE(WaitForEvents()); - DeleteDelegateOnFileThread(delegate.release()); } // Verify that deleting a target file that a link is pointing to @@ -741,7 +703,6 @@ // Now make sure we get notified if the target file is deleted. ASSERT_TRUE(base::DeleteFile(test_file(), false)); ASSERT_TRUE(WaitForEvents()); - DeleteDelegateOnFileThread(delegate.release()); } // Verify that watching a file whose parent directory is a link that @@ -770,7 +731,6 @@ ASSERT_TRUE(base::DeleteFile(file, false)); VLOG(1) << "Waiting for file deletion"; ASSERT_TRUE(WaitForEvents()); - DeleteDelegateOnFileThread(delegate.release()); } // Verify that watching a file whose parent directory is a @@ -800,7 +760,6 @@ ASSERT_TRUE(base::DeleteFile(file, false)); VLOG(1) << "Waiting for file deletion"; ASSERT_TRUE(WaitForEvents()); - DeleteDelegateOnFileThread(delegate.release()); } // Verify that watching a file with a symlink on the path @@ -828,7 +787,6 @@ ASSERT_TRUE(base::DeleteFile(file, false)); VLOG(1) << "Waiting for file deletion"; ASSERT_TRUE(WaitForEvents()); - DeleteDelegateOnFileThread(delegate.release()); } #endif // OS_LINUX @@ -906,7 +864,6 @@ ASSERT_TRUE(ChangeFilePermissions(test_dir1, Execute, false)); ASSERT_TRUE(WaitForEvents()); ASSERT_TRUE(ChangeFilePermissions(test_dir1, Execute, true)); - DeleteDelegateOnFileThread(delegate.release()); } #endif // OS_MACOSX
diff --git a/base/files/file_path_watcher_win.cc b/base/files/file_path_watcher_win.cc index 3bbf2fb..48470b6 100644 --- a/base/files/file_path_watcher_win.cc +++ b/base/files/file_path_watcher_win.cc
@@ -296,6 +296,7 @@ } // namespace FilePathWatcher::FilePathWatcher() { + sequence_checker_.DetachFromSequence(); impl_ = new FilePathWatcherImpl(); }
diff --git a/base/memory/shared_memory.h b/base/memory/shared_memory.h index aa36768..f68c861 100644 --- a/base/memory/shared_memory.h +++ b/base/memory/shared_memory.h
@@ -192,6 +192,13 @@ // identifier is not portable. SharedMemoryHandle handle() const; + // Returns the underlying OS handle for this segment. The caller also gets + // ownership of the handle. This is logically equivalent to: + // SharedMemoryHandle dup = DuplicateHandle(handle()); + // Close(); + // return dup; + SharedMemoryHandle TakeHandle(); + // Closes the open shared memory segment. The memory will remain mapped if // it was previously mapped. // It is safe to call Close repeatedly.
diff --git a/base/memory/shared_memory_mac.cc b/base/memory/shared_memory_mac.cc index 0b3a62f0..a8f09555 100644 --- a/base/memory/shared_memory_mac.cc +++ b/base/memory/shared_memory_mac.cc
@@ -177,6 +177,12 @@ return shm_; } +SharedMemoryHandle SharedMemory::TakeHandle() { + SharedMemoryHandle dup = DuplicateHandle(handle()); + Close(); + return dup; +} + void SharedMemory::Close() { shm_.Close(); shm_ = SharedMemoryHandle();
diff --git a/base/memory/shared_memory_nacl.cc b/base/memory/shared_memory_nacl.cc index 6775ddc..945fc613 100644 --- a/base/memory/shared_memory_nacl.cc +++ b/base/memory/shared_memory_nacl.cc
@@ -122,6 +122,14 @@ return FileDescriptor(mapped_file_, false); } +SharedMemoryHandle SharedMemory::TakeHandle() { + FileDescriptor handle(mapped_file_, true); + mapped_file_ = -1; + memory_ = nullptr; + mapped_size_ = 0; + return handle; +} + void SharedMemory::Close() { if (mapped_file_ > 0) { if (close(mapped_file_) < 0)
diff --git a/base/memory/shared_memory_posix.cc b/base/memory/shared_memory_posix.cc index 6e1175e..783bdfc 100644 --- a/base/memory/shared_memory_posix.cc +++ b/base/memory/shared_memory_posix.cc
@@ -379,6 +379,14 @@ return FileDescriptor(mapped_file_, false); } +SharedMemoryHandle SharedMemory::TakeHandle() { + FileDescriptor handle(mapped_file_, true); + mapped_file_ = -1; + memory_ = nullptr; + mapped_size_ = 0; + return handle; +} + void SharedMemory::Close() { if (mapped_file_ > 0) { if (IGNORE_EINTR(close(mapped_file_)) < 0)
diff --git a/base/memory/shared_memory_win.cc b/base/memory/shared_memory_win.cc index 5f8971ee..1eba23b 100644 --- a/base/memory/shared_memory_win.cc +++ b/base/memory/shared_memory_win.cc
@@ -384,4 +384,12 @@ return SharedMemoryHandle(mapped_file_.Get(), base::GetCurrentProcId()); } +SharedMemoryHandle SharedMemory::TakeHandle() { + SharedMemoryHandle handle(mapped_file_.Take(), base::GetCurrentProcId()); + handle.SetOwnershipPassesToIPC(true); + memory_ = nullptr; + mapped_size_ = 0; + return handle; +} + } // namespace base
diff --git a/base/metrics/field_trial.cc b/base/metrics/field_trial.cc index 47baafb..8ec56b8 100644 --- a/base/metrics/field_trial.cc +++ b/base/metrics/field_trial.cc
@@ -10,6 +10,7 @@ #include "base/base_switches.h" #include "base/build_time.h" #include "base/command_line.h" +#include "base/debug/alias.h" #include "base/feature_list.h" #include "base/logging.h" #include "base/pickle.h" @@ -37,7 +38,7 @@ // for now while the implementation is fleshed out (e.g. data format, single // shared memory segment). See https://codereview.chromium.org/2365273004/ and // crbug.com/653874 -const bool kUseSharedMemoryForFieldTrials = false; +const bool kUseSharedMemoryForFieldTrials = true; // Constants for the field trial allocator. const char kAllocatorName[] = "FieldTrialAllocator"; @@ -678,7 +679,8 @@ if (!shm.get()->Map(field_trial_length)) TerminateBecauseOutOfMemory(field_trial_length); - FieldTrialList::CreateTrialsFromSharedMemory(std::move(shm)); + bool result = FieldTrialList::CreateTrialsFromSharedMemory(std::move(shm)); + DCHECK(result); return; } #endif @@ -831,7 +833,7 @@ } // static -void FieldTrialList::CreateTrialsFromSharedMemory( +bool FieldTrialList::CreateTrialsFromSharedMemory( std::unique_ptr<SharedMemory> shm) { global_->field_trial_allocator_.reset(new SharedPersistentMemoryAllocator( std::move(shm), 0, kAllocatorName, true)); @@ -847,16 +849,32 @@ StringPiece trial_name; StringPiece group_name; - if (!entry->GetTrialAndGroupName(&trial_name, &group_name)) { - NOTREACHED(); - continue; - } + if (!entry->GetTrialAndGroupName(&trial_name, &group_name)) + return false; // TODO(lawrencewu): Convert the API for CreateFieldTrial to take // StringPieces. FieldTrial* trial = CreateFieldTrial(trial_name.as_string(), group_name.as_string()); + // If we failed to create the field trial, crash with debug info. + // TODO(665129): Remove this when the crash is resolved. + if (!trial) { + std::string trial_name_string = trial_name.as_string(); + std::string group_name_string = group_name.as_string(); + FieldTrial* existing_field_trial = + FieldTrialList::Find(trial_name_string); + if (existing_field_trial) + debug::Alias(existing_field_trial->group_name_internal().c_str()); + debug::Alias(trial_name_string.c_str()); + debug::Alias(group_name_string.c_str()); + CHECK(!trial_name_string.empty()); + CHECK(!group_name_string.empty()); + CHECK_EQ(existing_field_trial->group_name_internal(), + group_name.as_string()); + return false; + } + trial->ref_ = ref; if (entry->activated) { // Call |group()| to mark the trial as "used" and notify observers, if @@ -865,6 +883,7 @@ trial->group(); } } + return true; } #if !defined(OS_NACL) @@ -913,12 +932,13 @@ if (allocator->IsReadonly()) return; - // Or if we've already added it. - if (field_trial->ref_) + FieldTrial::State trial_state; + if (!field_trial->GetStateWhileLocked(&trial_state)) return; - FieldTrial::State trial_state; - if (!field_trial->GetState(&trial_state)) + // Or if we've already added it. We must check after GetState since it can + // also add to the allocator. + if (field_trial->ref_) return; Pickle pickle;
diff --git a/base/metrics/field_trial.h b/base/metrics/field_trial.h index ed5a398..7fd067a 100644 --- a/base/metrics/field_trial.h +++ b/base/metrics/field_trial.h
@@ -543,8 +543,9 @@ // Expects a mapped piece of shared memory |shm| that was created from the // browser process's field_trial_allocator and shared via the command line. // This function recreates the allocator, iterates through all the field - // trials in it, and creates them via CreateFieldTrial(). - static void CreateTrialsFromSharedMemory( + // trials in it, and creates them via CreateFieldTrial(). Returns true if + // successful and false otherwise. + static bool CreateTrialsFromSharedMemory( std::unique_ptr<base::SharedMemory> shm); // Instantiate the field trial allocator, add all existing field trials to it,
diff --git a/base/metrics/histogram_functions.cc b/base/metrics/histogram_functions.cc new file mode 100644 index 0000000..67dd2f8 --- /dev/null +++ b/base/metrics/histogram_functions.cc
@@ -0,0 +1,99 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/metrics/histogram_functions.h" + +#include "base/metrics/histogram.h" +#include "base/metrics/histogram_base.h" +#include "base/time/time.h" + +namespace base { + +void UmaHistogramBoolean(const std::string& name, bool sample) { + HistogramBase* histogram = BooleanHistogram::FactoryGet( + name, base::HistogramBase::kUmaTargetedHistogramFlag); + histogram->Add(sample); +} + +void UmaHistogramExactLinear(const std::string& name, + int sample, + int value_max) { + HistogramBase* histogram = + LinearHistogram::FactoryGet(name, 1, value_max, value_max + 1, + HistogramBase::kUmaTargetedHistogramFlag); + histogram->Add(sample); +} + +void UmaHistogramPercentage(const std::string& name, int percent) { + UmaHistogramExactLinear(name, percent, 100); +} + +void UmaHistogramCustomCounts(const std::string& name, + int sample, + int min, + int max, + int buckets) { + HistogramBase* histogram = Histogram::FactoryGet( + name, min, max, buckets, HistogramBase::kUmaTargetedHistogramFlag); + histogram->Add(sample); +} + +void UmaHistogramCounts100(const std::string& name, int sample) { + UmaHistogramCustomCounts(name, sample, 1, 100, 50); +} + +void UmaHistogramCounts1000(const std::string& name, int sample) { + UmaHistogramCustomCounts(name, sample, 1, 1000, 50); +} + +void UmaHistogramCounts10000(const std::string& name, int sample) { + UmaHistogramCustomCounts(name, sample, 1, 10000, 50); +} + +void UmaHistogramCounts100000(const std::string& name, int sample) { + UmaHistogramCustomCounts(name, sample, 1, 100000, 50); +} + +void UmaHistogramCounts1M(const std::string& name, int sample) { + UmaHistogramCustomCounts(name, sample, 1, 1000000, 50); +} + +void UmaHistogramCounts10M(const std::string& name, int sample) { + UmaHistogramCustomCounts(name, sample, 1, 10000000, 50); +} + +void UmaHistogramCustomTimes(const std::string& name, + TimeDelta sample, + TimeDelta min, + TimeDelta max, + int buckets) { + HistogramBase* histogram = Histogram::FactoryTimeGet( + name, min, max, buckets, HistogramBase::kUmaTargetedHistogramFlag); + histogram->AddTime(sample); +} + +void UmaHistogramTimes(const std::string& name, TimeDelta sample) { + UmaHistogramCustomTimes(name, sample, TimeDelta::FromMilliseconds(1), + TimeDelta::FromSeconds(10), 50); +} + +void UmaHistogramMediumTimes(const std::string& name, TimeDelta sample) { + UmaHistogramCustomTimes(name, sample, TimeDelta::FromMilliseconds(1), + TimeDelta::FromMinutes(3), 50); +} + +void UmaHistogramLongTimes(const std::string& name, TimeDelta sample) { + UmaHistogramCustomTimes(name, sample, TimeDelta::FromMilliseconds(1), + TimeDelta::FromHours(1), 50); +} + +void UmaHistogramMemoryKB(const std::string& name, int sample) { + UmaHistogramCustomCounts(name, sample, 1000, 500000, 50); +} + +void UmaHistogramMemoryLargeMB(const std::string& name, int sample) { + UmaHistogramCustomCounts(name, sample, 1, 64000, 100); +} + +} // namespace base
diff --git a/base/metrics/histogram_functions.h b/base/metrics/histogram_functions.h new file mode 100644 index 0000000..a18c464 --- /dev/null +++ b/base/metrics/histogram_functions.h
@@ -0,0 +1,100 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef BASE_METRICS_HISTOGRAM_FUNCTIONS_H_ +#define BASE_METRICS_HISTOGRAM_FUNCTIONS_H_ + +#include "base/metrics/histogram.h" +#include "base/metrics/histogram_base.h" +#include "base/time/time.h" + +// Functions for recording metrics. +// +// For best practices on deciding when to emit to a histogram and what form +// the histogram should take, see +// https://chromium.googlesource.com/chromium/src.git/+/HEAD/tools/metrics/histograms/README.md + +// Functions for recording UMA histograms. These can be used for cases +// when the histogram name is generated at runtime. The functionality is +// equivalent to macros defined in histogram_macros.h but allowing non-constant +// histogram names. These functions are slower compared to their macro +// equivalent because the histogram objects are not cached between calls. +// So, these shouldn't be used in performance critical code. +namespace base { + +// For histograms with linear buckets. +// Used for capturing integer data with a linear bucketing scheme. This can be +// used when you want the exact value of some small numeric count, with a max of +// 100 or less. If you need to capture a range of greater than 100, we recommend +// the use of the COUNT histograms below. +// Sample usage: +// base::UmaHistogramExactLinear("Histogram.Linear", some_value, 10); +BASE_EXPORT void UmaHistogramExactLinear(const std::string& name, + int sample, + int value_max); + +// For adding sample to enum histogram. +// Sample usage: +// base::UmaHistogramEnumeration("My.Enumeration", VALUE, EVENT_MAX_VALUE); +// Note that new Enum values can be added, but existing enums must never be +// renumbered or deleted and reused. +template <typename T> +void UmaHistogramEnumeration(const std::string& name, T sample, T max) { + static_assert(std::is_enum<T>::value, + "Non enum passed to UmaHistogramEnumeration"); + return UmaHistogramExactLinear(name, static_cast<int>(sample), max); +} + +// For adding boolean sample to histogram. +// Sample usage: +// base::UmaHistogramBoolean("My.Boolean", true) +BASE_EXPORT void UmaHistogramBoolean(const std::string& name, bool sample); + +// For adding histogram with percent. +// Percents are integer between 1 and 100. +// Sample usage: +// base::UmaHistogramPercentage("My.Percent", 69) +BASE_EXPORT void UmaHistogramPercentage(const std::string& name, int percent); + +// For adding counts histogram. +// Sample usage: +// base::UmaHistogramCounts("My.Counts", some_value, 1, 600, 30) +BASE_EXPORT void UmaHistogramCustomCounts(const std::string& name, + int sample, + int min, + int max, + int buckets); + +// Counts specialization for maximum counts 100, 1000, 10k, 100k, 1M and 10M. +BASE_EXPORT void UmaHistogramCounts100(const std::string& name, int sample); +BASE_EXPORT void UmaHistogramCounts1000(const std::string& name, int sample); +BASE_EXPORT void UmaHistogramCounts10000(const std::string& name, int sample); +BASE_EXPORT void UmaHistogramCounts100000(const std::string& name, int sample); +BASE_EXPORT void UmaHistogramCounts1M(const std::string& name, int sample); +BASE_EXPORT void UmaHistogramCounts10M(const std::string& name, int sample); + +// For histograms storing times. +BASE_EXPORT void UmaHistogramCustomTimes(const std::string& name, + TimeDelta sample, + TimeDelta min, + TimeDelta max, + int buckets); +// For short timings from 1 ms up to 10 seconds (50 buckets). +BASE_EXPORT void UmaHistogramTimes(const std::string& name, TimeDelta sample); +// For medium timings up to 3 minutes (50 buckets). +BASE_EXPORT void UmaHistogramMediumTimes(const std::string& name, + TimeDelta sample); +// For time intervals up to 1 hr (50 buckets). +BASE_EXPORT void UmaHistogramLongTimes(const std::string& name, + TimeDelta sample); + +// For recording memory related histograms. +// Used to measure common KB-granularity memory stats. Range is up to 500M. +BASE_EXPORT void UmaHistogramMemoryKB(const std::string& name, int sample); +// Used to measure common MB-granularity memory stats. Range is up to ~64G. +BASE_EXPORT void UmaHistogramMemoryLargeMB(const std::string& name, int sample); + +} // namespace base + +#endif // BASE_METRICS_HISTOGRAM_FUNCTIONS_H_
diff --git a/base/metrics/histogram_functions_unittest.cc b/base/metrics/histogram_functions_unittest.cc new file mode 100644 index 0000000..77a584b --- /dev/null +++ b/base/metrics/histogram_functions_unittest.cc
@@ -0,0 +1,109 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/metrics/histogram_functions.h" + +#include "base/metrics/histogram_macros.h" +#include "base/test/histogram_tester.h" +#include "base/time/time.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace base { + +enum UmaHistogramTestingEnum { + UMA_HISTOGRAM_TESTING_ENUM_FIRST, + UMA_HISTOGRAM_TESTING_ENUM_SECOND, + UMA_HISTOGRAM_TESTING_ENUM_THIRD +}; + +TEST(HistogramFunctionsTest, HistogramExactLinear) { + std::string histogram("Testing.UMA.HistogramExactLinear"); + HistogramTester tester; + UmaHistogramExactLinear(histogram, 10, 100); + tester.ExpectUniqueSample(histogram, 10, 1); + UmaHistogramExactLinear(histogram, 20, 100); + UmaHistogramExactLinear(histogram, 10, 100); + tester.ExpectBucketCount(histogram, 10, 2); + tester.ExpectBucketCount(histogram, 20, 1); + tester.ExpectTotalCount(histogram, 3); + // Test linear buckets overflow. + UmaHistogramExactLinear(histogram, 200, 100); + tester.ExpectBucketCount(histogram, 101, 1); + tester.ExpectTotalCount(histogram, 4); + // Test linear buckets underflow. + UmaHistogramExactLinear(histogram, 0, 100); + tester.ExpectBucketCount(histogram, 0, 1); + tester.ExpectTotalCount(histogram, 5); +} + +TEST(HistogramFunctionsTest, HistogramEnumeration) { + std::string histogram("Testing.UMA.HistogramEnumeration"); + HistogramTester tester; + UmaHistogramEnumeration(histogram, UMA_HISTOGRAM_TESTING_ENUM_FIRST, + UMA_HISTOGRAM_TESTING_ENUM_THIRD); + tester.ExpectUniqueSample(histogram, UMA_HISTOGRAM_TESTING_ENUM_FIRST, 1); + + // Verify the overflow & underflow bucket exists. + UMA_HISTOGRAM_ENUMERATION( + histogram, static_cast<int>(UMA_HISTOGRAM_TESTING_ENUM_THIRD) + 10, + UMA_HISTOGRAM_TESTING_ENUM_THIRD); + tester.ExpectBucketCount( + histogram, static_cast<int>(UMA_HISTOGRAM_TESTING_ENUM_THIRD) + 1, 1); + tester.ExpectTotalCount(histogram, 2); +} + +TEST(HistogramFunctionsTest, HistogramBoolean) { + std::string histogram("Testing.UMA.HistogramBoolean"); + HistogramTester tester; + UmaHistogramBoolean(histogram, true); + tester.ExpectUniqueSample(histogram, 1, 1); + UmaHistogramBoolean(histogram, false); + tester.ExpectBucketCount(histogram, 0, 1); + tester.ExpectTotalCount(histogram, 2); +} + +TEST(HistogramFunctionsTest, HistogramPercentage) { + std::string histogram("Testing.UMA.HistogramPercentage"); + HistogramTester tester; + UmaHistogramPercentage(histogram, 50); + tester.ExpectUniqueSample(histogram, 50, 1); + // Test overflows. + UmaHistogramPercentage(histogram, 110); + tester.ExpectBucketCount(histogram, 101, 1); + tester.ExpectTotalCount(histogram, 2); +} + +TEST(HistogramFunctionsTest, HistogramCounts) { + std::string histogram("Testing.UMA.HistogramCount.Custom"); + HistogramTester tester; + UmaHistogramCustomCounts(histogram, 10, 1, 100, 10); + tester.ExpectUniqueSample(histogram, 10, 1); + UmaHistogramCustomCounts(histogram, 20, 1, 100, 10); + UmaHistogramCustomCounts(histogram, 20, 1, 100, 10); + UmaHistogramCustomCounts(histogram, 20, 1, 100, 10); + tester.ExpectBucketCount(histogram, 20, 3); + tester.ExpectTotalCount(histogram, 4); + UmaHistogramCustomCounts(histogram, 110, 1, 100, 10); + tester.ExpectBucketCount(histogram, 101, 1); + tester.ExpectTotalCount(histogram, 5); +} + +TEST(HistogramFunctionsTest, HistogramTimes) { + std::string histogram("Testing.UMA.HistogramTimes"); + HistogramTester tester; + UmaHistogramTimes(histogram, TimeDelta::FromSeconds(1)); + tester.ExpectTimeBucketCount(histogram, TimeDelta::FromSeconds(1), 1); + tester.ExpectTotalCount(histogram, 1); + UmaHistogramTimes(histogram, TimeDelta::FromSeconds(9)); + tester.ExpectTimeBucketCount(histogram, TimeDelta::FromSeconds(9), 1); + tester.ExpectTotalCount(histogram, 2); + UmaHistogramTimes(histogram, TimeDelta::FromSeconds(10)); // Overflows + tester.ExpectTimeBucketCount(histogram, TimeDelta::FromSeconds(10), 1); + UmaHistogramTimes(histogram, TimeDelta::FromSeconds(20)); // Overflows. + // Check the value by picking any overflow time. + tester.ExpectTimeBucketCount(histogram, TimeDelta::FromSeconds(11), 2); + tester.ExpectTotalCount(histogram, 4); +} + +} // namespace base.
diff --git a/base/metrics/histogram_macros.h b/base/metrics/histogram_macros.h index 0ee7d2c..9e3caec 100644 --- a/base/metrics/histogram_macros.h +++ b/base/metrics/histogram_macros.h
@@ -67,8 +67,8 @@ // Sample usage: // UMA_HISTOGRAM_EXACT_LINEAR("Histogram.Linear", count, 10); -#define UMA_HISTOGRAM_EXACT_LINEAR(name, sample, value_max) \ - UMA_HISTOGRAM_ENUMERATION(name, sample, value_max+1) +#define UMA_HISTOGRAM_EXACT_LINEAR(name, sample, value_max) \ + UMA_HISTOGRAM_ENUMERATION(name, sample, value_max) // Used for capturing basic percentages. This will be 100 buckets of size 1.
diff --git a/base/pickle.cc b/base/pickle.cc index cfb316c..02f39b57 100644 --- a/base/pickle.cc +++ b/base/pickle.cc
@@ -233,7 +233,6 @@ void PickleSizer::AddAttachment() { // From IPC::Message::WriteAttachment - AddBool(); AddInt(); }
diff --git a/base/task_scheduler/scheduler_worker_pool_impl.cc b/base/task_scheduler/scheduler_worker_pool_impl.cc index 155f42dc..f15cc93 100644 --- a/base/task_scheduler/scheduler_worker_pool_impl.cc +++ b/base/task_scheduler/scheduler_worker_pool_impl.cc
@@ -320,26 +320,6 @@ return nullptr; } -void SchedulerWorkerPoolImpl::WaitForAllWorkersIdleForTesting() { - AutoSchedulerLock auto_lock(idle_workers_stack_lock_); - while (idle_workers_stack_.Size() < workers_.size()) - idle_workers_stack_cv_for_testing_->Wait(); -} - -void SchedulerWorkerPoolImpl::JoinForTesting() { - DCHECK(!CanWorkerDetachForTesting() || suggested_reclaim_time_.is_max()) << - "Workers can detach during join."; - for (const auto& worker : workers_) - worker->JoinForTesting(); - - DCHECK(!join_for_testing_returned_.IsSignaled()); - join_for_testing_returned_.Signal(); -} - -void SchedulerWorkerPoolImpl::DisallowWorkerDetachmentForTesting() { - worker_detachment_disallowed_.Set(); -} - scoped_refptr<TaskRunner> SchedulerWorkerPoolImpl::CreateTaskRunnerWithTraits( const TaskTraits& traits) { return make_scoped_refptr(new SchedulerParallelTaskRunner(traits, this)); @@ -452,6 +432,26 @@ histograms->push_back(num_tasks_between_waits_histogram_); } +void SchedulerWorkerPoolImpl::WaitForAllWorkersIdleForTesting() { + AutoSchedulerLock auto_lock(idle_workers_stack_lock_); + while (idle_workers_stack_.Size() < workers_.size()) + idle_workers_stack_cv_for_testing_->Wait(); +} + +void SchedulerWorkerPoolImpl::JoinForTesting() { + DCHECK(!CanWorkerDetachForTesting() || suggested_reclaim_time_.is_max()) + << "Workers can detach during join."; + for (const auto& worker : workers_) + worker->JoinForTesting(); + + DCHECK(!join_for_testing_returned_.IsSignaled()); + join_for_testing_returned_.Signal(); +} + +void SchedulerWorkerPoolImpl::DisallowWorkerDetachmentForTesting() { + worker_detachment_disallowed_.Set(); +} + SchedulerWorkerPoolImpl::SchedulerSingleThreadTaskRunner:: SchedulerSingleThreadTaskRunner(const TaskTraits& traits, SchedulerWorkerPool* worker_pool,
diff --git a/base/task_scheduler/scheduler_worker_pool_impl.h b/base/task_scheduler/scheduler_worker_pool_impl.h index 136ad623..178133d 100644 --- a/base/task_scheduler/scheduler_worker_pool_impl.h +++ b/base/task_scheduler/scheduler_worker_pool_impl.h
@@ -65,21 +65,6 @@ TaskTracker* task_tracker, DelayedTaskManager* delayed_task_manager); - // Waits until all workers are idle. - void WaitForAllWorkersIdleForTesting(); - - // Joins all workers of this worker pool. Tasks that are already running are - // allowed to complete their execution. This can only be called once. - void JoinForTesting(); - - // Disallows worker thread detachment. If the suggested reclaim time is not - // TimeDelta::Max(), then the test should call this before the detach code can - // run. The safest place to do this is before the a set of work is dispatched - // (the worker pool is idle and steady state) or before the last - // synchronization point for all workers (all threads are busy and can't be - // reclaimed). - void DisallowWorkerDetachmentForTesting(); - // SchedulerWorkerPool: scoped_refptr<TaskRunner> CreateTaskRunnerWithTraits( const TaskTraits& traits) override; @@ -106,6 +91,21 @@ void GetHistograms(std::vector<const HistogramBase*>* histograms) const; + // Waits until all workers are idle. + void WaitForAllWorkersIdleForTesting(); + + // Joins all workers of this worker pool. Tasks that are already running are + // allowed to complete their execution. This can only be called once. + void JoinForTesting(); + + // Disallows worker thread detachment. If the suggested reclaim time is not + // TimeDelta::Max(), then the test should call this before the detach code can + // run. The safest place to do this is before the a set of work is dispatched + // (the worker pool is idle and steady state) or before the last + // synchronization point for all workers (all threads are busy and can't be + // reclaimed). + void DisallowWorkerDetachmentForTesting(); + private: class SchedulerSingleThreadTaskRunner; class SchedulerWorkerDelegateImpl;
diff --git a/base/test/histogram_tester.cc b/base/test/histogram_tester.cc index 65c4285..90981e2 100644 --- a/base/test/histogram_tester.cc +++ b/base/test/histogram_tester.cc
@@ -78,6 +78,13 @@ } } +void HistogramTester::ExpectTimeBucketCount( + const std::string& name, + base::TimeDelta sample, + base::HistogramBase::Count count) const { + ExpectBucketCount(name, sample.InMilliseconds(), count); +} + std::vector<Bucket> HistogramTester::GetAllSamples( const std::string& name) const { std::vector<Bucket> samples;
diff --git a/base/test/histogram_tester.h b/base/test/histogram_tester.h index cd8534ac..55ca1b9 100644 --- a/base/test/histogram_tester.h +++ b/base/test/histogram_tester.h
@@ -15,6 +15,7 @@ #include "base/macros.h" #include "base/metrics/histogram.h" #include "base/metrics/histogram_base.h" +#include "base/time/time.h" namespace base { @@ -53,6 +54,12 @@ void ExpectTotalCount(const std::string& name, base::HistogramBase::Count count) const; + // We know exact number of samples for buckets corresponding to a time + // interval. Other intervals may have samples too. + void ExpectTimeBucketCount(const std::string& name, + base::TimeDelta sample, + base::HistogramBase::Count count) const; + // Returns a list of all of the buckets recorded since creation of this // object, as vector<Bucket>, where the Bucket represents the min boundary of // the bucket and the count of samples recorded to that bucket since creation.
diff --git a/base/timer/timer.cc b/base/timer/timer.cc index e554905..aba8fc8d 100644 --- a/base/timer/timer.cc +++ b/base/timer/timer.cc
@@ -6,11 +6,15 @@ #include <stddef.h> +#include <utility> + #include "base/logging.h" +#include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "base/single_thread_task_runner.h" #include "base/threading/platform_thread.h" #include "base/threading/thread_task_runner_handle.h" +#include "base/time/tick_clock.h" namespace base { @@ -60,26 +64,36 @@ }; Timer::Timer(bool retain_user_task, bool is_repeating) - : scheduled_task_(NULL), + : Timer(retain_user_task, is_repeating, nullptr) {} + +Timer::Timer(bool retain_user_task, bool is_repeating, TickClock* tick_clock) + : scheduled_task_(nullptr), thread_id_(0), is_repeating_(is_repeating), retain_user_task_(retain_user_task), - is_running_(false) { -} + tick_clock_(tick_clock), + is_running_(false) {} Timer::Timer(const tracked_objects::Location& posted_from, TimeDelta delay, const base::Closure& user_task, bool is_repeating) - : scheduled_task_(NULL), + : Timer(posted_from, delay, user_task, is_repeating, nullptr) {} + +Timer::Timer(const tracked_objects::Location& posted_from, + TimeDelta delay, + const base::Closure& user_task, + bool is_repeating, + TickClock* tick_clock) + : scheduled_task_(nullptr), posted_from_(posted_from), delay_(delay), user_task_(user_task), thread_id_(0), is_repeating_(is_repeating), retain_user_task_(true), - is_running_(false) { -} + tick_clock_(tick_clock), + is_running_(false) {} Timer::~Timer() { StopAndAbandon(); @@ -123,7 +137,7 @@ // Set the new desired_run_time_. if (delay_ > TimeDelta::FromMicroseconds(0)) - desired_run_time_ = TimeTicks::Now() + delay_; + desired_run_time_ = Now() + delay_; else desired_run_time_ = TimeTicks(); @@ -139,6 +153,10 @@ PostNewScheduledTask(delay_); } +TimeTicks Timer::Now() const { + return tick_clock_ ? tick_clock_->NowTicks() : TimeTicks::Now(); +} + void Timer::SetTaskInfo(const tracked_objects::Location& posted_from, TimeDelta delay, const base::Closure& user_task) { @@ -155,7 +173,7 @@ GetTaskRunner()->PostDelayedTask(posted_from_, base::Bind(&BaseTimerTaskInternal::Run, base::Owned(scheduled_task_)), delay); - scheduled_run_time_ = desired_run_time_ = TimeTicks::Now() + delay; + scheduled_run_time_ = desired_run_time_ = Now() + delay; } else { GetTaskRunner()->PostTask(posted_from_, base::Bind(&BaseTimerTaskInternal::Run, base::Owned(scheduled_task_))); @@ -189,9 +207,9 @@ // First check if we need to delay the task because of a new target time. if (desired_run_time_ > scheduled_run_time_) { - // TimeTicks::Now() can be expensive, so only call it if we know the user - // has changed the desired_run_time_. - TimeTicks now = TimeTicks::Now(); + // Now() can be expensive, so only call it if we know the user has changed + // the desired_run_time_. + TimeTicks now = Now(); // Task runner may have called us late anyway, so only post a continuation // task if the desired_run_time_ is in the future. if (desired_run_time_ > now) {
diff --git a/base/timer/timer.h b/base/timer/timer.h index 661829b..50aedbd 100644 --- a/base/timer/timer.h +++ b/base/timer/timer.h
@@ -49,6 +49,8 @@ // because they're flaky on the buildbot, but when you run them locally you // should be able to tell the difference. +#include <memory> + #include "base/base_export.h" #include "base/bind.h" #include "base/bind_helpers.h" @@ -61,6 +63,7 @@ class BaseTimerTaskInternal; class SingleThreadTaskRunner; +class TickClock; //----------------------------------------------------------------------------- // This class wraps MessageLoop::PostDelayedTask to manage delayed and repeating @@ -71,14 +74,23 @@ public: // Construct a timer in repeating or one-shot mode. Start or SetTaskInfo must // be called later to set task info. |retain_user_task| determines whether the - // user_task is retained or reset when it runs or stops. + // user_task is retained or reset when it runs or stops. If |tick_clock| is + // provided, it is used instead of TimeTicks::Now() to get TimeTicks when + // scheduling tasks. Timer(bool retain_user_task, bool is_repeating); + Timer(bool retain_user_task, bool is_repeating, TickClock* tick_clock); - // Construct a timer with retained task info. + // Construct a timer with retained task info. If |tick_clock| is provided, it + // is used instead of TimeTicks::Now() to get TimeTicks when scheduling tasks. Timer(const tracked_objects::Location& posted_from, TimeDelta delay, const base::Closure& user_task, bool is_repeating); + Timer(const tracked_objects::Location& posted_from, + TimeDelta delay, + const base::Closure& user_task, + bool is_repeating, + TickClock* tick_clock); virtual ~Timer(); @@ -111,6 +123,9 @@ const TimeTicks& desired_run_time() const { return desired_run_time_; } protected: + // Returns the current tick count. + TimeTicks Now() const; + // Used to initiate a new delayed task. This has the side-effect of disabling // scheduled_task_ if it is non-null. void SetTaskInfo(const tracked_objects::Location& posted_from, @@ -191,6 +206,9 @@ // If true, hold on to the user_task_ closure object for reuse. const bool retain_user_task_; + // The tick clock used to calculate the run time for scheduled tasks. + TickClock* const tick_clock_; + // If true, user_task_ is scheduled to run sometime in the future. bool is_running_; @@ -210,8 +228,8 @@ using Timer::Start; enum RepeatMode { ONE_SHOT, REPEATING }; - BaseTimerMethodPointer(RepeatMode mode) - : Timer(mode == REPEATING, mode == REPEATING) {} + BaseTimerMethodPointer(RepeatMode mode, TickClock* tick_clock) + : Timer(mode == REPEATING, mode == REPEATING, tick_clock) {} // Start the timer to run at the given |delay| from now. If the timer is // already running, it will be replaced to call a task formed from @@ -230,14 +248,18 @@ // A simple, one-shot timer. See usage notes at the top of the file. class OneShotTimer : public BaseTimerMethodPointer { public: - OneShotTimer() : BaseTimerMethodPointer(ONE_SHOT) {} + OneShotTimer() : OneShotTimer(nullptr) {} + explicit OneShotTimer(TickClock* tick_clock) + : BaseTimerMethodPointer(ONE_SHOT, tick_clock) {} }; //----------------------------------------------------------------------------- // A simple, repeating timer. See usage notes at the top of the file. class RepeatingTimer : public BaseTimerMethodPointer { public: - RepeatingTimer() : BaseTimerMethodPointer(REPEATING) {} + RepeatingTimer() : RepeatingTimer(nullptr) {} + explicit RepeatingTimer(TickClock* tick_clock) + : BaseTimerMethodPointer(REPEATING, tick_clock) {} }; //----------------------------------------------------------------------------- @@ -258,10 +280,19 @@ TimeDelta delay, Receiver* receiver, void (Receiver::*method)()) + : DelayTimer(posted_from, delay, receiver, method, nullptr) {} + + template <class Receiver> + DelayTimer(const tracked_objects::Location& posted_from, + TimeDelta delay, + Receiver* receiver, + void (Receiver::*method)(), + TickClock* tick_clock) : Timer(posted_from, delay, base::Bind(method, base::Unretained(receiver)), - false) {} + false, + tick_clock) {} void Reset() override; };
diff --git a/base/timer/timer_unittest.cc b/base/timer/timer_unittest.cc index 6fcd25b..b34da20b 100644 --- a/base/timer/timer_unittest.cc +++ b/base/timer/timer_unittest.cc
@@ -8,11 +8,15 @@ #include <memory> +#include "base/bind.h" +#include "base/bind_helpers.h" #include "base/macros.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/test/test_mock_time_task_runner.h" #include "base/test/test_simple_task_runner.h" #include "base/threading/thread_task_runner_handle.h" +#include "base/time/tick_clock.h" #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" @@ -32,6 +36,17 @@ const int kNumTestingMessageLoops = arraysize(testing_message_loops); +class Receiver { + public: + Receiver() : count_(0) {} + void OnCalled() { count_++; } + bool WasCalled() { return count_ > 0; } + int TimesCalled() { return count_; } + + private: + int count_; +}; + class OneShotTimerTester { public: explicit OneShotTimerTester(bool* did_run, unsigned milliseconds = 10) @@ -341,6 +356,21 @@ EXPECT_TRUE(did_run); } +TEST(TimerTest, OneShotTimerWithTickClock) { + scoped_refptr<base::TestMockTimeTaskRunner> task_runner( + new base::TestMockTimeTaskRunner(base::Time::Now(), + base::TimeTicks::Now())); + std::unique_ptr<base::TickClock> tick_clock(task_runner->GetMockTickClock()); + base::MessageLoop message_loop; + message_loop.SetTaskRunner(task_runner); + Receiver receiver; + base::OneShotTimer timer(tick_clock.get()); + timer.Start(FROM_HERE, base::TimeDelta::FromSeconds(1), + base::Bind(&Receiver::OnCalled, base::Unretained(&receiver))); + task_runner->FastForwardBy(base::TimeDelta::FromSeconds(1)); + EXPECT_TRUE(receiver.WasCalled()); +} + TEST(TimerTest, RepeatingTimer) { for (int i = 0; i < kNumTestingMessageLoops; i++) { RunTest_RepeatingTimer(testing_message_loops[i], @@ -369,6 +399,24 @@ } } +TEST(TimerTest, RepeatingTimerWithTickClock) { + scoped_refptr<base::TestMockTimeTaskRunner> task_runner( + new base::TestMockTimeTaskRunner(base::Time::Now(), + base::TimeTicks::Now())); + std::unique_ptr<base::TickClock> tick_clock(task_runner->GetMockTickClock()); + base::MessageLoop message_loop; + message_loop.SetTaskRunner(task_runner); + Receiver receiver; + const int expected_times_called = 10; + base::RepeatingTimer timer(tick_clock.get()); + timer.Start(FROM_HERE, base::TimeDelta::FromSeconds(1), + base::Bind(&Receiver::OnCalled, base::Unretained(&receiver))); + task_runner->FastForwardBy( + base::TimeDelta::FromSeconds(expected_times_called)); + timer.Stop(); + EXPECT_EQ(expected_times_called, receiver.TimesCalled()); +} + TEST(TimerTest, DelayTimer_NoCall) { for (int i = 0; i < kNumTestingMessageLoops; i++) { RunTest_DelayTimer_NoCall(testing_message_loops[i]); @@ -394,6 +442,26 @@ } } +TEST(TimerTest, DelayTimerWithTickClock) { + scoped_refptr<base::TestMockTimeTaskRunner> task_runner( + new base::TestMockTimeTaskRunner(base::Time::Now(), + base::TimeTicks::Now())); + std::unique_ptr<base::TickClock> tick_clock(task_runner->GetMockTickClock()); + base::MessageLoop message_loop; + message_loop.SetTaskRunner(task_runner); + Receiver receiver; + base::DelayTimer timer(FROM_HERE, base::TimeDelta::FromSeconds(1), &receiver, + &Receiver::OnCalled, tick_clock.get()); + task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(999)); + EXPECT_FALSE(receiver.WasCalled()); + timer.Reset(); + task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(999)); + EXPECT_FALSE(receiver.WasCalled()); + timer.Reset(); + task_runner->FastForwardBy(base::TimeDelta::FromSeconds(1)); + EXPECT_TRUE(receiver.WasCalled()); +} + TEST(TimerTest, MessageLoopShutdown) { // This test is designed to verify that shutdown of the // message loop does not cause crashes if there were pending
diff --git a/blimp/client/DEPS b/blimp/client/DEPS index 5553bfb..1256a76 100644 --- a/blimp/client/DEPS +++ b/blimp/client/DEPS
@@ -13,7 +13,8 @@ "+gpu", "+jni", "+net", - "+third_party/WebKit/public/web/WebInputEvent.h", + "+third_party/WebKit/public/platform/WebGestureEvent.h", + "+third_party/WebKit/public/platform/WebInputEvent.h", "+ui/android", "+ui/base/ime/text_input_type.h", "+ui/base/l10n",
diff --git a/blimp/client/app/BUILD.gn b/blimp/client/app/BUILD.gn index 73b8978f..b98da81 100644 --- a/blimp/client/app/BUILD.gn +++ b/blimp/client/app/BUILD.gn
@@ -216,11 +216,11 @@ visibility = [ ":*" ] sources = [ - "android/java/src/org/chromium/blimp/BlimpLibraryLoader.java", - "android/java/src/org/chromium/blimp/BlimpView.java", - "android/java/src/org/chromium/blimp/session/BlimpClientSession.java", - "android/java/src/org/chromium/blimp/session/TabControlFeature.java", - "android/java/src/org/chromium/blimp/toolbar/Toolbar.java", + "android/java/src/org/chromium/blimp/app/BlimpContentsDisplay.java", + "android/java/src/org/chromium/blimp/app/BlimpLibraryLoader.java", + "android/java/src/org/chromium/blimp/app/session/BlimpClientSession.java", + "android/java/src/org/chromium/blimp/app/session/TabControlFeature.java", + "android/java/src/org/chromium/blimp/app/toolbar/Toolbar.java", ] jni_package = "blimp" @@ -236,7 +236,7 @@ deps = [ ":blimp_strings_grd", ] - custom_package = "org.chromium.blimp" + custom_package = "org.chromium.blimp.app" } java_strings_grd("blimp_strings_grd") { @@ -298,6 +298,7 @@ "//blimp/client/core:core_java", "//blimp/client/public:public_headers_java", "//third_party/android_tools:android_support_annotations_java", + "//third_party/android_tools:android_support_v7_appcompat_java", # TODO(dtrainor): Remove the ui_java target once no more Android Toast # notifications are used. @@ -306,23 +307,23 @@ ] java_files = [ - "android/java/src/org/chromium/blimp/auth/RetryingTokenSource.java", - "android/java/src/org/chromium/blimp/auth/TokenSource.java", - "android/java/src/org/chromium/blimp/auth/TokenSourceImpl.java", - "android/java/src/org/chromium/blimp/BlimpApplication.java", - "android/java/src/org/chromium/blimp/BlimpLibraryLoader.java", - "android/java/src/org/chromium/blimp/BlimpRendererActivity.java", - "android/java/src/org/chromium/blimp/BlimpView.java", - "android/java/src/org/chromium/blimp/BrowserRestartActivity.java", - "android/java/src/org/chromium/blimp/preferences/PreferencesUtil.java", - "android/java/src/org/chromium/blimp/session/BlimpClientSession.java", - "android/java/src/org/chromium/blimp/session/EngineInfo.java", - "android/java/src/org/chromium/blimp/session/TabControlFeature.java", - "android/java/src/org/chromium/blimp/settings/AboutBlimpPreferences.java", - "android/java/src/org/chromium/blimp/settings/Preferences.java", - "android/java/src/org/chromium/blimp/toolbar/Toolbar.java", - "android/java/src/org/chromium/blimp/toolbar/ToolbarMenu.java", - "android/java/src/org/chromium/blimp/toolbar/UrlBar.java", + "android/java/src/org/chromium/blimp/app/auth/RetryingTokenSource.java", + "android/java/src/org/chromium/blimp/app/auth/TokenSource.java", + "android/java/src/org/chromium/blimp/app/auth/TokenSourceImpl.java", + "android/java/src/org/chromium/blimp/app/BlimpApplication.java", + "android/java/src/org/chromium/blimp/app/BlimpContentsDisplay.java", + "android/java/src/org/chromium/blimp/app/BlimpLibraryLoader.java", + "android/java/src/org/chromium/blimp/app/BlimpRendererActivity.java", + "android/java/src/org/chromium/blimp/app/BrowserRestartActivity.java", + "android/java/src/org/chromium/blimp/app/preferences/PreferencesUtil.java", + "android/java/src/org/chromium/blimp/app/session/BlimpClientSession.java", + "android/java/src/org/chromium/blimp/app/session/EngineInfo.java", + "android/java/src/org/chromium/blimp/app/session/TabControlFeature.java", + "android/java/src/org/chromium/blimp/app/settings/AboutBlimpPreferences.java", + "android/java/src/org/chromium/blimp/app/settings/Preferences.java", + "android/java/src/org/chromium/blimp/app/toolbar/Toolbar.java", + "android/java/src/org/chromium/blimp/app/toolbar/ToolbarMenu.java", + "android/java/src/org/chromium/blimp/app/toolbar/UrlBar.java", ] } @@ -347,13 +348,13 @@ ] java_files = [ - "android/javatests/src/org/chromium/blimp/auth/MockTokenSource.java", - "android/javatests/src/org/chromium/blimp/auth/RetryingTokenSourceTest.java", + "android/javatests/src/org/chromium/blimp/app/auth/MockTokenSource.java", + "android/javatests/src/org/chromium/blimp/app/auth/RetryingTokenSourceTest.java", + "android/javatests/src/org/chromium/blimp/app/BlimpNativeInstrumentationTestCase.java", "android/javatests/src/org/chromium/blimp/core/MockBlimpClientContext.java", "android/javatests/src/org/chromium/blimp/core/MockBlimpClientContextDelegate.java", "android/javatests/src/org/chromium/blimp/core/settings/BlimpPreferencesTest.java", "android/javatests/src/org/chromium/blimp/core/settings/MockPreferences.java", - "android/javatests/src/org/chromium/blimp/BlimpNativeInstrumentationTestCase.java", ] } @@ -385,10 +386,10 @@ "android/blimp_app_jni_registrar.h", "android/blimp_client_session_android.cc", "android/blimp_client_session_android.h", + "android/blimp_contents_display.cc", + "android/blimp_contents_display.h", "android/blimp_library_loader.cc", "android/blimp_library_loader.h", - "android/blimp_view.cc", - "android/blimp_view.h", "android/tab_control_feature_android.cc", "android/tab_control_feature_android.h", "android/toolbar.cc",
diff --git a/blimp/client/app/android/AndroidManifest.xml.jinja2 b/blimp/client/app/android/AndroidManifest.xml.jinja2 index 129722a..ee0fa22 100644 --- a/blimp/client/app/android/AndroidManifest.xml.jinja2 +++ b/blimp/client/app/android/AndroidManifest.xml.jinja2
@@ -15,10 +15,10 @@ <uses-permission android:name="android.permission.READ_SYNC_SETTINGS"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS"/> - <application android:name="org.chromium.blimp.BlimpApplication" + <application android:name="org.chromium.blimp.app.BlimpApplication" android:label="Blimp" android:icon="@mipmap/app_icon"> - <activity android:name="org.chromium.blimp.BlimpRendererActivity" + <activity android:name="org.chromium.blimp.app.BlimpRendererActivity" android:launchMode="singleTask" android:theme="@style/Theme.AppCompat.Light.NoActionBar" android:configChanges="orientation|keyboardHidden|keyboard|screenSize" @@ -39,8 +39,8 @@ <data android:scheme="https" /> </intent-filter> </activity> - <activity android:name="org.chromium.blimp.settings.Preferences"/> - <activity android:name="org.chromium.blimp.BrowserRestartActivity" + <activity android:name="org.chromium.blimp.app.settings.Preferences"/> + <activity android:name="org.chromium.blimp.app.BrowserRestartActivity" android:launchMode="singleInstance" android:exported="false" android:theme="@android:style/Theme.Translucent.NoTitleBar"
diff --git a/blimp/client/app/android/blimp_app_jni_registrar.cc b/blimp/client/app/android/blimp_app_jni_registrar.cc index ee1a0332..191a35d 100644 --- a/blimp/client/app/android/blimp_app_jni_registrar.cc +++ b/blimp/client/app/android/blimp_app_jni_registrar.cc
@@ -6,8 +6,8 @@ #include "base/android/jni_registrar.h" #include "blimp/client/app/android/blimp_client_session_android.h" +#include "blimp/client/app/android/blimp_contents_display.h" #include "blimp/client/app/android/blimp_library_loader.h" -#include "blimp/client/app/android/blimp_view.h" #include "blimp/client/app/android/tab_control_feature_android.h" #include "blimp/client/app/android/toolbar.h" #include "blimp/client/core/contents/android/ime_helper_dialog.h" @@ -20,7 +20,7 @@ base::android::RegistrationMethod kBlimpRegistrationMethods[] = { {"BlimpClientSessionAndroid", BlimpClientSessionAndroid::RegisterJni}, {"BlimpLibraryLoader", RegisterBlimpLibraryLoaderJni}, - {"BlimpView", app::BlimpView::RegisterJni}, + {"BlimpContentsDisplay", app::BlimpContentsDisplay::RegisterJni}, {"ImeHelperDialog", ImeHelperDialog::RegisterJni}, {"SafeJson", safe_json::android::RegisterSafeJsonJni}, {"TabControlFeatureAndroid", TabControlFeatureAndroid::RegisterJni},
diff --git a/blimp/client/app/android/blimp_view.cc b/blimp/client/app/android/blimp_contents_display.cc similarity index 64% rename from blimp/client/app/android/blimp_view.cc rename to blimp/client/app/android/blimp_contents_display.cc index 5e447f2e..6eebee8f 100644 --- a/blimp/client/app/android/blimp_view.cc +++ b/blimp/client/app/android/blimp_contents_display.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "blimp/client/app/android/blimp_view.h" +#include "blimp/client/app/android/blimp_contents_display.h" #include <android/native_window_jni.h> @@ -13,7 +13,7 @@ #include "blimp/client/core/render_widget/blimp_document_manager.h" #include "blimp/client/core/render_widget/render_widget_feature.h" #include "blimp/client/support/compositor/compositor_dependencies_impl.h" -#include "jni/BlimpView_jni.h" +#include "jni/BlimpContentsDisplay_jni.h" #include "ui/events/android/motion_event_android.h" #include "ui/gfx/geometry/size.h" @@ -41,22 +41,23 @@ // pass it through to the BlimpCompositor. ALLOW_UNUSED_LOCAL(client_session); - return reinterpret_cast<intptr_t>(new BlimpView( + return reinterpret_cast<intptr_t>(new BlimpContentsDisplay( env, jobj, gfx::Size(real_width, real_height), gfx::Size(width, height), dp_to_px, client_session->GetRenderWidgetFeature())); } // static -bool BlimpView::RegisterJni(JNIEnv* env) { +bool BlimpContentsDisplay::RegisterJni(JNIEnv* env) { return RegisterNativesImpl(env); } -BlimpView::BlimpView(JNIEnv* env, - const base::android::JavaParamRef<jobject>& jobj, - const gfx::Size& real_size, - const gfx::Size& size, - float dp_to_px, - blimp::client::RenderWidgetFeature* render_widget_feature) +BlimpContentsDisplay::BlimpContentsDisplay( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& jobj, + const gfx::Size& real_size, + const gfx::Size& size, + float dp_to_px, + blimp::client::RenderWidgetFeature* render_widget_feature) : device_scale_factor_(dp_to_px), current_surface_format_(0), window_(gfx::kNullAcceleratedWidget), @@ -66,8 +67,9 @@ compositor_ = base::MakeUnique<BrowserCompositor>( compositor_dependencies_->GetEmbedderDependencies()); - compositor_->set_did_complete_swap_buffers_callback(base::Bind( - &BlimpView::OnSwapBuffersCompleted, weak_ptr_factory_.GetWeakPtr())); + compositor_->set_did_complete_swap_buffers_callback( + base::Bind(&BlimpContentsDisplay::OnSwapBuffersCompleted, + weak_ptr_factory_.GetWeakPtr())); document_manager_ = base::MakeUnique<BlimpDocumentManager>( kDummyBlimpContentsId, render_widget_feature, @@ -77,7 +79,7 @@ java_obj_.Reset(env, jobj); } -BlimpView::~BlimpView() { +BlimpContentsDisplay::~BlimpContentsDisplay() { SetSurface(nullptr); // Destroy the BrowserCompositor and the BlimpCompositorManager before the @@ -87,12 +89,13 @@ compositor_dependencies_.reset(); } -void BlimpView::Destroy(JNIEnv* env, - const base::android::JavaParamRef<jobject>& jobj) { +void BlimpContentsDisplay::Destroy( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& jobj) { delete this; } -void BlimpView::OnContentAreaSizeChanged( +void BlimpContentsDisplay::OnContentAreaSizeChanged( JNIEnv* env, const base::android::JavaParamRef<jobject>& jobj, jint width, @@ -101,7 +104,7 @@ compositor_->SetSize(gfx::Size(width, height)); } -void BlimpView::OnSurfaceChanged( +void BlimpContentsDisplay::OnSurfaceChanged( JNIEnv* env, const base::android::JavaParamRef<jobject>& jobj, jint format, @@ -118,20 +121,20 @@ } } -void BlimpView::OnSurfaceCreated( +void BlimpContentsDisplay::OnSurfaceCreated( JNIEnv* env, const base::android::JavaParamRef<jobject>& jobj) { current_surface_format_ = 0 /** PixelFormat.UNKNOWN */; } -void BlimpView::OnSurfaceDestroyed( +void BlimpContentsDisplay::OnSurfaceDestroyed( JNIEnv* env, const base::android::JavaParamRef<jobject>& jobj) { current_surface_format_ = 0 /** PixelFormat.UNKNOWN */; SetSurface(nullptr); } -void BlimpView::SetSurface(jobject surface) { +void BlimpContentsDisplay::SetSurface(jobject surface) { JNIEnv* env = base::android::AttachCurrentThread(); // Release all references to the old surface. if (window_ != gfx::kNullAcceleratedWidget) { @@ -149,7 +152,7 @@ } } -jboolean BlimpView::OnTouchEvent( +jboolean BlimpContentsDisplay::OnTouchEvent( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jobject>& motion_event, @@ -178,43 +181,24 @@ jint android_tool_type_1, jint android_button_state, jint android_meta_state) { - ui::MotionEventAndroid::Pointer pointer0(pointer_id_0, - pos_x_0, - pos_y_0, - touch_major_0, - touch_minor_0, - orientation_0, - tilt_0, - android_tool_type_0); - ui::MotionEventAndroid::Pointer pointer1(pointer_id_1, - pos_x_1, - pos_y_1, - touch_major_1, - touch_minor_1, - orientation_1, - tilt_1, - android_tool_type_1); - ui::MotionEventAndroid event(1.f / device_scale_factor_, - env, - motion_event, - time_ms, - android_action, - pointer_count, - history_size, - action_index, - android_button_state, - android_meta_state, - raw_pos_x - pos_x_0, - raw_pos_y - pos_y_0, - &pointer0, - &pointer1); + ui::MotionEventAndroid::Pointer pointer0( + pointer_id_0, pos_x_0, pos_y_0, touch_major_0, touch_minor_0, + orientation_0, tilt_0, android_tool_type_0); + ui::MotionEventAndroid::Pointer pointer1( + pointer_id_1, pos_x_1, pos_y_1, touch_major_1, touch_minor_1, + orientation_1, tilt_1, android_tool_type_1); + ui::MotionEventAndroid event(1.f / device_scale_factor_, env, motion_event, + time_ms, android_action, pointer_count, + history_size, action_index, android_button_state, + android_meta_state, raw_pos_x - pos_x_0, + raw_pos_y - pos_y_0, &pointer0, &pointer1); return document_manager_->OnTouchEvent(event); } -void BlimpView::OnSwapBuffersCompleted() { +void BlimpContentsDisplay::OnSwapBuffersCompleted() { JNIEnv* env = base::android::AttachCurrentThread(); - Java_BlimpView_onSwapBuffersCompleted(env, java_obj_); + Java_BlimpContentsDisplay_onSwapBuffersCompleted(env, java_obj_); } } // namespace app
diff --git a/blimp/client/app/android/blimp_view.h b/blimp/client/app/android/blimp_contents_display.h similarity index 78% rename from blimp/client/app/android/blimp_view.h rename to blimp/client/app/android/blimp_contents_display.h index 2d9b1d4..4dfc5270 100644 --- a/blimp/client/app/android/blimp_view.h +++ b/blimp/client/app/android/blimp_contents_display.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BLIMP_CLIENT_APP_ANDROID_BLIMP_VIEW_H_ -#define BLIMP_CLIENT_APP_ANDROID_BLIMP_VIEW_H_ +#ifndef BLIMP_CLIENT_APP_ANDROID_BLIMP_CONTENTS_DISPLAY_H_ +#define BLIMP_CLIENT_APP_ANDROID_BLIMP_CONTENTS_DISPLAY_H_ #include <memory> @@ -25,10 +25,10 @@ namespace app { -// The native component of org.chromium.blimp.BlimpView. This builds and -// maintains a BlimpCompositorAndroid and handles notifying the compositor of -// SurfaceView surface changes (size, creation, destruction, etc.). -class BlimpView { +// The native component of org.chromium.blimp.BlimpContentsDisplay. This builds +// and maintains a BlimpCompositorAndroid and handles notifying the compositor +// of SurfaceView surface changes (size, creation, destruction, etc.). +class BlimpContentsDisplay { public: static bool RegisterJni(JNIEnv* env); @@ -37,12 +37,13 @@ // area not including system decorations (see android.view.Display.getSize()). // |dp_to_px| is the scale factor that is required to convert dp (device // pixels) to px. - BlimpView(JNIEnv* env, - const base::android::JavaParamRef<jobject>& jobj, - const gfx::Size& real_size, - const gfx::Size& size, - float dp_to_px, - blimp::client::RenderWidgetFeature* render_widget_feature); + BlimpContentsDisplay( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& jobj, + const gfx::Size& real_size, + const gfx::Size& size, + float dp_to_px, + blimp::client::RenderWidgetFeature* render_widget_feature); // Methods called from Java via JNI. void Destroy(JNIEnv* env, const base::android::JavaParamRef<jobject>& jobj); @@ -93,7 +94,7 @@ jint android_meta_state); private: - virtual ~BlimpView(); + virtual ~BlimpContentsDisplay(); void OnSwapBuffersCompleted(); @@ -114,13 +115,13 @@ gfx::AcceleratedWidget window_; - base::WeakPtrFactory<BlimpView> weak_ptr_factory_; + base::WeakPtrFactory<BlimpContentsDisplay> weak_ptr_factory_; - DISALLOW_COPY_AND_ASSIGN(BlimpView); + DISALLOW_COPY_AND_ASSIGN(BlimpContentsDisplay); }; } // namespace app } // namespace client } // namespace blimp -#endif // BLIMP_CLIENT_APP_ANDROID_BLIMP_VIEW_H_ +#endif // BLIMP_CLIENT_APP_ANDROID_BLIMP_CONTENTS_DISPLAY_H_
diff --git a/blimp/client/app/android/java/res/layout/blimp_main.xml b/blimp/client/app/android/java/res/layout/blimp_main.xml index 75190189..fb84581 100644 --- a/blimp/client/app/android/java/res/layout/blimp_main.xml +++ b/blimp/client/app/android/java/res/layout/blimp_main.xml
@@ -9,7 +9,7 @@ android:layout_height="match_parent" android:orientation="vertical"> <!-- Toolbar --> - <org.chromium.blimp.toolbar.Toolbar + <org.chromium.blimp.app.toolbar.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="56dp" @@ -18,7 +18,7 @@ android:orientation="horizontal" android:gravity="center" android:background="#f2f2f2"> - <org.chromium.blimp.toolbar.UrlBar + <org.chromium.blimp.app.toolbar.UrlBar android:id="@+id/toolbar_url_bar" android:layout_width="0dp" android:layout_height="48dp" @@ -53,10 +53,10 @@ android:layout_gravity="center" android:background="@null" android:src="@drawable/btn_menu" /> - </org.chromium.blimp.toolbar.Toolbar> - + </org.chromium.blimp.app.toolbar.Toolbar> + <!-- Content Area --> - <org.chromium.blimp.BlimpView + <org.chromium.blimp.app.BlimpContentsDisplay android:id="@+id/renderer" android:layout_width="match_parent" android:layout_height="match_parent" @@ -70,4 +70,4 @@ android:visibility="invisible" /> </RelativeLayout> -</merge> \ No newline at end of file +</merge>
diff --git a/blimp/client/app/android/java/src/org/chromium/blimp/BlimpApplication.java b/blimp/client/app/android/java/src/org/chromium/blimp/app/BlimpApplication.java similarity index 97% rename from blimp/client/app/android/java/src/org/chromium/blimp/BlimpApplication.java rename to blimp/client/app/android/java/src/org/chromium/blimp/app/BlimpApplication.java index 44b9d0b..2f49d61 100644 --- a/blimp/client/app/android/java/src/org/chromium/blimp/BlimpApplication.java +++ b/blimp/client/app/android/java/src/org/chromium/blimp/app/BlimpApplication.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.blimp; +package org.chromium.blimp.app; import android.app.Application; import android.content.Context;
diff --git a/blimp/client/app/android/java/src/org/chromium/blimp/BlimpView.java b/blimp/client/app/android/java/src/org/chromium/blimp/app/BlimpContentsDisplay.java similarity index 65% rename from blimp/client/app/android/java/src/org/chromium/blimp/BlimpView.java rename to blimp/client/app/android/java/src/org/chromium/blimp/app/BlimpContentsDisplay.java index aaa555b..9c6ce5b4 100644 --- a/blimp/client/app/android/java/src/org/chromium/blimp/BlimpView.java +++ b/blimp/client/app/android/java/src/org/chromium/blimp/app/BlimpContentsDisplay.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.blimp; +package org.chromium.blimp.app; import android.content.Context; import android.graphics.Color; @@ -18,7 +18,7 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; -import org.chromium.blimp.session.BlimpClientSession; +import org.chromium.blimp.app.session.BlimpClientSession; import org.chromium.ui.UiUtils; /** @@ -26,16 +26,16 @@ * a native compositor. */ @JNINamespace("blimp::client::app") -public class BlimpView +public class BlimpContentsDisplay extends SurfaceView implements SurfaceHolder.Callback, View.OnLayoutChangeListener { - private long mNativeBlimpViewPtr; + private long mNativeBlimpContentsDisplayPtr; /** - * Builds a new {@link BlimpView}. + * Builds a new {@link BlimpContentsDisplay}. * @param context A {@link Context} instance. * @param attrs An {@link AttributeSet} instance. */ - public BlimpView(Context context, AttributeSet attrs) { + public BlimpContentsDisplay(Context context, AttributeSet attrs) { super(context, attrs); setFocusable(true); setFocusableInTouchMode(true); @@ -49,7 +49,7 @@ * features required by the native components of the compositor. */ public void initializeRenderer(BlimpClientSession blimpClientSession) { - assert mNativeBlimpViewPtr == 0; + assert mNativeBlimpContentsDisplayPtr == 0; WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); @@ -60,8 +60,8 @@ windowManager.getDefaultDisplay().getRealSize(physicalSize); } float deviceScaleFactor = getContext().getResources().getDisplayMetrics().density; - mNativeBlimpViewPtr = nativeInit(blimpClientSession, physicalSize.x, physicalSize.y, - displaySize.x, displaySize.y, deviceScaleFactor); + mNativeBlimpContentsDisplayPtr = nativeInit(blimpClientSession, physicalSize.x, + physicalSize.y, displaySize.x, displaySize.y, deviceScaleFactor); getHolder().addCallback(this); setBackgroundColor(Color.WHITE); setVisibility(VISIBLE); @@ -73,9 +73,9 @@ */ public void destroyRenderer() { getHolder().removeCallback(this); - if (mNativeBlimpViewPtr != 0) { - nativeDestroy(mNativeBlimpViewPtr); - mNativeBlimpViewPtr = 0; + if (mNativeBlimpContentsDisplayPtr != 0) { + nativeDestroy(mNativeBlimpContentsDisplayPtr); + mNativeBlimpContentsDisplayPtr = 0; } } @@ -83,15 +83,16 @@ @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { - if (mNativeBlimpViewPtr == 0) return; - nativeOnContentAreaSizeChanged(mNativeBlimpViewPtr, right - left, bottom - top, + if (mNativeBlimpContentsDisplayPtr == 0) return; + nativeOnContentAreaSizeChanged(mNativeBlimpContentsDisplayPtr, right - left, bottom - top, getContext().getResources().getDisplayMetrics().density); } // View overrides. @Override public boolean onTouchEvent(MotionEvent event) { - if (mNativeBlimpViewPtr == 0) return false; + // Remove this (integrate with BlimpView). + if (mNativeBlimpContentsDisplayPtr == 0) return false; int eventAction = event.getActionMasked(); @@ -114,23 +115,18 @@ } } - boolean consumed = nativeOnTouchEvent(mNativeBlimpViewPtr, event, - event.getEventTime(), eventAction, - pointerCount, event.getHistorySize(), event.getActionIndex(), - event.getX(), event.getY(), - pointerCount > 1 ? event.getX(1) : 0, - pointerCount > 1 ? event.getY(1) : 0, - event.getPointerId(0), pointerCount > 1 ? event.getPointerId(1) : -1, - touchMajor[0], touchMajor[1], - touchMinor[0], touchMinor[1], - event.getOrientation(), pointerCount > 1 ? event.getOrientation(1) : 0, + boolean consumed = nativeOnTouchEvent(mNativeBlimpContentsDisplayPtr, event, + event.getEventTime(), eventAction, pointerCount, event.getHistorySize(), + event.getActionIndex(), event.getX(), event.getY(), + pointerCount > 1 ? event.getX(1) : 0, pointerCount > 1 ? event.getY(1) : 0, + event.getPointerId(0), pointerCount > 1 ? event.getPointerId(1) : -1, touchMajor[0], + touchMajor[1], touchMinor[0], touchMinor[1], event.getOrientation(), + pointerCount > 1 ? event.getOrientation(1) : 0, event.getAxisValue(MotionEvent.AXIS_TILT), pointerCount > 1 ? event.getAxisValue(MotionEvent.AXIS_TILT, 1) : 0, - event.getRawX(), event.getRawY(), - event.getToolType(0), + event.getRawX(), event.getRawY(), event.getToolType(0), pointerCount > 1 ? event.getToolType(1) : MotionEvent.TOOL_TYPE_UNKNOWN, - event.getButtonState(), - event.getMetaState()); + event.getButtonState(), event.getMetaState()); return consumed; } @@ -147,28 +143,28 @@ // SurfaceHolder.Callback2 interface. @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { - if (mNativeBlimpViewPtr == 0) return; - nativeOnSurfaceChanged(mNativeBlimpViewPtr, format, width, height, holder.getSurface()); + if (mNativeBlimpContentsDisplayPtr == 0) return; + nativeOnSurfaceChanged( + mNativeBlimpContentsDisplayPtr, format, width, height, holder.getSurface()); } @Override public void surfaceCreated(SurfaceHolder holder) { - if (mNativeBlimpViewPtr == 0) return; - nativeOnSurfaceCreated(mNativeBlimpViewPtr); + if (mNativeBlimpContentsDisplayPtr == 0) return; + nativeOnSurfaceCreated(mNativeBlimpContentsDisplayPtr); } @Override public void surfaceDestroyed(SurfaceHolder holder) { - if (mNativeBlimpViewPtr == 0) return; - nativeOnSurfaceDestroyed(mNativeBlimpViewPtr); + if (mNativeBlimpContentsDisplayPtr == 0) return; + nativeOnSurfaceDestroyed(mNativeBlimpContentsDisplayPtr); } private static boolean isValidTouchEventActionForNative(int eventAction) { // Only these actions have any effect on gesture detection. Other // actions have no corresponding WebTouchEvent type and may confuse the // touch pipline, so we ignore them entirely. - return eventAction == MotionEvent.ACTION_DOWN - || eventAction == MotionEvent.ACTION_UP + return eventAction == MotionEvent.ACTION_DOWN || eventAction == MotionEvent.ACTION_UP || eventAction == MotionEvent.ACTION_CANCEL || eventAction == MotionEvent.ACTION_MOVE || eventAction == MotionEvent.ACTION_POINTER_DOWN @@ -185,23 +181,18 @@ // Native Methods private native long nativeInit(BlimpClientSession blimpClientSession, int physicalWidth, int physicalHeight, int displayWidth, int displayHeight, float dpToPixel); - private native void nativeDestroy(long nativeBlimpView); + private native void nativeDestroy(long nativeBlimpContentsDisplay); private native void nativeOnContentAreaSizeChanged( - long nativeBlimpView, int width, int height, float dpToPx); + long nativeBlimpContentsDisplay, int width, int height, float dpToPx); private native void nativeOnSurfaceChanged( - long nativeBlimpView, int format, int width, int height, Surface surface); - private native void nativeOnSurfaceCreated(long nativeBlimpView); - private native void nativeOnSurfaceDestroyed(long nativeBlimpView); - private native boolean nativeOnTouchEvent( - long nativeBlimpView, MotionEvent event, - long timeMs, int action, int pointerCount, int historySize, int actionIndex, - float x0, float y0, float x1, float y1, - int pointerId0, int pointerId1, - float touchMajor0, float touchMajor1, - float touchMinor0, float touchMinor1, - float orientation0, float orientation1, - float tilt0, float tilt1, - float rawX, float rawY, - int androidToolType0, int androidToolType1, - int androidButtonState, int androidMetaState); + long nativeBlimpContentsDisplay, int format, int width, int height, Surface surface); + private native void nativeOnSurfaceCreated(long nativeBlimpContentsDisplay); + private native void nativeOnSurfaceDestroyed(long nativeBlimpContentsDisplay); + private native boolean nativeOnTouchEvent(long nativeBlimpContentsDisplay, MotionEvent event, + long timeMs, int action, int pointerCount, int historySize, int actionIndex, float x0, + float y0, float x1, float y1, int pointerId0, int pointerId1, float touchMajor0, + float touchMajor1, float touchMinor0, float touchMinor1, float orientation0, + float orientation1, float tilt0, float tilt1, float rawX, float rawY, + int androidToolType0, int androidToolType1, int androidButtonState, + int androidMetaState); }
diff --git a/blimp/client/app/android/java/src/org/chromium/blimp/BlimpLibraryLoader.java b/blimp/client/app/android/java/src/org/chromium/blimp/app/BlimpLibraryLoader.java similarity index 99% rename from blimp/client/app/android/java/src/org/chromium/blimp/BlimpLibraryLoader.java rename to blimp/client/app/android/java/src/org/chromium/blimp/app/BlimpLibraryLoader.java index 6136dc9..8cd81c68 100644 --- a/blimp/client/app/android/java/src/org/chromium/blimp/BlimpLibraryLoader.java +++ b/blimp/client/app/android/java/src/org/chromium/blimp/app/BlimpLibraryLoader.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.blimp; +package org.chromium.blimp.app; import android.os.Handler;
diff --git a/blimp/client/app/android/java/src/org/chromium/blimp/BlimpRendererActivity.java b/blimp/client/app/android/java/src/org/chromium/blimp/app/BlimpRendererActivity.java similarity index 91% rename from blimp/client/app/android/java/src/org/chromium/blimp/BlimpRendererActivity.java rename to blimp/client/app/android/java/src/org/chromium/blimp/app/BlimpRendererActivity.java index e07b93a4..d92f4763 100644 --- a/blimp/client/app/android/java/src/org/chromium/blimp/BlimpRendererActivity.java +++ b/blimp/client/app/android/java/src/org/chromium/blimp/app/BlimpRendererActivity.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.blimp; +package org.chromium.blimp.app; import android.annotation.SuppressLint; import android.app.Activity; @@ -17,16 +17,16 @@ import org.chromium.base.Log; import org.chromium.base.annotations.SuppressFBWarnings; import org.chromium.base.library_loader.ProcessInitException; -import org.chromium.blimp.auth.RetryingTokenSource; -import org.chromium.blimp.auth.TokenSource; -import org.chromium.blimp.auth.TokenSourceImpl; +import org.chromium.blimp.app.auth.RetryingTokenSource; +import org.chromium.blimp.app.auth.TokenSource; +import org.chromium.blimp.app.auth.TokenSourceImpl; +import org.chromium.blimp.app.preferences.PreferencesUtil; +import org.chromium.blimp.app.session.BlimpClientSession; +import org.chromium.blimp.app.session.EngineInfo; +import org.chromium.blimp.app.session.TabControlFeature; +import org.chromium.blimp.app.toolbar.Toolbar; +import org.chromium.blimp.app.toolbar.ToolbarMenu; import org.chromium.blimp.core.BlimpClientSwitches; -import org.chromium.blimp.preferences.PreferencesUtil; -import org.chromium.blimp.session.BlimpClientSession; -import org.chromium.blimp.session.EngineInfo; -import org.chromium.blimp.session.TabControlFeature; -import org.chromium.blimp.toolbar.Toolbar; -import org.chromium.blimp.toolbar.ToolbarMenu; import org.chromium.ui.base.WindowAndroid; import org.chromium.ui.widget.Toast; @@ -39,7 +39,7 @@ BlimpClientSession.ConnectionObserver, ToolbarMenu.ToolbarMenuDelegate, Toolbar.ToolbarDelegate { private static final int ACCOUNT_CHOOSER_INTENT_REQUEST_CODE = 100; - private static final String TAG = "BlimpRendererActivity"; + private static final String TAG = "BlimpRendActivity"; // Refresh interval for the debug view in milliseconds. private static final int DEBUG_VIEW_REFRESH_INTERVAL = 1000; @@ -50,7 +50,7 @@ * privileges for a chosen Android account. */ private TokenSource mTokenSource; - private BlimpView mBlimpView; + private BlimpContentsDisplay mBlimpContentsDisplay; private Toolbar mToolbar; private BlimpClientSession mBlimpClientSession; private TabControlFeature mTabControlFeature; @@ -71,7 +71,7 @@ private String mToken = null; @Override - @SuppressFBWarnings("DM_EXIT") // FindBugs doesn't like System.exit(). + @SuppressFBWarnings("DM_EXIT") // FindBugs doesn't like System.exit(). protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); buildAndTriggerTokenSourceIfNeeded(); @@ -91,9 +91,9 @@ mTabControlFeature = null; } - if (mBlimpView != null) { - mBlimpView.destroyRenderer(); - mBlimpView = null; + if (mBlimpContentsDisplay != null) { + mBlimpContentsDisplay.destroyRenderer(); + mBlimpContentsDisplay = null; } if (mToolbar != null) { @@ -157,13 +157,13 @@ new BlimpClientSession(PreferencesUtil.findAssignerUrl(this), mWindowAndroid); mBlimpClientSession.addObserver(this); - mBlimpView = (BlimpView) findViewById(R.id.renderer); - mBlimpView.initializeRenderer(mBlimpClientSession); + mBlimpContentsDisplay = (BlimpContentsDisplay) findViewById(R.id.renderer); + mBlimpContentsDisplay.initializeRenderer(mBlimpClientSession); mToolbar = (Toolbar) findViewById(R.id.toolbar); mToolbar.initialize(mBlimpClientSession, this); - mTabControlFeature = new TabControlFeature(mBlimpClientSession, mBlimpView); + mTabControlFeature = new TabControlFeature(mBlimpClientSession, mBlimpContentsDisplay); handleUrlFromIntent(getIntent());
diff --git a/blimp/client/app/android/java/src/org/chromium/blimp/BrowserRestartActivity.java b/blimp/client/app/android/java/src/org/chromium/blimp/app/BrowserRestartActivity.java similarity index 98% rename from blimp/client/app/android/java/src/org/chromium/blimp/BrowserRestartActivity.java rename to blimp/client/app/android/java/src/org/chromium/blimp/app/BrowserRestartActivity.java index ef7461e..d890f082 100644 --- a/blimp/client/app/android/java/src/org/chromium/blimp/BrowserRestartActivity.java +++ b/blimp/client/app/android/java/src/org/chromium/blimp/app/BrowserRestartActivity.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.blimp; +package org.chromium.blimp.app; import android.app.Activity; import android.content.Context;
diff --git a/blimp/client/app/android/java/src/org/chromium/blimp/auth/RetryingTokenSource.java b/blimp/client/app/android/java/src/org/chromium/blimp/app/auth/RetryingTokenSource.java similarity index 99% rename from blimp/client/app/android/java/src/org/chromium/blimp/auth/RetryingTokenSource.java rename to blimp/client/app/android/java/src/org/chromium/blimp/app/auth/RetryingTokenSource.java index 735eff7b..60407033 100644 --- a/blimp/client/app/android/java/src/org/chromium/blimp/auth/RetryingTokenSource.java +++ b/blimp/client/app/android/java/src/org/chromium/blimp/app/auth/RetryingTokenSource.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.blimp.auth; +package org.chromium.blimp.app.auth; import android.content.Intent; import android.os.Handler;
diff --git a/blimp/client/app/android/java/src/org/chromium/blimp/auth/TokenSource.java b/blimp/client/app/android/java/src/org/chromium/blimp/app/auth/TokenSource.java similarity index 98% rename from blimp/client/app/android/java/src/org/chromium/blimp/auth/TokenSource.java rename to blimp/client/app/android/java/src/org/chromium/blimp/app/auth/TokenSource.java index 1d753afc..f7d544c 100644 --- a/blimp/client/app/android/java/src/org/chromium/blimp/auth/TokenSource.java +++ b/blimp/client/app/android/java/src/org/chromium/blimp/app/auth/TokenSource.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.blimp.auth; +package org.chromium.blimp.app.auth; import android.content.Intent;
diff --git a/blimp/client/app/android/java/src/org/chromium/blimp/auth/TokenSourceImpl.java b/blimp/client/app/android/java/src/org/chromium/blimp/app/auth/TokenSourceImpl.java similarity index 98% rename from blimp/client/app/android/java/src/org/chromium/blimp/auth/TokenSourceImpl.java rename to blimp/client/app/android/java/src/org/chromium/blimp/app/auth/TokenSourceImpl.java index a20d798..9efab83 100644 --- a/blimp/client/app/android/java/src/org/chromium/blimp/auth/TokenSourceImpl.java +++ b/blimp/client/app/android/java/src/org/chromium/blimp/app/auth/TokenSourceImpl.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.blimp.auth; +package org.chromium.blimp.app.auth; import android.accounts.Account; import android.accounts.AccountManager; @@ -20,7 +20,7 @@ import org.chromium.base.ContextUtils; import org.chromium.base.Log; import org.chromium.base.ThreadUtils; -import org.chromium.blimp.R; +import org.chromium.blimp.app.R; import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean;
diff --git a/blimp/client/app/android/java/src/org/chromium/blimp/preferences/PreferencesUtil.java b/blimp/client/app/android/java/src/org/chromium/blimp/app/preferences/PreferencesUtil.java similarity index 92% rename from blimp/client/app/android/java/src/org/chromium/blimp/preferences/PreferencesUtil.java rename to blimp/client/app/android/java/src/org/chromium/blimp/app/preferences/PreferencesUtil.java index c6c1cd7..b90e54f5 100644 --- a/blimp/client/app/android/java/src/org/chromium/blimp/preferences/PreferencesUtil.java +++ b/blimp/client/app/android/java/src/org/chromium/blimp/app/preferences/PreferencesUtil.java
@@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.blimp.preferences; +package org.chromium.blimp.app.preferences; import android.content.Context; import org.chromium.base.ContextUtils; -import org.chromium.blimp.R; +import org.chromium.blimp.app.R; /** * Provides helper methods for storing and retrieving values in android shared preferences. @@ -27,8 +27,8 @@ public static String findAssignerUrl(Context context) { String lastAssigner = getLastUsedAssigner(context); if (lastAssigner.isEmpty()) { - String[] assignerUrls = context.getResources().getStringArray( - R.array.blimp_assigner_urls); + String[] assignerUrls = + context.getResources().getStringArray(R.array.blimp_assigner_urls); assert assignerUrls != null && assignerUrls.length > 0; lastAssigner = assignerUrls[0]; setLastUsedAssigner(context, lastAssigner);
diff --git a/blimp/client/app/android/java/src/org/chromium/blimp/session/BlimpClientSession.java b/blimp/client/app/android/java/src/org/chromium/blimp/app/session/BlimpClientSession.java similarity index 98% rename from blimp/client/app/android/java/src/org/chromium/blimp/session/BlimpClientSession.java rename to blimp/client/app/android/java/src/org/chromium/blimp/app/session/BlimpClientSession.java index 7579a04..659777f 100644 --- a/blimp/client/app/android/java/src/org/chromium/blimp/session/BlimpClientSession.java +++ b/blimp/client/app/android/java/src/org/chromium/blimp/app/session/BlimpClientSession.java
@@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.blimp.session; +package org.chromium.blimp.app.session; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; -import org.chromium.blimp.R; +import org.chromium.blimp.app.R; import org.chromium.blimp_public.session.AssignmentRequestResult; import org.chromium.ui.base.WindowAndroid;
diff --git a/blimp/client/app/android/java/src/org/chromium/blimp/session/EngineInfo.java b/blimp/client/app/android/java/src/org/chromium/blimp/app/session/EngineInfo.java similarity index 94% rename from blimp/client/app/android/java/src/org/chromium/blimp/session/EngineInfo.java rename to blimp/client/app/android/java/src/org/chromium/blimp/app/session/EngineInfo.java index 7425f31..ca8bc6f 100644 --- a/blimp/client/app/android/java/src/org/chromium/blimp/session/EngineInfo.java +++ b/blimp/client/app/android/java/src/org/chromium/blimp/app/session/EngineInfo.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.blimp.session; +package org.chromium.blimp.app.session; /** * Stores the information about the engine.
diff --git a/blimp/client/app/android/java/src/org/chromium/blimp/session/TabControlFeature.java b/blimp/client/app/android/java/src/org/chromium/blimp/app/session/TabControlFeature.java similarity index 95% rename from blimp/client/app/android/java/src/org/chromium/blimp/session/TabControlFeature.java rename to blimp/client/app/android/java/src/org/chromium/blimp/app/session/TabControlFeature.java index 4cbbde6b..4f536c6 100644 --- a/blimp/client/app/android/java/src/org/chromium/blimp/session/TabControlFeature.java +++ b/blimp/client/app/android/java/src/org/chromium/blimp/app/session/TabControlFeature.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.blimp.session; +package org.chromium.blimp.app.session; import android.view.View; @@ -52,8 +52,8 @@ // View.OnLayoutChangeListener implementation. @Override - public void onLayoutChange(View v, int left, int top, int right, int bottom, - int oldLeft, int oldTop, int oldRight, int oldBottom) { + public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, + int oldTop, int oldRight, int oldBottom) { if (mNativeTabControlFeatureAndroidPtr == 0) return; nativeOnContentAreaSizeChanged(mNativeTabControlFeatureAndroidPtr, right - left, bottom - top,
diff --git a/blimp/client/app/android/java/src/org/chromium/blimp/settings/AboutBlimpPreferences.java b/blimp/client/app/android/java/src/org/chromium/blimp/app/settings/AboutBlimpPreferences.java similarity index 95% rename from blimp/client/app/android/java/src/org/chromium/blimp/settings/AboutBlimpPreferences.java rename to blimp/client/app/android/java/src/org/chromium/blimp/app/settings/AboutBlimpPreferences.java index af62ca5..9b6b8ab 100644 --- a/blimp/client/app/android/java/src/org/chromium/blimp/settings/AboutBlimpPreferences.java +++ b/blimp/client/app/android/java/src/org/chromium/blimp/app/settings/AboutBlimpPreferences.java
@@ -2,10 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.blimp.settings; +package org.chromium.blimp.app.settings; import android.app.Activity; -import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; @@ -17,12 +16,13 @@ import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceFragment; +import android.support.v7.app.AlertDialog; import android.text.TextUtils; import org.chromium.base.Log; -import org.chromium.blimp.BrowserRestartActivity; -import org.chromium.blimp.R; -import org.chromium.blimp.preferences.PreferencesUtil; +import org.chromium.blimp.app.BrowserRestartActivity; +import org.chromium.blimp.app.R; +import org.chromium.blimp.app.preferences.PreferencesUtil; /** * Fragment to display blimp client and engine version related info.
diff --git a/blimp/client/app/android/java/src/org/chromium/blimp/settings/Preferences.java b/blimp/client/app/android/java/src/org/chromium/blimp/app/settings/Preferences.java similarity index 94% rename from blimp/client/app/android/java/src/org/chromium/blimp/settings/Preferences.java rename to blimp/client/app/android/java/src/org/chromium/blimp/app/settings/Preferences.java index 7cfcdac2..4a64c9c 100644 --- a/blimp/client/app/android/java/src/org/chromium/blimp/settings/Preferences.java +++ b/blimp/client/app/android/java/src/org/chromium/blimp/app/settings/Preferences.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.blimp.settings; +package org.chromium.blimp.app.settings; import android.app.Activity; import android.os.Bundle;
diff --git a/blimp/client/app/android/java/src/org/chromium/blimp/toolbar/Toolbar.java b/blimp/client/app/android/java/src/org/chromium/blimp/app/toolbar/Toolbar.java similarity index 98% rename from blimp/client/app/android/java/src/org/chromium/blimp/toolbar/Toolbar.java rename to blimp/client/app/android/java/src/org/chromium/blimp/app/toolbar/Toolbar.java index 93dfaf0..b1c11e9 100644 --- a/blimp/client/app/android/java/src/org/chromium/blimp/toolbar/Toolbar.java +++ b/blimp/client/app/android/java/src/org/chromium/blimp/app/toolbar/Toolbar.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.blimp.toolbar; +package org.chromium.blimp.app.toolbar; import android.content.Context; import android.graphics.Bitmap; @@ -15,8 +15,8 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; -import org.chromium.blimp.R; -import org.chromium.blimp.session.BlimpClientSession; +import org.chromium.blimp.app.R; +import org.chromium.blimp.app.session.BlimpClientSession; /** * A {@link View} that visually represents the Blimp toolbar, which lets users issue navigation
diff --git a/blimp/client/app/android/java/src/org/chromium/blimp/toolbar/ToolbarMenu.java b/blimp/client/app/android/java/src/org/chromium/blimp/app/toolbar/ToolbarMenu.java similarity index 95% rename from blimp/client/app/android/java/src/org/chromium/blimp/toolbar/ToolbarMenu.java rename to blimp/client/app/android/java/src/org/chromium/blimp/app/toolbar/ToolbarMenu.java index 6d8b5d2..e25e26dc 100644 --- a/blimp/client/app/android/java/src/org/chromium/blimp/toolbar/ToolbarMenu.java +++ b/blimp/client/app/android/java/src/org/chromium/blimp/app/toolbar/ToolbarMenu.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.blimp.toolbar; +package org.chromium.blimp.app.toolbar; import android.content.ActivityNotFoundException; import android.content.Context; @@ -15,11 +15,11 @@ import android.widget.ListPopupWindow; import org.chromium.base.Log; -import org.chromium.blimp.R; -import org.chromium.blimp.session.BlimpClientSession; -import org.chromium.blimp.session.EngineInfo; -import org.chromium.blimp.settings.AboutBlimpPreferences; -import org.chromium.blimp.settings.Preferences; +import org.chromium.blimp.app.R; +import org.chromium.blimp.app.session.BlimpClientSession; +import org.chromium.blimp.app.session.EngineInfo; +import org.chromium.blimp.app.settings.AboutBlimpPreferences; +import org.chromium.blimp.app.settings.Preferences; import java.util.ArrayList; import java.util.List;
diff --git a/blimp/client/app/android/java/src/org/chromium/blimp/toolbar/UrlBar.java b/blimp/client/app/android/java/src/org/chromium/blimp/app/toolbar/UrlBar.java similarity index 94% rename from blimp/client/app/android/java/src/org/chromium/blimp/toolbar/UrlBar.java rename to blimp/client/app/android/java/src/org/chromium/blimp/app/toolbar/UrlBar.java index 55d44fa..18202ceb4 100644 --- a/blimp/client/app/android/java/src/org/chromium/blimp/toolbar/UrlBar.java +++ b/blimp/client/app/android/java/src/org/chromium/blimp/app/toolbar/UrlBar.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.blimp.toolbar; +package org.chromium.blimp.app.toolbar; import android.content.Context; import android.util.AttributeSet; @@ -69,7 +69,7 @@ public boolean onKey(View view, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_UP && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER - || event.getKeyCode() == KeyEvent.KEYCODE_NUMPAD_ENTER)) { + || event.getKeyCode() == KeyEvent.KEYCODE_NUMPAD_ENTER)) { UiUtils.hideKeyboard(view); clearFocus(); for (UrlBarObserver observer : mObservers) {
diff --git a/blimp/client/app/android/javatests/src/org/chromium/blimp/BlimpNativeInstrumentationTestCase.java b/blimp/client/app/android/javatests/src/org/chromium/blimp/app/BlimpNativeInstrumentationTestCase.java similarity index 98% rename from blimp/client/app/android/javatests/src/org/chromium/blimp/BlimpNativeInstrumentationTestCase.java rename to blimp/client/app/android/javatests/src/org/chromium/blimp/app/BlimpNativeInstrumentationTestCase.java index 5a9e4992..12054e9 100644 --- a/blimp/client/app/android/javatests/src/org/chromium/blimp/BlimpNativeInstrumentationTestCase.java +++ b/blimp/client/app/android/javatests/src/org/chromium/blimp/app/BlimpNativeInstrumentationTestCase.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.blimp; +package org.chromium.blimp.app; import android.test.InstrumentationTestCase;
diff --git a/blimp/client/app/android/javatests/src/org/chromium/blimp/auth/MockTokenSource.java b/blimp/client/app/android/javatests/src/org/chromium/blimp/app/auth/MockTokenSource.java similarity index 94% rename from blimp/client/app/android/javatests/src/org/chromium/blimp/auth/MockTokenSource.java rename to blimp/client/app/android/javatests/src/org/chromium/blimp/app/auth/MockTokenSource.java index ea3691d..5fade2b 100644 --- a/blimp/client/app/android/javatests/src/org/chromium/blimp/auth/MockTokenSource.java +++ b/blimp/client/app/android/javatests/src/org/chromium/blimp/app/auth/MockTokenSource.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.blimp.auth; +package org.chromium.blimp.app.auth; import android.content.Intent; import android.os.Handler; @@ -62,8 +62,8 @@ public void getToken() { Assert.assertFalse("getToken() called after already returning a successful token.", isRetrievingToken()); - Assert.assertFalse("getToken() called after failing in an unrecoverable way.", - mAlreadyFailedHard); + Assert.assertFalse( + "getToken() called after failing in an unrecoverable way.", mAlreadyFailedHard); sendEmptyMessage(MSG_QUERY_TOKEN); }
diff --git a/blimp/client/app/android/javatests/src/org/chromium/blimp/auth/RetryingTokenSourceTest.java b/blimp/client/app/android/javatests/src/org/chromium/blimp/app/auth/RetryingTokenSourceTest.java similarity index 88% rename from blimp/client/app/android/javatests/src/org/chromium/blimp/auth/RetryingTokenSourceTest.java rename to blimp/client/app/android/javatests/src/org/chromium/blimp/app/auth/RetryingTokenSourceTest.java index 33fa7c5..be934b6 100644 --- a/blimp/client/app/android/javatests/src/org/chromium/blimp/auth/RetryingTokenSourceTest.java +++ b/blimp/client/app/android/javatests/src/org/chromium/blimp/app/auth/RetryingTokenSourceTest.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.blimp.auth; +package org.chromium.blimp.app.auth; import android.content.Intent; import android.test.InstrumentationTestCase; @@ -109,11 +109,8 @@ } private AtomicReference<TestRetryingTokenSource> buildAndTriggerTokenSource( - final String correctToken, - final int transientFailures, - final boolean hardFailure, - final Semaphore successSemaphore, - final Semaphore failureSemaphore, + final String correctToken, final int transientFailures, final boolean hardFailure, + final Semaphore successSemaphore, final Semaphore failureSemaphore, final Semaphore needsAccountSemaphore) { final AtomicReference<TestRetryingTokenSource> tokenSource = new AtomicReference<TestRetryingTokenSource>(); @@ -122,8 +119,8 @@ public void run() { TokenSource mockTokenSource = new MockTokenSource(correctToken, transientFailures, hardFailure); - tokenSource.set(new TestRetryingTokenSource(mockTokenSource, - successSemaphore, failureSemaphore, needsAccountSemaphore)); + tokenSource.set(new TestRetryingTokenSource(mockTokenSource, successSemaphore, + failureSemaphore, needsAccountSemaphore)); tokenSource.get().getToken(); assertTrue("RetryingTokenSource is not attempting to get a token.", tokenSource.get().isRetrievingToken()); @@ -133,8 +130,7 @@ } private void validateTokenSourceResults( - final AtomicReference<TestRetryingTokenSource> tokenSource, - final String expectedToken, + final AtomicReference<TestRetryingTokenSource> tokenSource, final String expectedToken, final int expectedTransientFailures) { getInstrumentation().runOnMainSync(new Runnable() { @Override @@ -150,12 +146,11 @@ for (int i = 0; i < delays.size(); i++) { Integer delay = delays.get(i); assertTrue("RetryingTokenSource did not increase delays between attempts " - + "(" + prevDelay + " < " + delay + " failed).", + + "(" + prevDelay + " < " + delay + " failed).", prevDelay < delay); - assertTrue("RetryingTokenSource used a negative delay.", - delay >= 0); - assertTrue("RetryingTokenSource used no delay for retries.", - delay > 0 || i == 0); + assertTrue("RetryingTokenSource used a negative delay.", delay >= 0); + assertTrue( + "RetryingTokenSource used no delay for retries.", delay > 0 || i == 0); prevDelay = delay; } } @@ -195,9 +190,8 @@ Semaphore success = new Semaphore(0); Semaphore failure = new Semaphore(0); Semaphore needsAccount = new Semaphore(0); - AtomicReference<TestRetryingTokenSource> tokenSource = - buildAndTriggerTokenSource(TEST_TOKEN, failureCount, false, success, failure, - needsAccount); + AtomicReference<TestRetryingTokenSource> tokenSource = buildAndTriggerTokenSource( + TEST_TOKEN, failureCount, false, success, failure, needsAccount); assertTrue("Did not receive a successful token in time.", success.tryAcquire(SEMAPHORE_TIMEOUT_MS, TimeUnit.MILLISECONDS)); @@ -219,9 +213,8 @@ Semaphore success = new Semaphore(0); Semaphore failure = new Semaphore(0); Semaphore needsAccount = new Semaphore(0); - AtomicReference<TestRetryingTokenSource> tokenSource = - buildAndTriggerTokenSource(TEST_TOKEN, failureCount, true, success, failure, - needsAccount); + AtomicReference<TestRetryingTokenSource> tokenSource = buildAndTriggerTokenSource( + TEST_TOKEN, failureCount, true, success, failure, needsAccount); assertTrue("Did not receive a failure in time.", failure.tryAcquire(SEMAPHORE_TIMEOUT_MS, TimeUnit.MILLISECONDS)); @@ -243,9 +236,8 @@ Semaphore success = new Semaphore(0); Semaphore failure = new Semaphore(0); Semaphore needsAccount = new Semaphore(0); - AtomicReference<TestRetryingTokenSource> tokenSource = - buildAndTriggerTokenSource(TEST_TOKEN, failureCount, false, success, failure, - needsAccount); + AtomicReference<TestRetryingTokenSource> tokenSource = buildAndTriggerTokenSource( + TEST_TOKEN, failureCount, false, success, failure, needsAccount); assertTrue("Did not receive a failure in time.", failure.tryAcquire(SEMAPHORE_TIMEOUT_MS, TimeUnit.MILLISECONDS));
diff --git a/blimp/client/core/input/blimp_input_manager.h b/blimp/client/core/input/blimp_input_manager.h index 8053427..23787a7 100644 --- a/blimp/client/core/input/blimp_input_manager.h +++ b/blimp/client/core/input/blimp_input_manager.h
@@ -12,7 +12,8 @@ #include "base/single_thread_task_runner.h" #include "base/synchronization/waitable_event.h" #include "base/threading/thread_checker.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/gesture_detection/filtered_gesture_provider.h" #include "ui/events/gesture_detection/motion_event.h"
diff --git a/blimp/client/core/render_widget/mock_render_widget_feature.cc b/blimp/client/core/render_widget/mock_render_widget_feature.cc index f3dfa4d..c19013f 100644 --- a/blimp/client/core/render_widget/mock_render_widget_feature.cc +++ b/blimp/client/core/render_widget/mock_render_widget_feature.cc
@@ -4,6 +4,8 @@ #include "blimp/client/core/render_widget/mock_render_widget_feature.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" + namespace blimp { namespace client {
diff --git a/blimp/client/core/render_widget/mock_render_widget_feature.h b/blimp/client/core/render_widget/mock_render_widget_feature.h index f5da239..119a910 100644 --- a/blimp/client/core/render_widget/mock_render_widget_feature.h +++ b/blimp/client/core/render_widget/mock_render_widget_feature.h
@@ -10,7 +10,7 @@ #include "base/macros.h" #include "cc/proto/compositor_message.pb.h" #include "testing/gmock/include/gmock/gmock.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" namespace blimp { namespace client {
diff --git a/blimp/engine/DEPS b/blimp/engine/DEPS index 52d1018..7e4c0fe 100644 --- a/blimp/engine/DEPS +++ b/blimp/engine/DEPS
@@ -16,7 +16,8 @@ "+services/service_manager/public/cpp", "+third_party/blimp_fonts", "+third_party/khronos/GLES2/gl2.h", - "+third_party/WebKit/public/web/WebInputEvent.h", + "+third_party/WebKit/public/platform/WebGestureEvent.h", + "+third_party/WebKit/public/platform/WebInputEvent.h", "+ui/aura", "+ui/base", "+ui/compositor",
diff --git a/blimp/engine/browser_tests/input_browsertest.cc b/blimp/engine/browser_tests/input_browsertest.cc index 44553ce..377e2ad 100644 --- a/blimp/engine/browser_tests/input_browsertest.cc +++ b/blimp/engine/browser_tests/input_browsertest.cc
@@ -19,7 +19,8 @@ #include "net/base/ip_endpoint.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/gfx/geometry/size.h" #include "url/gurl.h"
diff --git a/blimp/engine/feature/engine_render_widget_feature.cc b/blimp/engine/feature/engine_render_widget_feature.cc index 7de5e8b39..ff7f7b9 100644 --- a/blimp/engine/feature/engine_render_widget_feature.cc +++ b/blimp/engine/feature/engine_render_widget_feature.cc
@@ -15,7 +15,7 @@ #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "net/base/net_errors.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/event.h" #include "ui/events/keycodes/dom/dom_code.h"
diff --git a/blimp/engine/feature/engine_render_widget_feature_unittest.cc b/blimp/engine/feature/engine_render_widget_feature_unittest.cc index e5a868c..3d315b79 100644 --- a/blimp/engine/feature/engine_render_widget_feature_unittest.cc +++ b/blimp/engine/feature/engine_render_widget_feature_unittest.cc
@@ -21,7 +21,7 @@ #include "net/base/test_completion_callback.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/base/ime/dummy_text_input_client.h" using testing::_;
diff --git a/blimp/engine/session/page_load_tracker.cc b/blimp/engine/session/page_load_tracker.cc index 24e3a48..3345d06dc 100644 --- a/blimp/engine/session/page_load_tracker.cc +++ b/blimp/engine/session/page_load_tracker.cc
@@ -4,6 +4,7 @@ #include "blimp/engine/session/page_load_tracker.h" +#include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_widget_host_view.h" namespace blimp { @@ -11,12 +12,16 @@ namespace { -content::RenderWidgetHost* GetRenderWidgetHostIfMainFrame( - content::RenderFrameHost* render_frame_host) { - if (render_frame_host->GetParent() != nullptr) - return nullptr; +bool ShouldIgnoreNavigation(content::NavigationHandle* navigation_handle) { + // We change the progress bar for main frame navigations only. + if (!navigation_handle->IsInMainFrame()) + return true; - return render_frame_host->GetView()->GetRenderWidgetHost(); + // Same page navigations don't need to trigger a progress bar update. + if (navigation_handle->IsSamePage()) + return true; + + return false; } } // namespace @@ -30,74 +35,40 @@ PageLoadTracker::~PageLoadTracker() {} -void PageLoadTracker::DidStartProvisionalLoadForFrame( - content::RenderFrameHost* render_frame_host, - const GURL& validated_url, - bool is_error_page, - bool is_iframe_srcdoc) { - content::RenderWidgetHost* render_widget_host = - GetRenderWidgetHostIfMainFrame(render_frame_host); - if (!render_widget_host) +void PageLoadTracker::DidStartNavigation( + content::NavigationHandle* navigation_handle) { + if (ShouldIgnoreNavigation(navigation_handle)) return; - render_widget_load_status_[render_widget_host] = LoadStatus(); - - // Notify the client that a navigation was initiated. + // Cancel any pending callbacks for the previous navigation. We will send an + // update based on the progress of this navigation. + did_paint_after_navigation_callback_.Cancel(); client_->SendPageLoadStatusUpdate(PageLoadStatus::LOADING); } -void PageLoadTracker::DidFinishLoad(content::RenderFrameHost* render_frame_host, - const GURL& validated_url) { - content::RenderWidgetHost* render_widget_host = - GetRenderWidgetHostIfMainFrame(render_frame_host); - if (!render_widget_host) +void PageLoadTracker::DidFinishNavigation( + content::NavigationHandle* navigation_handle) { + if (ShouldIgnoreNavigation(navigation_handle)) return; - RenderWidgetLoadStatusMap::iterator it = - render_widget_load_status_.find(render_widget_host); - DCHECK(it != render_widget_load_status_.end()); - - it->second.page_loaded = true; - if (it->second.Loaded()) { + if (navigation_handle->HasCommitted()) { + // Make sure that at least one compositor content update after the + // navigation commits is sent to the client. + // Note that a visual state update in our case implies that this callback + // will be invoked after the update is queued to be sent to the client. + did_paint_after_navigation_callback_.Reset( + base::Bind(&PageLoadTracker::DidPaintAfterNavigationCommitted, + base::Unretained(this))); + navigation_handle->GetRenderFrameHost()->InsertVisualStateCallback( + did_paint_after_navigation_callback_.callback()); + } else { + // Inform the client to update the progress bar right away. client_->SendPageLoadStatusUpdate(PageLoadStatus::LOADED); - render_widget_load_status_.erase(it); } } -void PageLoadTracker::DidFailLoad(content::RenderFrameHost* render_frame_host, - const GURL& validated_url, - int error_code, - const base::string16& error_description, - bool was_ignored_by_handler) { - content::RenderWidgetHost* render_widget_host = - GetRenderWidgetHostIfMainFrame(render_frame_host); - if (!render_widget_host) - return; - - RenderWidgetLoadStatusMap::iterator it = - render_widget_load_status_.find(render_widget_host); - DCHECK(it != render_widget_load_status_.end()); - - // If the navigation failed, the client should dismiss the load indicator. +void PageLoadTracker::DidPaintAfterNavigationCommitted(bool result) { client_->SendPageLoadStatusUpdate(PageLoadStatus::LOADED); - render_widget_load_status_.erase(it); -} - -void PageLoadTracker::DidFirstPaintAfterLoad( - content::RenderWidgetHost* render_widget_host) { - RenderWidgetLoadStatusMap::iterator it = - render_widget_load_status_.find(render_widget_host); - DCHECK(it != render_widget_load_status_.end()); - - it->second.did_first_paint = true; - if (it->second.Loaded()) { - client_->SendPageLoadStatusUpdate(PageLoadStatus::LOADED); - render_widget_load_status_.erase(it); - } -} - -bool PageLoadTracker::LoadStatus::Loaded() const { - return page_loaded && did_first_paint; } } // namespace engine
diff --git a/blimp/engine/session/page_load_tracker.h b/blimp/engine/session/page_load_tracker.h index 2a1d02c..55d509a0 100644 --- a/blimp/engine/session/page_load_tracker.h +++ b/blimp/engine/session/page_load_tracker.h
@@ -5,7 +5,7 @@ #ifndef BLIMP_ENGINE_SESSION_PAGE_LOAD_TRACKER_H_ #define BLIMP_ENGINE_SESSION_PAGE_LOAD_TRACKER_H_ -#include "base/containers/small_map.h" +#include "base/cancelable_callback.h" #include "base/macros.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_widget_host.h" @@ -37,39 +37,17 @@ ~PageLoadTracker() override; private: - struct LoadStatus { - // Set to true on receiving a notification from the renderer that the load - // finished. See WebContentsObserver::DidFinishLoad. - bool page_loaded = false; - - // Set to true on receiving a notification from the renderer that the first - // paint after a navigation was performed. - // See WebContentsObserver::DidFirstPaintAfterLoad. - bool did_first_paint = false; - - bool Loaded() const; - }; - - typedef base::SmallMap<std::map<content::RenderWidgetHost*, LoadStatus>> - RenderWidgetLoadStatusMap; - // content::WebContentsObserver implementation. - void DidStartProvisionalLoadForFrame( - content::RenderFrameHost* render_frame_host, - const GURL& validated_url, - bool is_error_page, - bool is_iframe_srcdoc) override; - void DidFinishLoad(content::RenderFrameHost* render_frame_host, - const GURL& validated_url) override; - void DidFailLoad(content::RenderFrameHost* render_frame_host, - const GURL& validated_url, - int error_code, - const base::string16& error_description, - bool was_ignored_by_handler) override; - void DidFirstPaintAfterLoad( - content::RenderWidgetHost* render_widget_host) override; + void DidStartNavigation( + content::NavigationHandle* navigation_handle) override; + void DidFinishNavigation( + content::NavigationHandle* navigation_handle) override; - RenderWidgetLoadStatusMap render_widget_load_status_; + // Invoked when the renderer has performed at least one paint after the + // navigation was committed. + void DidPaintAfterNavigationCommitted(bool result); + + base::CancelableCallback<void(bool)> did_paint_after_navigation_callback_; PageLoadTrackerClient* client_;
diff --git a/blimp/net/DEPS b/blimp/net/DEPS index 9b51d8d..83020fb1 100644 --- a/blimp/net/DEPS +++ b/blimp/net/DEPS
@@ -1,7 +1,8 @@ include_rules = [ "+net", "+third_party/WebKit/public/platform/WebGestureDevice.h", - "+third_party/WebKit/public/web/WebInputEvent.h", + "+third_party/WebKit/public/platform/WebGestureEvent.h", + "+third_party/WebKit/public/platform/WebInputEvent.h", "+third_party/grpc", "+third_party/zlib", "+ui/base/ime/text_input_type.h",
diff --git a/blimp/net/input_message_converter.cc b/blimp/net/input_message_converter.cc index 19366af..cb0ed87 100644 --- a/blimp/net/input_message_converter.cc +++ b/blimp/net/input_message_converter.cc
@@ -7,7 +7,7 @@ #include "base/logging.h" #include "blimp/common/proto/input.pb.h" #include "third_party/WebKit/public/platform/WebGestureDevice.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" namespace blimp { namespace {
diff --git a/blimp/net/input_message_generator.cc b/blimp/net/input_message_generator.cc index 2c62b6ba..fb5864f8 100644 --- a/blimp/net/input_message_generator.cc +++ b/blimp/net/input_message_generator.cc
@@ -10,7 +10,7 @@ #include "blimp/common/proto/input.pb.h" #include "blimp/net/blimp_message_processor.h" #include "third_party/WebKit/public/platform/WebGestureDevice.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" namespace blimp { namespace {
diff --git a/blimp/net/input_message_unittest.cc b/blimp/net/input_message_unittest.cc index 86bd555..1c2fc43 100644 --- a/blimp/net/input_message_unittest.cc +++ b/blimp/net/input_message_unittest.cc
@@ -13,7 +13,7 @@ #include "blimp/net/input_message_generator.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/public/platform/WebGestureDevice.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" namespace blimp { namespace {
diff --git a/blimp/tools/client_engine_integration.py b/blimp/tools/client_engine_integration.py index e28c641..f1fabec 100755 --- a/blimp/tools/client_engine_integration.py +++ b/blimp/tools/client_engine_integration.py
@@ -25,6 +25,12 @@ DEVIL_PATH = os.path.join(SRC_PATH, 'third_party', 'catapult', 'devil') +DEVIL_CHROMIUM_PATH = os.path.join(SRC_PATH, 'build', 'android') + +if DEVIL_CHROMIUM_PATH not in sys.path: + sys.path.append(DEVIL_CHROMIUM_PATH) + +import devil_chromium if DEVIL_PATH not in sys.path: sys.path.append(DEVIL_PATH) @@ -273,6 +279,9 @@ required=True, help='Path to the root linux build directory.' ' Example: "out-linux/Debug"') + parser.add_argument('--adb-path', + type=os.path.abspath, + help='Path to the adb binary.') subparsers = parser.add_subparsers(dest="subparser_name") start_parser = subparsers.add_parser('start') @@ -299,6 +308,7 @@ stop_parser.set_defaults(func=_Stop) args = parser.parse_args() + devil_chromium.Initialize(adb_path=args.adb_path) json_file_path = os.path.join(SRC_PATH, args.output_linux_directory, ARGS_JSON_FILE)
diff --git a/build/android/pylib/gtest/gtest_test_instance.py b/build/android/pylib/gtest/gtest_test_instance.py index e289c02a..9cf76a27 100644 --- a/build/android/pylib/gtest/gtest_test_instance.py +++ b/build/android/pylib/gtest/gtest_test_instance.py
@@ -235,10 +235,11 @@ # TODO(jbudorick): Support multiple test suites. if len(args.suite_name) > 1: raise ValueError('Platform mode currently supports only 1 gtest suite') + self._exe_dist_dir = None self._extract_test_list_from_filter = args.extract_test_list_from_filter self._shard_timeout = args.shard_timeout + self._store_tombstones = args.store_tombstones self._suite = args.suite_name[0] - self._exe_dist_dir = None # GYP: if args.executable_dist_dir: @@ -366,6 +367,10 @@ return self._shard_timeout @property + def store_tombstones(self): + return self._store_tombstones + + @property def suite(self): return self._suite
diff --git a/build/android/pylib/instrumentation/instrumentation_test_instance.py b/build/android/pylib/instrumentation/instrumentation_test_instance.py index d393a58..566eb6e 100644 --- a/build/android/pylib/instrumentation/instrumentation_test_instance.py +++ b/build/android/pylib/instrumentation/instrumentation_test_instance.py
@@ -50,6 +50,8 @@ _PARAMETERIZED_TEST_ANNOTATION = 'ParameterizedTest' _PARAMETERIZED_TEST_SET_ANNOTATION = 'ParameterizedTest$Set' _NATIVE_CRASH_RE = re.compile('(process|native) crash', re.IGNORECASE) +_CMDLINE_NAME_SEGMENT_RE = re.compile( + r' with(?:out)? \{[^\}]*\}') _PICKLE_FORMAT_VERSION = 10 @@ -220,12 +222,19 @@ Return: A list of filtered tests """ - def gtest_filter(c, m): + def gtest_filter(t): if not test_filter: return True # Allow fully-qualified name as well as an omitted package. - names = ['%s.%s' % (c['class'], m['method']), - '%s.%s' % (c['class'].split('.')[-1], m['method'])] + unqualified_class_test = { + 'class': t['class'].split('.')[-1], + 'method': t['method'] + } + names = [ + GetTestName(t, sep='.'), + GetTestName(unqualified_class_test, sep='.'), + GetUniqueTestName(t, sep='.') + ] return unittest_util.FilterTestNames(names, test_filter) def annotation_filter(all_annotations): @@ -254,33 +263,24 @@ return filter_av in av return filter_av == av - filtered_classes = [] - for c in tests: - filtered_methods = [] - for m in c['methods']: - # Gtest filtering - if not gtest_filter(c, m): - continue + filtered_tests = [] + for t in tests: + # Gtest filtering + if not gtest_filter(t): + continue - all_annotations = dict(c['annotations']) - all_annotations.update(m['annotations']) + # Enforce that all tests declare their size. + if not any(a in _VALID_ANNOTATIONS for a in t['annotations']): + raise MissingSizeAnnotationError(GetTestName(t)) - # Enforce that all tests declare their size. - if not any(a in _VALID_ANNOTATIONS for a in all_annotations): - raise MissingSizeAnnotationError('%s.%s' % (c['class'], m['method'])) + if (not annotation_filter(t['annotations']) + or not excluded_annotation_filter(t['annotations'])): + continue - if (not annotation_filter(all_annotations) - or not excluded_annotation_filter(all_annotations)): - continue + filtered_tests.append(t) - filtered_methods.append(m) + return filtered_tests - if filtered_methods: - filtered_class = dict(c) - filtered_class['methods'] = filtered_methods - filtered_classes.append(filtered_class) - - return filtered_classes def GetAllTests(test_jar): pickle_path = '%s-proguard.pickle' % test_jar @@ -361,6 +361,43 @@ 'Test filter "%s" matched no tests.' % test_filter) +def GetTestName(test, sep='#'): + """Gets the name of the given test. + + Note that this may return the same name for more than one test, e.g. if a + test is being run multiple times with different parameters. + + Args: + test: the instrumentation test dict. + sep: the character(s) that should join the class name and the method name. + Returns: + The test name as a string. + """ + return '%s%s%s' % (test['class'], sep, test['method']) + + +def GetUniqueTestName(test, sep='#'): + """Gets the unique name of the given test. + + This will include text to disambiguate between tests for which GetTestName + would return the same name. + + Args: + test: the instrumentation test dict. + sep: the character(s) that should join the class name and the method name. + Returns: + The unique test name as a string. + """ + display_name = GetTestName(test, sep=sep) + if 'flags' in test: + flags = test['flags'] + if flags.add: + display_name = '%s with {%s}' % (display_name, ' '.join(flags.add)) + if flags.remove: + display_name = '%s without {%s}' % (display_name, ' '.join(flags.remove)) + return display_name + + class InstrumentationTestInstance(test_instance.TestInstance): def __init__(self, args, isolate_delegate, error_func): @@ -503,7 +540,8 @@ def _initializeTestFilterAttributes(self, args): if args.test_filter: - self._test_filter = args.test_filter.replace('#', '.') + self._test_filter = _CMDLINE_NAME_SEGMENT_RE.sub( + '', args.test_filter.replace('#', '.')) def annotation_element(a): a = a.split('=', 1) @@ -661,11 +699,15 @@ def GetTests(self): tests = GetAllTests(self.test_jar) + inflated_tests = self._ParametrizeTestsWithFlags(self._InflateTests(tests)) filtered_tests = FilterTests( - tests, self._test_filter, self._annotations, self._excluded_annotations) + inflated_tests, self._test_filter, self._annotations, + self._excluded_annotations) if self._test_filter and not filtered_tests: + for t in inflated_tests: + logging.debug(' %s', GetUniqueTestName(t)) raise UnmatchedFilterException(self._test_filter) - return self._ParametrizeTestsWithFlags(self._InflateTests(filtered_tests)) + return filtered_tests # pylint: disable=no-self-use def _InflateTests(self, tests):
diff --git a/build/android/pylib/local/device/local_device_gtest_run.py b/build/android/pylib/local/device/local_device_gtest_run.py index 6796734..4a612b8 100644 --- a/build/android/pylib/local/device/local_device_gtest_run.py +++ b/build/android/pylib/local/device/local_device_gtest_run.py
@@ -18,6 +18,7 @@ from pylib.local import local_test_server_spawner from pylib.local.device import local_device_environment from pylib.local.device import local_device_test_run +import tombstones _MAX_INLINE_FLAGS_LENGTH = 50 # Arbitrarily chosen. _EXTRA_COMMAND_LINE_FILE = ( @@ -356,6 +357,8 @@ # Run the test. timeout = (self._test_instance.shard_timeout * self.GetTool(device).GetTimeoutScale()) + if self._test_instance.store_tombstones: + tombstones.ClearAllTombstones(device) with device_temp_file.DeviceTempFile( adb=device.adb, dir=self._delegate.ResultsDirectory(device), @@ -392,6 +395,18 @@ # Check whether there are any crashed testcases. self._crashes.update(r.GetName() for r in results if r.GetType() == base_test_result.ResultType.CRASH) + + if self._test_instance.store_tombstones: + resolved_tombstones = None + for result in results: + if result.GetType() == base_test_result.ResultType.CRASH: + if not resolved_tombstones: + resolved_tombstones = '\n'.join(tombstones.ResolveTombstones( + device, + resolve_all_tombstones=True, + include_stack_symbols=False, + wipe_tombstones=True)) + result.SetTombstones(resolved_tombstones) return results #override
diff --git a/build/android/pylib/local/device/local_device_instrumentation_test_run.py b/build/android/pylib/local/device/local_device_instrumentation_test_run.py index 59d43a9..2705289f 100644 --- a/build/android/pylib/local/device/local_device_instrumentation_test_run.py +++ b/build/android/pylib/local/device/local_device_instrumentation_test_run.py
@@ -13,6 +13,7 @@ from devil.utils import reraiser_thread from pylib import valgrind_tools from pylib.base import base_test_result +from pylib.instrumentation import instrumentation_test_instance from pylib.local.device import local_device_environment from pylib.local.device import local_device_test_run import tombstones @@ -182,21 +183,9 @@ def _GetTests(self): return self._test_instance.GetTests() - def _GetTestName(self, test): - # pylint: disable=no-self-use - return '%s#%s' % (test['class'], test['method']) - #override def _GetUniqueTestName(self, test): - display_name = self._GetTestName(test) - if 'flags' in test: - flags = test['flags'] - if flags.add: - display_name = '%s with {%s}' % (display_name, ' '.join(flags.add)) - if flags.remove: - display_name = '%s without {%s}' % ( - display_name, ' '.join(flags.remove)) - return display_name + return instrumentation_test_instance.GetUniqueTestName(test) #override def _RunTest(self, device, test): @@ -220,7 +209,7 @@ 'Please build it and try again.') def name_and_timeout(t): - n = self._GetTestName(t) + n = instrumentation_test_instance.GetTestName(t) i = self._GetTimeoutFromAnnotations(t['annotations'], n) return (n, i) @@ -236,7 +225,7 @@ test_list=test_names)) timeout = sum(timeouts) else: - test_name = self._GetTestName(test) + test_name = instrumentation_test_instance.GetTestName(test) test_display_name = self._GetUniqueTestName(test) target = '%s/%s' % ( self._test_instance.test_package, self._test_instance.test_runner) @@ -343,14 +332,16 @@ device.RunShellCommand('rm -f %s' % os.path.join(coverage_directory, '*')) if self._test_instance.store_tombstones: + resolved_tombstones = None for result in results: if result.GetType() == base_test_result.ResultType.CRASH: - resolved_tombstones = tombstones.ResolveTombstones( - device, - resolve_all_tombstones=True, - include_stack_symbols=False, - wipe_tombstones=True) - result.SetTombstones('\n'.join(resolved_tombstones)) + if not resolved_tombstones: + resolved_tombstones = '\n'.join(tombstones.ResolveTombstones( + device, + resolve_all_tombstones=True, + include_stack_symbols=False, + wipe_tombstones=True)) + result.SetTombstones(resolved_tombstones) return results #override
diff --git a/build/android/test_runner.py b/build/android/test_runner.py index 42429d3..fe9bdbb9 100755 --- a/build/android/test_runner.py +++ b/build/android/test_runner.py
@@ -230,6 +230,9 @@ group.add_argument('--enable-xml-result-parsing', action='store_true', help=argparse.SUPPRESS) + group.add_argument('--store-tombstones', dest='store_tombstones', + action='store_true', + help='Add tombstones in results if crash.') filter_group = group.add_mutually_exclusive_group() filter_group.add_argument('-f', '--gtest_filter', '--gtest-filter',
diff --git a/build/config/BUILD.gn b/build/config/BUILD.gn index 122f254..c248758 100644 --- a/build/config/BUILD.gn +++ b/build/config/BUILD.gn
@@ -71,12 +71,6 @@ if (enable_pdf) { defines += [ "ENABLE_PDF=1" ] } - if (enable_spellcheck) { - defines += [ "ENABLE_SPELLCHECK=1" ] - } - if (use_browser_spellchecker) { - defines += [ "USE_BROWSER_SPELLCHECKER=1" ] - } if (dcheck_always_on) { defines += [ "DCHECK_ALWAYS_ON=1" ] } @@ -100,12 +94,6 @@ if (use_cairo) { defines += [ "USE_CAIRO=1" ] } - if (use_clipboard_aurax11) { - defines += [ "USE_CLIPBOARD_AURAX11=1" ] - } - if (use_default_render_theme) { - defines += [ "USE_DEFAULT_RENDER_THEME=1" ] - } if (use_glib) { defines += [ "USE_GLIB=1" ] }
diff --git a/build/config/android/config.gni b/build/config/android/config.gni index df64d40..0da122dd 100644 --- a/build/config/android/config.gni +++ b/build/config/android/config.gni
@@ -43,7 +43,7 @@ # Purposefully repeated so that downstream can change # default_android_sdk_root without changing lint version. default_lint_android_sdk_root = "//third_party/android_tools/sdk" - default_lint_android_sdk_version = "23" + default_lint_android_sdk_version = "24" } if (!defined(default_extras_android_sdk_root)) {
diff --git a/build/config/android/internal_rules.gni b/build/config/android/internal_rules.gni index 4bc405d..6a7cda3 100644 --- a/build/config/android/internal_rules.gni +++ b/build/config/android/internal_rules.gni
@@ -34,22 +34,7 @@ "//build/android/rezip:rezip", "//chrome/test/android/cast_emulator:cast_emulator", "//mojo/public/java:bindings", - "//third_party/android_tools:emma_device", - "//third_party/cardboard-java:cardboard-java", - "//third_party/custom_tabs_client:custom_tabs_client_shared_lib", "//third_party/custom_tabs_client:custom_tabs_support_lib", - "//third_party/errorprone:chromium_errorprone", - "//third_party/haha:haha", - "//third_party/junit:hamcrest", - "//third_party/netty4:netty_all", - "//third_party/netty-tcnative:netty-tcnative", - "//third_party/robolectric:android-all-4.3_r2-robolectric-0", - "//third_party/robolectric:android-all-5.0.0_r2-robolectric-1", - "//third_party/robolectric:json-20080701", - "//third_party/robolectric:tagsoup-1.2", - "//third_party/robolectric:shadows-core-3.0-18", - "//third_party/robolectric:shadows-core-3.0-21", - "//third_party/robolectric:shadows-multidex-3.0", ] # Targets that match the whitelist but are not actually java targets. @@ -70,10 +55,12 @@ # build/android/gyp/util/build_utils.py:ExpandFileArgs template("write_build_config") { type = invoker.type + _is_prebuilt_binary = + defined(invoker.is_prebuilt_binary) && invoker.is_prebuilt_binary # Don't need to enforce naming scheme for these targets since we never # consider them in dependency chains. - if (type != "android_apk" && type != "java_binary" && + if (!_is_prebuilt_binary && type != "android_apk" && type != "java_binary" && type != "resource_rewriter") { set_sources_assignment_filter(_java_target_whitelist) _parent_invoker = invoker.invoker @@ -925,6 +912,11 @@ main_dex_rules = "//build/android/main_dex_classes.flags" + if (!defined(inputs)) { + inputs = [] + } + inputs += [ main_dex_rules ] + outputs = [ _main_dex_list_path, ] @@ -1773,6 +1765,7 @@ write_build_config(_build_config_target_name) { type = "java_prebuilt" + is_prebuilt_binary = defined(invoker.main_class) forward_variables_from(invoker, [ "input_jars_paths",
diff --git a/build/config/android/rules.gni b/build/config/android/rules.gni index 6649a67f..7e634a7 100644 --- a/build/config/android/rules.gni +++ b/build/config/android/rules.gni
@@ -1620,7 +1620,8 @@ # Added emma to the target's classpath via its .build_config. if (emma_coverage && !_emma_never_instrument) { - possible_config_deps += [ "//third_party/android_tools:emma_device" ] + possible_config_deps += + [ "//third_party/android_tools:emma_device_java" ] } proguard_enabled = _proguard_enabled @@ -1785,7 +1786,7 @@ deps += [ "${invoker.apk_under_test}__java" ] } if (emma_coverage && !_emma_never_instrument) { - deps += [ "//third_party/android_tools:emma_device" ] + deps += [ "//third_party/android_tools:emma_device_java" ] } }
diff --git a/build/config/compiler/BUILD.gn b/build/config/compiler/BUILD.gn index 30ecab6..1eaa390c 100644 --- a/build/config/compiler/BUILD.gn +++ b/build/config/compiler/BUILD.gn
@@ -1563,14 +1563,7 @@ if (is_win) { # Linker symbols for backtraces only. cflags = [] - if (is_win_fastlink) { - # Tell VS 2015+ to create a PDB that references debug - # information in .obj and .lib files instead of copying - # it all. This flag is incompatible with /PROFILE - ldflags = [ "/DEBUG:FASTLINK" ] - } else { - ldflags = [ "/DEBUG" ] - } + ldflags = [ "/DEBUG" ] } else { if (is_android) { # Breakpad can't handle DWARF 4 symbols properly yet, so use DWARF 3
diff --git a/build/config/features.gni b/build/config/features.gni index b44b0770..ee7441a 100644 --- a/build/config/features.gni +++ b/build/config/features.gni
@@ -88,12 +88,6 @@ # Additional dependent variables ----------------------------------------------- -# Enable the spell checker. -enable_spellcheck = !is_ios - -# Use the operating system's spellchecker rather than hunspell. -use_browser_spellchecker = is_android || is_mac - # The seccomp-bpf sandbox is only supported on five architectures # currently. # Do not disable seccomp_bpf anywhere without talking to
diff --git a/build/config/ui.gni b/build/config/ui.gni index 1212ad2c..0f78dd9f 100644 --- a/build/config/ui.gni +++ b/build/config/ui.gni
@@ -54,9 +54,6 @@ # Enable experimental vulkan backend. enable_vulkan = false - - # Allow aura to access x11 clipboard. - enable_clipboard_aurax11 = false } # Additional dependent variables ----------------------------------------------- @@ -67,8 +64,6 @@ # with the Aura window manager. ui_compositor_image_transport = use_aura && is_linux -use_default_render_theme = use_aura && !is_android - # Indicates if the UI toolkit depends on X11. use_x11 = is_linux && !use_ozone @@ -87,9 +82,6 @@ # Whether to use atk, the Accessibility ToolKit library use_atk = is_desktop_linux && use_x11 - -use_clipboard_aurax11 = - (is_desktop_linux && use_aura && use_x11) || enable_clipboard_aurax11 # ============================================= # PLEASE DO NOT ADD MORE FLAGS TO THIS FILE # =============================================
diff --git a/build/config/win/BUILD.gn b/build/config/win/BUILD.gn index 2b9f7bf7..c36f80c 100644 --- a/build/config/win/BUILD.gn +++ b/build/config/win/BUILD.gn
@@ -86,15 +86,32 @@ lib_dirs = [ "$clang_base_path/lib/clang/$clang_version/lib/windows" ] } - # Ensures that the PDB file contains FIXUP information (growing the PDB file - # by about 5%) but does not otherwise alter the output binary. This + # /PROFILE ensures that the PDB file contains FIXUP information (growing the + # PDB file by about 5%) but does not otherwise alter the output binary. This # information is used by the Syzygy optimization tool when decomposing the # release image. It is enabled for syzyasan builds and opportunistically for # other builds where it is not prohibited (not supported when incrementally # linking, using /debug:fastlink, or building with clang). - if (is_syzyasan || - (!is_debug && !is_component_build && !is_win_fastlink && !is_clang)) { + if (is_syzyasan) { + assert(!is_win_fastlink) ldflags = [ "/PROFILE" ] + } else { + if (!is_debug && !is_component_build && !is_clang) { + if (is_win_fastlink) { + # /PROFILE implies the following linker flags. Therefore if we are + # skipping /PROFILE because it is incompatible with /DEBUG:FASTLINK + # we should explicitly add these flags in order to avoid unintended + # consequences such as larger binaries. + ldflags = [ + "/OPT:REF", + "/OPT:ICF", + "/INCREMENTAL:NO", + "/FIXED:NO", + ] + } else { + ldflags = [ "/PROFILE" ] + } + } } # arflags apply only to static_libraries. The normal linker configs are only
diff --git a/build/secondary/third_party/android_tools/BUILD.gn b/build/secondary/third_party/android_tools/BUILD.gn index 8fbf24f..6a167bca 100644 --- a/build/secondary/third_party/android_tools/BUILD.gn +++ b/build/secondary/third_party/android_tools/BUILD.gn
@@ -37,7 +37,7 @@ jar_path = "$android_sdk_root/extras/google/gcm/gcm-client/dist/gcm.jar" } -android_java_prebuilt("emma_device") { +android_java_prebuilt("emma_device_java") { jar_path = "$android_sdk_root/tools/lib/emma_device.jar" }
diff --git a/cc/BUILD.gn b/cc/BUILD.gn index 7b541f1..a5a859e 100644 --- a/cc/BUILD.gn +++ b/cc/BUILD.gn
@@ -24,8 +24,6 @@ "animation/animation_timeline.h", "animation/element_animations.cc", "animation/element_animations.h", - "animation/element_id.cc", - "animation/element_id.h", "animation/keyframed_animation_curve.cc", "animation/keyframed_animation_curve.h", "animation/property_animation_state.cc", @@ -510,6 +508,8 @@ "trees/draw_property_utils.h", "trees/effect_node.cc", "trees/effect_node.h", + "trees/element_id.cc", + "trees/element_id.h", "trees/latency_info_swap_promise_monitor.cc", "trees/latency_info_swap_promise_monitor.h", "trees/layer_tree.cc",
diff --git a/cc/animation/animation_events.h b/cc/animation/animation_events.h index fba3d33..c6cb0e9 100644 --- a/cc/animation/animation_events.h +++ b/cc/animation/animation_events.h
@@ -10,9 +10,9 @@ #include "cc/animation/animation.h" #include "cc/animation/animation_curve.h" -#include "cc/animation/element_id.h" #include "cc/base/cc_export.h" #include "cc/output/filter_operations.h" +#include "cc/trees/element_id.h" #include "cc/trees/mutator_host.h" #include "ui/gfx/transform.h"
diff --git a/cc/animation/animation_player.h b/cc/animation/animation_player.h index 5605054..06b4433b 100644 --- a/cc/animation/animation_player.h +++ b/cc/animation/animation_player.h
@@ -13,8 +13,8 @@ #include "cc/animation/animation.h" #include "cc/animation/animation_curve.h" #include "cc/animation/element_animations.h" -#include "cc/animation/element_id.h" #include "cc/base/cc_export.h" +#include "cc/trees/element_id.h" namespace cc {
diff --git a/cc/animation/element_animations.h b/cc/animation/element_animations.h index 5b10aab..df1ac05b 100644 --- a/cc/animation/element_animations.h +++ b/cc/animation/element_animations.h
@@ -12,10 +12,10 @@ #include "base/memory/ref_counted.h" #include "base/observer_list.h" #include "base/time/time.h" -#include "cc/animation/element_id.h" #include "cc/animation/property_animation_state.h" #include "cc/animation/target_property.h" #include "cc/base/cc_export.h" +#include "cc/trees/element_id.h" #include "ui/gfx/geometry/scroll_offset.h" #include "ui/gfx/transform.h"
diff --git a/cc/blink/web_layer_impl.cc b/cc/blink/web_layer_impl.cc index 76bad02..d4e6c9f3 100644 --- a/cc/blink/web_layer_impl.cc +++ b/cc/blink/web_layer_impl.cc
@@ -14,12 +14,12 @@ #include "base/strings/string_util.h" #include "base/threading/thread_checker.h" #include "base/trace_event/trace_event_impl.h" -#include "cc/animation/element_id.h" #include "cc/base/region.h" #include "cc/base/switches.h" #include "cc/blink/web_blend_mode.h" #include "cc/layers/layer.h" #include "cc/layers/layer_position_constraint.h" +#include "cc/trees/element_id.h" #include "cc/trees/layer_tree_host.h" #include "third_party/WebKit/public/platform/WebFloatPoint.h" #include "third_party/WebKit/public/platform/WebFloatRect.h"
diff --git a/cc/layers/layer.h b/cc/layers/layer.h index 04cc9c0..80db449 100644 --- a/cc/layers/layer.h +++ b/cc/layers/layer.h
@@ -17,7 +17,6 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/observer_list.h" -#include "cc/animation/element_id.h" #include "cc/animation/target_property.h" #include "cc/base/cc_export.h" #include "cc/base/region.h" @@ -27,6 +26,7 @@ #include "cc/layers/layer_position_constraint.h" #include "cc/layers/paint_properties.h" #include "cc/output/filter_operations.h" +#include "cc/trees/element_id.h" #include "cc/trees/layer_tree.h" #include "cc/trees/mutator_host_client.h" #include "cc/trees/property_tree.h"
diff --git a/cc/layers/layer_impl.cc b/cc/layers/layer_impl.cc index dede0f6e..70d7df7 100644 --- a/cc/layers/layer_impl.cc +++ b/cc/layers/layer_impl.cc
@@ -80,7 +80,6 @@ mutable_properties_(MutableProperty::kNone), debug_info_(nullptr), has_preferred_raster_bounds_(false), - scrolls_drawn_descendant_(false), has_will_change_transform_hint_(false), needs_push_properties_(false), scrollbars_hidden_(false) {
diff --git a/cc/layers/layer_impl.h b/cc/layers/layer_impl.h index b5b8a12..1ab2193 100644 --- a/cc/layers/layer_impl.h +++ b/cc/layers/layer_impl.h
@@ -18,7 +18,6 @@ #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/values.h" -#include "cc/animation/element_id.h" #include "cc/animation/target_property.h" #include "cc/base/cc_export.h" #include "cc/base/region.h" @@ -33,6 +32,7 @@ #include "cc/quads/shared_quad_state.h" #include "cc/resources/resource_provider.h" #include "cc/tiles/tile_priority.h" +#include "cc/trees/element_id.h" #include "cc/trees/mutator_host_client.h" #include "third_party/skia/include/core/SkColor.h" #include "third_party/skia/include/core/SkXfermode.h" @@ -423,12 +423,6 @@ virtual gfx::Rect GetEnclosingRectInTargetSpace() const; - void set_scrolls_drawn_descendant(bool scrolls_drawn_descendant) { - scrolls_drawn_descendant_ = scrolls_drawn_descendant; - } - - bool scrolls_drawn_descendant() { return scrolls_drawn_descendant_; } - int num_copy_requests_in_target_subtree(); void UpdatePropertyTreeForScrollingAndAnimationIfNeeded(); @@ -576,11 +570,14 @@ std::unique_ptr<base::trace_event::ConvertableToTraceFormat> owned_debug_info_; base::trace_event::ConvertableToTraceFormat* debug_info_; + // TODO(http://crbug.com/557160): EffectNode instead of LayerImpl should + // own RenderSurfaceImpl. Currently SPv2 creates dummy layers for the sole + // purpose of holding a render surface. Once done, remember to remove dummy + // layers from PaintArtifactCompositor as well std::unique_ptr<RenderSurfaceImpl> render_surface_; gfx::Size preferred_raster_bounds_; bool has_preferred_raster_bounds_ : 1; - bool scrolls_drawn_descendant_ : 1; bool has_will_change_transform_hint_ : 1; bool needs_push_properties_ : 1; bool scrollbars_hidden_ : 1;
diff --git a/cc/layers/viewport.cc b/cc/layers/viewport.cc index 844703f2..d690d85 100644 --- a/cc/layers/viewport.cc +++ b/cc/layers/viewport.cc
@@ -36,13 +36,14 @@ Viewport::ScrollResult Viewport::ScrollBy(const gfx::Vector2dF& delta, const gfx::Point& viewport_point, bool is_direct_manipulation, - bool affect_top_controls) { + bool affect_browser_controls, + bool scroll_outer_viewport) { if (!OuterScrollLayer()) return ScrollResult(); gfx::Vector2dF content_delta = delta; - if (affect_top_controls && ShouldBrowserControlsConsumeScroll(delta)) + if (affect_browser_controls && ShouldBrowserControlsConsumeScroll(delta)) content_delta -= ScrollBrowserControls(delta); gfx::Vector2dF pending_content_delta = content_delta; @@ -57,11 +58,14 @@ ScrollResult result; - ScrollNode* outer_node = - scroll_tree.Node(OuterScrollLayer()->scroll_tree_index()); - pending_content_delta -= host_impl_->ScrollSingleNode( - outer_node, pending_content_delta, viewport_point, is_direct_manipulation, - &scroll_tree); + if (scroll_outer_viewport) { + ScrollNode* outer_node = + scroll_tree.Node(OuterScrollLayer()->scroll_tree_index()); + pending_content_delta -= host_impl_->ScrollSingleNode( + outer_node, pending_content_delta, viewport_point, + is_direct_manipulation, &scroll_tree); + } + result.consumed_delta = delta - AdjustOverscroll(pending_content_delta); result.content_scrolled_delta = content_delta - pending_content_delta;
diff --git a/cc/layers/viewport.h b/cc/layers/viewport.h index daa0622..5a254fe5 100644 --- a/cc/layers/viewport.h +++ b/cc/layers/viewport.h
@@ -42,11 +42,13 @@ void Pan(const gfx::Vector2dF& delta); // Scrolls the viewport, applying the unique bubbling between the inner and - // outer viewport. Scrolls can be consumed by browser controls. + // outer viewport unless the scroll_outer_viewport bit is off. Scrolls can be + // consumed by browser controls. ScrollResult ScrollBy(const gfx::Vector2dF& delta, const gfx::Point& viewport_point, bool is_wheel_scroll, - bool affect_top_controls); + bool affect_browser_controls, + bool scroll_outer_viewport); // Scrolls the viewport. Unlike the above method, scrolls the inner before // the outer viewport. Doesn't affect browser controls or return a result
diff --git a/cc/memory.md b/cc/memory.md index 1bac0f5..b00d705 100644 --- a/cc/memory.md +++ b/cc/memory.md
@@ -1,125 +1 @@ -# Memory Usage in CC - -This document gives an overview of memory usage in the CC component, as well as -information on how to analyze that memory. - -[TOC] - -## Types of Memory in Use - -CC uses a number of types of memory: - -1. Malloc Memory - Standard system memory used for all manner of objects in CC. -2. Discardable Memory - Memory allocated by the discardable memory system. - Designed to be freeable by the system at any time (under memory pressure). - In most cases, only pinned discardable memory should be considered to - have a cost; however, the implementation of discardable memory is platform - dependent, and on certain platforms unpinned memory can contribute to - memory pressure to some degree. -3. Shared Memory - Memory which is allocated by the Browser and can safely - be transferred between processes. This memory is allocated by the browser - but may count against a renderer process depending on who logically "owns" - the memory. -4. GPU Memory - Memory which is allocated on the GPU and typically does not - count against system memory. This mainly includes OpenGL objects. - -## Categories Of Memory - -Memory-infra tracing will grab dumps of CC memory in several categories. - -### CC Category - -The CC category contains resource allocations made by ResourceProvider. All -resource allocations are enumerated under cc/resource_memory. A subset of -resources are used as tile memory, and are also enumerated under cc/tile_memory. -For resources that appear in both cc/tile_memory and cc/resource_memory, the -size will be attributed to cc/tile_memory (effective_size of cc/resource_memory -will not include these resources). - -If the one-copy tile update path is in use, the cc category will also enumerate -staging resources used as intermediates when drawing tiles. These resources are -like tile_memory, in that they are shared with cc/resource_memory. - -Note that depending on the path being used, CC memory may be either shared -memory or GPU memory: - -Path | Tile Memory Type | Staging Memory Type --------------|------------------------------------------- -Bitmap | Shared Memory | N/A -One Copy | GPU Memory | Shared Memory -Zero Copy | GPU or Shared Memory | N/A -GPU | GPU Memory | N/A - -Note that these values can be determined from a memory-infra dump. For a given -resource, hover over the small green arrow next to it's "size". This will show -the other allocations that this resource is aliased with. If you see an -allocation in the GPU process, the memory is generally GPU memory. Otherwise, -the resource is typically Shared Memory. - -Tile and Staging memory managers are set up to evict any resource not used -within 1s. - -### GPU Category - -This category lists the memory allocations needed to support CC's GPU path. -Despite the name, the data in this category (within a Renderer process) is not -GPU memory but Shared Memory. - -Allocations tracked here include GL command buffer support allocations such as: - -1. Command Buffer Memory - memory used to send commands across the GL command - buffer. This is backed by Shared Memory. -2. Mapped Memory - memory used in certain image upload paths to share data - with the GPU process. This is backed by Shared Memory. -3. Transfer Buffer Memory - memory used to transfer data to the GPU - used in - different paths than mapped memory. Also backed by Shared Memory. - -### Discardable Category - -Cached images make use of Discardable memory. These allocations are managed by -Skia and a better summary of these allocations can likely be found in the Skia -category. - -### Malloc Category - -The malloc category shows a summary of all memory allocated through malloc. - -Currently the information here is not granular enough to be useful, and a -good project would be to track down and instrument any large pools of memory -using malloc. - -Some Skia caches also make use of malloc memory. For these allocations, a better -summary can be seen in the Skia category. - -### Skia Category - -The Skia category shows all resources used by the Skia rendering system. These -can be divided into a few subcategories. skia/gpu_resources/* includes all -resources using GPU memory. All other categories draw from either Shared or -malloc memory. To determine which type of memory a resource is using, hover -over the green arrow next to its size. This will show the other allocations -which the resource is aliased with. - -## Other Areas of Interest - -Many of the allocations under CC are aliased with memory in the Browser or GPU -process. When investigating CC memory it may be worth looking at the following -external categories: - -1. GPU Process / GPU Category - All GPU resources allocated by CC have a - counterpart in the GPU/GPU category. This includes GL Textures, buffers, and - other GPU backed objects such as Native GPU Memory Buffers. -2. Browser Process / GpuMemoryBuffer Category - Resources backed by Shared - Memory GpuMemoryBuffers are allocated by the browser and will be tracked - in this category. -3. Browser Process / SharedMemory Category - Resources backed by Bitmap and - Shared Memory GpuMemoryBuffer objects are allocated by the browser and will - also tracked in this category. - -## Memory TODOs - -The following areas have insufficient memory instrumentation. - -1. DisplayLists - DisplayLists can be quite large and are currently - un-instrumented. These use malloc memory and currently contribute to - malloc/allocated_objects/<unspecified>. [BUG](crbug.com/567465) +This document has moved to [//docs/memory-infra/probe-cc.md](/docs/memory-infra/probe-cc.md).
diff --git a/cc/test/animation_test_common.h b/cc/test/animation_test_common.h index 588448f..eace8da 100644 --- a/cc/test/animation_test_common.h +++ b/cc/test/animation_test_common.h
@@ -8,10 +8,10 @@ #include "cc/animation/animation.h" #include "cc/animation/animation_curve.h" #include "cc/animation/animation_timeline.h" -#include "cc/animation/element_id.h" #include "cc/animation/transform_operations.h" #include "cc/output/filter_operations.h" #include "cc/test/geometry_test_utils.h" +#include "cc/trees/element_id.h" namespace cc { class AnimationPlayer;
diff --git a/cc/tiles/software_image_decode_controller.cc b/cc/tiles/software_image_decode_controller.cc index 14dec63..1277ed57 100644 --- a/cc/tiles/software_image_decode_controller.cc +++ b/cc/tiles/software_image_decode_controller.cc
@@ -594,10 +594,14 @@ TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("cc.debug"), "SoftwareImageDecodeController::GetSubrectImageDecode - " "allocate subrect pixels"); + // TODO(vmpstr): This is using checked math to diagnose a problem reported + // in crbug.com/662217. If this is causing crashes, then it should be fixed + // elsewhere by skipping images that are too large. + base::CheckedNumeric<size_t> byte_size = subrect_info.minRowBytes(); + byte_size *= subrect_info.height(); subrect_pixels = base::DiscardableMemoryAllocator::GetInstance() - ->AllocateLockedDiscardableMemory(subrect_info.minRowBytes() * - subrect_info.height()); + ->AllocateLockedDiscardableMemory(byte_size.ValueOrDie()); } { TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("cc.debug"),
diff --git a/cc/animation/element_id.cc b/cc/trees/element_id.cc similarity index 97% rename from cc/animation/element_id.cc rename to cc/trees/element_id.cc index 4b6e6e6f..4591330 100644 --- a/cc/animation/element_id.cc +++ b/cc/trees/element_id.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "cc/animation/element_id.h" +#include "cc/trees/element_id.h" #include <limits> #include <ostream>
diff --git a/cc/animation/element_id.h b/cc/trees/element_id.h similarity index 94% rename from cc/animation/element_id.h rename to cc/trees/element_id.h index bca7d6c..4c0b652 100644 --- a/cc/animation/element_id.h +++ b/cc/trees/element_id.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CC_ANIMATION_ELEMENT_ID_H_ -#define CC_ANIMATION_ELEMENT_ID_H_ +#ifndef CC_TREES_ELEMENT_ID_H_ +#define CC_TREES_ELEMENT_ID_H_ #include <stddef.h> @@ -67,4 +67,4 @@ } // namespace cc -#endif // CC_ANIMATION_ELEMENT_ID_H_ +#endif // CC_TREES_ELEMENT_ID_H_
diff --git a/cc/trees/layer_tree_host_common.cc b/cc/trees/layer_tree_host_common.cc index 7f974027..8fcfccb4 100644 --- a/cc/trees/layer_tree_host_common.cc +++ b/cc/trees/layer_tree_host_common.cc
@@ -212,15 +212,8 @@ static inline void ClearIsDrawnRenderSurfaceLayerListMember( LayerImplList* layer_list, ScrollTree* scroll_tree) { - for (LayerImpl* layer : *layer_list) { - if (layer->is_drawn_render_surface_layer_list_member()) { - DCHECK_GT( - scroll_tree->Node(layer->scroll_tree_index())->num_drawn_descendants, - 0); - scroll_tree->Node(layer->scroll_tree_index())->num_drawn_descendants--; - } + for (LayerImpl* layer : *layer_list) layer->set_is_drawn_render_surface_layer_list_member(false); - } } static bool CdpPerfTracingEnabled() { @@ -293,33 +286,11 @@ DONT_BUILD_PROPERTY_TREES }; -static void ComputeLayerScrollsDrawnDescendants(LayerTreeImpl* layer_tree_impl, - ScrollTree* scroll_tree) { - for (int i = static_cast<int>(scroll_tree->size()) - 1; i > 0; --i) { - ScrollNode* node = scroll_tree->Node(i); - scroll_tree->parent(node)->num_drawn_descendants += - node->num_drawn_descendants; - } - for (LayerImpl* layer : *layer_tree_impl) { - bool scrolls_drawn_descendant = false; - if (layer->scrollable()) { - ScrollNode* node = scroll_tree->Node(layer->scroll_tree_index()); - if (node->num_drawn_descendants > 0) - scrolls_drawn_descendant = true; - } - layer->set_scrolls_drawn_descendant(scrolls_drawn_descendant); - } -} - static void ComputeInitialRenderSurfaceLayerList( LayerTreeImpl* layer_tree_impl, PropertyTrees* property_trees, LayerImplList* render_surface_layer_list, bool can_render_to_separate_surface) { - ScrollTree* scroll_tree = &property_trees->scroll_tree; - for (int i = 0; i < static_cast<int>(scroll_tree->size()); ++i) - scroll_tree->Node(i)->num_drawn_descendants = 0; - // Add all non-skipped surfaces to the initial render surface layer list. Add // all non-skipped layers to the layer list of their target surface, and // add their content rect to their target surface's accumulated content rect. @@ -391,7 +362,6 @@ continue; layer->set_is_drawn_render_surface_layer_list_member(true); - scroll_tree->Node(layer->scroll_tree_index())->num_drawn_descendants++; layer->render_target()->layer_list().push_back(layer); // The layer contributes its drawable content rect to its render target. @@ -487,9 +457,6 @@ ComputeListOfNonEmptySurfaces(layer_tree_impl, property_trees, &initial_render_surface_list, render_surface_layer_list); - - ComputeLayerScrollsDrawnDescendants(layer_tree_impl, - &property_trees->scroll_tree); } void CalculateDrawPropertiesInternal(
diff --git a/cc/trees/layer_tree_host_common_unittest.cc b/cc/trees/layer_tree_host_common_unittest.cc index b5e6d8a..8b7a4fc 100644 --- a/cc/trees/layer_tree_host_common_unittest.cc +++ b/cc/trees/layer_tree_host_common_unittest.cc
@@ -6900,6 +6900,80 @@ sticky_pos_impl->ScreenSpaceTransform().To2dTranslation()); } +TEST_F(LayerTreeHostCommonTest, StickyPositionTopScrollParent) { + scoped_refptr<Layer> root = Layer::Create(); + scoped_refptr<Layer> container = Layer::Create(); + scoped_refptr<Layer> scroller = Layer::Create(); + scoped_refptr<Layer> sticky_pos = Layer::Create(); + root->AddChild(container); + container->AddChild(scroller); + root->AddChild(sticky_pos); + sticky_pos->SetScrollParent(scroller.get()); + host()->SetRootLayer(root); + scroller->SetScrollClipLayerId(container->id()); + + LayerStickyPositionConstraint sticky_position; + sticky_position.is_sticky = true; + sticky_position.is_anchored_top = true; + sticky_position.top_offset = 10.0f; + sticky_position.parent_relative_sticky_box_offset = gfx::Point(10, 20); + sticky_position.scroll_container_relative_sticky_box_rect = + gfx::Rect(10, 20, 10, 10); + sticky_position.scroll_container_relative_containing_block_rect = + gfx::Rect(0, 0, 50, 50); + sticky_pos->SetStickyPositionConstraint(sticky_position); + + root->SetBounds(gfx::Size(200, 200)); + container->SetBounds(gfx::Size(100, 100)); + container->SetPosition(gfx::PointF(50, 50)); + scroller->SetBounds(gfx::Size(1000, 1000)); + sticky_pos->SetBounds(gfx::Size(10, 10)); + sticky_pos->SetPosition(gfx::PointF(60, 70)); + + ExecuteCalculateDrawProperties(root.get()); + host()->host_impl()->CreatePendingTree(); + host()->CommitAndCreatePendingTree(); + host()->host_impl()->ActivateSyncTree(); + LayerTreeImpl* layer_tree_impl = host()->host_impl()->active_tree(); + + LayerImpl* root_impl = layer_tree_impl->LayerById(root->id()); + LayerImpl* scroller_impl = layer_tree_impl->LayerById(scroller->id()); + LayerImpl* sticky_pos_impl = layer_tree_impl->LayerById(sticky_pos->id()); + + ExecuteCalculateDrawProperties(root_impl); + EXPECT_VECTOR2DF_EQ( + gfx::Vector2dF(60.f, 70.f), + sticky_pos_impl->ScreenSpaceTransform().To2dTranslation()); + + // Scroll less than sticking point, sticky element should move with scroll as + // we haven't gotten to the initial sticky item location yet. + SetScrollOffsetDelta(scroller_impl, gfx::Vector2dF(5.f, 5.f)); + ExecuteCalculateDrawProperties(root_impl); + EXPECT_VECTOR2DF_EQ( + gfx::Vector2dF(55.f, 65.f), + sticky_pos_impl->ScreenSpaceTransform().To2dTranslation()); + + // Scroll past the sticking point, the Y coordinate should now be clamped. + SetScrollOffsetDelta(scroller_impl, gfx::Vector2dF(15.f, 15.f)); + ExecuteCalculateDrawProperties(root_impl); + EXPECT_VECTOR2DF_EQ( + gfx::Vector2dF(45.f, 60.f), + sticky_pos_impl->ScreenSpaceTransform().To2dTranslation()); + SetScrollOffsetDelta(scroller_impl, gfx::Vector2dF(15.f, 25.f)); + ExecuteCalculateDrawProperties(root_impl); + EXPECT_VECTOR2DF_EQ( + gfx::Vector2dF(45.f, 60.f), + sticky_pos_impl->ScreenSpaceTransform().To2dTranslation()); + + // Scroll past the end of the sticky container (note: this element does not + // have its own layer as it does not need to be composited). + SetScrollOffsetDelta(scroller_impl, gfx::Vector2dF(15.f, 50.f)); + ExecuteCalculateDrawProperties(root_impl); + EXPECT_VECTOR2DF_EQ( + gfx::Vector2dF(45.f, 40.f), + sticky_pos_impl->ScreenSpaceTransform().To2dTranslation()); +} + TEST_F(LayerTreeHostCommonTest, StickyPositionSubpixelScroll) { scoped_refptr<Layer> root = Layer::Create(); scoped_refptr<Layer> container = Layer::Create();
diff --git a/cc/trees/layer_tree_host_impl.cc b/cc/trees/layer_tree_host_impl.cc index 7889ddc..0cf868ff 100644 --- a/cc/trees/layer_tree_host_impl.cc +++ b/cc/trees/layer_tree_host_impl.cc
@@ -2974,6 +2974,7 @@ scroll_state->position_y()); const gfx::Vector2dF delta(scroll_state->delta_x(), scroll_state->delta_y()); gfx::Vector2dF applied_delta; + gfx::Vector2dF delta_applied_to_content; // TODO(tdresser): Use a more rational epsilon. See crbug.com/510550 for // details. const float kEpsilon = 0.1f; @@ -2982,16 +2983,21 @@ viewport()->MainScrollLayer() && scroll_node->owner_id == viewport()->MainScrollLayer()->id(); - if (is_viewport_scroll_layer) { - bool affect_top_controls = !wheel_scrolling_; + // This is needed if the scroll chains up to the viewport without going + // through the outer viewport scroll layer. This can happen if we scroll an + // element that's not a descendant of the document.rootScroller. In that case + // we want to scroll the inner viewport -- to allow panning while zoomed -- + // but also move browser controls if needed. + bool is_inner_viewport_scroll_layer = + scroll_node->owner_id == InnerViewportScrollLayer()->id(); + + if (is_viewport_scroll_layer || is_inner_viewport_scroll_layer) { Viewport::ScrollResult result = viewport()->ScrollBy( delta, viewport_point, scroll_state->is_direct_manipulation(), - affect_top_controls); + !wheel_scrolling_, is_viewport_scroll_layer); + applied_delta = result.consumed_delta; - scroll_state->set_caused_scroll( - std::abs(result.content_scrolled_delta.x()) > kEpsilon, - std::abs(result.content_scrolled_delta.y()) > kEpsilon); - scroll_state->ConsumeDelta(applied_delta.x(), applied_delta.y()); + delta_applied_to_content = result.content_scrolled_delta; } else { applied_delta = ScrollSingleNode( scroll_node, delta, viewport_point, @@ -3002,8 +3008,16 @@ // If the layer wasn't able to move, try the next one in the hierarchy. bool scrolled = std::abs(applied_delta.x()) > kEpsilon; scrolled = scrolled || std::abs(applied_delta.y()) > kEpsilon; + if (!scrolled) { + // TODO(bokan): This preserves existing behavior by not allowing tiny + // scrolls to produce overscroll but is inconsistent in how delta gets + // chained up. We need to clean this up. + if (is_viewport_scroll_layer) + scroll_state->ConsumeDelta(applied_delta.x(), applied_delta.y()); + return; + } - if (scrolled && !is_viewport_scroll_layer) { + if (!is_viewport_scroll_layer && !is_inner_viewport_scroll_layer) { // If the applied delta is within 45 degrees of the input // delta, bail out to make it easier to scroll just one layer // in one direction without affecting any of its parents. @@ -3016,13 +3030,13 @@ // in which the layer moved. applied_delta = MathUtil::ProjectVector(delta, applied_delta); } - scroll_state->set_caused_scroll(std::abs(applied_delta.x()) > kEpsilon, - std::abs(applied_delta.y()) > kEpsilon); - scroll_state->ConsumeDelta(applied_delta.x(), applied_delta.y()); + delta_applied_to_content = applied_delta; } - if (!scrolled) - return; + scroll_state->set_caused_scroll( + std::abs(delta_applied_to_content.x()) > kEpsilon, + std::abs(delta_applied_to_content.y()) > kEpsilon); + scroll_state->ConsumeDelta(applied_delta.x(), applied_delta.y()); scroll_state->set_current_native_scrolling_node(scroll_node); } @@ -3417,7 +3431,7 @@ return false; DCHECK(viewport()); - viewport()->ScrollBy(scroll, gfx::Point(), false, false); + viewport()->ScrollBy(scroll, gfx::Point(), false, false, true); client_->SetNeedsCommitOnImplThread(); client_->RenewTreePriority(); return true;
diff --git a/cc/trees/layer_tree_host_impl_unittest.cc b/cc/trees/layer_tree_host_impl_unittest.cc index 834967f..f2702a3 100644 --- a/cc/trees/layer_tree_host_impl_unittest.cc +++ b/cc/trees/layer_tree_host_impl_unittest.cc
@@ -4840,26 +4840,23 @@ gfx::Size contents_size(20, 20); std::unique_ptr<LayerImpl> content_layer = - LayerImpl::Create(host_impl_->active_tree(), 1); + LayerImpl::Create(host_impl_->active_tree(), 11); content_layer->SetDrawsContent(true); content_layer->SetPosition(gfx::PointF()); content_layer->SetBounds(contents_size); - std::unique_ptr<LayerImpl> scroll_clip_layer = - LayerImpl::Create(host_impl_->active_tree(), 3); - scroll_clip_layer->SetBounds(surface_size); + LayerImpl* scroll_clip_layer = + CreateBasicVirtualViewportLayers(surface_size, surface_size); std::unique_ptr<LayerImpl> scroll_layer = - LayerImpl::Create(host_impl_->active_tree(), 2); - scroll_layer->SetScrollClipLayer(3); + LayerImpl::Create(host_impl_->active_tree(), 12); + scroll_layer->SetScrollClipLayer(scroll_clip_layer->id()); scroll_layer->SetBounds(contents_size); scroll_layer->SetPosition(gfx::PointF()); scroll_layer->test_properties()->AddChild(std::move(content_layer)); scroll_clip_layer->test_properties()->AddChild(std::move(scroll_layer)); scroll_clip_layer->test_properties()->force_render_surface = true; - host_impl_->active_tree()->SetRootLayerForTesting( - std::move(scroll_clip_layer)); host_impl_->active_tree()->BuildPropertyTreesForTesting(); host_impl_->SetViewportSize(surface_size); @@ -4878,13 +4875,13 @@ TEST_F(LayerTreeHostImplTest, ScrollChildCallsCommitAndRedraw) { gfx::Size surface_size(10, 10); gfx::Size contents_size(20, 20); - std::unique_ptr<LayerImpl> root = - LayerImpl::Create(host_impl_->active_tree(), 1); - root->SetBounds(surface_size); + + LayerImpl* root = + CreateBasicVirtualViewportLayers(surface_size, surface_size); + root->test_properties()->AddChild( - CreateScrollableLayer(2, contents_size, root.get())); + CreateScrollableLayer(12, contents_size, root)); root->test_properties()->force_render_surface = true; - host_impl_->active_tree()->SetRootLayerForTesting(std::move(root)); host_impl_->active_tree()->BuildPropertyTreesForTesting(); host_impl_->SetViewportSize(surface_size); @@ -5199,21 +5196,21 @@ // parent layer isn't scrolled. gfx::Size surface_size(10, 10); gfx::Size content_size(20, 20); - std::unique_ptr<LayerImpl> root = - LayerImpl::Create(host_impl_->active_tree(), 1); - root->SetBounds(surface_size); + + LayerImpl* root = + CreateBasicVirtualViewportLayers(surface_size, surface_size); + root->test_properties()->force_render_surface = true; std::unique_ptr<LayerImpl> grand_child = - CreateScrollableLayer(3, content_size, root.get()); + CreateScrollableLayer(13, content_size, root); std::unique_ptr<LayerImpl> child = - CreateScrollableLayer(2, content_size, root.get()); + CreateScrollableLayer(12, content_size, root); LayerImpl* grand_child_layer = grand_child.get(); child->test_properties()->AddChild(std::move(grand_child)); LayerImpl* child_layer = child.get(); root->test_properties()->AddChild(std::move(child)); - host_impl_->active_tree()->SetRootLayerForTesting(std::move(root)); host_impl_->active_tree()->BuildPropertyTreesForTesting(); host_impl_->active_tree()->DidBecomeActive(); @@ -5245,8 +5242,7 @@ ->root_layer_for_testing() ->test_properties() ->children[0]; - LayerImpl* grand_child = child->test_properties()->children[0]; - EXPECT_TRUE(ScrollInfoContains(*scroll_info.get(), grand_child->id(), + EXPECT_TRUE(ScrollInfoContains(*scroll_info.get(), grand_child_layer->id(), gfx::Vector2d(0, -5))); // The child should not have scrolled. @@ -6119,7 +6115,6 @@ host_impl_->ScrollEnd(EndState().get()); } - TEST_F(LayerTreeHostImplTest, OverscrollChildWithoutBubbling) { // Scroll child layers beyond their maximum scroll range and make sure root // overscroll does not accumulate. @@ -6140,6 +6135,9 @@ LayerImpl* grand_child_layer = grand_child.get(); child->test_properties()->AddChild(std::move(grand_child)); + host_impl_->active_tree()->SetViewportLayersFromIds( + Layer::INVALID_ID, Layer::INVALID_ID, root->id(), Layer::INVALID_ID); + LayerImpl* child_layer = child.get(); root->test_properties()->AddChild(std::move(child)); root_clip->test_properties()->AddChild(std::move(root)); @@ -6180,11 +6178,17 @@ .thread); EXPECT_EQ(host_impl_->CurrentlyScrollingLayer(), grand_child_layer); EXPECT_EQ(gfx::Vector2dF(), host_impl_->accumulated_root_overscroll()); + host_impl_->ScrollEnd(EndState().get()); + EXPECT_EQ(InputHandler::SCROLL_ON_IMPL_THREAD, + host_impl_ + ->ScrollBegin(BeginState(gfx::Point(5, 5)).get(), + InputHandler::NON_BUBBLING_GESTURE) + .thread); scroll_result = host_impl_->ScrollBy(UpdateState(gfx::Point(), scroll_delta).get()); EXPECT_TRUE(scroll_result.did_scroll); EXPECT_FALSE(scroll_result.did_overscroll_root); - EXPECT_EQ(host_impl_->CurrentlyScrollingLayer(), child_layer); + EXPECT_EQ(host_impl_->CurrentlyScrollingLayer()->id(), child_layer->id()); EXPECT_EQ(gfx::Vector2dF(), host_impl_->accumulated_root_overscroll()); host_impl_->ScrollEnd(EndState().get()); @@ -6271,7 +6275,13 @@ TEST_F(LayerTreeHostImplTest, NoOverscrollWhenNotAtEdge) { InputHandlerScrollResult scroll_result; - SetupScrollAndContentsLayers(gfx::Size(200, 200)); + gfx::Size viewport_size(100, 100); + gfx::Size content_size(200, 200); + LayerImpl* root_scroll_layer = + CreateBasicVirtualViewportLayers(viewport_size, viewport_size); + host_impl_->active_tree()->OuterViewportScrollLayer()->SetBounds( + content_size); + root_scroll_layer->SetBounds(content_size); host_impl_->active_tree()->BuildPropertyTreesForTesting(); DrawFrame(); @@ -6375,6 +6385,97 @@ .thread); } +// Test that scrolling the inner viewport directly works, as can happen when the +// scroll chains up to it from an sibling of the outer viewport. +TEST_F(LayerTreeHostImplTest, ScrollFromOuterViewportSibling) { + const gfx::Size content_size(200, 200); + const gfx::Size viewport_size(100, 100); + + LayerTreeImpl* layer_tree_impl = host_impl_->active_tree(); + + CreateBasicVirtualViewportLayers(viewport_size, viewport_size); + host_impl_->active_tree()->set_top_controls_height(10); + host_impl_->active_tree()->SetCurrentBrowserControlsShownRatio(1.f); + + LayerImpl* outer_scroll_layer = host_impl_->OuterViewportScrollLayer(); + LayerImpl* inner_scroll_layer = host_impl_->InnerViewportScrollLayer(); + + LayerImpl* scroll_layer = nullptr; + + // Create a scrolling layer that's parented directly to the inner viewport. + // This will test that scrolls that chain up to the inner viewport without + // passing through the outer viewport still scroll correctly and affect + // browser controls. + { + std::unique_ptr<LayerImpl> clip = LayerImpl::Create(layer_tree_impl, 10); + clip->SetBounds(viewport_size); + clip->SetPosition(gfx::PointF()); + + std::unique_ptr<LayerImpl> scroll = LayerImpl::Create(layer_tree_impl, 11); + scroll->SetBounds(gfx::Size(400, 400)); + scroll->SetScrollClipLayer(clip->id()); + scroll->SetDrawsContent(true); + + scroll_layer = scroll.get(); + + clip->test_properties()->AddChild(std::move(scroll)); + inner_scroll_layer->test_properties()->AddChild(std::move(clip)); + + // Move the outer viewport layer away so that scrolls won't target it. + host_impl_->active_tree()->OuterViewportContainerLayer()->SetPosition( + gfx::PointF(400, 400)); + + layer_tree_impl->BuildPropertyTreesForTesting(); + + float min_page_scale = 1.f, max_page_scale = 4.f; + float page_scale_factor = 2.f; + host_impl_->active_tree()->PushPageScaleFromMainThread( + page_scale_factor, min_page_scale, max_page_scale); + host_impl_->active_tree()->SetPageScaleOnActiveTree(page_scale_factor); + } + + // Fully scroll the child. + { + host_impl_->ScrollBegin(BeginState(gfx::Point(0, 0)).get(), + InputHandler::TOUCHSCREEN); + host_impl_->ScrollBy( + UpdateState(gfx::Point(0, 0), gfx::Vector2dF(1000.f, 1000.f)).get()); + host_impl_->ScrollEnd(EndState().get()); + + EXPECT_EQ(1.f, + host_impl_->active_tree()->CurrentBrowserControlsShownRatio()); + EXPECT_VECTOR_EQ(gfx::Vector2dF(300.f, 300.f), + scroll_layer->CurrentScrollOffset()); + EXPECT_VECTOR_EQ(gfx::Vector2dF(), + inner_scroll_layer->CurrentScrollOffset()); + EXPECT_VECTOR_EQ(gfx::Vector2dF(), + outer_scroll_layer->CurrentScrollOffset()); + } + + // Scrolling on the child now should chain up directly to the inner viewport. + // Scrolling it should cause browser controls to hide. The outer viewport + // should not be affected. + { + host_impl_->ScrollBegin(BeginState(gfx::Point(0, 0)).get(), + InputHandler::TOUCHSCREEN); + gfx::Vector2d scroll_delta(0, 10); + host_impl_->ScrollBy(UpdateState(gfx::Point(), scroll_delta).get()); + EXPECT_EQ(0.f, + host_impl_->active_tree()->CurrentBrowserControlsShownRatio()); + EXPECT_VECTOR_EQ(gfx::Vector2dF(), + inner_scroll_layer->CurrentScrollOffset()); + + host_impl_->ScrollBy(UpdateState(gfx::Point(), scroll_delta).get()); + host_impl_->ScrollBy(UpdateState(gfx::Point(), scroll_delta).get()); + + EXPECT_VECTOR_EQ(gfx::Vector2dF(0, 10.f), + inner_scroll_layer->CurrentScrollOffset()); + EXPECT_VECTOR_EQ(gfx::Vector2dF(), + outer_scroll_layer->CurrentScrollOffset()); + host_impl_->ScrollEnd(EndState().get()); + } +} + // Test that scrolls chain correctly when a child scroller on the page (e.g. a // scrolling div) is set as the outer viewport. This happens in the // rootScroller proposal. @@ -8349,26 +8450,25 @@ // Scroll a child layer beyond its maximum scroll range and make sure the // the scroll doesn't bubble up to the parent layer. gfx::Size surface_size(10, 10); - std::unique_ptr<LayerImpl> root = - LayerImpl::Create(host_impl_->active_tree(), 1); + LayerImpl* root = + CreateBasicVirtualViewportLayers(surface_size, surface_size); root->test_properties()->force_render_surface = true; std::unique_ptr<LayerImpl> root_scrolling_owned = - CreateScrollableLayer(2, surface_size, root.get()); + CreateScrollableLayer(12, surface_size, root); auto* root_scrolling = root_scrolling_owned.get(); root->test_properties()->AddChild(std::move(root_scrolling_owned)); std::unique_ptr<LayerImpl> child_owned = - CreateScrollableLayer(3, surface_size, root.get()); + CreateScrollableLayer(13, surface_size, root); auto* child = child_owned.get(); root_scrolling->test_properties()->AddChild(std::move(child_owned)); std::unique_ptr<LayerImpl> grand_child_owned = - CreateScrollableLayer(4, surface_size, root.get()); + CreateScrollableLayer(14, surface_size, root); auto* grand_child = grand_child_owned.get(); child->test_properties()->AddChild(std::move(grand_child_owned)); - host_impl_->active_tree()->SetRootLayerForTesting(std::move(root)); host_impl_->active_tree()->BuildPropertyTreesForTesting(); host_impl_->active_tree()->DidBecomeActive(); @@ -8385,13 +8485,6 @@ DrawFrame(); { std::unique_ptr<ScrollAndScaleSet> scroll_info; - LayerImpl* child = host_impl_->active_tree() - ->root_layer_for_testing() - ->test_properties() - ->children[0] - ->test_properties() - ->children[0]; - LayerImpl* grand_child = child->test_properties()->children[0]; gfx::Vector2d scroll_delta(0, -2); EXPECT_EQ(InputHandler::SCROLL_ON_IMPL_THREAD, @@ -8448,19 +8541,18 @@ // When flinging via wheel, we shouldn't bubble. gfx::Size surface_size(10, 10); gfx::Size content_size(20, 20); - std::unique_ptr<LayerImpl> root_clip = - LayerImpl::Create(host_impl_->active_tree(), 3); + LayerImpl* root_clip = + CreateBasicVirtualViewportLayers(surface_size, surface_size); root_clip->test_properties()->force_render_surface = true; std::unique_ptr<LayerImpl> root_scroll = - CreateScrollableLayer(1, content_size, root_clip.get()); + CreateScrollableLayer(11, content_size, root_clip); int root_scroll_id = root_scroll->id(); std::unique_ptr<LayerImpl> child = - CreateScrollableLayer(2, content_size, root_clip.get()); + CreateScrollableLayer(12, content_size, root_clip); root_scroll->test_properties()->AddChild(std::move(child)); root_clip->test_properties()->AddChild(std::move(root_scroll)); - host_impl_->active_tree()->SetRootLayerForTesting(std::move(root_clip)); host_impl_->active_tree()->BuildPropertyTreesForTesting(); host_impl_->active_tree()->DidBecomeActive(); @@ -8568,7 +8660,7 @@ status.main_thread_scrolling_reasons); } -TEST_F(LayerTreeHostImplTest, NotScrollInvisibleScroller) { +TEST_F(LayerTreeHostImplTest, ScrollInvisibleScroller) { gfx::Size content_size(100, 100); SetupScrollAndContentsLayers(content_size); @@ -8588,110 +8680,8 @@ DrawFrame(); - // We should not have scrolled |child_scroll| even though we technically "hit" - // it. The reason for this is that if the scrolling the scroll would not move - // any layer that is a drawn RSLL member, then we can ignore the hit. - // - // Why SCROLL_STARTED? In this case, it's because we've bubbled out and - // started scrolling the viewport. - EXPECT_EQ(InputHandler::SCROLL_ON_IMPL_THREAD, - host_impl_->ScrollBegin(BeginState(gfx::Point()).get(), - InputHandler::WHEEL) - .thread); - - EXPECT_EQ(117, host_impl_->CurrentlyScrollingLayer()->id()); -} - -TEST_F(LayerTreeHostImplTest, ScrollInvisibleScrollerWithVisibleDescendent) { - gfx::Size content_size(100, 100); - SetupScrollAndContentsLayers(content_size); - - LayerImpl* root = host_impl_->active_tree()->LayerById(1); - LayerImpl* root_scroll_layer = host_impl_->active_tree()->LayerById(2); - - std::unique_ptr<LayerImpl> invisible_scroll_layer = - CreateScrollableLayer(7, content_size, root); - invisible_scroll_layer->SetDrawsContent(false); - - std::unique_ptr<LayerImpl> child_layer = - LayerImpl::Create(host_impl_->active_tree(), 8); - child_layer->SetDrawsContent(false); - - std::unique_ptr<LayerImpl> grand_child_layer = - LayerImpl::Create(host_impl_->active_tree(), 9); - grand_child_layer->SetDrawsContent(true); - grand_child_layer->SetBounds(content_size); - // Move the grand child so it's not hit by our test point. - grand_child_layer->SetPosition(gfx::PointF(10.f, 10.f)); - - child_layer->test_properties()->AddChild(std::move(grand_child_layer)); - invisible_scroll_layer->test_properties()->AddChild(std::move(child_layer)); - root_scroll_layer->test_properties()->AddChild( - std::move(invisible_scroll_layer)); - host_impl_->active_tree()->BuildPropertyTreesForTesting(); - - DrawFrame(); - - // We should have scrolled |invisible_scroll_layer| as it was hit and it has - // a descendant which is a drawn RSLL member. - EXPECT_EQ(InputHandler::SCROLL_ON_IMPL_THREAD, - host_impl_->ScrollBegin(BeginState(gfx::Point()).get(), - InputHandler::WHEEL) - .thread); - - EXPECT_EQ(7, host_impl_->CurrentlyScrollingLayer()->id()); -} - -TEST_F(LayerTreeHostImplTest, ScrollInvisibleScrollerWithVisibleScrollChild) { - // This test case is very similar to the one above with one key difference: - // the invisible scroller has a scroll child that is indeed draw contents. - // If we attempt to initiate a gesture scroll off of the visible scroll child - // we should still start the scroll child. - gfx::Size content_size(100, 100); - SetupScrollAndContentsLayers(content_size); - - LayerImpl* root = host_impl_->active_tree()->LayerById(1); - - int scroll_layer_id = 2; - LayerImpl* scroll_layer = - host_impl_->active_tree()->LayerById(scroll_layer_id); - - int scroll_child_id = 6; - std::unique_ptr<LayerImpl> scroll_child = - LayerImpl::Create(host_impl_->active_tree(), scroll_child_id); - scroll_child->SetDrawsContent(true); - scroll_child->SetBounds(content_size); - // Move the scroll child so it's not hit by our test point. - scroll_child->SetPosition(gfx::PointF(10.f, 10.f)); - - int invisible_scroll_layer_id = 7; - std::unique_ptr<LayerImpl> invisible_scroll = - CreateScrollableLayer(invisible_scroll_layer_id, content_size, root); - invisible_scroll->SetDrawsContent(false); - - int container_id = 8; - std::unique_ptr<LayerImpl> container = - LayerImpl::Create(host_impl_->active_tree(), container_id); - - std::unique_ptr<std::set<LayerImpl*>> scroll_children( - new std::set<LayerImpl*>); - scroll_children->insert(scroll_child.get()); - invisible_scroll->test_properties()->scroll_children.reset( - scroll_children.release()); - - scroll_child->test_properties()->scroll_parent = invisible_scroll.get(); - - container->test_properties()->AddChild(std::move(invisible_scroll)); - container->test_properties()->AddChild(std::move(scroll_child)); - - scroll_layer->test_properties()->AddChild(std::move(container)); - host_impl_->active_tree()->BuildPropertyTreesForTesting(); - - DrawFrame(); - - // We should have scrolled |child_scroll| even though it is invisible. - // The reason for this is that if the scrolling the scroll would move a layer - // that is a drawn RSLL member, then we should accept this hit. + // We should have scrolled |child_scroll| even though it does not move + // any layer that is a drawn RSLL member. EXPECT_EQ(InputHandler::SCROLL_ON_IMPL_THREAD, host_impl_->ScrollBegin(BeginState(gfx::Point()).get(), InputHandler::WHEEL)
diff --git a/cc/trees/layer_tree_impl.cc b/cc/trees/layer_tree_impl.cc index 1aad8e4a..edfd5b0a 100644 --- a/cc/trees/layer_tree_impl.cc +++ b/cc/trees/layer_tree_impl.cc
@@ -1887,16 +1887,15 @@ } } -static bool ScrollsOrScrollbarAnyDrawnRenderSurfaceLayerListMember( - LayerImpl* layer) { - return layer->scrolls_drawn_descendant() || +static bool IsScrollableOrDrawnScrollbarLayer(LayerImpl* layer) { + return layer->scrollable() || (layer->ToScrollbarLayer() && layer->is_drawn_render_surface_layer_list_member()); } struct FindScrollingLayerOrScrollbarLayerFunctor { bool operator()(LayerImpl* layer) const { - return ScrollsOrScrollbarAnyDrawnRenderSurfaceLayerListMember(layer); + return IsScrollableOrDrawnScrollbarLayer(layer); } }; @@ -1913,7 +1912,7 @@ struct HitTestVisibleScrollableOrTouchableFunctor { bool operator()(LayerImpl* layer) const { return layer->is_drawn_render_surface_layer_list_member() || - ScrollsOrScrollbarAnyDrawnRenderSurfaceLayerListMember(layer) || + IsScrollableOrDrawnScrollbarLayer(layer) || !layer->touch_event_handler_region().IsEmpty(); } };
diff --git a/cc/trees/mutator_host.h b/cc/trees/mutator_host.h index 666217d..bd3ed1d 100644 --- a/cc/trees/mutator_host.h +++ b/cc/trees/mutator_host.h
@@ -9,7 +9,7 @@ #include "base/memory/ptr_util.h" #include "base/time/time.h" -#include "cc/animation/element_id.h" +#include "cc/trees/element_id.h" #include "cc/trees/mutator_host_client.h" #include "ui/gfx/geometry/box_f.h" #include "ui/gfx/geometry/vector2d_f.h"
diff --git a/cc/trees/mutator_host_client.h b/cc/trees/mutator_host_client.h index 0dca15b..193dc65 100644 --- a/cc/trees/mutator_host_client.h +++ b/cc/trees/mutator_host_client.h
@@ -6,9 +6,9 @@ #define CC_TREES_MUTATOR_HOST_CLIENT_H_ // TODO(loyso) Move these headers out of cc/animation. -#include "cc/animation/element_id.h" #include "cc/animation/property_animation_state.h" #include "cc/animation/target_property.h" +#include "cc/trees/element_id.h" namespace gfx { class Transform;
diff --git a/cc/trees/property_tree.cc b/cc/trees/property_tree.cc index 2969a69b..3e67f101 100644 --- a/cc/trees/property_tree.cc +++ b/cc/trees/property_tree.cc
@@ -426,7 +426,7 @@ top_delta = available_space; sticky_offset.set_y(sticky_offset.y() + top_delta); } - return sticky_offset - layer_offset - + return sticky_offset - layer_offset - node->source_to_parent - constraint.scroll_container_relative_sticky_box_rect .OffsetFromOrigin(); }
diff --git a/cc/trees/property_tree.h b/cc/trees/property_tree.h index ef53147..85a8d47 100644 --- a/cc/trees/property_tree.h +++ b/cc/trees/property_tree.h
@@ -11,11 +11,11 @@ #include <unordered_map> #include <vector> -#include "cc/animation/element_id.h" #include "cc/base/cc_export.h" #include "cc/base/synced_property.h" #include "cc/layers/layer_sticky_position_constraint.h" #include "cc/output/filter_operations.h" +#include "cc/trees/element_id.h" #include "ui/gfx/geometry/rect_f.h" #include "ui/gfx/geometry/scroll_offset.h" #include "ui/gfx/transform.h"
diff --git a/cc/trees/scroll_node.cc b/cc/trees/scroll_node.cc index c2ba952..5da6957 100644 --- a/cc/trees/scroll_node.cc +++ b/cc/trees/scroll_node.cc
@@ -3,10 +3,10 @@ // found in the LICENSE file. #include "base/trace_event/trace_event_argument.h" -#include "cc/animation/element_id.h" #include "cc/base/math_util.h" #include "cc/input/main_thread_scrolling_reason.h" #include "cc/proto/gfx_conversions.h" +#include "cc/trees/element_id.h" #include "cc/trees/scroll_node.h" namespace cc { @@ -25,8 +25,7 @@ should_flatten(false), user_scrollable_horizontal(false), user_scrollable_vertical(false), - transform_id(0), - num_drawn_descendants(0) {} + transform_id(0) {} ScrollNode::ScrollNode(const ScrollNode& other) = default;
diff --git a/cc/trees/scroll_node.h b/cc/trees/scroll_node.h index 4ebb795..f68fd59 100644 --- a/cc/trees/scroll_node.h +++ b/cc/trees/scroll_node.h
@@ -57,8 +57,6 @@ bool user_scrollable_vertical; ElementId element_id; int transform_id; - // Number of drawn layers pointing to this node or any of its descendants. - int num_drawn_descendants; bool operator==(const ScrollNode& other) const; void AsValueInto(base::trace_event::TracedValue* value) const;
diff --git a/chrome/VERSION b/chrome/VERSION index 2f527ea8..a6e4bd78 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=56 MINOR=0 -BUILD=2920 +BUILD=2921 PATCH=0
diff --git a/chrome/android/BUILD.gn b/chrome/android/BUILD.gn index 50ccd56..e7e2432 100644 --- a/chrome/android/BUILD.gn +++ b/chrome/android/BUILD.gn
@@ -8,6 +8,7 @@ import("//build/util/process_version.gni") import("//build_overrides/v8.gni") import("//chrome/android/chrome_public_apk_tmpl.gni") +import("//chrome/android/monochrome_android_manifest_jinja_variables.gni") import("//chrome/chrome_paks.gni") import("//chrome/common/features.gni") import("//chrome/process_version_rc_template.gni") # For branding_file_path. @@ -28,6 +29,8 @@ "$target_gen_dir/chrome_modern_public_apk/AndroidManifest.xml" chrome_sync_shell_android_manifest = "$target_gen_dir/chrome_sync_shell_apk/AndroidManifest.xml" +monochrome_public_android_manifest = + "$target_gen_dir/monochrome_public_apk/AndroidManifest.xml" chrome_sync_shell_jinja_variables = default_chrome_public_jinja_variables + @@ -58,6 +61,14 @@ ] } +jinja_template("monochrome_public_android_manifest") { + input = "java/AndroidManifest_monochrome.xml" + output = monochrome_public_android_manifest + variables = + chrome_public_jinja_variables + + monochrome_android_manifest_jinja_variables + [ "target_sdk_version=24" ] +} + java_cpp_template("chrome_webapk_signature_srcjar") { sources = [ "java/src/org/chromium/chrome/browser/webapps/ChromeWebApkHostSignature.template", @@ -195,7 +206,7 @@ "//third_party/android_tools:android_support_v7_recyclerview_java", "//third_party/cacheinvalidation:cacheinvalidation_javalib", "//third_party/cacheinvalidation:cacheinvalidation_proto_java", - "//third_party/custom_tabs_client:custom_tabs_support_lib", + "//third_party/custom_tabs_client:custom_tabs_support_java", "//third_party/gif_player:gif_player_java", "//third_party/jsr-305:jsr_305_javalib", "//third_party/leakcanary:leakcanary_java", @@ -428,7 +439,7 @@ "//third_party/android_tools:android_support_v7_recyclerview_java", "//third_party/android_tools:legacy_http_javalib", "//third_party/cacheinvalidation:cacheinvalidation_javalib", - "//third_party/custom_tabs_client:custom_tabs_support_lib", + "//third_party/custom_tabs_client:custom_tabs_support_java", "//third_party/jsr-305:jsr_305_javalib", "//ui/android:ui_java", "//ui/android:ui_javatests", @@ -686,6 +697,18 @@ load_library_from_apk = chromium_linker_supported } +monochrome_public_apk_tmpl("monochrome_public_apk") { + android_manifest = monochrome_public_android_manifest + android_manifest_dep = ":monochrome_public_android_manifest" + apk_name = "MonochromePublic" + + deps = [ + "//base:base_java", + "//chrome/android:chrome_java", + "//chrome/android/java/templates:public_monochrome_java", + ] +} + chrome_public_apk_tmpl_shared("chrome_sync_shell_apk") { testonly = true android_manifest = chrome_sync_shell_android_manifest
diff --git a/chrome/android/chrome_public_apk_tmpl.gni b/chrome/android/chrome_public_apk_tmpl.gni index 57492b2..5c98830 100644 --- a/chrome/android/chrome_public_apk_tmpl.gni +++ b/chrome/android/chrome_public_apk_tmpl.gni
@@ -107,7 +107,12 @@ if (!defined(deps)) { deps = [] } - deps += [ "//android_webview/glue" ] + deps += [ + "//android_webview:monochrome_webview_assets", + "//android_webview/glue", + "//chrome/android:chrome_public_non_pak_assets", + "//chrome/android:monochrome_pak_assets", + ] if (!is_java_debug) { if (!defined(proguard_configs)) {
diff --git a/chrome/android/java/AndroidManifest_monochrome.xml b/chrome/android/java/AndroidManifest_monochrome.xml new file mode 100644 index 0000000..5ae85de --- /dev/null +++ b/chrome/android/java/AndroidManifest_monochrome.xml
@@ -0,0 +1,32 @@ +{% extends "chrome/android/java/AndroidManifest.xml" %} +{% import 'android_webview/apk/java/AndroidManifest.xml' as webview %} + +## Copyright 2016 The Chromium Authors. All rights reserved. +## Use of this source code is governed by a BSD-style license that can be +## found in the LICENSE file. + +## Note: This is a jinja2 template, processed at build time into the final manifest. +## + +{% block application_name %}org.chromium.chrome.browser.MonochromeApplication{% endblock %} + +## +## The below is same as internal version, it seems that jinja doesn't have +## a good way to share it, this code has to be duplicated. +## + +{% block extra_application_attributes %} +{{ super() }} +android:multiArch="true" +android:extractNativeLibs="false" +{{use32bitAbi|default('')}} +{% endblock %} + +{% block extra_keyset_definitions %} + <!-- No keyset definitions should exist for any monochrome apks --> +{% endblock %} + +{% block extra_application_definitions %} +{{ super() }} +{{ webview.common(manifest_package, 'libmonochrome.so') }} +{% endblock %}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java b/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java index ca56877..985a2228 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java
@@ -52,6 +52,7 @@ public static final String ANDROID_PAY_INTEGRATION_V1 = "AndroidPayIntegrationV1"; public static final String AUTOFILL_SCAN_CARDHOLDER_NAME = "AutofillScanCardholderName"; public static final String CCT_EXTERNAL_LINK_HANDLING = "CCTExternalLinkHandling"; + public static final String CCT_POST_MESSAGE_API = "CCTPostMessageAPI"; public static final String CHROME_HOME = "ChromeHome"; public static final String CONSISTENT_OMNIBOX_GEOLOCATION = "ConsistentOmniboxGeolocation"; public static final String CONTEXTUAL_SEARCH_SINGLE_ACTIONS = "ContextualSearchSingleActions";
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/LayoutManager.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/LayoutManager.java index 17a70c9e..2c8f08e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/LayoutManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/LayoutManager.java
@@ -282,6 +282,11 @@ TabContentManager tabContentManager, ResourceManager resourceManager, ChromeFullscreenManager fullscreenManager) { getViewportPixel(mCachedVisibleViewport); + // TODO(mdjones): The concept of visible viewport is pretty confising since |viewport| can + // also take the browser controls into consideration; this should be made more clear. + // Furthermore, the below adjustments should not be necessary. + mCachedVisibleViewport.right = mCachedVisibleViewport.left + mHost.getWidth(); + mCachedVisibleViewport.bottom = mCachedVisibleViewport.top + mHost.getHeight(); return mActiveLayout.getUpdatedSceneLayer(viewport, mCachedVisibleViewport, layerTitleCache, tabContentManager, resourceManager, fullscreenManager); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/ClientManager.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/ClientManager.java index 561443e7..7dced043e3 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/ClientManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/ClientManager.java
@@ -9,9 +9,11 @@ import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.PackageManager; +import android.net.Uri; import android.os.IBinder; import android.os.SystemClock; import android.support.customtabs.CustomTabsCallback; +import android.support.customtabs.CustomTabsService; import android.support.customtabs.CustomTabsSessionToken; import android.text.TextUtils; import android.util.SparseBooleanArray; @@ -21,6 +23,7 @@ import org.chromium.base.metrics.RecordHistogram; import org.chromium.chrome.browser.IntentHandler; import org.chromium.chrome.browser.util.UrlUtilities; +import org.chromium.content_public.browser.WebContents; import org.chromium.content_public.common.Referrer; import java.util.ArrayList; @@ -54,6 +57,7 @@ public final int uid; public final DisconnectCallback disconnectCallback; public final String packageName; + public final PostMessageHandler postMessageHandler; public boolean mIgnoreFragments; private boolean mShouldHideDomain; private boolean mShouldPrerenderOnCellular; @@ -62,10 +66,12 @@ private String mPredictedUrl; private long mLastMayLaunchUrlTimestamp; - public SessionParams(Context context, int uid, DisconnectCallback callback) { + public SessionParams(Context context, int uid, DisconnectCallback callback, + PostMessageHandler postMessageHandler) { this.uid = uid; packageName = getPackageName(context, uid); disconnectCallback = callback; + this.postMessageHandler = postMessageHandler; } private static String getPackageName(Context context, int uid) { @@ -119,12 +125,13 @@ * @param session Session provided by the client. * @param uid Client UID, as returned by Binder.getCallingUid(), * @param onDisconnect To be called on the UI thread when a client gets disconnected. + * @param postMessageHandler The handler to be used for postMessage related operations. * @return true for success. */ - public boolean newSession( - CustomTabsSessionToken session, int uid, DisconnectCallback onDisconnect) { + public boolean newSession(CustomTabsSessionToken session, int uid, + DisconnectCallback onDisconnect, PostMessageHandler postMessageHandler) { if (session == null) return false; - SessionParams params = new SessionParams(mContext, uid, onDisconnect); + SessionParams params = new SessionParams(mContext, uid, onDisconnect, postMessageHandler); synchronized (this) { if (mSessionParams.containsKey(session)) return false; mSessionParams.put(session, params); @@ -132,6 +139,12 @@ return true; } + public synchronized int postMessage(CustomTabsSessionToken session, String message) { + SessionParams params = mSessionParams.get(session); + if (params == null) return CustomTabsService.RESULT_FAILURE_MESSAGING_ERROR; + return params.postMessageHandler.postMessage(message); + } + /** * Records that {@link CustomTabsConnection#warmup(long)} has been called from the given uid. */ @@ -210,6 +223,26 @@ } /** + * See {@link PostMessageHandler#setPostMessageOrigin(Uri)}. + */ + public synchronized void setPostMessageOriginForSession( + CustomTabsSessionToken session, Uri origin) { + SessionParams params = mSessionParams.get(session); + if (params == null) return; + params.postMessageHandler.setPostMessageOrigin(origin); + } + + /** + * See {@link PostMessageHandler#reset(WebContents)}. + */ + public synchronized void resetPostMessageHandlerForSession( + CustomTabsSessionToken session, WebContents webContents) { + SessionParams params = mSessionParams.get(session); + if (params == null) return; + params.postMessageHandler.reset(webContents); + } + + /** * @return The referrer that is associated with the client owning given session. */ public synchronized Referrer getReferrerForSession(CustomTabsSessionToken session) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java index b133dd5d..8fb9fc717 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java
@@ -206,6 +206,15 @@ } /** + * @return Whether the given session is the currently active session. + */ + public static boolean isActiveSession(CustomTabsSessionToken session) { + if (sActiveContentHandler == null) return false; + if (session == null || sActiveContentHandler.getSession() == null) return false; + return sActiveContentHandler.getSession().equals(session); + } + + /** * Checks whether the active {@link CustomTabContentHandler} belongs to the given session, and * if true, update toolbar's custom button. * @param session The {@link IBinder} that the calling client represents. @@ -501,6 +510,7 @@ RecordHistogram.recordEnumeratedHistogram("CustomTabs.WebcontentsStateOnLaunch", webContentsStateOnLaunch, WEBCONTENTS_STATE_MAX); if (webContents == null) webContents = WebContentsFactory.createWebContents(false, false); + customTabsConnection.resetPostMessageHandlerForSession(mSession, webContents); tab.initialize( webContents, getTabContentManager(), new CustomTabDelegateFactory(
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabsConnection.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabsConnection.java index f2694e7..4443ff3 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabsConnection.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabsConnection.java
@@ -36,6 +36,7 @@ import org.chromium.base.metrics.RecordHistogram; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeApplication; +import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.IntentHandler; import org.chromium.chrome.browser.WarmupManager; import org.chromium.chrome.browser.device.DeviceClassManager; @@ -158,11 +159,11 @@ * No rate-limiting, can be spammy if the app is misbehaved. * * @param name Call name to log. - * @param success Whether the call was successful. + * @param The return value for the logged call. */ - void logCall(String name, boolean success) { + void logCall(String name, Object result) { if (mLogRequests) { - Log.w(TAG, "%s = %b, Calling UID = %d", name, success, Binder.getCallingUid()); + Log.w(TAG, "%s = %b, Calling UID = %d", name, result, Binder.getCallingUid()); } } @@ -179,7 +180,8 @@ cancelPrerender(session); } }; - return mClientManager.newSession(session, Binder.getCallingUid(), onDisconnect); + PostMessageHandler handler = new PostMessageHandler(session); + return mClientManager.newSession(session, Binder.getCallingUid(), onDisconnect, handler); } /** Warmup activities that should only happen once. */ @@ -425,6 +427,55 @@ } /** + * Sends a request to look for a valid postMessage origin that is associated with the app + * owning the given {@link CustomTabsSessionToken}. + * @param session The session that the request is associated with + * @return Whether the validation request was accepted. + */ + public boolean validatePostMessageOrigin(CustomTabsSessionToken session) { + boolean success = validatePostMessageOriginInternal(session); + logCall("validatePostMessageOrigin()", success); + return success; + } + + private boolean validatePostMessageOriginInternal(final CustomTabsSessionToken session) { + if (!mWarmupHasBeenCalled.get()) return false; + if (!isCallerForegroundOrSelf()) return false; + ThreadUtils.postOnUiThread(new Runnable() { + @Override + public void run() { + // If the API is not enabled, we don't set the post message origin, which will + // avoid PostMessageHandler initialization and disallow postMessage calls. + if (!ChromeFeatureList.isEnabled(ChromeFeatureList.CCT_POST_MESSAGE_API)) return; + mClientManager.setPostMessageOriginForSession(session, Uri.EMPTY); + } + }); + return true; + } + + public int postMessage(CustomTabsSessionToken session, String message, Bundle extras) { + int result; + if (!mWarmupHasBeenCalled.get()) result = CustomTabsService.RESULT_FAILURE_DISALLOWED; + if (!isCallerForegroundOrSelf() && !CustomTabActivity.isActiveSession(session)) { + result = CustomTabsService.RESULT_FAILURE_DISALLOWED; + } + // If called before a validatePostMessageOrigin, the post message origin will be invalid and + // will return a failure result here. + result = mClientManager.postMessage(session, message); + logCall("postMessage", result); + return result; + } + + /** + * See + * {@link ClientManager#resetPostMessageHandlerForSession(CustomTabsSessionToken, WebContents)}. + */ + public void resetPostMessageHandlerForSession( + CustomTabsSessionToken session, WebContents webContents) { + mClientManager.resetPostMessageHandlerForSession(session, webContents); + } + + /** * Registers a launch of a |url| for a given |session|. * * This is used for accounting.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabsConnectionService.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabsConnectionService.java index 5f19e6e1..a4b5818 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabsConnectionService.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabsConnectionService.java
@@ -76,6 +76,19 @@ } @Override + protected boolean validatePostMessageOrigin(CustomTabsSessionToken sessionToken) { + if (!isFirstRunDone()) return false; + return mConnection.validatePostMessageOrigin(sessionToken); + } + + @Override + protected int postMessage(CustomTabsSessionToken sessionToken, String message, + Bundle extras) { + if (!isFirstRunDone()) return CustomTabsService.RESULT_FAILURE_DISALLOWED; + return mConnection.postMessage(sessionToken, message, extras); + } + + @Override protected boolean cleanUpSession(CustomTabsSessionToken sessionToken) { mConnection.cleanUpSession(sessionToken); return super.cleanUpSession(sessionToken);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/PostMessageHandler.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/PostMessageHandler.java new file mode 100644 index 0000000..cc5ebcc --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/PostMessageHandler.java
@@ -0,0 +1,151 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.customtabs; + +import android.net.Uri; +import android.support.customtabs.CustomTabsService; +import android.support.customtabs.CustomTabsSessionToken; + +import org.chromium.base.ThreadUtils; +import org.chromium.chrome.browser.tab.Tab; +import org.chromium.content.browser.AppWebMessagePort; +import org.chromium.content.browser.AppWebMessagePortService; +import org.chromium.content.browser.AppWebMessagePortService.MessageChannelObserver; +import org.chromium.content.browser.PostMessageSender; +import org.chromium.content.browser.PostMessageSender.PostMessageSenderDelegate; +import org.chromium.content_public.browser.MessagePort; +import org.chromium.content_public.browser.MessagePort.MessageCallback; +import org.chromium.content_public.browser.WebContents; +import org.chromium.content_public.browser.WebContentsObserver; + +/** + * A class that handles postMessage communications with a designated {@link CustomTabsSessionToken}. + */ +public class PostMessageHandler { + private static AppWebMessagePortService sService; + + private final CustomTabsSessionToken mSession; + private final MessageCallback mMessageCallback; + private AppWebMessagePort[] mChannel; + private PostMessageSender mPostMessageSender; + private PostMessageSenderDelegate mSenderDelegate; + private Uri mOrigin; + + private static AppWebMessagePortService getAppWebMessagePortService() { + if (sService == null) sService = new AppWebMessagePortService(); + return sService; + } + + /** + * Basic constructor. Everytime the given {@link CustomTabsSessionToken} is associated with a + * new {@link WebContents}, + * {@link PostMessageHandler#reset(WebContents)} should be called to + * reset all internal state. + * @param session The {@link CustomTabsSessionToken} to establish the postMessage communication + * with. + */ + public PostMessageHandler(CustomTabsSessionToken session) { + mSession = session; + mMessageCallback = new MessageCallback() { + @Override + public void onMessage(String message, MessagePort[] sentPorts) { + mSession.getCallback().onPostMessage(message, null); + } + }; + } + + /** + * Resets the internal state of the handler, linking the associated + * {@link CustomTabsSessionToken} with a new {@link WebContents} and the {@link Tab} that + * contains it. + * @param webContents The new {@link WebContents} that the session got associated with. + */ + public void reset(final WebContents webContents) { + if (mOrigin == null) return; + webContents.addObserver(new WebContentsObserver() { + private boolean mNavigatedOnce; + + @Override + public void didNavigateMainFrame(String url, String baseUrl, + boolean isNavigationToDifferentPage, boolean isFragmentNavigation, + int statusCode) { + if (mNavigatedOnce && isNavigationToDifferentPage && mChannel != null) { + mChannel[0].close(); + mChannel = null; + mSenderDelegate = null; + mPostMessageSender = null; + webContents.removeObserver(this); + return; + } + mNavigatedOnce = true; + } + + @Override + public void documentLoadedInFrame(long frameId, boolean isMainFrame) { + if (!isMainFrame || mChannel != null) return; + + final AppWebMessagePortService service = getAppWebMessagePortService(); + mChannel = (AppWebMessagePort[]) webContents.createMessageChannel(service); + mChannel[0].setMessageCallback(mMessageCallback, null); + mSenderDelegate = new PostMessageSenderDelegate() { + @Override + public void postMessageToWeb( + String frameName, String message, String targetOrigin, + int[] sentPortIds) { + webContents.postMessageToFrame( + frameName, message, targetOrigin, sentPortIds); + } + + @Override + public void onPostMessageQueueEmpty() {} + + @Override + public boolean isPostMessageSenderReady() { + return true; + } + }; + mPostMessageSender = new PostMessageSender( + mSenderDelegate, getAppWebMessagePortService()); + service.addObserver(new MessageChannelObserver() { + @Override + public void onMessageChannelCreated() { + service.removeObserver(this); + if (mChannel == null) return; + mPostMessageSender.postMessage( + null, "", "", new AppWebMessagePort[] {mChannel[1]}); + mSession.getCallback().onMessageChannelReady(mOrigin, null); + } + }); + } + }); + } + + /** + * Sets the postMessage origin for this session to the given {@link Uri}. + * @param origin The origin value to be set. + */ + public void setPostMessageOrigin(Uri origin) { + mOrigin = origin; + } + + /** + * Relay a postMessage request through the current channel assigned to this session. + * @param message The message to be sent. + * @return The result of the postMessage request. Returning true means the request was accepted, + * not necessarily that the postMessage was successful. + */ + public int postMessage(final String message) { + if (mChannel == null || !mChannel[0].isReady() || mChannel[0].isClosed()) { + return CustomTabsService.RESULT_FAILURE_MESSAGING_ERROR; + } + ThreadUtils.postOnUiThread(new Runnable() { + @Override + public void run() { + mChannel[0].postMessage(message, null); + } + }); + return CustomTabsService.RESULT_SUCCESS; + } +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadManagerService.java b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadManagerService.java index 74170ec..9dc1a2f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadManagerService.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadManagerService.java
@@ -1566,7 +1566,7 @@ @CalledByNative private void onDownloadItemUpdated(DownloadItem item) { for (DownloadHistoryAdapter adapter : mHistoryAdapters) { - adapter.onDownloadItemUpdated(item, item.getDownloadInfo().isOffTheRecord()); + adapter.onDownloadItemUpdated(item); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/ui/DeletedFileTracker.java b/chrome/android/java/src/org/chromium/chrome/browser/download/ui/DeletedFileTracker.java new file mode 100644 index 0000000..194c2497 --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/ui/DeletedFileTracker.java
@@ -0,0 +1,47 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.download.ui; + +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Tracks items that have been removed from downloads history because they were deleted externally. + * For use solely by the {@link DownloadHistoryAdapter}. + * + * TODO(dfalcantara): Make this class unnecessary. + */ +class DeletedFileTracker { + private final Set<String> mRegularItems = new HashSet<>(); + private final Set<String> mIncognitoItems = new HashSet<>(); + private final AtomicInteger mNumInstances = new AtomicInteger(); + + /** Called when a new {@link DownloadHistoryAdapter} is tracking deleted downloads. */ + void incrementInstanceCount() { + mNumInstances.getAndIncrement(); + } + + /** Called when a {@link DownloadHistoryAdapter} is no longer traking deleted downloads. */ + void decrementInstanceCount() { + if (mNumInstances.decrementAndGet() == 0) { + // If there is no interest, clear out the maps so that they stop taking up space. + mRegularItems.clear(); + mIncognitoItems.clear(); + } + } + + /** Add a new item to the tracker. */ + void add(String id, boolean isOffTheRecord) { + Set<String> items = isOffTheRecord ? mIncognitoItems : mRegularItems; + items.add(id); + } + + /** Checks if an item is in the tracker. */ + boolean contains(String id, boolean isOffTheRecord) { + Set<String> items = isOffTheRecord ? mIncognitoItems : mRegularItems; + return items.contains(id); + } +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/ui/DownloadHistoryAdapter.java b/chrome/android/java/src/org/chromium/chrome/browser/download/ui/DownloadHistoryAdapter.java index dd44abfb..22b1148 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/ui/DownloadHistoryAdapter.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/ui/DownloadHistoryAdapter.java
@@ -26,10 +26,7 @@ import org.chromium.content_public.browser.DownloadState; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicInteger; /** Bridges the user's download history and the UI used to display it. */ public class DownloadHistoryAdapter extends DateDividedAdapter implements DownloadUiObserver { @@ -38,21 +35,10 @@ private static final int INVALID_INDEX = -1; /** - * Externally deleted items that have been removed from downloads history. + * Tracks externally deleted items that have been removed from downloads history. * Shared across instances. */ - private static Map<String, Boolean> sExternallyDeletedItems = new HashMap<>(); - - /** - * Externally deleted off-the-record items that have been removed from downloads history. - * Shared across instances. - */ - private static Map<String, Boolean> sExternallyDeletedOffTheRecordItems = new HashMap<>(); - - /** - * The number of DownloadHistoryAdapater instances in existence that have been initialized. - */ - private static final AtomicInteger sNumInstancesInitialized = new AtomicInteger(); + private static final DeletedFileTracker sDeletedFileTracker = new DeletedFileTracker(); private final List<DownloadItemWrapper> mDownloadItems = new ArrayList<>(); private final List<DownloadItemWrapper> mDownloadOffTheRecordItems = new ArrayList<>(); @@ -93,7 +79,7 @@ initializeOfflinePageBridge(); - sNumInstancesInitialized.getAndIncrement(); + sDeletedFileTracker.incrementInstanceCount(); } /** Called when the user's download history has been gathered. */ @@ -119,22 +105,11 @@ int[] mItemCounts = new int[DownloadFilter.FILTER_BOUNDARY]; for (DownloadItem item : result) { - DownloadItemWrapper wrapper = createDownloadItemWrapper(item, isOffTheRecord); - // Don't display any incomplete downloads, yet. if (item.getDownloadInfo().state() != DownloadState.COMPLETE) continue; - // TODO(twellington): The native downloads service should remove externally deleted - // downloads rather than passing them to Java. - if (getExternallyDeletedItemsMap(isOffTheRecord).containsKey(wrapper.getId())) { - continue; - } else if (wrapper.hasBeenExternallyRemoved()) { - removeExternallyDeletedItem(wrapper, isOffTheRecord); - } else { - list.add(wrapper); - mItemCounts[wrapper.getFilterType()]++; - mFilePathsToItemsMap.addItem(wrapper); - } + DownloadItemWrapper wrapper = createDownloadItemWrapper(item); + if (addDownloadItemToList(wrapper)) mItemCounts[wrapper.getFilterType()]++; } if (!isOffTheRecord) recordDownloadCountHistograms(mItemCounts); @@ -142,6 +117,38 @@ onItemsRetrieved(); } + /** + * Checks if a wrapper corresponds to a DownloadItem that was already deleted. + * @return True if it does, false otherwise. + */ + private boolean updateDeletedFileMap(DownloadItemWrapper wrapper) { + boolean isOffTheRecord = wrapper.isOffTheRecord(); + + // TODO(twellington): The native downloads service should remove externally deleted + // downloads rather than passing them to Java. + if (sDeletedFileTracker.contains(wrapper.getId(), isOffTheRecord)) { + return true; + } + + if (wrapper.hasBeenExternallyRemoved()) { + sDeletedFileTracker.add(wrapper.getId(), isOffTheRecord); + wrapper.remove(); + mFilePathsToItemsMap.removeItem(wrapper); + RecordUserAction.record("Android.DownloadManager.Item.ExternallyDeleted"); + return true; + } + + return false; + } + + private boolean addDownloadItemToList(DownloadItemWrapper wrapper) { + if (updateDeletedFileMap(wrapper)) return false; + + getDownloadItemList(wrapper.isOffTheRecord()).add(wrapper); + mFilePathsToItemsMap.addItem(wrapper); + return true; + } + /** Called when the user's offline page history has been gathered. */ private void onAllOfflinePagesRetrieved(List<OfflinePageDownloadItem> result) { if (mAllOfflinePagesRetrieved) return; @@ -210,30 +217,21 @@ /** * Updates the list when new information about a download comes in. */ - public void onDownloadItemUpdated(DownloadItem item, boolean isOffTheRecord) { - if (isOffTheRecord && !mShowOffTheRecord) return; + public void onDownloadItemUpdated(DownloadItem item) { + if (item.getDownloadInfo().isOffTheRecord() && !mShowOffTheRecord) return; // The adapter currently only cares about completion events. if (item.getDownloadInfo().state() != DownloadState.COMPLETE) return; - List<DownloadItemWrapper> list = getDownloadItemList(isOffTheRecord); + // Check if the item had already been deleted. + DownloadItemWrapper wrapper = createDownloadItemWrapper(item); + if (updateDeletedFileMap(wrapper)) return; + + List<DownloadItemWrapper> list = getDownloadItemList(wrapper.isOffTheRecord()); int index = findItemIndex(list, item.getId()); - DownloadItemWrapper wrapper = createDownloadItemWrapper(item, isOffTheRecord); - - // If an externally deleted item has already been removed from the history service, it - // shouldn't be removed again. - if (getExternallyDeletedItemsMap(isOffTheRecord).containsKey(wrapper.getId())) return; - - if (wrapper.hasBeenExternallyRemoved()) { - removeExternallyDeletedItem(wrapper, isOffTheRecord); - return; - } - if (index == INVALID_INDEX) { - // Add a new entry. - list.add(wrapper); - mFilePathsToItemsMap.addItem(wrapper); + addDownloadItemToList(wrapper); } else { DownloadItemWrapper previousWrapper = list.get(index); // If the previous item was selected, the updated item should be selected as well. @@ -276,13 +274,7 @@ public void onManagerDestroyed() { getDownloadDelegate().removeDownloadHistoryAdapter(this); getOfflinePageBridge().removeObserver(mOfflinePageObserver); - - // If there are no more instances, clear out externally deleted items maps so that they stop - // taking up space. - if (sNumInstancesInitialized.decrementAndGet() == 0) { - sExternallyDeletedItems.clear(); - sExternallyDeletedOffTheRecordItems.clear(); - } + sDeletedFileTracker.decrementInstanceCount(); } /** @@ -442,9 +434,9 @@ return false; } - private DownloadItemWrapper createDownloadItemWrapper( - DownloadItem item, boolean isOffTheRecord) { - return new DownloadItemWrapper(item, isOffTheRecord, mBackendProvider, mParentComponent); + private DownloadItemWrapper createDownloadItemWrapper(DownloadItem item) { + return new DownloadItemWrapper( + item, item.getDownloadInfo().isOffTheRecord(), mBackendProvider, mParentComponent); } private OfflinePageItemWrapper createOfflinePageItemWrapper(OfflinePageDownloadItem item) { @@ -471,17 +463,6 @@ mDownloadItems.size() + mOfflinePageItems.size()); } - private void removeExternallyDeletedItem(DownloadItemWrapper wrapper, boolean isOffTheRecord) { - getExternallyDeletedItemsMap(isOffTheRecord).put(wrapper.getId(), true); - wrapper.remove(); - mFilePathsToItemsMap.removeItem(wrapper); - RecordUserAction.record("Android.DownloadManager.Item.ExternallyDeleted"); - } - - private Map<String, Boolean> getExternallyDeletedItemsMap(boolean isOffTheRecord) { - return isOffTheRecord ? sExternallyDeletedOffTheRecordItems : sExternallyDeletedItems; - } - /** * Determines when the data from all of the backends has been loaded. * <p>
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ntp/NewTabPage.java b/chrome/android/java/src/org/chromium/chrome/browser/ntp/NewTabPage.java index 96fd23a1..7be3f76 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ntp/NewTabPage.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ntp/NewTabPage.java
@@ -53,6 +53,7 @@ import org.chromium.chrome.browser.ntp.snippets.SnippetsConfig; import org.chromium.chrome.browser.ntp.snippets.SuggestionsSource; import org.chromium.chrome.browser.offlinepages.OfflinePageBridge; +import org.chromium.chrome.browser.offlinepages.OfflinePageUtils; import org.chromium.chrome.browser.offlinepages.downloads.OfflinePageDownloadBridge; import org.chromium.chrome.browser.preferences.PrefServiceBridge; import org.chromium.chrome.browser.profiles.MostVisitedSites; @@ -349,7 +350,7 @@ mSnippetsBridge.onSuggestionOpened(article, windowOpenDisposition); NewTabPageUma.recordAction(NewTabPageUma.ACTION_OPENED_SNIPPET); - if (article.mIsDownloadedAsset) { + if (article.isDownload() && article.mIsDownloadedAsset) { DownloadUtils.openFile( article.getDownloadAssetFile(), article.getDownloadAssetMimeType(), false); return; @@ -360,6 +361,14 @@ return; } + if (article.isRecentTab()) { + assert windowOpenDisposition == WindowOpenDisposition.CURRENT_TAB; + // TODO(vitaliii): Add a debug check that the result is true after crbug.com/662924 + // is resolved. + openRecentTabSnippet(article); + return; + } + NewTabPageUma.monitorContentSuggestionVisit(mTab, article.mCategory); LoadUrlParams loadUrlParams = new LoadUrlParams(article.mUrl, PageTransition.AUTO_BOOKMARK); @@ -375,6 +384,17 @@ openUrl(windowOpenDisposition, loadUrlParams); } + private boolean openRecentTabSnippet(SnippetArticle recentTabArticle) { + TabModel tabModel = mTabModelSelector.getModel(false); + int tabId = Integer.parseInt(recentTabArticle.getRecentTabId()); + int tabIndex = TabModelUtils.getTabIndexById(tabModel, tabId); + if (tabIndex == TabModel.INVALID_TAB_INDEX) return false; + TabModelUtils.setIndex(tabModel, tabIndex); + OfflinePageUtils.openInExistingTab(recentTabArticle.mUrl, + Long.parseLong(recentTabArticle.getRecentTabId()), tabModel.getTabAt(tabIndex)); + return true; + } + private void openUrl(int windowOpenDisposition, LoadUrlParams loadUrlParams) { assert !mIsDestroyed; switch (windowOpenDisposition) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ntp/snippets/SnippetArticle.java b/chrome/android/java/src/org/chromium/chrome/browser/ntp/snippets/SnippetArticle.java index 2587aa2..0893699 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ntp/snippets/SnippetArticle.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ntp/snippets/SnippetArticle.java
@@ -72,6 +72,12 @@ /** The mime type of the downloaded asset (only for download asset articles). */ private String mDownloadAssetMimeType; + /** The tab id of the corresponding tab (only for recent tab articles). */ + private String mRecentTabId; + + /** The offline page id (only for recent tab articles). */ + private String mRecentTabOfflinePageId; + /** The path to the offline page, if any. */ private String mOfflinePagePath; @@ -135,30 +141,74 @@ mOfflineStatusChangeRunnable = runnable; } + /** @return whether a snippet is either offline page or asset download. */ + public boolean isDownload() { + return mCategory == KnownCategories.DOWNLOADS; + } + /** - * @return the downloaded asset. May only be called if mIsDownloadedAsset is {@code true}. + * @return the downloaded asset. May only be called if mIsDownloadedAsset is {@code true} and + * this snippet belongs to DOWNLOADS category. */ public File getDownloadAssetFile() { - assert mIsDownloadedAsset; + assert isDownload(); if (mFile == null) mFile = new File(mDownloadAssetPath); return mFile; } - /** Returns the mime type of the download asset. May only be called if mIsDownloadAsset is true. + /** + * @return the mime type of the download asset. May only be called if mIsDownloadAsset is + * {@code true} and this snippet belongs to DOWNLOADS category. */ public String getDownloadAssetMimeType() { - assert mIsDownloadedAsset; + assert isDownload(); return mDownloadAssetMimeType; } - /** Marks the article suggestion as a download asset with the given path and mime type. */ - public void setDownloadAsset(String filePath, String mimeType) { + /** + * Marks the article suggestion as a download asset with the given path and mime type. May only + * be called if this snippet belongs to DOWNLOADS category. + */ + public void setDownloadAssetData(String filePath, String mimeType) { + assert isDownload(); mIsDownloadedAsset = true; mDownloadAssetPath = filePath; mDownloadAssetMimeType = mimeType; } - /** Sets OfflinePageDownloads guid for the offline version of the snippet. Null to clear.*/ + public boolean isRecentTab() { + return mCategory == KnownCategories.RECENT_TABS; + } + + /** + * @return the corresponding recent tab id. May only be called if this snippet is a recent tab + * article. + */ + public String getRecentTabId() { + assert isRecentTab(); + return mRecentTabId; + } + + /** + * @return the corresponding recent tab offline page id. May only be called if this snippet is a + * recent tab article. + */ + public String getRecentTabOfflinePageId() { + assert isRecentTab(); + return mRecentTabOfflinePageId; + } + + /** + * Sets tab id and offline page id for recent tab articles. May only be called if this snippet + * is a recent tab article. + */ + public void setRecentTabData(String tabId, String offlinePageId) { + assert isRecentTab(); + mRecentTabId = tabId; + mRecentTabOfflinePageId = offlinePageId; + } + + /** Sets OfflinePageDownloads guid for the offline version of the snippet. Null to clear. */ public void setOfflinePageDownloadGuid(String path) { String previous = mOfflinePagePath; mOfflinePagePath = path;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ntp/snippets/SnippetsBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/ntp/snippets/SnippetsBridge.java index b7ab35a8..9658d36 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ntp/snippets/SnippetsBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ntp/snippets/SnippetsBridge.java
@@ -213,7 +213,14 @@ private static void setDownloadAssetDataForLastSuggestion( List<SnippetArticle> suggestions, String filePath, String mimeType) { assert suggestions.size() > 0; - suggestions.get(suggestions.size() - 1).setDownloadAsset(filePath, mimeType); + suggestions.get(suggestions.size() - 1).setDownloadAssetData(filePath, mimeType); + } + + @CalledByNative + private static void setRecentTabDataForLastSuggestion( + List<SnippetArticle> suggestions, String tabId, String offlinePageId) { + assert suggestions.size() > 0; + suggestions.get(suggestions.size() - 1).setRecentTabData(tabId, offlinePageId); } @CalledByNative
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/offlinepages/OfflinePageUtils.java b/chrome/android/java/src/org/chromium/chrome/browser/offlinepages/OfflinePageUtils.java index 8f97ad4..17cec46 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/offlinepages/OfflinePageUtils.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/offlinepages/OfflinePageUtils.java
@@ -42,6 +42,8 @@ import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; +import java.util.HashMap; +import java.util.Map; import java.util.concurrent.TimeUnit; /** @@ -548,6 +550,22 @@ } /** + * A load url parameters to open offline version of the offline page (i.e. to ensure no + * automatic redirection based on the connection status). + * @param url The url of the offline page to open. + * @param offlineId The ID of the offline page to open. + * @return The LoadUrlParams with a special header. + */ + public static LoadUrlParams getLoadUrlParamsForOpeningOfflineVersion( + String url, long offlineId) { + LoadUrlParams params = new LoadUrlParams(url); + Map<String, String> headers = new HashMap<String, String>(); + headers.put("X-Chrome-offline", "persist=1 reason=download id=" + Long.toString(offlineId)); + params.setExtraHeaders(headers); + return params; + } + + /** * @return True if an offline preview is being shown. * @param tab The current tab. */ @@ -570,6 +588,21 @@ tab.loadUrl(params); } + /** + * Navigates the given tab to the saved local snapshot of the offline page identified by the URL + * and the offline ID. No automatic redirection is happening based on the connection status. + * @param url The URL of the offine page. + * @param offlineId The ID of the offline page. + * @param tab The tab to navigate to the page. + */ + public static void openInExistingTab(String url, long offlineId, Tab tab) { + LoadUrlParams params = + OfflinePageUtils.getLoadUrlParamsForOpeningOfflineVersion(url, offlineId); + // Extra headers are not read in loadUrl, but verbatim headers are. + params.setVerbatimHeaders(params.getExtraHeadersString()); + tab.loadUrl(params); + } + private static boolean isPowerConnected(Intent batteryStatus) { int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1); boolean isConnected = (status == BatteryManager.BATTERY_STATUS_CHARGING
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/offlinepages/downloads/OfflinePageDownloadBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/offlinepages/downloads/OfflinePageDownloadBridge.java index 5a52c51..af1a65b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/offlinepages/downloads/OfflinePageDownloadBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/offlinepages/downloads/OfflinePageDownloadBridge.java
@@ -13,6 +13,7 @@ import org.chromium.chrome.browser.download.DownloadItem; import org.chromium.chrome.browser.download.DownloadServiceDelegate; import org.chromium.chrome.browser.download.ui.BackendProvider.OfflinePageDelegate; +import org.chromium.chrome.browser.offlinepages.OfflinePageUtils; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tabmodel.TabModel.TabLaunchType; @@ -21,9 +22,7 @@ import org.chromium.content_public.browser.LoadUrlParams; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; /** * Serves as an interface between Download Home UI and offline page related items that are to be @@ -173,12 +172,8 @@ OfflinePageDownloadItem item = getItem(guid); if (item == null) return; - LoadUrlParams params = new LoadUrlParams(item.getUrl()); - Map<String, String> headers = new HashMap<String, String>(); - headers.put("X-Chrome-offline", "persist=1 reason=download id=" - + Long.toString(nativeGetOfflineIdByGuid( - mNativeOfflinePageDownloadBridge, guid))); - params.setExtraHeaders(headers); + LoadUrlParams params = OfflinePageUtils.getLoadUrlParamsForOpeningOfflineVersion( + item.getUrl(), nativeGetOfflineIdByGuid(mNativeOfflinePageDownloadBridge, guid)); AsyncTabCreationParams asyncParams = componentName == null ? new AsyncTabCreationParams(params) : new AsyncTabCreationParams(params, componentName);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/website/SiteSettingsPreferences.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/website/SiteSettingsPreferences.java index 0c970c1..44551cb7 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/website/SiteSettingsPreferences.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/website/SiteSettingsPreferences.java
@@ -10,9 +10,7 @@ import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceFragment; -import org.chromium.base.FieldTrialList; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.ContentSettingsType; import org.chromium.chrome.browser.net.spdyproxy.DataReductionProxySettings; import org.chromium.chrome.browser.preferences.LocationSettings; @@ -51,11 +49,6 @@ static final String TRANSLATE_KEY = "translate"; static final String USB_KEY = "usb"; - static final String AUTOPLAY_MUTED_VIDEOS = "AutoplayMutedVideos"; - - // Whether the Autoplay menu is available for display. - boolean mAutoplayMenuAvailable = false; - // Whether the Protected Content menu is available for display. boolean mProtectedContentMenuAvailable = false; @@ -70,11 +63,6 @@ mProtectedContentMenuAvailable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; - String autoplayTrialGroupName = - FieldTrialList.findFullName("MediaElementGestureOverrideExperiment"); - mAutoplayMenuAvailable = autoplayTrialGroupName.startsWith("Enabled") - || ChromeFeatureList.isEnabled(AUTOPLAY_MUTED_VIDEOS); - String category = ""; if (getArguments() != null) { category = getArguments().getString(SingleCategoryPreferences.EXTRA_CATEGORY, ""); @@ -133,15 +121,9 @@ } else { // If both Autoplay and Protected Content menus are available, they'll be tucked under // the Media key. Otherwise, we can remove the Media menu entry. - if (!mAutoplayMenuAvailable || !mProtectedContentMenuAvailable) { + if (!mProtectedContentMenuAvailable) { getPreferenceScreen().removePreference(findPreference(MEDIA_KEY)); - - if (!mAutoplayMenuAvailable) { - getPreferenceScreen().removePreference(findPreference(AUTOPLAY_KEY)); - } - if (!mProtectedContentMenuAvailable) { - getPreferenceScreen().removePreference(findPreference(PROTECTED_CONTENT_KEY)); - } + getPreferenceScreen().removePreference(findPreference(PROTECTED_CONTENT_KEY)); } else { // These two will be tucked under the Media subkey, so no reason to show them now. getPreferenceScreen().removePreference(findPreference(AUTOPLAY_KEY)); @@ -165,12 +147,9 @@ websitePrefs.add(PROTECTED_CONTENT_KEY); websitePrefs.add(AUTOPLAY_KEY); } else { - // When showing the main menu, only one of these two will be visible, at most. - if (mProtectedContentMenuAvailable && !mAutoplayMenuAvailable) { - websitePrefs.add(PROTECTED_CONTENT_KEY); - } else if (mAutoplayMenuAvailable && !mProtectedContentMenuAvailable) { - websitePrefs.add(AUTOPLAY_KEY); - } + // When showing the main menu, if Protected Content is not available, only Autoplay + // will be visible. + if (!mProtectedContentMenuAvailable) websitePrefs.add(AUTOPLAY_KEY); websitePrefs.add(BACKGROUND_SYNC_KEY); websitePrefs.add(CAMERA_KEY); websitePrefs.add(COOKIES_KEY);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/vr_shell/VrShellImpl.java b/chrome/android/java/src/org/chromium/chrome/browser/vr_shell/VrShellImpl.java index 7b82f344..9fcaf3e5 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/vr_shell/VrShellImpl.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/vr_shell/VrShellImpl.java
@@ -279,6 +279,7 @@ @Override public void onResume() { super.onResume(); + mGlSurfaceView.onResume(); if (mNativeVrShell != 0) { // Refreshing the viewer profile accesses disk, so we need to temporarily allow disk // reads. The GVR team promises this will be fixed when they launch. @@ -294,6 +295,7 @@ @Override public void onPause() { super.onPause(); + mGlSurfaceView.onPause(); if (mNativeVrShell != 0) { nativeOnPause(mNativeVrShell); } @@ -303,6 +305,8 @@ public void shutdown() { super.shutdown(); if (mNativeVrShell != 0) { + // Ensure our GL thread is stopped before we destroy the native VR Shell. + mGlSurfaceView.onPause(); nativeDestroy(mNativeVrShell); mNativeVrShell = 0; }
diff --git a/chrome/android/java/templates/BUILD.gn b/chrome/android/java/templates/BUILD.gn new file mode 100644 index 0000000..52a597c2d --- /dev/null +++ b/chrome/android/java/templates/BUILD.gn
@@ -0,0 +1,27 @@ +# Copyright 2016 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//build/config/android/config.gni") +import("//build/config/android/rules.gni") +import("monochrome_application.gni") + +monochrome_application = "$target_gen_dir/public_monochrome_application/org/chromium/chrome/browser/MonochromeApplication.java" + +generate_monochrome_application("monochrome_application_class") { + package = "org.chromium.chrome.browser" + super_class = "ChromeApplication" + monochrome_application_class = "MonochromeApplication" + output = monochrome_application +} + +android_library("public_monochrome_java") { + deps = [ + ":monochrome_application_class", + "//android_webview/glue", + "//base:base_java", + "//chrome/android:chrome_java", + "//content/public/android:content_java", + ] + java_files = [ monochrome_application ] +}
diff --git a/chrome/android/java/templates/MonochromeApplication.template b/chrome/android/java/templates/MonochromeApplication.template new file mode 100644 index 0000000..d721fbb --- /dev/null +++ b/chrome/android/java/templates/MonochromeApplication.template
@@ -0,0 +1,40 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package {{package}}; + +import android.content.Context; + +import com.android.webview.chromium.MonochromeLibraryPreloader; + +import org.chromium.base.library_loader.LibraryLoader; +import org.chromium.base.library_loader.LibraryProcessType; +import org.chromium.content.browser.ChildProcessCreationParams; + +/** + * This is Application class for Monochrome. + * + * You shouldn't add anything else in this file, this class is split off from + * normal chrome in order to access Android system API through Android WebView + * glue layer and have monochrome specific code. + */ +public class {{ monochrome_application_class }} extends {{ super_class }} { + private ChildProcessCreationParams mChildProcessCreationParams; + + @Override + public ChildProcessCreationParams getChildProcessCreationParams() { + return mChildProcessCreationParams; + } + + @Override + public void onCreate() { + super.onCreate(); + LibraryLoader.setNativeLibraryPreloader(new MonochromeLibraryPreloader()); + // ChildProcessCreationParams is only needed for browser process, though it is + // created and set in all processes. + mChildProcessCreationParams = new ChildProcessCreationParams(getPackageName(), + true /* isExternalService */, LibraryProcessType.PROCESS_CHILD); + ChildProcessCreationParams.set(mChildProcessCreationParams); + } +}
diff --git a/chrome/android/java/templates/monochrome_application.gni b/chrome/android/java/templates/monochrome_application.gni new file mode 100644 index 0000000..70a1918c --- /dev/null +++ b/chrome/android/java/templates/monochrome_application.gni
@@ -0,0 +1,35 @@ +# Copyright 2016 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//build/config/android/config.gni") +import("//build/config/android/rules.gni") + +# Generates monochrome application class. +# +# Variables +# monochrome_application_class: the name of monochrome application class. +# package: the package name of monochrome class. +# super_class: the super class of monochrome application. +# output: the generated application class. +template("generate_monochrome_application") { + jinja_template(target_name) { + forward_variables_from(invoker, + [ + "output", + "monochrome_application_class", + "package", + "super_class", + ]) + assert(defined(output)) + assert(defined(monochrome_application_class)) + assert(defined(package)) + assert(defined(super_class)) + input = "//chrome/android/java/templates/MonochromeApplication.template" + variables = [ + "package=${package}", + "super_class=${super_class}", + "monochrome_application_class=${monochrome_application_class}", + ] + } +}
diff --git a/chrome/android/java_sources.gni b/chrome/android/java_sources.gni index 60b89eb..3e97f05 100644 --- a/chrome/android/java_sources.gni +++ b/chrome/android/java_sources.gni
@@ -274,6 +274,7 @@ "java/src/org/chromium/chrome/browser/customtabs/CustomTabsConnection.java", "java/src/org/chromium/chrome/browser/customtabs/CustomTabsConnectionService.java", "java/src/org/chromium/chrome/browser/customtabs/CustomTabTabPersistencePolicy.java", + "java/src/org/chromium/chrome/browser/customtabs/PostMessageHandler.java", "java/src/org/chromium/chrome/browser/customtabs/RequestThrottler.java", "java/src/org/chromium/chrome/browser/customtabs/SeparateTaskCustomTabActivity.java", "java/src/org/chromium/chrome/browser/customtabs/SeparateTaskCustomTabActivity0.java", @@ -324,6 +325,7 @@ "java/src/org/chromium/chrome/browser/download/OMADownloadHandler.java", "java/src/org/chromium/chrome/browser/download/SystemDownloadNotifier.java", "java/src/org/chromium/chrome/browser/download/ui/BackendProvider.java", + "java/src/org/chromium/chrome/browser/download/ui/DeletedFileTracker.java", "java/src/org/chromium/chrome/browser/download/ui/DownloadFilter.java", "java/src/org/chromium/chrome/browser/download/ui/DownloadHistoryAdapter.java", "java/src/org/chromium/chrome/browser/download/ui/DownloadHistoryItemViewHolder.java",
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/ClientManagerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/ClientManagerTest.java index c2e793b..d27e67c 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/ClientManagerTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/ClientManagerTest.java
@@ -53,7 +53,7 @@ @SmallTest public void testValidSessionNoWarmup() { - mClientManager.newSession(mSession, mUid, null); + mClientManager.newSession(mSession, mUid, null, null); assertEquals(ClientManager.SESSION_NO_WARMUP_NOT_CALLED, mClientManager.getWarmupState(mSession)); } @@ -61,7 +61,7 @@ @SmallTest public void testValidSessionOtherWarmup() { mClientManager.recordUidHasCalledWarmup(mUid + 1); - mClientManager.newSession(mSession, mUid, null); + mClientManager.newSession(mSession, mUid, null, null); assertEquals(ClientManager.SESSION_NO_WARMUP_ALREADY_CALLED, mClientManager.getWarmupState(mSession)); } @@ -69,25 +69,25 @@ @SmallTest public void testValidSessionWarmup() { mClientManager.recordUidHasCalledWarmup(mUid); - mClientManager.newSession(mSession, mUid, null); + mClientManager.newSession(mSession, mUid, null, null); assertEquals(ClientManager.SESSION_WARMUP, mClientManager.getWarmupState(mSession)); } @SmallTest public void testValidSessionWarmupSeveralCalls() { mClientManager.recordUidHasCalledWarmup(mUid); - mClientManager.newSession(mSession, mUid, null); + mClientManager.newSession(mSession, mUid, null, null); assertEquals(ClientManager.SESSION_WARMUP, mClientManager.getWarmupState(mSession)); CustomTabsSessionToken token = CustomTabsSessionToken.createDummySessionTokenForTesting(); - mClientManager.newSession(token, mUid, null); + mClientManager.newSession(token, mUid, null, null); assertEquals(ClientManager.SESSION_WARMUP, mClientManager.getWarmupState(token)); } @SmallTest @RetryOnFailure public void testPredictionOutcomeSuccess() { - assertTrue(mClientManager.newSession(mSession, mUid, null)); + assertTrue(mClientManager.newSession(mSession, mUid, null, null)); assertTrue(mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, URL)); assertEquals( ClientManager.GOOD_PREDICTION, mClientManager.getPredictionOutcome(mSession, URL)); @@ -95,7 +95,7 @@ @SmallTest public void testPredictionOutcomeNoPrediction() { - assertTrue(mClientManager.newSession(mSession, mUid, null)); + assertTrue(mClientManager.newSession(mSession, mUid, null, null)); mClientManager.recordUidHasCalledWarmup(mUid); assertEquals( ClientManager.NO_PREDICTION, mClientManager.getPredictionOutcome(mSession, URL)); @@ -103,7 +103,7 @@ @SmallTest public void testPredictionOutcomeBadPrediction() { - assertTrue(mClientManager.newSession(mSession, mUid, null)); + assertTrue(mClientManager.newSession(mSession, mUid, null, null)); assertTrue(mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, URL)); assertEquals( ClientManager.BAD_PREDICTION, @@ -112,7 +112,7 @@ @SmallTest public void testPredictionOutcomeIgnoreFragment() { - assertTrue(mClientManager.newSession(mSession, mUid, null)); + assertTrue(mClientManager.newSession(mSession, mUid, null, null)); assertTrue(mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, URL)); mClientManager.setIgnoreFragmentsForSession(mSession, true); assertEquals(
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityTest.java index bd2b8fb5..5116be5 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityTest.java
@@ -27,6 +27,7 @@ import android.support.customtabs.CustomTabsCallback; import android.support.customtabs.CustomTabsClient; import android.support.customtabs.CustomTabsIntent; +import android.support.customtabs.CustomTabsService; import android.support.customtabs.CustomTabsServiceConnection; import android.support.customtabs.CustomTabsSession; import android.support.customtabs.CustomTabsSessionToken; @@ -78,6 +79,7 @@ import org.chromium.content.browser.test.util.JavaScriptUtils; import org.chromium.content_public.browser.LoadUrlParams; import org.chromium.net.test.EmbeddedTestServer; +import org.chromium.net.test.util.TestWebServer; import java.util.ArrayList; import java.util.concurrent.Callable; @@ -100,6 +102,30 @@ private static final String TEST_MENU_TITLE = "testMenuTitle"; private static final String PRIVATE_DATA_DIRECTORY_SUFFIX = "chrome"; private static final String WEBLITE_PREFIX = "http://googleweblight.com/?lite_url="; + private static final String JS_MESSAGE = "from_js"; + private static final String TITLE_FROM_POSTMESSAGE_TO_CHANNEL = + "<!DOCTYPE html><html><body>" + + " <script>" + + " var received = '';" + + " onmessage = function (e) {" + + " var myport = e.ports[0];" + + " myport.onmessage = function (f) {" + + " received += f.data;" + + " document.title = received;" + + " }" + + " }" + + " </script>" + + "</body></html>"; + private static final String MESSAGE_FROM_PAGE_TO_CHANNEL = + "<!DOCTYPE html><html><body>" + + " <script>" + + " onmessage = function (e) {" + + " if (e.ports != null && e.ports.length > 0) {" + + " e.ports[0].postMessage(\"" + JS_MESSAGE + "\");" + + " }" + + " }" + + " </script>" + + "</body></html>"; private static int sIdToIncrement = 1; @@ -107,6 +133,7 @@ private String mTestPage; private String mTestPage2; private EmbeddedTestServer mTestServer; + private TestWebServer mWebServer; @Override protected void setUp() throws Exception { @@ -117,6 +144,7 @@ mTestPage2 = mTestServer.getURL(TEST_PAGE_2); PathUtils.setPrivateDataDirectorySuffix(PRIVATE_DATA_DIRECTORY_SUFFIX); LibraryLoader.get(LibraryProcessType.PROCESS_BROWSER).ensureInitialized(); + mWebServer = TestWebServer.start(); } @Override @@ -133,7 +161,7 @@ if (handler != null) handler.hideAppMenu(); } }); - + mWebServer.shutdown(); super.tearDown(); } @@ -856,6 +884,171 @@ */ @SmallTest @RetryOnFailure + public void testPostMessageBasic() throws InterruptedException { + final CustomTabsConnection connection = warmUpAndWait(); + Context context = getInstrumentation().getTargetContext(); + Intent intent = CustomTabsTestUtils.createMinimalCustomTabIntent(context, mTestPage); + final CustomTabsSessionToken token = + CustomTabsSessionToken.getSessionTokenFromIntent(intent); + assertTrue(connection.newSession(token)); + assertTrue(connection.validatePostMessageOrigin(token)); + try { + startCustomTabActivityWithIntent(intent); + } catch (InterruptedException e) { + fail(); + } + CriteriaHelper.pollInstrumentationThread(new Criteria() { + @Override + public boolean isSatisfied() { + final Tab currentTab = getActivity().getActivityTab(); + return mTestPage.equals(currentTab.getUrl()); + } + }); + CriteriaHelper.pollInstrumentationThread(new Criteria() { + @Override + public boolean isSatisfied() { + return connection.postMessage(token, "Message", null) + == CustomTabsService.RESULT_SUCCESS; + } + }); + ThreadUtils.runOnUiThreadBlocking(new Runnable() { + @Override + public void run() { + getActivity().getActivityTab().loadUrl(new LoadUrlParams(mTestPage2)); + } + }); + CriteriaHelper.pollInstrumentationThread(new Criteria() { + @Override + public boolean isSatisfied() { + final Tab currentTab = getActivity().getActivityTab(); + return mTestPage2.equals(currentTab.getUrl()); + } + }); + CriteriaHelper.pollInstrumentationThread(new Criteria() { + @Override + public boolean isSatisfied() { + return connection.postMessage(token, "Message", null) + == CustomTabsService.RESULT_FAILURE_MESSAGING_ERROR; + } + }); + } + + @SmallTest + @RetryOnFailure + public void testPostMessageRequiresValidation() throws InterruptedException { + final CustomTabsConnection connection = warmUpAndWait(); + Context context = getInstrumentation().getTargetContext(); + Intent intent = CustomTabsTestUtils.createMinimalCustomTabIntent(context, mTestPage); + final CustomTabsSessionToken token = + CustomTabsSessionToken.getSessionTokenFromIntent(intent); + assertTrue(connection.newSession(token)); + try { + startCustomTabActivityWithIntent(intent); + } catch (InterruptedException e) { + fail(); + } + CriteriaHelper.pollInstrumentationThread(new Criteria() { + @Override + public boolean isSatisfied() { + final Tab currentTab = getActivity().getActivityTab(); + return mTestPage.equals(currentTab.getUrl()); + } + }); + assertEquals(connection.postMessage(token, "Message", null), + CustomTabsService.RESULT_FAILURE_MESSAGING_ERROR); + } + + @SmallTest + @RetryOnFailure + public void testPostMessageReceivedInPage() throws InterruptedException { + final String url = + mWebServer.setResponse("/test.html", TITLE_FROM_POSTMESSAGE_TO_CHANNEL, null); + final CustomTabsConnection connection = warmUpAndWait(); + Context context = getInstrumentation().getTargetContext(); + Intent intent = CustomTabsTestUtils.createMinimalCustomTabIntent(context, url); + final CustomTabsSessionToken token = + CustomTabsSessionToken.getSessionTokenFromIntent(intent); + assertTrue(connection.newSession(token)); + assertTrue(connection.validatePostMessageOrigin(token)); + try { + startCustomTabActivityWithIntent(intent); + } catch (InterruptedException e) { + fail(); + } + CriteriaHelper.pollInstrumentationThread(new Criteria() { + @Override + public boolean isSatisfied() { + final Tab currentTab = getActivity().getActivityTab(); + return url.equals(currentTab.getUrl()); + } + }); + CriteriaHelper.pollInstrumentationThread(new Criteria() { + @Override + public boolean isSatisfied() { + return connection.postMessage(token, "New title", null) + == CustomTabsService.RESULT_SUCCESS; + } + }); + CriteriaHelper.pollInstrumentationThread(new Criteria() { + @Override + public boolean isSatisfied() { + final Tab currentTab = getActivity().getActivityTab(); + return "New title".equals(currentTab.getTitle()); + } + }); + } + + @SmallTest + @RetryOnFailure + public void testPostMessageReceivedFromPage() throws InterruptedException { + final String url = mWebServer.setResponse("/test.html", MESSAGE_FROM_PAGE_TO_CHANNEL, null); + warmUpAndWait(); + final CallbackHelper channelReadyHelper = new CallbackHelper(); + final CallbackHelper messageReceivedHelper = new CallbackHelper(); + final CustomTabsSession session = bindWithCallback(new CustomTabsCallback() { + @Override + public void onMessageChannelReady(Uri origin, Bundle extras) { + channelReadyHelper.notifyCalled(); + } + + @Override + public void onPostMessage(String message, Bundle extras) { + messageReceivedHelper.notifyCalled(); + } + }); + session.validatePostMessageOrigin(); + Intent intent = new CustomTabsIntent.Builder(session).build().intent; + intent.setData(Uri.parse(url)); + intent.setComponent(new ComponentName( + getInstrumentation().getTargetContext(), ChromeLauncherActivity.class)); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + + assertEquals(session.postMessage("Message", null), + CustomTabsService.RESULT_FAILURE_MESSAGING_ERROR); + + try { + startCustomTabActivityWithIntent(intent); + } catch (InterruptedException e) { + fail(); + } + try { + channelReadyHelper.waitForCallback(0); + } catch (TimeoutException e) { + fail(); + } + try { + messageReceivedHelper.waitForCallback(0); + } catch (TimeoutException e) { + fail(); + } + } + + /** + * Tests that when we use a pre-created renderer, the page loaded is the + * only one in the navigation history. + */ + @SmallTest + @RetryOnFailure public void testPrecreatedRenderer() throws InterruptedException { CustomTabsConnection connection = warmUpAndWait(); Context context = getInstrumentation().getTargetContext();
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/download/DownloadActivityTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/download/DownloadActivityTest.java index 5f606830..6326016 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/download/DownloadActivityTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/download/DownloadActivityTest.java
@@ -157,7 +157,7 @@ ThreadUtils.runOnUiThread(new Runnable() { @Override public void run() { - mAdapter.onDownloadItemUpdated(updateItem, false); + mAdapter.onDownloadItemUpdated(updateItem); } }); mAdapterObserver.onSpaceDisplayUpdatedCallback.waitForCallback(callCount); @@ -170,7 +170,7 @@ ThreadUtils.runOnUiThread(new Runnable() { @Override public void run() { - mAdapter.onDownloadItemUpdated(deletedItem, false); + mAdapter.onDownloadItemUpdated(deletedItem); } }); mAdapterObserver.onSpaceDisplayUpdatedCallback.waitForCallback(callCount); @@ -286,8 +286,8 @@ ThreadUtils.runOnUiThread(new Runnable() { @Override public void run() { - mAdapter.onDownloadItemUpdated(item7, false); - mAdapter.onDownloadItemUpdated(item8, false); + mAdapter.onDownloadItemUpdated(item7); + mAdapter.onDownloadItemUpdated(item8); } }); mAdapterObserver.onSpaceDisplayUpdatedCallback.waitForCallback(callCount, 2); @@ -363,8 +363,8 @@ ThreadUtils.runOnUiThread(new Runnable() { @Override public void run() { - mAdapter.onDownloadItemUpdated(item7, false); - mAdapter.onDownloadItemUpdated(item8, false); + mAdapter.onDownloadItemUpdated(item7); + mAdapter.onDownloadItemUpdated(item8); } }); mAdapterObserver.onSpaceDisplayUpdatedCallback.waitForCallback(callCount, 2);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/download/ui/DownloadHistoryAdapterTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/download/ui/DownloadHistoryAdapterTest.java index df804fc..f73ba60c 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/download/ui/DownloadHistoryAdapterTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/download/ui/DownloadHistoryAdapterTest.java
@@ -158,7 +158,7 @@ // Add the first item. assertEquals(1, mObserver.onChangedCallback.getCallCount()); DownloadItem item0 = StubbedProvider.createDownloadItem(0, "19840116 12:00"); - mAdapter.onDownloadItemUpdated(item0, false); + mAdapter.onDownloadItemUpdated(item0); mObserver.onChangedCallback.waitForCallback(1); checkAdapterContents(null, item0); assertEquals(1, mAdapter.getTotalDownloadSize()); @@ -166,7 +166,7 @@ // Add a second item with a different date. assertEquals(2, mObserver.onChangedCallback.getCallCount()); DownloadItem item1 = StubbedProvider.createDownloadItem(1, "19840117 12:00"); - mAdapter.onDownloadItemUpdated(item1, false); + mAdapter.onDownloadItemUpdated(item1); mObserver.onChangedCallback.waitForCallback(2); checkAdapterContents(null, item1, null, item0); assertEquals(11, mAdapter.getTotalDownloadSize()); @@ -174,7 +174,7 @@ // Add a third item with the same date as the second item. assertEquals(3, mObserver.onChangedCallback.getCallCount()); DownloadItem item2 = StubbedProvider.createDownloadItem(2, "19840117 18:00"); - mAdapter.onDownloadItemUpdated(item2, false); + mAdapter.onDownloadItemUpdated(item2); mObserver.onChangedCallback.waitForCallback(3); checkAdapterContents(null, item2, item1, null, item0); assertEquals(111, mAdapter.getTotalDownloadSize()); @@ -182,7 +182,7 @@ // An item with the same download ID as the second item should just update the old one. assertEquals(4, mObserver.onChangedCallback.getCallCount()); DownloadItem item3 = StubbedProvider.createDownloadItem(2, "19840117 18:00"); - mAdapter.onDownloadItemUpdated(item3, false); + mAdapter.onDownloadItemUpdated(item3); mObserver.onChangedCallback.waitForCallback(4); checkAdapterContents(null, item3, item1, null, item0); assertEquals(111, mAdapter.getTotalDownloadSize()); @@ -207,7 +207,8 @@ public void testRemove_ThreeItemsTwoDates() throws Exception { // Initialize the DownloadHistoryAdapter with three items in two date buckets. DownloadItem regularItem = StubbedProvider.createDownloadItem(0, "19840116 18:00"); - DownloadItem offTheRecordItem = StubbedProvider.createDownloadItem(1, "19840116 12:00"); + DownloadItem offTheRecordItem = + StubbedProvider.createDownloadItem(1, "19840116 12:00", true); OfflinePageDownloadItem offlineItem = StubbedProvider.createOfflineItem(2, "19840117 12:01"); mDownloadDelegate.regularItems.add(regularItem);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/download/ui/StubbedProvider.java b/chrome/android/javatests/src/org/chromium/chrome/browser/download/ui/StubbedProvider.java index 5748292..c35cb6e 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/download/ui/StubbedProvider.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/download/ui/StubbedProvider.java
@@ -196,8 +196,14 @@ @Override public void destroy() {} - /** Creates a new DownloadItem with pre-defined values. */ + /** See {@link #createDownloadItem(int, String, boolean)}. */ public static DownloadItem createDownloadItem(int which, String date) throws Exception { + return createDownloadItem(which, date, false); + } + + /** Creates a new DownloadItem with pre-defined values. */ + public static DownloadItem createDownloadItem(int which, String date, boolean isIncognito) + throws Exception { DownloadItem item = null; if (which == 0) { item = new DownloadItem(false, new DownloadInfo.Builder() @@ -208,6 +214,7 @@ .setDownloadGuid("first_guid") .setMimeType("image/jpeg") .setState(DownloadState.COMPLETE) + .setIsOffTheRecord(isIncognito) .build()); } else if (which == 1) { item = new DownloadItem(false, new DownloadInfo.Builder() @@ -218,6 +225,7 @@ .setDownloadGuid("second_guid") .setMimeType("image/gif") .setState(DownloadState.COMPLETE) + .setIsOffTheRecord(isIncognito) .build()); } else if (which == 2) { item = new DownloadItem(false, new DownloadInfo.Builder() @@ -228,6 +236,7 @@ .setDownloadGuid("third_guid") .setMimeType("text/plain") .setState(DownloadState.COMPLETE) + .setIsOffTheRecord(isIncognito) .build()); } else if (which == 3) { item = new DownloadItem(false, new DownloadInfo.Builder() @@ -238,6 +247,7 @@ .setDownloadGuid("fourth_guid") .setMimeType("video/webm") .setState(DownloadState.COMPLETE) + .setIsOffTheRecord(isIncognito) .build()); } else if (which == 4) { item = new DownloadItem(false, new DownloadInfo.Builder() @@ -248,6 +258,7 @@ .setDownloadGuid("fifth_guid") .setMimeType("audio/mp3") .setState(DownloadState.COMPLETE) + .setIsOffTheRecord(isIncognito) .build()); } else if (which == 5) { item = new DownloadItem(false, new DownloadInfo.Builder() @@ -258,6 +269,7 @@ .setDownloadGuid("sixth_guid") .setMimeType("audio/mp3") .setState(DownloadState.COMPLETE) + .setIsOffTheRecord(isIncognito) .build()); } else if (which == 6) { item = new DownloadItem(false, new DownloadInfo.Builder() @@ -278,6 +290,7 @@ .setDownloadGuid("eighth_guid") .setMimeType("application/pdf") .setState(DownloadState.COMPLETE) + .setIsOffTheRecord(isIncognito) .build()); } else if (which == 8) { // This is a duplicate of item 7 above. @@ -289,6 +302,7 @@ .setDownloadGuid("ninth_guid") .setMimeType("application/pdf") .setState(DownloadState.COMPLETE) + .setIsOffTheRecord(isIncognito) .build()); } else { return null;
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/media/ui/AutoplayMutedNotificationTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/media/ui/AutoplayMutedNotificationTest.java index 3e7a1ba..8ec407f 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/media/ui/AutoplayMutedNotificationTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/media/ui/AutoplayMutedNotificationTest.java
@@ -4,10 +4,13 @@ package org.chromium.chrome.browser.media.ui; +import static org.chromium.base.test.util.Restriction.RESTRICTION_TYPE_NON_LOW_END_DEVICE; + import android.content.Context; import android.media.AudioManager; import android.test.suitebuilder.annotation.SmallTest; +import org.chromium.base.test.util.Restriction; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.tab.Tab; @@ -83,6 +86,7 @@ } @SmallTest + @Restriction(RESTRICTION_TYPE_NON_LOW_END_DEVICE) public void testBasic() throws Exception { Tab tab = getActivity().getActivityTab(); @@ -103,6 +107,7 @@ } @SmallTest + @Restriction(RESTRICTION_TYPE_NON_LOW_END_DEVICE) public void testDoesNotReactToAudioFocus() throws Exception { Tab tab = getActivity().getActivityTab(); @@ -125,6 +130,7 @@ } @SmallTest + @Restriction(RESTRICTION_TYPE_NON_LOW_END_DEVICE) public void testAutoplayMutedThenUnmute() throws Exception { Tab tab = getActivity().getActivityTab();
diff --git a/chrome/android/monochrome_android_manifest_jinja_variables.gni b/chrome/android/monochrome_android_manifest_jinja_variables.gni new file mode 100644 index 0000000..44baf85 --- /dev/null +++ b/chrome/android/monochrome_android_manifest_jinja_variables.gni
@@ -0,0 +1,10 @@ +# Copyright 2016 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +monochrome_android_manifest_jinja_variables = [ + "min_sdk_version=24", + "sandboxed_service_exported=true", + "sandboxed_service_extra_flags=android:externalService=\"true\"", + "use32bitAbi=android:use32bitAbi=\"true\"", +]
diff --git a/chrome/app/chromeos_strings.grdp b/chrome/app/chromeos_strings.grdp index 68514623..1fbadf5 100644 --- a/chrome/app/chromeos_strings.grdp +++ b/chrome/app/chromeos_strings.grdp
@@ -5545,7 +5545,7 @@ Managed by <ph name="DOMAIN">$1<ex>yourdomain.com</ex></ph> </message> <message name="IDS_LOGIN_PUBLIC_ACCOUNT_SIGNOUT_REMINDER" desc="Text shown in the public account user pod, reminding the user to log out."> - Your information will be removed when you sign out. + Your information will be removed from the device when you sign out. </message> <message name="IDS_LOGIN_PUBLIC_SESSION_LANGUAGE_AND_INPUT" desc="Link in public session pod that shows a section which allows the user to change the UI language and keyboard layout."> Language and input @@ -5556,6 +5556,27 @@ <message name="IDS_LOGIN_PUBLIC_ACCOUNT_ENTER_ACCESSIBLE_NAME" desc="Text to be spoken when focus is set to the sign-in button in the public account user pod."> Enter public session </message> + <message name="IDS_LOGIN_PUBLIC_ACCOUNT_MONITORING_WARNING" desc="Text shown in the public account user pod, warning the user about potential admin monitoring."> + The device admin may monitor your browsing activity. + </message> + <message name="IDS_LOGIN_PUBLIC_ACCOUNT_LEARN_MORE" desc="Link shown in the public account user pod, showing the user more information about the monitoring."> + Learn more + </message> + <message name="IDS_LOGIN_PUBLIC_ACCOUNT_MONITORING_INFO" desc="Text shown in the warning dialog after user clicks on the learn more link, notifying the user of potential security and privacy implications of using the device"> + The device admin may monitor the following: + </message> + <message name="IDS_LOGIN_PUBLIC_ACCOUNT_MONITORING_INFO_ITEM_1" desc="Text shown in the warning dialog after user clicks on the learn more link, notifying the user of potential security and privacy implications of using the device"> + Access your browsing activity + </message> + <message name="IDS_LOGIN_PUBLIC_ACCOUNT_MONITORING_INFO_ITEM_2" desc="Text shown in the warning dialog after user clicks on the learn more link, notifying the user of potential security and privacy implications of using the device"> + Manipulate settings that specify whether websites can use features such as geolocation, microphone, camera, etc. + </message> + <message name="IDS_LOGIN_PUBLIC_ACCOUNT_MONITORING_INFO_ITEM_3" desc="Text shown in the warning dialog after user clicks on the learn more link, notifying the user of potential security and privacy implications of using the device"> + Manage your apps, extensions, and themes + </message> + <message name="IDS_LOGIN_PUBLIC_ACCOUNT_MONITORING_INFO_ITEM_4" desc="Text shown in the warning dialog after user clicks on the learn more link, notifying the user of potential security and privacy implications of using the device"> + Manipulate privacy-related settings + </message> <message name="IDS_LOGIN_CONFIRM_KIOSK_DIAGNOSTIC_FORMAT" desc="Text to be shown on a dialog to confirm launching kiosk app in diagnostic mode."> Are you sure you want to launch "<ph name="APP_NAME">$1<ex>Kiosk App</ex></ph>" in diagnostic mode? </message>
diff --git a/chrome/app/chromium_strings.grd b/chrome/app/chromium_strings.grd index 272d776..1c330eca 100644 --- a/chrome/app/chromium_strings.grd +++ b/chrome/app/chromium_strings.grd
@@ -1206,17 +1206,8 @@ </message> <!-- Page Information Window --> - <message name="IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_NO_CT" desc="The text of the identity section when the page is secure and no Certificate Transparency information is present."> - Chromium verified that <ph name="ISSUER">$1<ex>VeriSign</ex></ph> issued this website's certificate. The server did not supply any Certificate Transparency information. - </message> - <message name="IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_CT_VERIFIED" desc="The text of the identity section when the page is secure and a Signed Certificate Timestamp from a known Certificate Transparency log is present and valid."> - Chromium verified that <ph name="ISSUER">$1<ex>VeriSign</ex></ph> issued this website's certificate. The server supplied valid Certificate Transparency information. - </message> - <message name="IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_CT_UNVERIFIED" desc="The text of the identity section when the page is secure and contains a Signed Certificate Timestamp from an unknown Certificate Transparency log."> - Chromium verified that <ph name="ISSUER">$1<ex>VeriSign</ex></ph> issued this website's certificate. The server supplied Certificate Transparency information, but Chromium did not recognize any of the Certificate Transparency logs. - </message> - <message name="IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_CT_INVALID" desc="The text of the identity section when the page is secure, but it contains a Signed Certificate Timestamp from a known Certificate Transparency log that failed to verify."> - Chromium verified that <ph name="ISSUER">$1<ex>VeriSign</ex></ph> issued this website's certificate. The server supplied Certificate Transparency information, but it was invalid. + <message name="IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_VERIFIED" desc="The text of the identity section when the page is secure and uses a valid certificate"> + Chromium verified that <ph name="ISSUER">$1<ex>VeriSign</ex></ph> issued this website's certificate. </message> <!-- Desktop Capture -->
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index 06b87de..d9d34f7 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -368,9 +368,6 @@ <message name="IDS_WEBSITE_SETTINGS_DETAILS_LINK" desc="Link in the Website Settings that opens up additional security details about the current page in the DevTools Security panel."> Details </message> - <message name="IDS_WEBSITE_SETTINGS_CT_ERROR" desc="Text that is displayed in the header of the Website Settings popup if the website has provided Signed Certificate Timestamps but none are valid."> - This site supplied invalid Certificate Transparency information. - </message> <message name="IDS_WEBSITE_SETTINGS_BROKEN_TRANSPORT" desc="Text that is displayed in the header of the Website Settings popup if the website uses nominally secure transport that had authentication or other cryptpgraphic errors."> Your connection to this site is not private. Attackers might be trying to steal your information (for example, photos, passwords, messages and credit cards) from <ph name="DOMAIN">$1<ex>www.example.com</ex></ph>. </message> @@ -5872,12 +5869,6 @@ <message name="IDS_FLAGS_IMPORTANT_SITES_IN_CBD_DESCRIPTION" desc="Description for the flag for using important sites whitelisting in the clear browsing dialog."> Include the option to whitelist important sites in the clear browsing data dialog. </message> - <message name="IDS_FLAGS_ENABLE_AUTOPLAY_MUTED_VIDEOS_NAME" desc="Title for the flag to enable autoplay of muted videos."> - Autoplay muted videos - </message> - <message name="IDS_FLAGS_ENABLE_AUTOPLAY_MUTED_VIDEOS_DESCRIPTION" desc="Description for the flag to enable autoplay of muted videos."> - Allow muted videos to autoplay. - </message> </if> <if expr="use_ash"> <message name="IDS_FLAGS_ASH_MD" desc="Title of the flag which enables or disables material design in Chrome OS system UI."> @@ -9146,14 +9137,8 @@ <message name="IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV_NO_CT" desc="The text of the identity section when the page is secured with an EV cert and no Certificate Transparency information is present."> The identity of <ph name="ORGANIZATION">$1<ex>Google</ex></ph> at <ph name="LOCALITY">$2<ex>Mountain View, CA US</ex></ph> has been verified by <ph name="ISSUER">$3<ex>VeriSign</ex></ph>. No Certificate Transparency information was supplied by the server. </message> - <message name="IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV_CT_VERIFIED" desc="The text of the identity section when the page is secured with an EV cert and a Signed Certificate Timestamp from a known Certificate Transparency log is present and valid."> - The identity of <ph name="ORGANIZATION">$1<ex>Google</ex></ph> at <ph name="LOCALITY">$2<ex>Mountain View, CA US</ex></ph> has been verified by <ph name="ISSUER">$3<ex>VeriSign</ex></ph>. Valid Certificate Transparency information was supplied by the server. - </message> - <message name="IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV_CT_UNVERIFIED" desc="The text of the identity section when the page is secured with an EV cert and contains a Signed Certificate Timestamp from an unknown Certificate Transparency log."> - The identity of <ph name="ORGANIZATION">$1<ex>Google</ex></ph> at <ph name="LOCALITY">$2<ex>Mountain View, CA US</ex></ph> has been verified by <ph name="ISSUER">$3<ex>VeriSign</ex></ph>. Certificate Transparency information was supplied by the server, but one or more of the Certificate Transparency logs were not recognized. - </message> - <message name="IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV_CT_INVALID" desc="The text of the identity section when the page is secured with an EV cert, but it contains a Signed Certificate Timestamp from a known Certificate Transparency log that failed to verify."> - The identity of <ph name="ORGANIZATION">$1<ex>Google</ex></ph> at <ph name="LOCALITY">$2<ex>Mountain View, CA US</ex></ph> has been verified by <ph name="ISSUER">$3<ex>VeriSign</ex></ph>. Certificate Transparency information was supplied by the server, but it was invalid. + <message name="IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV_VERIFIED" desc="The text of the identity section when the page is secured with a valid EV cert."> + The identity of <ph name="ORGANIZATION">$1<ex>Google</ex></ph> at <ph name="LOCALITY">$2<ex>Mountain View, CA US</ex></ph> has been verified by <ph name="ISSUER">$3<ex>VeriSign</ex></ph>. </message> <!-- Screen Capture strings -->
diff --git a/chrome/app/google_chrome_strings.grd b/chrome/app/google_chrome_strings.grd index 2eb68d92..2eea30f 100644 --- a/chrome/app/google_chrome_strings.grd +++ b/chrome/app/google_chrome_strings.grd
@@ -1207,17 +1207,8 @@ </message> <!-- Page Information Window --> - <message name="IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_NO_CT" desc="The text of the identity section when the page is secure and no Certificate Transparency information is present."> - Chrome verified that <ph name="ISSUER">$1<ex>VeriSign</ex></ph> issued this website's certificate. The server did not supply any Certificate Transparency information. - </message> - <message name="IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_CT_VERIFIED" desc="The text of the identity section when the page is secure and a Signed Certificate Timestamp from a known Certificate Transparency log is present and valid."> - Chrome verified that <ph name="ISSUER">$1<ex>VeriSign</ex></ph> issued this website's certificate. The server supplied valid Certificate Transparency information. - </message> - <message name="IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_CT_UNVERIFIED" desc="The text of the identity section when the page is secure and contains a Signed Certificate Timestamp from an unknown Certificate Transparency log."> - Chrome verified that <ph name="ISSUER">$1<ex>VeriSign</ex></ph> issued this website's certificate. The server supplied Certificate Transparency information, but Chrome did not recognize any of the Certificate Transparency logs. - </message> - <message name="IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_CT_INVALID" desc="The text of the identity section when the page is secure, but it contains a Signed Certificate Timestamp from a known Certificate Transparency log that failed to verify."> - Chrome verified that <ph name="ISSUER">$1<ex>VeriSign</ex></ph> issued this website's certificate. The server supplied Certificate Transparency information, but it was invalid. + <message name="IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_VERIFIED" desc="The text of the identity section when the page is secure and uses a valid certificate."> + Chrome verified that <ph name="ISSUER">$1<ex>VeriSign</ex></ph> issued this website's certificate. </message> <!-- Desktop Capture -->
diff --git a/chrome/app/mash/chrome_mash_content_browser_manifest_overlay.json b/chrome/app/mash/chrome_mash_content_browser_manifest_overlay.json index 9801281..67a4b3e 100644 --- a/chrome/app/mash/chrome_mash_content_browser_manifest_overlay.json +++ b/chrome/app/mash/chrome_mash_content_browser_manifest_overlay.json
@@ -11,7 +11,6 @@ "provides": { "content_browser:ash": [ "ash::mojom::NewWindowClient", - "ash::mojom::ShutdownClient", "ash::mojom::SystemTrayClient", "ash::mojom::VolumeController", "ash::mojom::WallpaperManager",
diff --git a/chrome/app/nibs/MainMenu.xib b/chrome/app/nibs/MainMenu.xib index 1a081a1..07124be 100644 --- a/chrome/app/nibs/MainMenu.xib +++ b/chrome/app/nibs/MainMenu.xib
@@ -156,6 +156,12 @@ <action selector="commandDispatch:" target="-1" id="695"/> </connections> </menuItem> + <menuItem title="^IDS_MEDIA_ROUTER_MENU_ITEM_TITLE" tag="35011" id="OVr-QF-3s6"> + <modifierMask key="keyEquivalentModifierMask"/> + <connections> + <action selector="commandDispatch:" target="-1" id="i0s-9w-Djk"/> + </connections> + </menuItem> </items> </menu> </menuItem>
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 32ad6dab..48b4dc7 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -9,6 +9,7 @@ import("//build/split_static_library.gni") import("//chrome/common/features.gni") import("//components/os_crypt/features.gni") +import("//components/spellcheck/spellcheck_build_features.gni") import("//extensions/features/features.gni") import("//media/media_options.gni") import("//net/features.gni") @@ -1381,6 +1382,7 @@ "//components/security_state", "//components/sessions", "//components/signin/core/browser", + "//components/spellcheck:build_features", "//components/ssl_config", "//components/ssl_errors", "//components/startup_metric_utils/browser:host", @@ -2215,6 +2217,7 @@ "//services/ui/public/cpp/input_devices", "//ui/aura", "//ui/compositor", + "//ui/snapshot", "//ui/views/mus", ] }
diff --git a/chrome/browser/DEPS b/chrome/browser/DEPS index a368b31..4fbfa36 100644 --- a/chrome/browser/DEPS +++ b/chrome/browser/DEPS
@@ -95,6 +95,8 @@ "-third_party/WebKit", "+third_party/WebKit/public/platform/WebDisplayMode.h", "+third_party/WebKit/public/platform/WebLoadingBehaviorFlag.h", + "+third_party/WebKit/public/platform/WebGestureEvent.h", + "+third_party/WebKit/public/platform/WebInputEvent.h", "+third_party/WebKit/public/platform/WebReferrerPolicy.h", "+third_party/WebKit/public/platform/WebSecurityStyle.h", "+third_party/WebKit/public/platform/modules/app_banner/app_banner.mojom.h", @@ -109,7 +111,6 @@ "+third_party/WebKit/public/web/WebCache.h", "+third_party/WebKit/public/web/WebContextMenuData.h", "+third_party/WebKit/public/web/WebFindOptions.h", - "+third_party/WebKit/public/web/WebInputEvent.h", "+third_party/WebKit/public/web/WebMediaPlayerAction.h", "+third_party/WebKit/public/web/WebPluginAction.h", "+third_party/WebKit/public/web/WebTextDirection.h",
diff --git a/chrome/browser/OWNERS b/chrome/browser/OWNERS index 08b726e..59a9170f 100644 --- a/chrome/browser/OWNERS +++ b/chrome/browser/OWNERS
@@ -28,10 +28,9 @@ per-file chrome_content_browser_client_browsertest.cc=* per-file chrome_content_browser_client_unittest.cc=* -per-file content_browser_manifest_overlay.json=set noparent -per-file content_browser_manifest_overlay.json=file://ipc/SECURITY_OWNERS -per-file content_utility_manifest_overlay.json=set noparent -per-file content_utility_manifest_overlay.json=file://ipc/SECURITY_OWNERS +# Mojo manfiests +per-file *manifest_overlay.json=set noparent +per-file *manifest_overlay.json=file://ipc/SECURITY_OWNERS per-file chrome_browser_field_trials*=file://components/variations/OWNERS
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 271f618a3..86d89ae2 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -56,6 +56,7 @@ #include "components/signin/core/common/signin_switches.h" #include "components/spellcheck/common/spellcheck_features.h" #include "components/spellcheck/common/spellcheck_switches.h" +#include "components/spellcheck/spellcheck_build_features.h" #include "components/ssl_config/ssl_config_switches.h" #include "components/strings/grit/components_strings.h" #include "components/sync/driver/sync_driver_switches.h" @@ -844,7 +845,7 @@ IDS_FLAGS_SILENT_DEBUGGER_EXTENSION_API_NAME, IDS_FLAGS_SILENT_DEBUGGER_EXTENSION_API_DESCRIPTION, kOsDesktop, SINGLE_VALUE_TYPE(switches::kSilentDebuggerExtensionAPI)}, -#if defined(ENABLE_SPELLCHECK) && defined(OS_ANDROID) +#if BUILDFLAG(ENABLE_SPELLCHECK) && defined(OS_ANDROID) {"enable-android-spellchecker", IDS_OPTIONS_ENABLE_SPELLCHECK, IDS_OPTIONS_ENABLE_ANDROID_SPELLCHECKER_DESCRIPTION, kOsAndroid, FEATURE_VALUE_TYPE(spellcheck::kAndroidSpellChecker)}, @@ -1198,7 +1199,7 @@ SINGLE_DISABLE_VALUE_TYPE( switches::kDisableHideInactiveStackedTabCloseButtons)}, #endif // TOOLKIT_VIEWS -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) {"enable-spelling-feedback-field-trial", IDS_FLAGS_SPELLING_FEEDBACK_FIELD_TRIAL_NAME, IDS_FLAGS_SPELLING_FEEDBACK_FIELD_TRIAL_DESCRIPTION, kOsAll, @@ -1968,9 +1969,6 @@ {"important-sites-in-cbd", IDS_FLAGS_IMPORTANT_SITES_IN_CBD_NAME, IDS_FLAGS_IMPORTANT_SITES_IN_CBD_DESCRIPTION, kOsAndroid, FEATURE_VALUE_TYPE(chrome::android::kImportantSitesInCBD)}, - {"autoplay-muted-videos", IDS_FLAGS_ENABLE_AUTOPLAY_MUTED_VIDEOS_NAME, - IDS_FLAGS_ENABLE_AUTOPLAY_MUTED_VIDEOS_DESCRIPTION, kOsAndroid, - FEATURE_VALUE_TYPE(features::kAutoplayMutedVideos)}, #endif // OS_ANDROID {"enable-pointer-events", IDS_FLAGS_EXPERIMENTAL_POINTER_EVENT_NAME, IDS_FLAGS_EXPERIMENTAL_POINTER_EVENT_DESCRIPTION, kOsAll,
diff --git a/chrome/browser/android/chrome_feature_list.cc b/chrome/browser/android/chrome_feature_list.cc index dedbca3..9342c8a 100644 --- a/chrome/browser/android/chrome_feature_list.cc +++ b/chrome/browser/android/chrome_feature_list.cc
@@ -32,7 +32,6 @@ // in other locations in the code base (e.g. chrome/, components/, etc). const base::Feature* kFeaturesExposedToJava[] = { &autofill::kAutofillScanCardholderName, - &features::kAutoplayMutedVideos, &features::kConsistentOmniboxGeolocation, &features::kCredentialManagementAPI, &features::kSimplifiedFullscreenUI, @@ -40,6 +39,7 @@ &features::kWebPayments, &kAndroidPayIntegrationV1, &kCCTExternalLinkHandling, + &kCCTPostMessageAPI, &kChromeHomeFeature, &kContextualSearchSingleActions, &kDownloadsUiFeature, @@ -74,6 +74,9 @@ const base::Feature kCCTExternalLinkHandling{"CCTExternalLinkHandling", base::FEATURE_ENABLED_BY_DEFAULT}; +const base::Feature kCCTPostMessageAPI{"CCTPostMessageAPI", + base::FEATURE_ENABLED_BY_DEFAULT}; + const base::Feature kChromeHomeFeature{"ChromeHome", base::FEATURE_DISABLED_BY_DEFAULT}; @@ -90,7 +93,7 @@ base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kNTPOfflinePagesFeature{"NTPOfflinePages", - base::FEATURE_DISABLED_BY_DEFAULT}; + base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kNTPFakeOmniboxTextFeature{ "NTPFakeOmniboxText", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/chrome/browser/android/chrome_feature_list.h b/chrome/browser/android/chrome_feature_list.h index b5707bd..4378165 100644 --- a/chrome/browser/android/chrome_feature_list.h +++ b/chrome/browser/android/chrome_feature_list.h
@@ -15,6 +15,7 @@ // Alphabetical: extern const base::Feature kAndroidPayIntegrationV1; extern const base::Feature kCCTExternalLinkHandling; +extern const base::Feature kCCTPostMessageAPI; extern const base::Feature kChromeHomeFeature; extern const base::Feature kContextualSearchSingleActions; extern const base::Feature kDownloadsUiFeature;
diff --git a/chrome/browser/android/chrome_jni_registrar.cc b/chrome/browser/android/chrome_jni_registrar.cc index 015b8afc..81a9111 100644 --- a/chrome/browser/android/chrome_jni_registrar.cc +++ b/chrome/browser/android/chrome_jni_registrar.cc
@@ -169,6 +169,7 @@ #include "components/safe_json/android/component_jni_registrar.h" #include "components/signin/core/browser/android/component_jni_registrar.h" #include "components/spellcheck/browser/android/component_jni_registrar.h" +#include "components/spellcheck/spellcheck_build_features.h" #include "components/sync/android/sync_jni_registrar.h" #include "components/url_formatter/android/component_jni_registrar.h" #include "components/variations/android/component_jni_registrar.h" @@ -369,7 +370,7 @@ {"SigninInvestigator", SigninInvestigatorAndroid::Register}, {"SigninManager", SigninManagerAndroid::Register}, {"SingleTabModel", RegisterSingleTabModel}, -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) {"SpellCheckerSessionBridge", spellcheck::android::RegisterSpellcheckJni}, #endif {"SqliteCursor", SQLiteCursor::RegisterSqliteCursor},
diff --git a/chrome/browser/android/ntp/ntp_snippets_bridge.cc b/chrome/browser/android/ntp/ntp_snippets_bridge.cc index d56645f8..7f03d7f 100644 --- a/chrome/browser/android/ntp/ntp_snippets_bridge.cc +++ b/chrome/browser/android/ntp/ntp_snippets_bridge.cc
@@ -79,8 +79,8 @@ ConvertUTF8ToJavaString(env, suggestion.amp_url().spec()), suggestion.publish_date().ToJavaTime(), suggestion.score(), static_cast<int>(info->card_layout())); - if (suggestion.id().category().id() == - static_cast<int>(KnownCategories::DOWNLOADS) && + if (suggestion.id().category().IsKnownCategory( + KnownCategories::DOWNLOADS) && suggestion.download_suggestion_extra() != nullptr && suggestion.download_suggestion_extra()->is_download_asset) { Java_SnippetsBridge_setDownloadAssetDataForLastSuggestion( @@ -91,6 +91,16 @@ ConvertUTF8ToJavaString( env, suggestion.download_suggestion_extra()->mime_type)); } + if (suggestion.id().category().IsKnownCategory( + KnownCategories::RECENT_TABS) && + suggestion.recent_tab_suggestion_extra() != nullptr) { + Java_SnippetsBridge_setRecentTabDataForLastSuggestion( + env, result, + ConvertUTF8ToJavaString( + env, suggestion.recent_tab_suggestion_extra()->tab_id), + ConvertUTF8ToJavaString( + env, suggestion.recent_tab_suggestion_extra()->offline_page_id)); + } } return result;
diff --git a/chrome/browser/android/vr_shell/BUILD.gn b/chrome/browser/android/vr_shell/BUILD.gn index 0b10738..cfae01f 100644 --- a/chrome/browser/android/vr_shell/BUILD.gn +++ b/chrome/browser/android/vr_shell/BUILD.gn
@@ -44,6 +44,9 @@ "vr_web_contents_observer.h", ] + if (enable_vr_shell) { + defines += [ "ENABLE_VR_SHELL" ] + } if (enable_vr_shell_ui_dev) { assert(enable_vr_shell) defines += [ "ENABLE_VR_SHELL_UI_DEV" ]
diff --git a/chrome/browser/android/vr_shell/ui_interface.cc b/chrome/browser/android/vr_shell/ui_interface.cc index 10648c2..06c7e4d 100644 --- a/chrome/browser/android/vr_shell/ui_interface.cc +++ b/chrome/browser/android/vr_shell/ui_interface.cc
@@ -16,6 +16,7 @@ UiInterface::~UiInterface() {} void UiInterface::SetMode(Mode mode) { + mode_ = mode; updates_.SetInteger("mode", static_cast<int>(mode)); FlushUpdates(); }
diff --git a/chrome/browser/android/vr_shell/ui_interface.h b/chrome/browser/android/vr_shell/ui_interface.h index 05d294bb..2972dfd 100644 --- a/chrome/browser/android/vr_shell/ui_interface.h +++ b/chrome/browser/android/vr_shell/ui_interface.h
@@ -24,12 +24,14 @@ enum Mode { STANDARD, WEB_VR, + MENU, }; UiInterface(); virtual ~UiInterface(); void SetMode(Mode mode); + Mode GetMode() { return mode_; } void SetSecureOrigin(bool secure); void SetLoading(bool loading); void SetURL(const GURL& url); @@ -41,6 +43,7 @@ private: void FlushUpdates(); + Mode mode_; UiCommandHandler* handler_; bool loaded_ = false; base::DictionaryValue updates_;
diff --git a/chrome/browser/android/vr_shell/vr_controller.cc b/chrome/browser/android/vr_shell/vr_controller.cc index bfd52a51..a3ddfb6 100644 --- a/chrome/browser/android/vr_shell/vr_controller.cc +++ b/chrome/browser/android/vr_shell/vr_controller.cc
@@ -210,10 +210,13 @@ fling->timeStampSeconds = gesture_list.back()->timeStampSeconds; fling->sourceDevice = blink::WebGestureDeviceTouchpad; fling->type = WebInputEvent::GestureFlingStart; - fling->data.flingStart.velocityX = - overall_velocity_.x * kDisplacementScaleFactor; - fling->data.flingStart.velocityY = - overall_velocity_.y * kDisplacementScaleFactor; + if (IsHorizontalGesture()) { + fling->data.flingStart.velocityX = + overall_velocity_.x * kDisplacementScaleFactor; + } else { + fling->data.flingStart.velocityY = + overall_velocity_.y * kDisplacementScaleFactor; + } gesture_list.push_back(std::move(fling)); Reset(); } @@ -227,7 +230,7 @@ switch (state_) { // User has not put finger on touch pad. case WAITING: - HandleWaitingState(); + HandleWaitingState(gesture); break; // User has not started a gesture (by moving out of slop). case TOUCHING: @@ -243,7 +246,7 @@ } } -void VrController::HandleWaitingState() { +void VrController::HandleWaitingState(WebGestureEvent* gesture) { // User puts finger on touch pad (or when the touch down for current gesture // is missed, initiate gesture from current touch point). if (touch_info_->touch_down || touch_info_->is_touching) { @@ -252,6 +255,9 @@ // update current touchpoint *cur_touch_point_ = touch_info_->touch_point; state_ = TOUCHING; + + gesture->type = WebInputEvent::GestureFlingCancel; + gesture->data.flingCancel.preventBoosting = false; } } @@ -286,13 +292,20 @@ // User continues scrolling and there is a change in touch position. gesture->type = WebInputEvent::GestureScrollUpdate; UpdateGesture(gesture); - gesture->data.scrollUpdate.deltaX = - displacement_.x * kDisplacementScaleFactor; - gesture->data.scrollUpdate.deltaY = - displacement_.y * kDisplacementScaleFactor; + if (IsHorizontalGesture()) { + gesture->data.scrollUpdate.deltaX = + displacement_.x * kDisplacementScaleFactor; + } else { + gesture->data.scrollUpdate.deltaY = + displacement_.y * kDisplacementScaleFactor; + } } } +bool VrController::IsHorizontalGesture() { + return std::abs(overall_velocity_.x) > std::abs(overall_velocity_.y); +} + bool VrController::InSlop(const gvr::Vec2f touch_position) { return (std::abs(touch_position.x - init_touch_point_->position.x) < kSlopHorizontal) &&
diff --git a/chrome/browser/android/vr_shell/vr_controller.h b/chrome/browser/android/vr_shell/vr_controller.h index fc0d09c..18a7326 100644 --- a/chrome/browser/android/vr_shell/vr_controller.h +++ b/chrome/browser/android/vr_shell/vr_controller.h
@@ -9,7 +9,8 @@ #include <vector> #include "base/macros.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/gvr-android-sdk/src/ndk/include/vr/gvr/capi/include/gvr_types.h" using blink::WebGestureEvent; @@ -90,7 +91,7 @@ bool GetButtonLongPressFromButtonInfo(); // Handle the waiting state. - void HandleWaitingState(); + void HandleWaitingState(WebGestureEvent* gesture); // Handle the detecting state. void HandleDetectingState(WebGestureEvent* gesture); @@ -103,6 +104,9 @@ // point, false otherwise. bool InSlop(const gvr::Vec2f touch_position); + // Returns true if the gesture is in horizontal direction. + bool IsHorizontalGesture(); + void Reset(); // Update gesture parameters,
diff --git a/chrome/browser/android/vr_shell/vr_input_manager.h b/chrome/browser/android/vr_shell/vr_input_manager.h index 0c3c7b6..33a9cb9 100644 --- a/chrome/browser/android/vr_shell/vr_input_manager.h +++ b/chrome/browser/android/vr_shell/vr_input_manager.h
@@ -6,7 +6,8 @@ #define CHROME_BROWSER_ANDROID_VR_SHELL_VR_INPUT_MANAGER_H_ #include "base/memory/ref_counted.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" namespace content { class WebContents;
diff --git a/chrome/browser/android/vr_shell/vr_shell.cc b/chrome/browser/android/vr_shell/vr_shell.cc index 14af36179..14d6343 100644 --- a/chrome/browser/android/vr_shell/vr_shell.cc +++ b/chrome/browser/android/vr_shell/vr_shell.cc
@@ -21,6 +21,7 @@ #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" #include "content/public/common/referrer.h" +#include "device/vr/android/gvr/gvr_device_provider.h" #include "jni/VrShellImpl_jni.h" #include "ui/android/view_android.h" #include "ui/android/window_android.h" @@ -137,6 +138,7 @@ : WebContentsObserver(ui_contents), main_contents_(main_contents), ui_contents_(ui_contents), + main_thread_task_runner_(base::ThreadTaskRunnerHandle::Get()), weak_ptr_factory_(this) { DCHECK(g_instance == nullptr); g_instance = this; @@ -177,6 +179,9 @@ } VrShell::~VrShell() { + if (delegate_ && delegate_->GetDeviceProvider()) { + delegate_->GetDeviceProvider()->OnGvrDelegateRemoved(); + } g_instance = nullptr; gl::init::ClearGLBindings(); } @@ -184,11 +189,17 @@ void VrShell::SetDelegate(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jobject>& delegate) { - delegate_ = VrShellDelegate::getNativeDelegate(env, delegate); + base::AutoLock lock(gvr_init_lock_); + delegate_ = VrShellDelegate::GetNativeDelegate(env, delegate); + if (gvr_api_) { + main_thread_task_runner_->PostTask( + FROM_HERE, base::Bind(&device::GvrDeviceProvider::OnGvrDelegateReady, + delegate_->GetDeviceProvider(), + weak_ptr_factory_.GetWeakPtr())); + } } -enum class ViewerType -{ +enum class ViewerType { UNKNOWN_TYPE = 0, CARDBOARD = 1, DAYDREAM = 2, @@ -198,19 +209,23 @@ void VrShell::GvrInit(JNIEnv* env, const JavaParamRef<jobject>& obj, jlong native_gvr_api) { + base::AutoLock lock(gvr_init_lock_); gvr_api_ = gvr::GvrApi::WrapNonOwned(reinterpret_cast<gvr_context*>(native_gvr_api)); - if (delegate_) - delegate_->OnVrShellReady(this); + if (delegate_) { + main_thread_task_runner_->PostTask( + FROM_HERE, base::Bind(&device::GvrDeviceProvider::OnGvrDelegateReady, + delegate_->GetDeviceProvider(), + weak_ptr_factory_.GetWeakPtr())); + } controller_.reset( new VrController(reinterpret_cast<gvr_context*>(native_gvr_api))); content_input_manager_ = new VrInputManager(main_contents_); ui_input_manager_ = new VrInputManager(ui_contents_); ViewerType viewerType; - switch (gvr_api_->GetViewerType()) - { + switch (gvr_api_->GetViewerType()) { case gvr::ViewerType::GVR_VIEWER_TYPE_DAYDREAM: viewerType = ViewerType::DAYDREAM; break; @@ -272,6 +287,37 @@ void VrShell::UpdateController(const gvr::Vec3f& forward_vector) { controller_->UpdateState(); +#if defined(ENABLE_VR_SHELL) + // Note that button up/down state is transient, so IsButtonUp only returns + // true for a single frame (and we're guaranteed not to miss it). + if (controller_->IsButtonUp( + gvr::ControllerButton::GVR_CONTROLLER_BUTTON_APP)) { + if (html_interface_->GetMode() == UiInterface::Mode::MENU) { + // Temporary: Hit app button a second time to exit menu mode. + if (webvr_mode_) { + html_interface_->SetMode(UiInterface::Mode::WEB_VR); + main_thread_task_runner_->PostTask( + FROM_HERE, base::Bind(&device::GvrDeviceProvider::OnDisplayFocus, + delegate_->GetDeviceProvider())); + } else { + html_interface_->SetMode(UiInterface::Mode::STANDARD); + } + } else { + if (html_interface_->GetMode() == UiInterface::Mode::WEB_VR) { + main_thread_task_runner_->PostTask( + FROM_HERE, base::Bind(&device::GvrDeviceProvider::OnDisplayBlur, + delegate_->GetDeviceProvider())); + } + html_interface_->SetMode(UiInterface::Mode::MENU); + // TODO(mthiesse): The page is no longer visible here. We should unfocus + // or otherwise let it know it's hidden. + } + } +#endif + if (html_interface_->GetMode() == UiInterface::Mode::WEB_VR) { + return; + } + gvr::Vec3f ergo_neutral_pose; if (!controller_->IsConnected()) { // No controller detected, set up a gaze cursor that tracks the @@ -375,7 +421,8 @@ // TODO(asimjour) for now, scroll is sent to the main content. if (gesture->type == WebInputEvent::GestureScrollBegin || gesture->type == WebInputEvent::GestureScrollUpdate || - gesture->type == WebInputEvent::GestureScrollEnd) { + gesture->type == WebInputEvent::GestureScrollEnd || + gesture->type == WebInputEvent::GestureFlingCancel) { content_input_manager_->ProcessUpdatedGesture(*gesture.get()); } @@ -429,7 +476,7 @@ // encodes the pose index, and device/vr/android/gvr/gvr_device.cc // which tracks poses. uint8_t pixels[4]; - // Assume we're reading from the frambebuffer we just wrote to. + // Assume we're reading from the framebuffer we just wrote to. // That's true currently, we may need to use glReadBuffer(GL_BACK) // or equivalent if the rendering setup changes in the future. glReadPixels(0, 0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixels); @@ -467,7 +514,7 @@ UpdateController(GetForwardVector(head_pose)); - if (webvr_mode_) { + if (html_interface_->GetMode() == UiInterface::Mode::WEB_VR) { DrawWebVr(); // When using async reprojection, we need to know which pose was used in @@ -504,16 +551,16 @@ } } - if (!webvr_mode_) { + bool not_web_vr = html_interface_->GetMode() != UiInterface::Mode::WEB_VR; + + if (not_web_vr) { glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glEnable(GL_SCISSOR_TEST); glClearColor(0.1f, 0.1f, 0.1f, 1.0f); } - if (!world_elements.empty()) { - DrawUiView(&head_pose, world_elements); - } + DrawUiView(&head_pose, world_elements, not_web_vr); if (!head_locked_elements.empty()) { // Switch to head-locked viewports. @@ -525,14 +572,14 @@ // Bind the headlocked framebuffer. frame.BindBuffer(kFrameHeadlockedBuffer); - glClear(GL_COLOR_BUFFER_BIT); - - DrawUiView(nullptr, head_locked_elements); + glClearColor(0.0f, 0.0f, 0.0f, 0.0f); + DrawUiView(nullptr, head_locked_elements, true); } } void VrShell::DrawUiView(const gvr::Mat4f* head_pose, - const std::vector<const ContentRectangle*>& elements) { + const std::vector<const ContentRectangle*>& elements, + bool clear) { for (auto eye : {GVR_LEFT_EYE, GVR_RIGHT_EYE}) { buffer_viewport_list_->GetBufferViewport(eye, buffer_viewport_.get()); @@ -550,7 +597,7 @@ pixel_rect.right - pixel_rect.left, pixel_rect.top - pixel_rect.bottom); - if (!webvr_mode_) { + if (clear) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } @@ -560,7 +607,8 @@ view_matrix); DrawElements(render_matrix, elements); - if (head_pose != nullptr) { + if (head_pose != nullptr && + html_interface_->GetMode() != UiInterface::Mode::WEB_VR) { DrawCursor(render_matrix); } } @@ -673,9 +721,6 @@ glDisable(GL_BLEND); glDisable(GL_POLYGON_OFFSET_FILL); - // Don't need to clear, since we're drawing over the entire render target. - glClear(GL_COLOR_BUFFER_BIT); - glViewport(0, 0, render_size_.width, render_size_.height); vr_shell_renderer_->GetWebVrRenderer()->Draw(content_texture_id_); }
diff --git a/chrome/browser/android/vr_shell/vr_shell.h b/chrome/browser/android/vr_shell/vr_shell.h index 6eafffe..087181c 100644 --- a/chrome/browser/android/vr_shell/vr_shell.h +++ b/chrome/browser/android/vr_shell/vr_shell.h
@@ -12,11 +12,12 @@ #include "base/android/jni_weak_ref.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" +#include "base/single_thread_task_runner.h" #include "base/synchronization/lock.h" #include "chrome/browser/android/vr_shell/vr_math.h" #include "content/public/browser/web_contents_observer.h" #include "device/vr/android/gvr/gvr_delegate.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/gvr-android-sdk/src/ndk/include/vr/gvr/capi/include/gvr.h" #include "third_party/gvr-android-sdk/src/ndk/include/vr/gvr/capi/include/gvr_types.h" @@ -121,7 +122,8 @@ void LoadUIContent(); void DrawVrShell(const gvr::Mat4f& head_pose, gvr::Frame &frame); void DrawUiView(const gvr::Mat4f* head_pose, - const std::vector<const ContentRectangle*>& elements); + const std::vector<const ContentRectangle*>& elements, + bool clear); void DrawElements(const gvr::Mat4f& render_matrix, const std::vector<const ContentRectangle*>& elements); void DrawCursor(const gvr::Mat4f& render_matrix); @@ -157,6 +159,7 @@ std::queue<base::Callback<void()>> task_queue_; base::Lock task_queue_lock_; + base::Lock gvr_init_lock_; std::unique_ptr<VrCompositor> content_compositor_; content::WebContents* main_contents_; @@ -191,6 +194,8 @@ scoped_refptr<VrInputManager> content_input_manager_; scoped_refptr<VrInputManager> ui_input_manager_; + scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner_; + base::WeakPtrFactory<VrShell> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(VrShell);
diff --git a/chrome/browser/android/vr_shell/vr_shell_delegate.cc b/chrome/browser/android/vr_shell/vr_shell_delegate.cc index d4ce924..b341bdfd 100644 --- a/chrome/browser/android/vr_shell/vr_shell_delegate.cc +++ b/chrome/browser/android/vr_shell/vr_shell_delegate.cc
@@ -6,6 +6,7 @@ #include "base/android/jni_android.h" #include "chrome/browser/android/vr_shell/vr_shell.h" +#include "device/vr/android/gvr/gvr_device_provider.h" #include "jni/VrShellDelegate_jni.h" using base::android::JavaParamRef; @@ -16,7 +17,7 @@ // A non presenting delegate for magic window mode. class GvrNonPresentingDelegate : public device::GvrDelegate { public: - explicit GvrNonPresentingDelegate(jlong context) { + explicit GvrNonPresentingDelegate(jlong context) : weak_ptr_factory_(this) { gvr_api_ = gvr::GvrApi::WrapNonOwned(reinterpret_cast<gvr_context*>(context)); } @@ -34,9 +35,12 @@ void SetGvrPoseForWebVr(const gvr::Mat4f& pose, uint32_t pose_index) override {} gvr::GvrApi* gvr_api() override { return gvr_api_.get(); } - + base::WeakPtr<GvrNonPresentingDelegate> GetWeakPtr() { + return weak_ptr_factory_.GetWeakPtr(); + } private: std::unique_ptr<gvr::GvrApi> gvr_api_; + base::WeakPtrFactory<GvrNonPresentingDelegate> weak_ptr_factory_; }; VrShellDelegate::VrShellDelegate(JNIEnv* env, jobject obj) @@ -49,12 +53,16 @@ GvrDelegateProvider::SetInstance(nullptr); } -VrShellDelegate* VrShellDelegate::getNativeDelegate( +VrShellDelegate* VrShellDelegate::GetNativeDelegate( JNIEnv* env, jobject jdelegate) { long native_delegate = Java_VrShellDelegate_getNativePointer(env, jdelegate); return reinterpret_cast<VrShellDelegate*>(native_delegate); } +base::WeakPtr<device::GvrDeviceProvider> VrShellDelegate::GetDeviceProvider() { + return device_provider_; +} + void VrShellDelegate::ExitWebVRIfNecessary(JNIEnv* env, jobject obj) { if (!device_provider_) return; @@ -63,7 +71,7 @@ } bool VrShellDelegate::RequestWebVRPresent( - device::GvrDeviceProvider* device_provider) { + base::WeakPtr<device::GvrDeviceProvider> device_provider) { // Only set one device provider at a time DCHECK(!device_provider_); device_provider_ = device_provider; @@ -76,10 +84,7 @@ } void VrShellDelegate::ExitWebVRPresent() { - if (!device_provider_) - return; - - device_provider_ = nullptr; + device_provider_.reset(); // VRShell is no longer needed by WebVR, allow it to shut down if it's not // being used elsewhere. @@ -87,7 +92,7 @@ Java_VrShellDelegate_exitWebVR(env, j_vr_shell_delegate_.obj()); } -device::GvrDelegate* VrShellDelegate::GetNonPresentingDelegate() { +base::WeakPtr<device::GvrDelegate> VrShellDelegate::GetNonPresentingDelegate() { if (!non_presenting_delegate_) { JNIEnv* env = AttachCurrentThread(); jlong context = Java_VrShellDelegate_createNonPresentingNativeContext( @@ -97,7 +102,8 @@ non_presenting_delegate_.reset(new GvrNonPresentingDelegate(context)); } - return non_presenting_delegate_.get(); + return static_cast<GvrNonPresentingDelegate*>(non_presenting_delegate_.get()) + ->GetWeakPtr(); } void VrShellDelegate::DestroyNonPresentingDelegate() { @@ -107,11 +113,6 @@ env, j_vr_shell_delegate_.obj()); } -void VrShellDelegate::OnVrShellReady(VrShell* vr_shell) { - if (device_provider_) - device_provider_->OnGvrDelegateReady(vr_shell); -} - // ---------------------------------------------------------------------------- // Native JNI methods // ----------------------------------------------------------------------------
diff --git a/chrome/browser/android/vr_shell/vr_shell_delegate.h b/chrome/browser/android/vr_shell/vr_shell_delegate.h index 4ac1dfc..ff8b228b 100644 --- a/chrome/browser/android/vr_shell/vr_shell_delegate.h +++ b/chrome/browser/android/vr_shell/vr_shell_delegate.h
@@ -11,6 +11,10 @@ #include "base/macros.h" #include "device/vr/android/gvr/gvr_delegate.h" +namespace device { +class GvrDeviceProvider; +} + namespace vr_shell { class VrShell; @@ -20,25 +24,25 @@ VrShellDelegate(JNIEnv* env, jobject obj); virtual ~VrShellDelegate(); - static VrShellDelegate* getNativeDelegate(JNIEnv* env, jobject jdelegate); + static VrShellDelegate* GetNativeDelegate(JNIEnv* env, jobject jdelegate); + + base::WeakPtr<device::GvrDeviceProvider> GetDeviceProvider(); // Called by the Java VrShellDelegate. Returns true if the GvrDeviceProvider // needs to handle shutdown first. void ExitWebVRIfNecessary(JNIEnv* env, jobject obj); - // device::vrDelegateProvider implementation - bool RequestWebVRPresent(device::GvrDeviceProvider* device_provider) override; + // device::GvrDelegateProvider implementation + bool RequestWebVRPresent( + base::WeakPtr<device::GvrDeviceProvider> device_provider) override; void ExitWebVRPresent() override; - device::GvrDelegate* GetNonPresentingDelegate() override; + base::WeakPtr<device::GvrDelegate> GetNonPresentingDelegate() override; void DestroyNonPresentingDelegate() override; - // Called from VRShell - void OnVrShellReady(VrShell* vr_shell); - private: std::unique_ptr<device::GvrDelegate> non_presenting_delegate_; base::android::ScopedJavaGlobalRef<jobject> j_vr_shell_delegate_; - device::GvrDeviceProvider* device_provider_; + base::WeakPtr<device::GvrDeviceProvider> device_provider_; DISALLOW_COPY_AND_ASSIGN(VrShellDelegate); };
diff --git a/chrome/browser/banners/app_banner_manager.cc b/chrome/browser/banners/app_banner_manager.cc index 9f98619a..63aa7b3 100644 --- a/chrome/browser/banners/app_banner_manager.cc +++ b/chrome/browser/banners/app_banner_manager.cc
@@ -81,7 +81,8 @@ bool AppBannerManager::URLsAreForTheSamePage(const GURL& first, const GURL& second) { return first.GetWithEmptyPath() == second.GetWithEmptyPath() && - first.path() == second.path() && first.query() == second.query(); + first.path_piece() == second.path_piece() && + first.query_piece() == second.query_piece(); } void AppBannerManager::RequestAppBanner(const GURL& validated_url,
diff --git a/chrome/browser/browser_process_impl.cc b/chrome/browser/browser_process_impl.cc index e455394..dabbb39 100644 --- a/chrome/browser/browser_process_impl.cc +++ b/chrome/browser/browser_process_impl.cc
@@ -100,7 +100,7 @@ #include "components/prefs/pref_service.h" #include "components/safe_json/safe_json_parser.h" #include "components/signin/core/common/profile_management_switches.h" -#include "components/subresource_filter/content/browser/content_ruleset_distributor.h" +#include "components/subresource_filter/content/browser/content_ruleset_service_delegate.h" #include "components/subresource_filter/core/browser/ruleset_service.h" #include "components/subresource_filter/core/browser/subresource_filter_constants.h" #include "components/subresource_filter/core/browser/subresource_filter_features.h" @@ -1212,9 +1212,9 @@ .Append(subresource_filter::kIndexedRulesetBaseDirectoryName); subresource_filter_ruleset_service_.reset( new subresource_filter::RulesetService( - local_state(), blocking_task_runner, indexed_ruleset_base_dir)); - subresource_filter_ruleset_service_->RegisterDistributor( - base::WrapUnique(new subresource_filter::ContentRulesetDistributor)); + local_state(), blocking_task_runner, + base::MakeUnique<subresource_filter::ContentRulesetServiceDelegate>(), + indexed_ruleset_base_dir)); } void BrowserProcessImpl::CreateGCMDriver() {
diff --git a/chrome/browser/browser_resources.grd b/chrome/browser/browser_resources.grd index bd05bf6..bf65593 100644 --- a/chrome/browser/browser_resources.grd +++ b/chrome/browser/browser_resources.grd
@@ -548,8 +548,10 @@ <include name="IDR_SOUND_PASSTHROUGH_WAV" file="resources\chromeos\sounds\earcons\passthrough.wav" type="BINDATA" /> <include name="IDR_SOUND_EXIT_SCREEN_WAV" file="resources\chromeos\sounds\earcons\exit_screen.wav" type="BINDATA" /> <include name="IDR_SOUND_ENTER_SCREEN_WAV" file="resources\chromeos\sounds\earcons\enter_screen.wav" type="BINDATA" /> + <include name="IDR_SOUND_SPOKEN_FEEDBACK_TOGGLE_COUNTDOWN_HIGH_WAV" file="resources\chromeos\sounds\spoken_feedback_toggle_countdown_high.wav" type="BINDATA" /> + <include name="IDR_SOUND_SPOKEN_FEEDBACK_TOGGLE_COUNTDOWN_LOW_WAV" file="resources\chromeos\sounds\spoken_feedback_toggle_countdown_low.wav" type="BINDATA" /> </if> - <if expr="chromeos"> + <if expr="chromeos"> <include name="IDR_ABOUT_POWER_HTML" file="resources\chromeos\power.html" type="BINDATA" /> <include name="IDR_ABOUT_POWER_JS" file="resources\chromeos\power.js" type="BINDATA" /> <include name="IDR_ABOUT_POWER_CSS" file="resources\chromeos\power.css" type="BINDATA" />
diff --git a/chrome/browser/budget_service/budget_database.cc b/chrome/browser/budget_service/budget_database.cc index b4e7f88a..d59bc1d 100644 --- a/chrome/browser/budget_service/budget_database.cc +++ b/chrome/browser/budget_service/budget_database.cc
@@ -26,8 +26,8 @@ const char kDatabaseUMAName[] = "BudgetManager"; // The default amount of time during which a budget will be valid. -// This is 10 days = 240 hours. -constexpr double kBudgetDurationInHours = 240; +// This is 4 days = 96 hours. +constexpr double kBudgetDurationInHours = 96; } // namespace
diff --git a/chrome/browser/budget_service/budget_database_unittest.cc b/chrome/browser/budget_service/budget_database_unittest.cc index 2dbaa9c..3487a1f 100644 --- a/chrome/browser/budget_service/budget_database_unittest.cc +++ b/chrome/browser/budget_service/budget_database_unittest.cc
@@ -24,7 +24,7 @@ namespace { -const double kDefaultExpirationInHours = 240; +const double kDefaultExpirationInHours = 96; const double kDefaultEngagement = 30.0; const char kTestOrigin[] = "https://example.com"; @@ -243,14 +243,15 @@ // Set the default site engagement. SetSiteEngagementScore(kDefaultEngagement); - // Initialize the budget with some interesting chunks: 30 budget, 3 budget, - // 0 budget, and then after the first two expire, another 30 budget. + // Initialize the budget with some interesting chunks: 30 budget (full + // engagement), 15 budget (half of the engagement), 0 budget (less than an + // hour), and then after the first two expire, another 30 budget. GetBudgetDetails(); - clock->Advance(base::TimeDelta::FromDays(2)); + clock->Advance(base::TimeDelta::FromHours(kDefaultExpirationInHours / 2)); GetBudgetDetails(); clock->Advance(base::TimeDelta::FromMinutes(59)); GetBudgetDetails(); - clock->Advance(base::TimeDelta::FromDays(11)); + clock->Advance(base::TimeDelta::FromHours(kDefaultExpirationInHours + 1)); GetBudgetDetails(); // The BackgroundBudget UMA is recorded when budget is added to the origin. @@ -258,11 +259,11 @@ std::vector<base::Bucket> buckets = GetHistogramTester()->GetAllSamples("PushMessaging.BackgroundBudget"); ASSERT_EQ(2U, buckets.size()); - // First bucket is for 30 budget, which should have 2 entries. - EXPECT_EQ(30, buckets[0].min); + // First bucket is for full engagement, which should have 2 entries. + EXPECT_EQ(kDefaultEngagement, buckets[0].min); EXPECT_EQ(2, buckets[0].count); - // Second bucket is for 36 budget, which should have 1 entry. - EXPECT_EQ(36, buckets[1].min); + // Second bucket is for 1.5 * engagement, which should have 1 entry. + EXPECT_EQ(kDefaultEngagement * 1.5, buckets[1].min); EXPECT_EQ(1, buckets[1].count); }
diff --git a/chrome/browser/chrome_content_browser_client.cc b/chrome/browser/chrome_content_browser_client.cc index ce9507de..4c38d49 100644 --- a/chrome/browser/chrome_content_browser_client.cc +++ b/chrome/browser/chrome_content_browser_client.cc
@@ -139,6 +139,7 @@ #include "components/rappor/rappor_utils.h" #include "components/security_interstitials/core/ssl_error_ui.h" #include "components/signin/core/common/profile_management_switches.h" +#include "components/spellcheck/spellcheck_build_features.h" #include "components/startup_metric_utils/browser/startup_metric_host_impl.h" #include "components/translate/core/common/translate_switches.h" #include "components/url_formatter/url_fixer.h" @@ -318,11 +319,11 @@ #include "chrome/browser/plugins/flash_download_interception.h" #endif -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) #include "chrome/browser/spellchecker/spellcheck_message_filter.h" #endif -#if defined(USE_BROWSER_SPELLCHECKER) +#if BUILDFLAG(USE_BROWSER_SPELLCHECKER) #include "components/spellcheck/browser/spellcheck_message_filter_platform.h" #endif @@ -1033,10 +1034,10 @@ #if BUILDFLAG(ENABLE_PRINTING) host->AddFilter(new printing::PrintingMessageFilter(id, profile)); #endif -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) host->AddFilter(new SpellCheckMessageFilter(id)); #endif -#if defined(USE_BROWSER_SPELLCHECKER) +#if BUILDFLAG(USE_BROWSER_SPELLCHECKER) host->AddFilter(new SpellCheckMessageFilterPlatform(id)); #endif host->AddFilter(new ChromeNetBenchmarkingMessageFilter(profile, context)); @@ -1228,9 +1229,9 @@ // to a shared library. if (site_instance && site_instance->GetSiteURL().SchemeIs(chrome::kChromeSearchScheme) && - (site_instance->GetSiteURL().host() == + (site_instance->GetSiteURL().host_piece() == chrome::kChromeSearchRemoteNtpHost || - site_instance->GetSiteURL().host() == + site_instance->GetSiteURL().host_piece() == chrome::kChromeSearchLocalNtpHost) && ui::PageTransitionCoreTypeIs(*transition, ui::PAGE_TRANSITION_LINK)) { // Use AUTO_BOOKMARK for clicks on tiles of the new tab page, consistently
diff --git a/chrome/browser/chrome_content_browser_manifest_overlay.json b/chrome/browser/chrome_content_browser_manifest_overlay.json index ed6a8a1..113e2952e 100644 --- a/chrome/browser/chrome_content_browser_manifest_overlay.json +++ b/chrome/browser/chrome_content_browser_manifest_overlay.json
@@ -17,10 +17,11 @@ "metrics::mojom::CallStackProfileCollector" ], "ash": [ + // Under classic ash the browser provides ash interfaces to itself. "ash::mojom::LocaleNotificationController", "ash::mojom::NewWindowClient", "ash::mojom::ShelfController", - "ash::mojom::ShutdownClient", + "ash::mojom::ShutdownController", "ash::mojom::SystemTray", "ash::mojom::SystemTrayClient", "ash::mojom::WallpaperController", @@ -46,6 +47,7 @@ "bluetooth::mojom::AdapterFactory", "device::usb::ChooserService", "device::usb::DeviceManager", + "contextual_search::mojom::ContextualSearchJsApiService", "dom_distiller::mojom::DistillabilityService", "dom_distiller::mojom::DistillerJavaScriptService", "extensions::KeepAlive",
diff --git a/chrome/browser/chrome_content_renderer_manifest_overlay.json b/chrome/browser/chrome_content_renderer_manifest_overlay.json index 22840f982..3a81d7f 100644 --- a/chrome/browser/chrome_content_renderer_manifest_overlay.json +++ b/chrome/browser/chrome_content_renderer_manifest_overlay.json
@@ -14,6 +14,7 @@ "autofill::mojom::AutofillAgent", "autofill::mojom::PasswordAutofillAgent", "autofill::mojom::PasswordGenerationAgent", + "contextual_search::mojom::OverlayPageNotifierService", "dom_distiller::mojom::DistillerPageNotifierService" ] }
diff --git a/chrome/browser/chromeos/BUILD.gn b/chrome/browser/chromeos/BUILD.gn index f445d09..947aec9 100644 --- a/chrome/browser/chromeos/BUILD.gn +++ b/chrome/browser/chromeos/BUILD.gn
@@ -1113,8 +1113,6 @@ "power/power_prefs.h", "power/renderer_freezer.cc", "power/renderer_freezer.h", - "power/shutdown_client_impl.cc", - "power/shutdown_client_impl.h", "preferences.cc", "preferences.h", "printer_detector/printer_detector.cc", @@ -1181,6 +1179,8 @@ "settings/owner_flags_storage.h", "settings/session_manager_operation.cc", "settings/session_manager_operation.h", + "settings/shutdown_policy_forwarder.cc", + "settings/shutdown_policy_forwarder.h", "settings/shutdown_policy_handler.cc", "settings/shutdown_policy_handler.h", "settings/stub_cros_settings_provider.cc", @@ -1384,6 +1384,7 @@ "arc/arc_auth_service_unittest.cc", "arc/downloads_watcher/arc_downloads_watcher_service_unittest.cc", "arc/fileapi/arc_content_file_system_async_file_util_unittest.cc", + "arc/fileapi/arc_content_file_system_file_stream_reader_unittest.cc", "arc/fileapi/arc_content_file_system_url_util_unittest.cc", "arc/intent_helper/arc_external_protocol_dialog_unittest.cc", "arc/intent_helper/arc_navigation_throttle_unittest.cc",
diff --git a/chrome/browser/chromeos/accessibility/accessibility_manager.cc b/chrome/browser/chromeos/accessibility/accessibility_manager.cc index fe448ff..252ba75 100644 --- a/chrome/browser/chromeos/accessibility/accessibility_manager.cc +++ b/chrome/browser/chromeos/accessibility/accessibility_manager.cc
@@ -295,6 +295,12 @@ bundle.GetRawDataResource(IDR_SOUND_EXIT_SCREEN_WAV)); manager->Initialize(SOUND_ENTER_SCREEN, bundle.GetRawDataResource(IDR_SOUND_ENTER_SCREEN_WAV)); + manager->Initialize(SOUND_SPOKEN_FEEDBACK_TOGGLE_COUNTDOWN_HIGH, + bundle.GetRawDataResource( + IDR_SOUND_SPOKEN_FEEDBACK_TOGGLE_COUNTDOWN_HIGH_WAV)); + manager->Initialize(SOUND_SPOKEN_FEEDBACK_TOGGLE_COUNTDOWN_LOW, + bundle.GetRawDataResource( + IDR_SOUND_SPOKEN_FEEDBACK_TOGGLE_COUNTDOWN_LOW_WAV)); base::FilePath resources_path; if (!PathService::Get(chrome::DIR_RESOURCES, &resources_path)) @@ -551,6 +557,12 @@ return media::SoundsManager::Get()->Play(sound_key); } +bool AccessibilityManager::PlaySpokenFeedbackToggleCountdown(int tick_count) { + return media::SoundsManager::Get()->Play( + tick_count % 2 ? SOUND_SPOKEN_FEEDBACK_TOGGLE_COUNTDOWN_HIGH + : SOUND_SPOKEN_FEEDBACK_TOGGLE_COUNTDOWN_LOW); +} + void AccessibilityManager::HandleAccessibilityGesture(ui::AXGesture gesture) { extensions::EventRouter* event_router = extensions::EventRouter::Get(profile());
diff --git a/chrome/browser/chromeos/accessibility/accessibility_manager.h b/chrome/browser/chromeos/accessibility/accessibility_manager.h index dda34505..9ed80be 100644 --- a/chrome/browser/chromeos/accessibility/accessibility_manager.h +++ b/chrome/browser/chromeos/accessibility/accessibility_manager.h
@@ -249,6 +249,9 @@ // Notify accessibility when locale changes occur. void OnLocaleChanged(); + // Play tick sound indicating spoken feedback will be toggled after countdown. + bool PlaySpokenFeedbackToggleCountdown(int tick_count); + // Plays an earcon. Earcons are brief and distinctive sounds that indicate // when their mapped event has occurred. The sound key enums can be found in // chromeos/audio/chromeos_sounds.h.
diff --git a/chrome/browser/chromeos/arc/arc_auth_service.cc b/chrome/browser/chromeos/arc/arc_auth_service.cc index a342fc0..31145be 100644 --- a/chrome/browser/chromeos/arc/arc_auth_service.cc +++ b/chrome/browser/chromeos/arc/arc_auth_service.cc
@@ -353,11 +353,7 @@ void ArcAuthService::GetAuthCodeDeprecated0( const GetAuthCodeDeprecated0Callback& callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - DCHECK(!IsOptInVerificationDisabled()); - // For robot account we must use RequestAccountInfo because it allows to - // specify account type. - DCHECK(!IsArcKioskMode()); - callback.Run(GetAndResetAuthCode()); + NOTREACHED() << "GetAuthCodeDeprecated0() should no longer be callable"; } void ArcAuthService::GetAuthCodeDeprecated( @@ -450,7 +446,9 @@ // 3. For any other state on Android side that leads device appears in // non-signed state. DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - DCHECK(state_ != State::ACTIVE || IsAuthCodeRequest()); + DCHECK(state_ == State::FETCHING_CODE || state_ == State::ACTIVE); + if (state_ == State::ACTIVE) + DCHECK(IsAuthCodeRequest()); DCHECK(!IsArcKioskMode()); context_->PrepareContext(); } @@ -601,6 +599,7 @@ preference_handler_->Start(); } + DCHECK_EQ(State::NOT_INITIALIZED, state_); SetState(State::STOPPED); PrefServiceSyncableFromProfile(profile_)->AddSyncedPrefObserver( @@ -695,16 +694,7 @@ void ArcAuthService::OnContextReady() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - // TODO(hidehiko): The check is not necessary if this is a part of re-auth - // flow and OOBE OptIn where Android Management check must be a part of - // checking if Arc OptIn should be skip. Remove this. - android_management_checker_.reset(new ArcAndroidManagementChecker( - profile_, context_->token_service(), context_->account_id(), - false /* retry_on_error */)); - android_management_checker_->StartCheck( - base::Bind(&ArcAuthService::OnAndroidManagementChecked, - weak_ptr_factory_.GetWeakPtr())); + FetchAuthCode(); } void ArcAuthService::OnSyncedPrefChanged(const std::string& path, @@ -854,8 +844,6 @@ DCHECK(!auth_code.empty()); if (IsAuthCodeRequest()) { - DCHECK_EQ(state_, State::FETCHING_CODE); - SetState(State::ACTIVE); account_info_notifier_->Notify(!IsOptInVerificationDisabled(), auth_code, GetAccountType(), policy_util::IsAccountManaged(profile_)); @@ -863,7 +851,9 @@ return; } - if (state_ != State::FETCHING_CODE) { + if (state_ != State::SHOWING_TERMS_OF_SERVICE && + state_ != State::CHECKING_ANDROID_MANAGEMENT && + state_ != State::FETCHING_CODE) { ShutdownBridgeAndCloseUI(); return; } @@ -885,25 +875,6 @@ OnSignInFailedInternal(ProvisioningResult::OVERALL_SIGN_IN_TIMEOUT); } -void ArcAuthService::StartLso() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - // Terms were accepted - profile_->GetPrefs()->SetBoolean(prefs::kArcTermsAccepted, true); - - // Update UMA only if error (with or without feedback) is currently shown. - if (ui_page_ == ArcSupportHost::UIPage::ERROR) { - UpdateOptInActionUMA(OptInActionType::RETRY); - } else if (ui_page_ == ArcSupportHost::UIPage::ERROR_WITH_FEEDBACK) { - UpdateOptInActionUMA(OptInActionType::RETRY); - ShutdownBridge(); - } - - DCHECK(arc_bridge_service()->stopped()); - SetState(State::FETCHING_CODE); - PrepareContextForAuthCodeRequest(); -} - void ArcAuthService::CancelAuthCode() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); @@ -915,7 +886,9 @@ // In case |state_| is ACTIVE, |ui_page_| can be START_PROGRESS (which means // normal Arc booting) or ERROR or ERROR_WITH_FEEDBACK (in case Arc can not // be started). If Arc is booting normally dont't stop it on progress close. - if (state_ != State::FETCHING_CODE && + if ((state_ != State::FETCHING_CODE && + state_ != State::SHOWING_TERMS_OF_SERVICE && + state_ != State::CHECKING_ANDROID_MANAGEMENT) && ui_page_ != ArcSupportHost::UIPage::ERROR && ui_page_ != ArcSupportHost::UIPage::ERROR_WITH_FEEDBACK) { return; @@ -989,7 +962,7 @@ return; } - SetState(State::FETCHING_CODE); + SetState(State::SHOWING_TERMS_OF_SERVICE); ShowUI(ArcSupportHost::UIPage::TERMS, base::string16()); } @@ -1015,12 +988,35 @@ UpdateOptInCancelUMA(OptInCancelReason::NETWORK_ERROR); } +void ArcAuthService::StartArcAndroidManagementCheck() { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + DCHECK(arc_bridge_service()->stopped()); + DCHECK(state_ == State::SHOWING_TERMS_OF_SERVICE || + state_ == State::CHECKING_ANDROID_MANAGEMENT); + SetState(State::CHECKING_ANDROID_MANAGEMENT); + + android_management_checker_.reset(new ArcAndroidManagementChecker( + profile_, context_->token_service(), context_->account_id(), + false /* retry_on_error */)); + android_management_checker_->StartCheck( + base::Bind(&ArcAuthService::OnAndroidManagementChecked, + weak_ptr_factory_.GetWeakPtr())); +} + void ArcAuthService::OnAndroidManagementChecked( policy::AndroidManagementClient::Result result) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + DCHECK_EQ(state_, State::CHECKING_ANDROID_MANAGEMENT); + switch (result) { case policy::AndroidManagementClient::Result::UNMANAGED: - OnAndroidManagementPassed(); + if (IsOptInVerificationDisabled()) { + StartArc(); + } else { + // TODO(hidehiko): Merge this prefetching into re-auth case. + SetState(State::FETCHING_CODE); + PrepareContextForAuthCodeRequest(); + } break; case policy::AndroidManagementClient::Result::MANAGED: ShutdownBridgeAndShowUI( @@ -1073,23 +1069,6 @@ } } -void ArcAuthService::OnAndroidManagementPassed() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - if (state_ == State::ACTIVE) { - if (IsAuthCodeRequest()) - FetchAuthCode(); - return; - } - - if (profile_->GetPrefs()->GetBoolean(prefs::kArcSignedIn) || - IsOptInVerificationDisabled()) { - StartArc(); - } else { - FetchAuthCode(); - } -} - void ArcAuthService::OnWindowClosed() { CancelAuthCode(); } @@ -1097,6 +1076,9 @@ void ArcAuthService::OnTermsAgreed(bool is_metrics_enabled, bool is_backup_and_restore_enabled, bool is_location_service_enabled) { + // Terms were accepted + profile_->GetPrefs()->SetBoolean(prefs::kArcTermsAccepted, true); + // This is ARC support's UI event callback, so this is called only when // the UI is visible. The condition to open the UI is // !g_disable_ui_for_testing && !IsOptInVerificationDisabled() (see ShowUI()) @@ -1107,13 +1089,39 @@ preference_handler_->EnableMetrics(is_metrics_enabled); preference_handler_->EnableBackupRestore(is_backup_and_restore_enabled); preference_handler_->EnableLocationService(is_location_service_enabled); - StartLso(); + StartArcAndroidManagementCheck(); } void ArcAuthService::OnAuthSucceeded(const std::string& auth_code) { SetAuthCodeAndStartArc(auth_code); } +void ArcAuthService::OnRetryClicked() { + UpdateOptInActionUMA(OptInActionType::RETRY); + // ERROR_WITH_FEEDBACK is set in OnSignInFailed(). In the case, we postpone + // to stop the ARC to obtain the internal state. + // Here, on retry, stop it. + if (ui_page_ == ArcSupportHost::UIPage::ERROR_WITH_FEEDBACK) + ShutdownBridge(); + + switch (state_) { + case State::NOT_INITIALIZED: + NOTREACHED(); + break; + case State::STOPPED: + case State::SHOWING_TERMS_OF_SERVICE: + ShowUI(ArcSupportHost::UIPage::TERMS, base::string16()); + break; + case State::CHECKING_ANDROID_MANAGEMENT: + StartArcAndroidManagementCheck(); + break; + case State::FETCHING_CODE: + case State::ACTIVE: + PrepareContextForAuthCodeRequest(); + break; + } +} + void ArcAuthService::OnSendFeedbackClicked() { chrome::OpenFeedbackDialog(nullptr); } @@ -1142,14 +1150,20 @@ return os << "NOT_INITIALIZED"; case ArcAuthService::State::STOPPED: return os << "STOPPED"; + case ArcAuthService::State::SHOWING_TERMS_OF_SERVICE: + return os << "SHOWING_TERMS_OF_SERVICE"; + case ArcAuthService::State::CHECKING_ANDROID_MANAGEMENT: + return os << "CHECKING_ANDROID_MANAGEMENT"; case ArcAuthService::State::FETCHING_CODE: return os << "FETCHING_CODE"; case ArcAuthService::State::ACTIVE: return os << "ACTIVE"; - default: - NOTREACHED(); - return os; } + + // Some compiler reports an error even if all values of an enum-class are + // covered indivisually in a switch statement. + NOTREACHED(); + return os; } } // namespace arc
diff --git a/chrome/browser/chromeos/arc/arc_auth_service.h b/chrome/browser/chromeos/arc/arc_auth_service.h index 036be0b..891c278 100644 --- a/chrome/browser/chromeos/arc/arc_auth_service.h +++ b/chrome/browser/chromeos/arc/arc_auth_service.h
@@ -60,11 +60,53 @@ public sync_preferences::PrefServiceSyncableObserver, public sync_preferences::SyncedPrefObserver { public: + // Represents each State of ARC session. + // NOT_INITIALIZED: represents the state that the Profile is not yet ready + // so that this service is not yet initialized, or Chrome is being shut + // down so that this is destroyed. + // STOPPED: ARC session is not running, or being terminated. + // SHOWING_TERMS_OF_SERVICE: "Terms Of Service" page is shown on ARC support + // Chrome app. + // CHECKING_ANDROID_MANAGEMENT: Checking Android management status. Note that + // the status is checked for each ARC session starting, but this is the + // state only for the first boot case (= opt-in case). The second time and + // later the management check is running in parallel with ARC session + // starting, and in such a case, State is ACTIVE, instead. + // FETCHING_CODE: Fetching an auth token. Similar to + // CHECKING_ANDROID_MANAGEMENT case, this is only for the first boot case. + // In re-auth flow (fetching an auth token while ARC is running), the + // State should be ACTIVE. + // TODO(hidehiko): Migrate into re-auth flow, then remove this state. + // ACTIVE: ARC is running. + // + // State transition should be as follows: + // + // NOT_INITIALIZED -> STOPPED: when the primary Profile gets ready. + // ...(any)... -> NOT_INITIALIZED: when the Chrome is being shutdown. + // ...(any)... -> STOPPED: on error. + // + // In the first boot case (no OOBE case): + // STOPPED -> SHOWING_TERMS_OF_SERVICE: when arc.enabled preference is set. + // SHOWING_TERMS_OF_SERVICE -> CHECKING_ANDROID_MANAGEMENT: when a user + // agree with "Terms Of Service" + // CHECKING_ANDROID_MANAGEMENT -> FETCHING_CODE: when Android management + // check passes. + // FETCHING_CODE -> ACTIVE: when the auth token is successfully fetched. + // + // In the first boot case (OOBE case): + // STOPPED -> FETCHING_CODE: When arc.enabled preference is set. + // FETCHING_CODE -> ACTIVE: when the auth token is successfully fetched. + // + // In the second (or later) boot case: + // STOPPED -> ACTIVE: when arc.enabled preference is checked that it is + // true. Practically, this is when the primary Profile gets ready. enum class State { - NOT_INITIALIZED, // Service is not initialized. - STOPPED, // ARC is not running. - FETCHING_CODE, // ARC may be running or not. Auth code is fetching. - ACTIVE, // ARC is running. + NOT_INITIALIZED, + STOPPED, + SHOWING_TERMS_OF_SERVICE, + CHECKING_ANDROID_MANAGEMENT, + FETCHING_CODE, + ACTIVE, }; class Observer { @@ -144,9 +186,6 @@ void OnSignInFailedInternal(ProvisioningResult result); - // Called from Arc support platform app to start LSO. - void StartLso(); - // Called from Arc support platform app to set auth code and start arc. void SetAuthCodeAndStartArc(const std::string& auth_code); @@ -184,6 +223,7 @@ bool is_backup_and_restore_enabled, bool is_location_service_enabled) override; void OnAuthSucceeded(const std::string& auth_code) override; + void OnRetryClicked() override; void OnSendFeedbackClicked() override; // arc::ArcOptInPreferenceHandlerObserver: @@ -227,7 +267,6 @@ const base::string16& status); void OnOptInPreferenceChanged(); void StartUI(); - void StartAndroidManagementClient(); void OnAndroidManagementPassed(); void OnArcDataRemoved(bool success); void OnArcSignInTimeout(); @@ -239,6 +278,8 @@ void OnAccountInfoReady(mojom::AccountInfoPtr account_info); void OnRobotAuthCodeFetched(const std::string& auth_code); + void StartArcAndroidManagementCheck(); + // Called when the Android management check is done in opt-in flow or // re-auth flow. void OnAndroidManagementChecked(
diff --git a/chrome/browser/chromeos/arc/arc_auth_service_unittest.cc b/chrome/browser/chromeos/arc/arc_auth_service_unittest.cc index 414f6c2..a956c61 100644 --- a/chrome/browser/chromeos/arc/arc_auth_service_unittest.cc +++ b/chrome/browser/chromeos/arc/arc_auth_service_unittest.cc
@@ -132,7 +132,8 @@ ASSERT_EQ(ArcAuthService::State::STOPPED, auth_service()->state()); pref->SetBoolean(prefs::kArcEnabled, true); - ASSERT_EQ(ArcAuthService::State::FETCHING_CODE, auth_service()->state()); + ASSERT_EQ(ArcAuthService::State::SHOWING_TERMS_OF_SERVICE, + auth_service()->state()); pref->SetBoolean(prefs::kArcEnabled, false); ASSERT_EQ(ArcAuthService::State::STOPPED, auth_service()->state()); @@ -195,8 +196,12 @@ profile()->GetPrefs()->SetBoolean(prefs::kArcEnabled, true); // Setting profile and pref initiates a code fetching process. - ASSERT_EQ(ArcAuthService::State::FETCHING_CODE, auth_service()->state()); + ASSERT_EQ(ArcAuthService::State::SHOWING_TERMS_OF_SERVICE, + auth_service()->state()); + // TODO(hidehiko): Verify state transition from SHOWINING_TERMS_OF_SERVICE -> + // CHECKING_ANDROID_MANAGEMENT -> FETCHING_CODE, when we extract + // ArcSessionManager. auth_service()->SetAuthCodeAndStartArc(kTestAuthCode); ASSERT_EQ(ArcAuthService::State::ACTIVE, auth_service()->state()); @@ -214,13 +219,15 @@ auth_service()->OnPrimaryUserProfilePrepared(profile()); // Setting profile initiates a code fetching process. - ASSERT_EQ(ArcAuthService::State::FETCHING_CODE, auth_service()->state()); + ASSERT_EQ(ArcAuthService::State::SHOWING_TERMS_OF_SERVICE, + auth_service()->state()); content::BrowserThread::GetBlockingPool()->FlushForTesting(); base::RunLoop().RunUntilIdle(); // UI is disabled in unit tests and this code is unchanged. - ASSERT_EQ(ArcAuthService::State::FETCHING_CODE, auth_service()->state()); + ASSERT_EQ(ArcAuthService::State::SHOWING_TERMS_OF_SERVICE, + auth_service()->state()); // Correctly stop service. auth_service()->Shutdown(); @@ -231,7 +238,8 @@ auth_service()->OnPrimaryUserProfilePrepared(profile()); pref->SetBoolean(prefs::kArcEnabled, true); - ASSERT_EQ(ArcAuthService::State::FETCHING_CODE, auth_service()->state()); + ASSERT_EQ(ArcAuthService::State::SHOWING_TERMS_OF_SERVICE, + auth_service()->state()); auth_service()->CancelAuthCode(); ASSERT_EQ(ArcAuthService::State::STOPPED, auth_service()->state()); @@ -280,7 +288,8 @@ prefs->SetBoolean(prefs::kArcEnabled, true); auth_service()->OnPrimaryUserProfilePrepared(profile()); - EXPECT_EQ(ArcAuthService::State::FETCHING_CODE, auth_service()->state()); + EXPECT_EQ(ArcAuthService::State::SHOWING_TERMS_OF_SERVICE, + auth_service()->state()); auth_service()->SetAuthCodeAndStartArc(kTestAuthCode); EXPECT_EQ(ArcAuthService::State::ACTIVE, auth_service()->state()); EXPECT_TRUE(bridge_service()->ready());
diff --git a/chrome/browser/chromeos/arc/arc_support_host.cc b/chrome/browser/chromeos/arc/arc_support_host.cc index dafb167..189fa749 100644 --- a/chrome/browser/chromeos/arc/arc_support_host.cc +++ b/chrome/browser/chromeos/arc/arc_support_host.cc
@@ -75,6 +75,10 @@ constexpr char kIsBackupRestoreEnabled[] = "isBackupRestoreEnabled"; constexpr char kIsLocationServiceEnabled[] = "isLocationServiceEnabled"; +// "onRetryClicked" is fired when a user clicks "RETRY" button on the error +// page. +constexpr char kEventOnRetryClicked[] = "onRetryClicked"; + // "onSendFeedbackClicked" is fired when a user clicks "Send Feedback" button. constexpr char kEventOnSendFeedbackClicked[] = "onSendFeedbackClicked"; @@ -375,6 +379,8 @@ } else { NOTREACHED(); } + } else if (event == kEventOnRetryClicked) { + observer_->OnRetryClicked(); } else if (event == kEventOnSendFeedbackClicked) { observer_->OnSendFeedbackClicked(); } else {
diff --git a/chrome/browser/chromeos/arc/arc_support_host.h b/chrome/browser/chromeos/arc/arc_support_host.h index 5909909..c7dd72a 100644 --- a/chrome/browser/chromeos/arc/arc_support_host.h +++ b/chrome/browser/chromeos/arc/arc_support_host.h
@@ -48,6 +48,9 @@ // Called when LSO auth token fetch is successfully completed. virtual void OnAuthSucceeded(const std::string& auth_code) = 0; + // Called when "RETRY" button on the error page is clicked. + virtual void OnRetryClicked() = 0; + // Called when send feedback button on error page is clicked. virtual void OnSendFeedbackClicked() = 0; };
diff --git a/chrome/browser/chromeos/arc/fileapi/arc_content_file_system_backend_delegate.cc b/chrome/browser/chromeos/arc/fileapi/arc_content_file_system_backend_delegate.cc index b003e70..19abf6ca 100644 --- a/chrome/browser/chromeos/arc/fileapi/arc_content_file_system_backend_delegate.cc +++ b/chrome/browser/chromeos/arc/fileapi/arc_content_file_system_backend_delegate.cc
@@ -4,8 +4,10 @@ #include "chrome/browser/chromeos/arc/fileapi/arc_content_file_system_backend_delegate.h" +#include "base/memory/ptr_util.h" #include "chrome/browser/chromeos/arc/fileapi/arc_content_file_system_async_file_util.h" #include "chrome/browser/chromeos/arc/fileapi/arc_content_file_system_file_stream_reader.h" +#include "chrome/browser/chromeos/arc/fileapi/arc_content_file_system_url_util.h" #include "content/public/browser/browser_thread.h" #include "storage/browser/fileapi/file_stream_writer.h" #include "storage/browser/fileapi/file_system_url.h" @@ -34,8 +36,9 @@ storage::FileSystemContext* context) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); DCHECK_EQ(storage::kFileSystemTypeArcContent, url.type()); - return std::unique_ptr<storage::FileStreamReader>( - new ArcContentFileSystemFileStreamReader(url, offset, max_bytes_to_read)); + GURL arc_url = FileSystemUrlToArcUrl(url); + return base::MakeUnique<ArcContentFileSystemFileStreamReader>(arc_url, + offset); } std::unique_ptr<storage::FileStreamWriter>
diff --git a/chrome/browser/chromeos/arc/fileapi/arc_content_file_system_file_stream_reader.cc b/chrome/browser/chromeos/arc/fileapi/arc_content_file_system_file_stream_reader.cc index fb41b95..3788e6e 100644 --- a/chrome/browser/chromeos/arc/fileapi/arc_content_file_system_file_stream_reader.cc +++ b/chrome/browser/chromeos/arc/fileapi/arc_content_file_system_file_stream_reader.cc
@@ -4,14 +4,28 @@ #include "chrome/browser/chromeos/arc/fileapi/arc_content_file_system_file_stream_reader.h" +#include "chrome/browser/chromeos/arc/fileapi/intent_helper_util.h" +#include "content/public/browser/browser_thread.h" +#include "mojo/edk/embedder/embedder.h" +#include "net/base/file_stream.h" +#include "net/base/io_buffer.h" #include "net/base/net_errors.h" namespace arc { +namespace { + +void OnGetFileSize(const net::Int64CompletionCallback& callback, int64_t size) { + DCHECK_CURRENTLY_ON(content::BrowserThread::IO); + callback.Run(size < 0 ? net::ERR_FAILED : size); +} + +} // namespace + ArcContentFileSystemFileStreamReader::ArcContentFileSystemFileStreamReader( - const storage::FileSystemURL& url, - int64_t offset, - int64_t max_bytes_to_read) {} + const GURL& arc_url, + int64_t offset) + : arc_url_(arc_url), offset_(offset), weak_ptr_factory_(this) {} ArcContentFileSystemFileStreamReader::~ArcContentFileSystemFileStreamReader() = default; @@ -20,14 +34,58 @@ net::IOBuffer* buffer, int buffer_length, const net::CompletionCallback& callback) { - NOTIMPLEMENTED(); - return net::ERR_NOT_IMPLEMENTED; + DCHECK_CURRENTLY_ON(content::BrowserThread::IO); + if (file_stream_) + return file_stream_->Read(buffer, buffer_length, callback); + + if (offset_ != 0) { + // TODO(hashimoto): Handle offset_ != 0 cases. + NOTIMPLEMENTED() << "Non-zero offset is not supported yet: offset_ = " + << offset_; + return net::ERR_FAILED; + } + intent_helper_util::OpenFileToReadOnIOThread( + arc_url_, + base::Bind(&ArcContentFileSystemFileStreamReader::OnOpenFile, + weak_ptr_factory_.GetWeakPtr(), make_scoped_refptr(buffer), + buffer_length, callback)); + return net::ERR_IO_PENDING; } int64_t ArcContentFileSystemFileStreamReader::GetLength( const net::Int64CompletionCallback& callback) { - NOTIMPLEMENTED(); - return net::ERR_NOT_IMPLEMENTED; + DCHECK_CURRENTLY_ON(content::BrowserThread::IO); + intent_helper_util::GetFileSizeOnIOThread( + arc_url_, base::Bind(&OnGetFileSize, callback)); + return net::ERR_IO_PENDING; +} + +void ArcContentFileSystemFileStreamReader::OnOpenFile( + scoped_refptr<net::IOBuffer> buf, + int buffer_length, + const net::CompletionCallback& callback, + mojo::ScopedHandle handle) { + DCHECK_CURRENTLY_ON(content::BrowserThread::IO); + + mojo::edk::ScopedPlatformHandle platform_handle; + if (mojo::edk::PassWrappedPlatformHandle( + handle.release().value(), &platform_handle) != MOJO_RESULT_OK) { + LOG(ERROR) << "PassWrappedPlatformHandle failed"; + callback.Run(net::ERR_FAILED); + return; + } + base::File file(platform_handle.release().handle); + if (!file.IsValid()) { + LOG(ERROR) << "Invalid file."; + callback.Run(net::ERR_FAILED); + return; + } + file_stream_.reset(new net::FileStream( + std::move(file), content::BrowserThread::GetBlockingPool())); + // Resume Read(). + int result = Read(buf.get(), buffer_length, callback); + if (result != net::ERR_IO_PENDING) + callback.Run(result); } } // namespace arc
diff --git a/chrome/browser/chromeos/arc/fileapi/arc_content_file_system_file_stream_reader.h b/chrome/browser/chromeos/arc/fileapi/arc_content_file_system_file_stream_reader.h index 2d946744..2d49c1e 100644 --- a/chrome/browser/chromeos/arc/fileapi/arc_content_file_system_file_stream_reader.h +++ b/chrome/browser/chromeos/arc/fileapi/arc_content_file_system_file_stream_reader.h
@@ -5,15 +5,25 @@ #ifndef CHROME_BROWSER_CHROMEOS_ARC_FILEAPI_ARC_CONTENT_FILE_SYSTEM_FILE_STREAM_READER_H_ #define CHROME_BROWSER_CHROMEOS_ARC_FILEAPI_ARC_CONTENT_FILE_SYSTEM_FILE_STREAM_READER_H_ +#include <memory> + +#include "base/memory/weak_ptr.h" +#include "mojo/public/cpp/system/handle.h" +#include "net/base/completion_callback.h" #include "storage/browser/fileapi/file_stream_reader.h" +#include "url/gurl.h" + +namespace net { +class FileStream; +class IOBuffer; +} namespace arc { +// FileStreamReader implementation for ARC content file system. class ArcContentFileSystemFileStreamReader : public storage::FileStreamReader { public: - ArcContentFileSystemFileStreamReader(const storage::FileSystemURL& url, - int64_t offset, - int64_t max_bytes_to_read); + ArcContentFileSystemFileStreamReader(const GURL& arc_url, int64_t offset); ~ArcContentFileSystemFileStreamReader() override; // storage::FileStreamReader override: @@ -23,6 +33,18 @@ int64_t GetLength(const net::Int64CompletionCallback& callback) override; private: + void OnOpenFile(scoped_refptr<net::IOBuffer> buf, + int buffer_length, + const net::CompletionCallback& callback, + mojo::ScopedHandle handle); + + GURL arc_url_; + int64_t offset_; + + std::unique_ptr<net::FileStream> file_stream_; + + base::WeakPtrFactory<ArcContentFileSystemFileStreamReader> weak_ptr_factory_; + DISALLOW_COPY_AND_ASSIGN(ArcContentFileSystemFileStreamReader); };
diff --git a/chrome/browser/chromeos/arc/fileapi/arc_content_file_system_file_stream_reader_unittest.cc b/chrome/browser/chromeos/arc/fileapi/arc_content_file_system_file_stream_reader_unittest.cc new file mode 100644 index 0000000..0fd80e0e --- /dev/null +++ b/chrome/browser/chromeos/arc/fileapi/arc_content_file_system_file_stream_reader_unittest.cc
@@ -0,0 +1,123 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/files/file_util.h" +#include "base/files/scoped_temp_dir.h" +#include "base/location.h" +#include "base/threading/thread_task_runner_handle.h" +#include "chrome/browser/chromeos/arc/fileapi/arc_content_file_system_file_stream_reader.h" +#include "components/arc/test/fake_arc_bridge_service.h" +#include "components/arc/test/fake_intent_helper_instance.h" +#include "content/public/test/test_browser_thread_bundle.h" +#include "mojo/edk/embedder/embedder.h" +#include "net/base/io_buffer.h" +#include "net/base/test_completion_callback.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace arc { + +namespace { + +const char kArcUrl[] = "content://org.chromium.foo/bar"; +const char kData[] = "abcdefghijklmnopqrstuvwxyz"; + +class ArcIntentHelperInstanceTestImpl : public FakeIntentHelperInstance { + public: + explicit ArcIntentHelperInstanceTestImpl(const base::FilePath& file_path) + : file_path_(file_path) {} + + ~ArcIntentHelperInstanceTestImpl() override = default; + + void GetFileSize(const mojo::String& url, + const GetFileSizeCallback& callback) override { + EXPECT_EQ(kArcUrl, url.get()); + base::File::Info info; + EXPECT_TRUE(base::GetFileInfo(file_path_, &info)); + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::Bind(callback, info.size)); + } + + void OpenFileToRead(const mojo::String& url, + const OpenFileToReadCallback& callback) override { + EXPECT_EQ(kArcUrl, url.get()); + + base::File file(file_path_, base::File::FLAG_OPEN | base::File::FLAG_READ); + EXPECT_TRUE(file.IsValid()); + + mojo::edk::ScopedPlatformHandle platform_handle( + mojo::edk::PlatformHandle(file.TakePlatformFile())); + MojoHandle wrapped_handle; + EXPECT_EQ(MOJO_RESULT_OK, mojo::edk::CreatePlatformHandleWrapper( + std::move(platform_handle), &wrapped_handle)); + + mojo::ScopedHandle scoped_handle{mojo::Handle(wrapped_handle)}; + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::Bind(callback, base::Passed(std::move(scoped_handle)))); + } + + private: + base::FilePath file_path_; + + DISALLOW_COPY_AND_ASSIGN(ArcIntentHelperInstanceTestImpl); +}; + +class ArcContentFileSystemFileStreamReaderTest : public testing::Test { + public: + ArcContentFileSystemFileStreamReaderTest() = default; + + ~ArcContentFileSystemFileStreamReaderTest() override = default; + + void SetUp() override { + mojo::edk::Init(); + + ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); + + base::FilePath path = temp_dir_.GetPath().AppendASCII("bar"); + ASSERT_TRUE(base::WriteFile(path, kData, arraysize(kData))); + + intent_helper_.reset(new ArcIntentHelperInstanceTestImpl(path)); + + fake_arc_bridge_service_.intent_helper()->SetInstance(intent_helper_.get()); + } + + private: + base::ScopedTempDir temp_dir_; + content::TestBrowserThreadBundle thread_bundle_; + FakeArcBridgeService fake_arc_bridge_service_; + std::unique_ptr<ArcIntentHelperInstanceTestImpl> intent_helper_; + + DISALLOW_COPY_AND_ASSIGN(ArcContentFileSystemFileStreamReaderTest); +}; + +} // namespace + +TEST_F(ArcContentFileSystemFileStreamReaderTest, Read) { + ArcContentFileSystemFileStreamReader reader(GURL(kArcUrl), 0); + + auto base_buffer = + make_scoped_refptr(new net::IOBufferWithSize(arraysize(kData))); + auto drainable_buffer = make_scoped_refptr( + new net::DrainableIOBuffer(base_buffer.get(), base_buffer->size())); + while (drainable_buffer->BytesRemaining()) { + net::TestCompletionCallback callback; + int result = callback.GetResult( + reader.Read(drainable_buffer.get(), drainable_buffer->BytesRemaining(), + callback.callback())); + ASSERT_GT(result, 0); + drainable_buffer->DidConsume(result); + } + EXPECT_EQ(base::StringPiece(kData, arraysize(kData)), + base::StringPiece(base_buffer->data(), base_buffer->size())); +} + +TEST_F(ArcContentFileSystemFileStreamReaderTest, GetLength) { + ArcContentFileSystemFileStreamReader reader(GURL(kArcUrl), 0); + + net::TestInt64CompletionCallback callback; + EXPECT_EQ(static_cast<int64_t>(arraysize(kData)), + callback.GetResult(reader.GetLength(callback.callback()))); +} + +} // namespace arc
diff --git a/chrome/browser/chromeos/chrome_browser_main_chromeos.cc b/chrome/browser/chromeos/chrome_browser_main_chromeos.cc index c053795..8b9664c 100644 --- a/chrome/browser/chromeos/chrome_browser_main_chromeos.cc +++ b/chrome/browser/chromeos/chrome_browser_main_chromeos.cc
@@ -80,6 +80,7 @@ #include "chrome/browser/chromeos/resource_reporter/resource_reporter.h" #include "chrome/browser/chromeos/settings/device_oauth2_token_service_factory.h" #include "chrome/browser/chromeos/settings/device_settings_service.h" +#include "chrome/browser/chromeos/settings/shutdown_policy_forwarder.h" #include "chrome/browser/chromeos/status/data_promo_notification.h" #include "chrome/browser/chromeos/system/input_device_settings.h" #include "chrome/browser/chromeos/ui/low_disk_notification.h" @@ -768,6 +769,10 @@ keyboard_event_rewriters_->Init(); } + // In classic ash must occur after ash::WmShell is initialized. Triggers a + // fetch of the initial CrosSettings DeviceRebootOnShutdown policy. + shutdown_policy_forwarder_ = base::MakeUnique<ShutdownPolicyForwarder>(); + ChromeBrowserMainPartsLinux::PostBrowserStart(); } @@ -780,6 +785,9 @@ arc_service_launcher_->Shutdown(); arc_kiosk_app_manager_.reset(); + // Unregister CrosSettings observers before CrosSettings is destroyed. + shutdown_policy_forwarder_.reset(); + // Destroy the application name notifier for Kiosk mode. KioskModeIdleAppNameNotification::Shutdown();
diff --git a/chrome/browser/chromeos/chrome_browser_main_chromeos.h b/chrome/browser/chromeos/chrome_browser_main_chromeos.h index 7722f9c..0847ae7f 100644 --- a/chrome/browser/chromeos/chrome_browser_main_chromeos.h +++ b/chrome/browser/chromeos/chrome_browser_main_chromeos.h
@@ -33,13 +33,14 @@ class LowDiskNotification; class MagnificationManager; class NetworkPrefStateObserver; +class NetworkThrottlingObserver; class PeripheralBatteryObserver; class PowerPrefs; class RendererFreezer; class SessionManagerObserver; +class ShutdownPolicyForwarder; class SwapMetrics; class WakeOnWifiManager; -class NetworkThrottlingObserver; namespace default_app_order { class ExternalLoader; @@ -87,6 +88,8 @@ std::unique_ptr<session_manager::SessionManager> session_manager_; + std::unique_ptr<ShutdownPolicyForwarder> shutdown_policy_forwarder_; + std::unique_ptr<EventRewriterController> keyboard_event_rewriters_; scoped_refptr<chromeos::ExternalMetrics> external_metrics_;
diff --git a/chrome/browser/chromeos/chrome_interface_factory.cc b/chrome/browser/chromeos/chrome_interface_factory.cc index 7401321..1c9a68d 100644 --- a/chrome/browser/chromeos/chrome_interface_factory.cc +++ b/chrome/browser/chromeos/chrome_interface_factory.cc
@@ -16,7 +16,6 @@ #include "base/threading/thread_checker.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager.h" -#include "chrome/browser/chromeos/power/shutdown_client_impl.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/ash/app_list/app_list_presenter_service.h" @@ -126,13 +125,6 @@ std::move(request)); } - void BindRequest(ash::mojom::ShutdownClientRequest request) { - if (!shutdown_client_) - shutdown_client_ = base::MakeUnique<ShutdownClientImpl>(); - shutdown_client_bindings_.AddBinding(shutdown_client_.get(), - std::move(request)); - } - void BindRequest(ash::mojom::SystemTrayClientRequest request) { system_tray_client_bindings_.AddBinding(SystemTrayClient::Get(), std::move(request)); @@ -162,8 +154,6 @@ std::unique_ptr<ChromeLaunchable> launchable_; std::unique_ptr<ChromeNewWindowClient> new_window_client_; mojo::BindingSet<ash::mojom::NewWindowClient> new_window_client_bindings_; - std::unique_ptr<ShutdownClientImpl> shutdown_client_; - mojo::BindingSet<ash::mojom::ShutdownClient> shutdown_client_bindings_; mojo::BindingSet<ash::mojom::SystemTrayClient> system_tray_client_bindings_; std::unique_ptr<VolumeController> volume_controller_; std::unique_ptr<AppListPresenterService> app_list_presenter_service_; @@ -187,14 +177,15 @@ const service_manager::Identity& remote_identity, service_manager::InterfaceRegistry* registry, service_manager::Connector* connector) { + // TODO(jamescook): Only register the interfaces needed for a particular + // |remote_identity|. For example, a connection from service:ash needs these, + // but a connection from service:content_gpu does not. FactoryImpl::AddFactory<keyboard::mojom::Keyboard>(registry, main_thread_task_runner_); FactoryImpl::AddFactory<mash::mojom::Launchable>(registry, main_thread_task_runner_); FactoryImpl::AddFactory<ash::mojom::NewWindowClient>( registry, main_thread_task_runner_); - FactoryImpl::AddFactory<ash::mojom::ShutdownClient>(registry, - main_thread_task_runner_); FactoryImpl::AddFactory<ash::mojom::SystemTrayClient>( registry, main_thread_task_runner_); FactoryImpl::AddFactory<ash::mojom::VolumeController>(
diff --git a/chrome/browser/chromeos/first_run/first_run_view.cc b/chrome/browser/chromeos/first_run/first_run_view.cc index 9e372778..7df04171 100644 --- a/chrome/browser/chromeos/first_run/first_run_view.cc +++ b/chrome/browser/chromeos/first_run/first_run_view.cc
@@ -11,7 +11,7 @@ #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/views/controls/webview/webview.h" #include "url/gurl.h"
diff --git a/chrome/browser/chromeos/login/supervised/supervised_user_creation_flow.cc b/chrome/browser/chromeos/login/supervised/supervised_user_creation_flow.cc index a94ea4f..a6101e6ea 100644 --- a/chrome/browser/chromeos/login/supervised/supervised_user_creation_flow.cc +++ b/chrome/browser/chromeos/login/supervised/supervised_user_creation_flow.cc
@@ -46,6 +46,10 @@ return false; } +bool SupervisedUserCreationFlow::ShouldShowNotificationTray() { + return false; +} + bool SupervisedUserCreationFlow::ShouldLaunchBrowser() { return false; }
diff --git a/chrome/browser/chromeos/login/supervised/supervised_user_creation_flow.h b/chrome/browser/chromeos/login/supervised/supervised_user_creation_flow.h index d78ba93..5e5da704 100644 --- a/chrome/browser/chromeos/login/supervised/supervised_user_creation_flow.h +++ b/chrome/browser/chromeos/login/supervised/supervised_user_creation_flow.h
@@ -24,6 +24,7 @@ bool CanLockScreen() override; bool ShouldShowSettings() override; + bool ShouldShowNotificationTray() override; bool ShouldLaunchBrowser() override; bool ShouldSkipPostLoginScreens() override; bool SupportsEarlyRestartToApplyFlags() override;
diff --git a/chrome/browser/chromeos/login/ui/webui_login_view.cc b/chrome/browser/chromeos/login/ui/webui_login_view.cc index 90f8179..4f99cb70 100644 --- a/chrome/browser/chromeos/login/ui/webui_login_view.cc +++ b/chrome/browser/chromeos/login/ui/webui_login_view.cc
@@ -50,7 +50,7 @@ #include "content/public/browser/web_ui.h" #include "content/public/common/renderer_preferences.h" #include "extensions/browser/view_type_utils.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" #include "ui/views/controls/webview/webview.h"
diff --git a/chrome/browser/chromeos/login/user_flow.cc b/chrome/browser/chromeos/login/user_flow.cc index 66c4ae6e..6e1a6a7 100644 --- a/chrome/browser/chromeos/login/user_flow.cc +++ b/chrome/browser/chromeos/login/user_flow.cc
@@ -34,6 +34,10 @@ return true; } +bool DefaultUserFlow::ShouldShowNotificationTray() { + return true; +} + bool DefaultUserFlow::ShouldLaunchBrowser() { return true; } @@ -76,6 +80,10 @@ return true; } +bool ExtendedUserFlow::ShouldShowNotificationTray() { + return true; +} + void ExtendedUserFlow::HandleOAuthTokenStatusChange( user_manager::User::OAuthTokenStatus status) { }
diff --git a/chrome/browser/chromeos/login/user_flow.h b/chrome/browser/chromeos/login/user_flow.h index d90d3cc..91578aa 100644 --- a/chrome/browser/chromeos/login/user_flow.h +++ b/chrome/browser/chromeos/login/user_flow.h
@@ -29,6 +29,7 @@ // Indicates if screen locking should be enabled or disabled for a flow. virtual bool CanLockScreen() = 0; virtual bool ShouldShowSettings() = 0; + virtual bool ShouldShowNotificationTray() = 0; virtual bool ShouldLaunchBrowser() = 0; virtual bool ShouldSkipPostLoginScreens() = 0; virtual bool SupportsEarlyRestartToApplyFlags() = 0; @@ -56,6 +57,7 @@ void AppendAdditionalCommandLineSwitches() override; bool CanLockScreen() override; bool ShouldShowSettings() override; + bool ShouldShowNotificationTray() override; bool ShouldLaunchBrowser() override; bool ShouldSkipPostLoginScreens() override; bool SupportsEarlyRestartToApplyFlags() override; @@ -75,6 +77,7 @@ void AppendAdditionalCommandLineSwitches() override; bool ShouldShowSettings() override; + bool ShouldShowNotificationTray() override; void HandleOAuthTokenStatusChange( user_manager::User::OAuthTokenStatus status) override;
diff --git a/chrome/browser/chromeos/power/shutdown_client_impl.cc b/chrome/browser/chromeos/power/shutdown_client_impl.cc deleted file mode 100644 index 9799557..0000000 --- a/chrome/browser/chromeos/power/shutdown_client_impl.cc +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/chromeos/power/shutdown_client_impl.h" - -#include "base/logging.h" -#include "chrome/browser/chromeos/settings/cros_settings.h" -#include "chromeos/dbus/dbus_thread_manager.h" -#include "chromeos/dbus/power_manager_client.h" -#include "chromeos/dbus/session_manager_client.h" -#include "chromeos/settings/cros_settings_names.h" - -namespace chromeos { - -ShutdownClientImpl::ShutdownClientImpl() : weak_factory_(this) {} - -ShutdownClientImpl::~ShutdownClientImpl() {} - -void ShutdownClientImpl::RequestShutdown() { - CrosSettings* cros_settings = CrosSettings::Get(); - CrosSettingsProvider::TrustedStatus status = - cros_settings->PrepareTrustedValues(base::Bind( - &ShutdownClientImpl::RequestShutdown, weak_factory_.GetWeakPtr())); - if (status != CrosSettingsProvider::TRUSTED) - return; - - // Get the updated policy. - bool reboot_on_shutdown = false; - cros_settings->GetBoolean(kRebootOnShutdown, &reboot_on_shutdown); - - if (reboot_on_shutdown) - DBusThreadManager::Get()->GetPowerManagerClient()->RequestRestart(); - else - DBusThreadManager::Get()->GetPowerManagerClient()->RequestShutdown(); -} - -} // namespace chromeos
diff --git a/chrome/browser/chromeos/power/shutdown_client_impl.h b/chrome/browser/chromeos/power/shutdown_client_impl.h deleted file mode 100644 index 10d320ff..0000000 --- a/chrome/browser/chromeos/power/shutdown_client_impl.h +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_CHROMEOS_POWER_SHUTDOWN_CLIENT_IMPL_H_ -#define CHROME_BROWSER_CHROMEOS_POWER_SHUTDOWN_CLIENT_IMPL_H_ - -#include "ash/public/interfaces/shutdown.mojom.h" -#include "base/macros.h" -#include "base/memory/weak_ptr.h" - -namespace chromeos { - -class ShutdownClientImpl : public ash::mojom::ShutdownClient { - public: - ShutdownClientImpl(); - ~ShutdownClientImpl() override; - - private: - // ash::mojom::ShutdownClient implementation. - void RequestShutdown() override; - - base::WeakPtrFactory<ShutdownClientImpl> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(ShutdownClientImpl); -}; - -} // namespace chromeos - -#endif // CHROME_BROWSER_CHROMEOS_POWER_SHUTDOWN_CLIENT_IMPL_H_
diff --git a/chrome/browser/chromeos/settings/shutdown_policy_forwarder.cc b/chrome/browser/chromeos/settings/shutdown_policy_forwarder.cc new file mode 100644 index 0000000..a651156 --- /dev/null +++ b/chrome/browser/chromeos/settings/shutdown_policy_forwarder.cc
@@ -0,0 +1,43 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/chromeos/settings/shutdown_policy_forwarder.h" + +#include "ash/public/interfaces/shutdown.mojom.h" +#include "chrome/browser/chromeos/settings/cros_settings.h" +#include "chrome/browser/ui/ash/ash_util.h" +#include "content/public/common/service_manager_connection.h" +#include "services/service_manager/public/cpp/connector.h" + +namespace chromeos { + +ShutdownPolicyForwarder::ShutdownPolicyForwarder() + : shutdown_policy_handler_(CrosSettings::Get(), this) { + // Request the initial setting. + shutdown_policy_handler_.NotifyDelegateWithShutdownPolicy(); +} + +ShutdownPolicyForwarder::~ShutdownPolicyForwarder() {} + +void ShutdownPolicyForwarder::OnShutdownPolicyChanged(bool reboot_on_shutdown) { + service_manager::Connector* connector = + content::ServiceManagerConnection::GetForProcess()->GetConnector(); + + // Shutdown policy changes rarely so don't bother caching the connection. + ash::mojom::ShutdownControllerPtr shutdown_controller; + + // Under mash the ShutdownController interface is in the ash process. In + // classic ash the browser provides it to itself. + if (chrome::IsRunningInMash()) { + connector->ConnectToInterface("service:ash", &shutdown_controller); + } else { + connector->ConnectToInterface("service:content_browser", + &shutdown_controller); + } + + // Forward the setting to ash. + shutdown_controller->SetRebootOnShutdown(reboot_on_shutdown); +} + +} // namespace chromeos
diff --git a/chrome/browser/chromeos/settings/shutdown_policy_forwarder.h b/chrome/browser/chromeos/settings/shutdown_policy_forwarder.h new file mode 100644 index 0000000..c385f39 --- /dev/null +++ b/chrome/browser/chromeos/settings/shutdown_policy_forwarder.h
@@ -0,0 +1,30 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_CHROMEOS_SETTINGS_SHUTDOWN_POLICY_FORWARDER_H_ +#define CHROME_BROWSER_CHROMEOS_SETTINGS_SHUTDOWN_POLICY_FORWARDER_H_ + +#include "base/macros.h" +#include "chrome/browser/chromeos/settings/shutdown_policy_handler.h" + +namespace chromeos { + +// Forwards the current DeviceRebootOnShutdown policy to ash. +class ShutdownPolicyForwarder : public ShutdownPolicyHandler::Delegate { + public: + ShutdownPolicyForwarder(); + ~ShutdownPolicyForwarder() override; + + private: + // ShutdownPolicyHandler::Delegate: + void OnShutdownPolicyChanged(bool reboot_on_shutdown) override; + + ShutdownPolicyHandler shutdown_policy_handler_; + + DISALLOW_COPY_AND_ASSIGN(ShutdownPolicyForwarder); +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_CHROMEOS_SETTINGS_SHUTDOWN_POLICY_FORWARDER_H_
diff --git a/chrome/browser/chromeos/settings/shutdown_policy_handler.cc b/chrome/browser/chromeos/settings/shutdown_policy_handler.cc index 095a9868..c3c87ae 100644 --- a/chrome/browser/chromeos/settings/shutdown_policy_handler.cc +++ b/chrome/browser/chromeos/settings/shutdown_policy_handler.cc
@@ -14,44 +14,28 @@ ShutdownPolicyHandler::ShutdownPolicyHandler(CrosSettings* cros_settings, Delegate* delegate) : cros_settings_(cros_settings), delegate_(delegate), weak_factory_(this) { - if (delegate_) { - shutdown_policy_subscription_ = cros_settings_->AddSettingsObserver( - kRebootOnShutdown, - base::Bind(&ShutdownPolicyHandler::OnShutdownPolicyChanged, - weak_factory_.GetWeakPtr())); - } + DCHECK(cros_settings_); + DCHECK(delegate); + shutdown_policy_subscription_ = cros_settings_->AddSettingsObserver( + kRebootOnShutdown, + base::Bind(&ShutdownPolicyHandler::NotifyDelegateWithShutdownPolicy, + weak_factory_.GetWeakPtr())); } ShutdownPolicyHandler::~ShutdownPolicyHandler() {} -void ShutdownPolicyHandler::Shutdown() { - shutdown_policy_subscription_.reset(); - delegate_ = nullptr; -} - -void ShutdownPolicyHandler::CallDelegate(bool reboot_on_shutdown) { - if (delegate_) - delegate_->OnShutdownPolicyChanged(reboot_on_shutdown); -} - -void ShutdownPolicyHandler::OnShutdownPolicyChanged() { - CheckIfRebootOnShutdown(base::Bind(&ShutdownPolicyHandler::CallDelegate, - weak_factory_.GetWeakPtr())); -} - -void ShutdownPolicyHandler::CheckIfRebootOnShutdown( - const RebootOnShutdownCallback& callback) { +void ShutdownPolicyHandler::NotifyDelegateWithShutdownPolicy() { CrosSettingsProvider::TrustedStatus status = cros_settings_->PrepareTrustedValues( - base::Bind(&ShutdownPolicyHandler::CheckIfRebootOnShutdown, - weak_factory_.GetWeakPtr(), callback)); + base::Bind(&ShutdownPolicyHandler::NotifyDelegateWithShutdownPolicy, + weak_factory_.GetWeakPtr())); if (status != CrosSettingsProvider::TRUSTED) return; // Get the updated policy. bool reboot_on_shutdown = false; cros_settings_->GetBoolean(kRebootOnShutdown, &reboot_on_shutdown); - callback.Run(reboot_on_shutdown); + delegate_->OnShutdownPolicyChanged(reboot_on_shutdown); } } // namespace chromeos
diff --git a/chrome/browser/chromeos/settings/shutdown_policy_handler.h b/chrome/browser/chromeos/settings/shutdown_policy_handler.h index a13dfe9..c2c290a 100644 --- a/chrome/browser/chromeos/settings/shutdown_policy_handler.h +++ b/chrome/browser/chromeos/settings/shutdown_policy_handler.h
@@ -19,12 +19,8 @@ // calling its OnShutdownPolicyChanged method with the new state of the policy. class ShutdownPolicyHandler { public: - // This callback is passed to CheckIfRebootOnShutdown, which invokes it with - // the current state of the |DeviceRebootOnShutdown| policy once a trusted of - // policies is established. - using RebootOnShutdownCallback = base::Callback<void(bool)>; - // This delegate is called when the |DeviceRebootOnShutdown| policy changes. + // NotifyDelegateWithShutdownPolicy() can manually request a notification. class Delegate { public: virtual void OnShutdownPolicyChanged(bool reboot_on_shutdown) = 0; @@ -36,18 +32,11 @@ ShutdownPolicyHandler(CrosSettings* cros_settings, Delegate* delegate); ~ShutdownPolicyHandler(); - // Once a trusted set of policies is established, this function calls - // |callback| with the trusted state of the |DeviceRebootOnShutdown| policy. - void CheckIfRebootOnShutdown(const RebootOnShutdownCallback& callback); - - // Resets the policy subscription and clears the delegate. - void Shutdown(); + // Once a trusted set of policies is established, this function notifies + // |delegate_| with the trusted state of the |DeviceRebootOnShutdown| policy. + void NotifyDelegateWithShutdownPolicy(); private: - void CallDelegate(bool reboot_on_shutdown); - - void OnShutdownPolicyChanged(); - CrosSettings* cros_settings_; Delegate* delegate_;
diff --git a/chrome/browser/chromeos/settings/shutdown_policy_handler_unittest.cc b/chrome/browser/chromeos/settings/shutdown_policy_handler_unittest.cc index 8b9669f9..f85c27d 100644 --- a/chrome/browser/chromeos/settings/shutdown_policy_handler_unittest.cc +++ b/chrome/browser/chromeos/settings/shutdown_policy_handler_unittest.cc
@@ -18,16 +18,8 @@ class ShutdownPolicyHandlerTest : public testing::Test, public ShutdownPolicyHandler::Delegate { public: - void ResultCallback(bool reboot_on_shutdown) { - reboot_on_shutdown_ = reboot_on_shutdown; - callback_called_ = true; - } - - protected: ShutdownPolicyHandlerTest() - : callback_called_(false), - reboot_on_shutdown_(false), - delegate_invocations_count_(0) {} + : reboot_on_shutdown_(false), delegate_invocations_count_(0) {} // testing::Test: void SetUp() override { @@ -52,13 +44,12 @@ protected: content::TestBrowserThreadBundle thread_bundle_; ScopedCrosSettingsTestHelper settings_helper_; - bool callback_called_; bool reboot_on_shutdown_; int delegate_invocations_count_; }; TEST_F(ShutdownPolicyHandlerTest, RetrieveTrustedDevicePolicies) { - ShutdownPolicyHandler shutdown_policy_observer(CrosSettings::Get(), this); + ShutdownPolicyHandler shutdown_policy_handler(CrosSettings::Get(), this); base::RunLoop().RunUntilIdle(); EXPECT_EQ(0, delegate_invocations_count_); @@ -71,36 +62,28 @@ base::RunLoop().RunUntilIdle(); EXPECT_EQ(2, delegate_invocations_count_); EXPECT_FALSE(reboot_on_shutdown_); - - shutdown_policy_observer.Shutdown(); - - SetRebootOnShutdown(true); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(2, delegate_invocations_count_); - EXPECT_FALSE(reboot_on_shutdown_); } -TEST_F(ShutdownPolicyHandlerTest, CheckIfRebootOnShutdown) { - ShutdownPolicyHandler shutdown_policy_observer(CrosSettings::Get(), this); +TEST_F(ShutdownPolicyHandlerTest, NotifyDelegateWithShutdownPolicy) { + ShutdownPolicyHandler shutdown_policy_handler(CrosSettings::Get(), this); base::RunLoop().RunUntilIdle(); // Allow shutdown. SetRebootOnShutdown(true); - callback_called_ = false; - shutdown_policy_observer.CheckIfRebootOnShutdown( - base::Bind(&ShutdownPolicyHandlerTest::ResultCallback, - base::Unretained(this))); + delegate_invocations_count_ = 0; + // Request a manual update. + shutdown_policy_handler.NotifyDelegateWithShutdownPolicy(); base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(callback_called_); + EXPECT_EQ(1, delegate_invocations_count_); EXPECT_TRUE(reboot_on_shutdown_); + // Forbid shutdown. SetRebootOnShutdown(false); - callback_called_ = false; - shutdown_policy_observer.CheckIfRebootOnShutdown( - base::Bind(&ShutdownPolicyHandlerTest::ResultCallback, - base::Unretained(this))); + delegate_invocations_count_ = 0; + // Request a manual update. + shutdown_policy_handler.NotifyDelegateWithShutdownPolicy(); base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(callback_called_); + EXPECT_EQ(1, delegate_invocations_count_); EXPECT_FALSE(reboot_on_shutdown_); }
diff --git a/chrome/browser/chromeos/shutdown_policy_browsertest.cc b/chrome/browser/chromeos/shutdown_policy_browsertest.cc index 5ccdd82..50dbf70 100644 --- a/chrome/browser/chromeos/shutdown_policy_browsertest.cc +++ b/chrome/browser/chromeos/shutdown_policy_browsertest.cc
@@ -146,78 +146,74 @@ ShutdownPolicyInSessionTest() {} ~ShutdownPolicyInSessionTest() override {} - void SetUpOnMainThread() override { - ShutdownPolicyBaseTest::SetUpOnMainThread(); + // Opens the system tray menu. This creates the tray views. + void OpenSystemTrayMenu() { + ash::Shell::GetInstance()->GetPrimarySystemTray()->ShowDefaultView( + ash::BUBBLE_CREATE_NEW); + } + + // Closes the system tray menu. This deletes the tray views. + void CloseSystemTrayMenu() { + ash::Shell::GetInstance()->GetPrimarySystemTray()->CloseSystemBubble(); + } + + // Gets the shutdown button view. + const views::View* GetShutdownButton() { + ash::SystemTray* tray = ash::Shell::GetInstance()->GetPrimarySystemTray(); if (ash::MaterialDesignController::IsSystemTrayMenuMaterial()) { - ash::TrayTiles* tray_tiles = ash::Shell::GetInstance() - ->GetPrimarySystemTray() - ->GetTrayTilesForTesting(); - ASSERT_TRUE(tray_tiles); - tiles_default_view_.reset(static_cast<ash::TilesDefaultView*>( - tray_tiles->CreateDefaultViewForTesting(ash::LoginStatus::USER))); - ASSERT_TRUE(tiles_default_view_); - } else { - ash::TrayDate* tray_date = ash::Shell::GetInstance() - ->GetPrimarySystemTray() - ->GetTrayDateForTesting(); - ASSERT_TRUE(tray_date); - date_default_view_.reset(static_cast<ash::DateDefaultView*>( - tray_date->CreateDefaultViewForTesting(ash::LoginStatus::USER))); - ASSERT_TRUE(date_default_view_); + return tray->GetTrayTilesForTesting() + ->GetDefaultViewForTesting() + ->GetShutdownButtonViewForTest(); } + return tray->GetTrayDateForTesting() + ->GetDefaultViewForTesting() + ->GetShutdownButtonViewForTest(); } - void TearDownOnMainThread() override { - if (ash::MaterialDesignController::IsSystemTrayMenuMaterial()) - tiles_default_view_.reset(); - else - date_default_view_.reset(); - ShutdownPolicyBaseTest::TearDownOnMainThread(); - } - - // Get the shutdown and reboot button view from the date default view. - const views::CustomButton* GetShutdownButton() { - if (ash::MaterialDesignController::IsSystemTrayMenuMaterial()) - return tiles_default_view_->GetShutdownButtonViewForTest(); - return static_cast<const views::CustomButton*>( - date_default_view_->GetShutdownButtonViewForTest()); - } - - bool HasButtonTooltipText(const views::CustomButton* button, - int message_id) const { + // Returns true if the shutdown button's tooltip matches the text of the + // resource |message_id|. + bool HasShutdownButtonTooltip(int message_id) { + const views::View* button = GetShutdownButton(); base::string16 actual_tooltip; button->GetTooltipText(gfx::Point(), &actual_tooltip); return l10n_util::GetStringUTF16(message_id) == actual_tooltip; } private: - // Not used in material design. - std::unique_ptr<ash::DateDefaultView> date_default_view_; - - // Only used in material design. - std::unique_ptr<ash::TilesDefaultView> tiles_default_view_; - DISALLOW_COPY_AND_ASSIGN(ShutdownPolicyInSessionTest); }; +// Tests that by default the shutdown button tooltip is "shutdown". IN_PROC_BROWSER_TEST_F(ShutdownPolicyInSessionTest, TestBasic) { - const views::CustomButton* shutdown_button = GetShutdownButton(); - EXPECT_TRUE( - HasButtonTooltipText(shutdown_button, IDS_ASH_STATUS_TRAY_SHUTDOWN)); + OpenSystemTrayMenu(); + EXPECT_TRUE(HasShutdownButtonTooltip(IDS_ASH_STATUS_TRAY_SHUTDOWN)); + CloseSystemTrayMenu(); } +// Tests that enabling the reboot-on-shutdown policy changes the shutdown button +// tooltip to "restart". Note that the tooltip doesn't change dynamically if the +// menu is open during the policy change -- that's a rare condition and +// supporting it would add complexity. IN_PROC_BROWSER_TEST_F(ShutdownPolicyInSessionTest, PolicyChange) { - const views::CustomButton* shutdown_button = GetShutdownButton(); - + // Change the policy to reboot and let it propagate over mojo to ash. UpdateRebootOnShutdownPolicy(true); SyncRefreshDevicePolicy(); - EXPECT_TRUE( - HasButtonTooltipText(shutdown_button, IDS_ASH_STATUS_TRAY_REBOOT)); + content::RunAllPendingInMessageLoop(); + // When the menu is opened the tooltip reads "reboot". + OpenSystemTrayMenu(); + EXPECT_TRUE(HasShutdownButtonTooltip(IDS_ASH_STATUS_TRAY_REBOOT)); + CloseSystemTrayMenu(); + + // Change the policy to shutdown and let it propagate over mojo to ash. UpdateRebootOnShutdownPolicy(false); SyncRefreshDevicePolicy(); - EXPECT_TRUE( - HasButtonTooltipText(shutdown_button, IDS_ASH_STATUS_TRAY_SHUTDOWN)); + content::RunAllPendingInMessageLoop(); + + // When the menu is opened the tooltip reads "shutdown". + OpenSystemTrayMenu(); + EXPECT_TRUE(HasShutdownButtonTooltip(IDS_ASH_STATUS_TRAY_SHUTDOWN)); + CloseSystemTrayMenu(); } class ShutdownPolicyLockerTest : public ShutdownPolicyBaseTest {
diff --git a/chrome/browser/component_updater/recovery_component_installer.cc b/chrome/browser/component_updater/recovery_component_installer.cc index aca11bba..7128ff4 100644 --- a/chrome/browser/component_updater/recovery_component_installer.cc +++ b/chrome/browser/component_updater/recovery_component_installer.cc
@@ -26,9 +26,6 @@ #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" -#if defined(OS_WIN) -#include "chrome/installer/util/install_util.h" -#endif // OS_WIN #include "components/component_updater/component_updater_paths.h" #include "components/component_updater/component_updater_service.h" #include "components/component_updater/pref_names.h" @@ -235,15 +232,6 @@ NOTREACHED(); return; } - - update_client::InstallerAttributes installer_attributes; -#if defined(OS_WIN) - base::FilePath exe_path; - PathService::Get(base::FILE_EXE, &exe_path); - installer_attributes["ismachine"] = - InstallUtil::IsPerUserInstall(exe_path) ? "0" : "1"; -#endif // OS_WIN - update_client::CrxComponent recovery; recovery.name = "recovery"; recovery.installer = new RecoveryComponentInstaller(version, prefs); @@ -251,7 +239,6 @@ recovery.pk_hash.assign(kSha2Hash, &kSha2Hash[sizeof(kSha2Hash)]); recovery.supports_group_policy_enable_component_updates = true; recovery.requires_network_encryption = false; - recovery.installer_attributes = installer_attributes; if (!cus->RegisterComponent(recovery)) { NOTREACHED() << "Recovery component registration failed."; }
diff --git a/chrome/browser/component_updater/subresource_filter_component_installer.cc b/chrome/browser/component_updater/subresource_filter_component_installer.cc index 8646899a..861819b 100644 --- a/chrome/browser/component_updater/subresource_filter_component_installer.cc +++ b/chrome/browser/component_updater/subresource_filter_component_installer.cc
@@ -6,7 +6,6 @@ #include <utility> -#include "base/bind.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/path_service.h" @@ -16,24 +15,9 @@ #include "components/subresource_filter/core/browser/ruleset_service.h" #include "components/subresource_filter/core/browser/subresource_filter_constants.h" #include "components/subresource_filter/core/browser/subresource_filter_features.h" -#include "content/public/browser/browser_thread.h" using component_updater::ComponentUpdateService; -namespace { - -void IndexAndStoreAndPublishRulesetIfNeeded( - const subresource_filter::UnindexedRulesetInfo& unindexed_ruleset_info) { - subresource_filter::RulesetService* ruleset_service = - g_browser_process->subresource_filter_ruleset_service(); - if (ruleset_service) { - ruleset_service->IndexAndStoreAndPublishRulesetIfNeeded( - unindexed_ruleset_info); - } -} - -} // namespace - namespace component_updater { // The extension id is: gcmjkmgdlgnkkcocmoeiminaijmmjnii @@ -103,10 +87,10 @@ ruleset_info.content_version = version.GetString(); ruleset_info.ruleset_path = install_dir.Append(kRulesetDataFileName); ruleset_info.license_path = install_dir.Append(kLicenseFileName); - content::BrowserThread::PostAfterStartupTask( - FROM_HERE, content::BrowserThread::GetTaskRunnerForThread( - content::BrowserThread::UI), - base::Bind(&IndexAndStoreAndPublishRulesetIfNeeded, ruleset_info)); + subresource_filter::RulesetService* ruleset_service = + g_browser_process->subresource_filter_ruleset_service(); + if (ruleset_service) + ruleset_service->IndexAndStoreAndPublishRulesetIfNeeded(ruleset_info); } // Called during startup and installation before ComponentReady().
diff --git a/chrome/browser/component_updater/subresource_filter_component_installer_unittest.cc b/chrome/browser/component_updater/subresource_filter_component_installer_unittest.cc index c8c278f..706aecf 100644 --- a/chrome/browser/component_updater/subresource_filter_component_installer_unittest.cc +++ b/chrome/browser/component_updater/subresource_filter_component_installer_unittest.cc
@@ -17,10 +17,10 @@ #include "base/strings/string_util.h" #include "base/test/test_simple_task_runner.h" #include "base/version.h" -#include "chrome/browser/after_startup_task_utils.h" #include "chrome/test/base/testing_browser_process.h" #include "components/component_updater/mock_component_updater_service.h" #include "components/prefs/testing_pref_service.h" +#include "components/subresource_filter/content/browser/content_ruleset_service_delegate.h" #include "components/subresource_filter/core/browser/ruleset_service.h" #include "components/subresource_filter/core/browser/subresource_filter_features.h" #include "components/subresource_filter/core/browser/subresource_filter_features_test_support.h" @@ -37,8 +37,12 @@ TestRulesetService(PrefService* local_state, scoped_refptr<base::SequencedTaskRunner> task_runner, const base::FilePath& base_dir) - : subresource_filter::RulesetService(local_state, task_runner, base_dir) { - } + : subresource_filter::RulesetService( + local_state, + task_runner, + base::MakeUnique< + subresource_filter::ContentRulesetServiceDelegate>(), + base_dir) {} ~TestRulesetService() override {} @@ -102,11 +106,8 @@ TestingBrowserProcess::GetGlobal()->SetRulesetService(std::move(service)); traits_.reset(new SubresourceFilterComponentInstallerTraits()); - AfterStartupTaskUtils::SetBrowserStartupIsCompleteForTesting(); } - void TearDown() override { AfterStartupTaskUtils::UnsafeResetForTesting(); } - TestRulesetService* service() { return static_cast<TestRulesetService*>( TestingBrowserProcess::GetGlobal()
diff --git a/chrome/browser/devtools/devtools_sanity_browsertest.cc b/chrome/browser/devtools/devtools_sanity_browsertest.cc index 7c954b7f..4c558054 100644 --- a/chrome/browser/devtools/devtools_sanity_browsertest.cc +++ b/chrome/browser/devtools/devtools_sanity_browsertest.cc
@@ -74,7 +74,7 @@ #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_filter.h" #include "net/url_request/url_request_http_job.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/compositor/compositor_switches.h" #include "ui/gl/gl_switches.h" #include "url/gurl.h"
diff --git a/chrome/browser/devtools/devtools_window.cc b/chrome/browser/devtools/devtools_window.cc index 04443805e..a090462 100644 --- a/chrome/browser/devtools/devtools_window.cc +++ b/chrome/browser/devtools/devtools_window.cc
@@ -51,8 +51,9 @@ #include "content/public/common/content_client.h" #include "content/public/common/url_constants.h" #include "net/base/escape.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/public_features.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" #include "ui/base/page_transition_types.h" #include "ui/events/keycodes/dom/keycode_converter.h" #include "ui/events/keycodes/keyboard_code_conversion.h"
diff --git a/chrome/browser/download/download_request_limiter.cc b/chrome/browser/download/download_request_limiter.cc index 89ba925..85c47e9 100644 --- a/chrome/browser/download/download_request_limiter.cc +++ b/chrome/browser/download/download_request_limiter.cc
@@ -89,7 +89,7 @@ // reset the download state if the user is navigating to a different host // (or host is empty). if (!initial_page_host_.empty() && - navigation_handle->GetURL().host() == initial_page_host_) { + navigation_handle->GetURL().host_piece() == initial_page_host_) { return; } }
diff --git a/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc b/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc index 3ccd0e7..0031c79 100644 --- a/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc +++ b/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc
@@ -54,8 +54,8 @@ #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/embedded_test_server/http_request.h" #include "net/test/embedded_test_server/http_response.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/web/WebContextMenuData.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" using content::ResourceType; using content::WebContents;
diff --git a/chrome/browser/extensions/api/web_request/web_request_apitest.cc b/chrome/browser/extensions/api/web_request/web_request_apitest.cc index 06e1da8..112156d0 100644 --- a/chrome/browser/extensions/api/web_request/web_request_apitest.cc +++ b/chrome/browser/extensions/api/web_request/web_request_apitest.cc
@@ -38,7 +38,7 @@ #include "extensions/test/result_catcher.h" #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/embedded_test_server.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" using content::WebContents;
diff --git a/chrome/browser/extensions/browser_context_keyed_service_factories.cc b/chrome/browser/extensions/browser_context_keyed_service_factories.cc index d050ab9..50cd87b 100644 --- a/chrome/browser/extensions/browser_context_keyed_service_factories.cc +++ b/chrome/browser/extensions/browser_context_keyed_service_factories.cc
@@ -53,6 +53,7 @@ #include "chrome/browser/speech/extension_api/tts_extension_api.h" #include "chrome/browser/ui/toolbar/toolbar_actions_model_factory.h" #include "chrome/common/features.h" +#include "components/spellcheck/spellcheck_build_features.h" #include "extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_api.h" #if defined(OS_CHROMEOS) @@ -70,7 +71,7 @@ #include "chrome/browser/extensions/api/mdns/mdns_api.h" #endif -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) #include "chrome/browser/extensions/api/spellcheck/spellcheck_api.h" #endif @@ -135,7 +136,7 @@ extensions::SettingsPrivateEventRouterFactory::GetInstance(); extensions::SettingsOverridesAPI::GetFactoryInstance(); extensions::SignedInDevicesManager::GetFactoryInstance(); -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) extensions::SpellcheckAPI::GetFactoryInstance(); #endif extensions::StreamsPrivateAPI::GetFactoryInstance();
diff --git a/chrome/browser/extensions/extension_messages_apitest.cc b/chrome/browser/extensions/extension_messages_apitest.cc index 9747d06..a46af89 100644 --- a/chrome/browser/extensions/extension_messages_apitest.cc +++ b/chrome/browser/extensions/extension_messages_apitest.cc
@@ -28,6 +28,7 @@ #include "chrome/browser/infobars/infobar_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" @@ -35,9 +36,11 @@ #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_service.h" #include "content/public/test/browser_test_utils.h" +#include "content/public/test/test_utils.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_system.h" +#include "extensions/browser/process_manager.h" #include "extensions/common/api/runtime.h" #include "extensions/common/extension_builder.h" #include "extensions/common/value_builder.h" @@ -1286,6 +1289,44 @@ #endif // !defined(OS_WIN) - http://crbug.com/350517. +// Tests that messages sent in the unload handler of a window arrive. +IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MessagingOnUnload) { + host_resolver()->AddRule("*", "127.0.0.1"); + ASSERT_TRUE(StartEmbeddedTestServer()); + const Extension* extension = + LoadExtension(test_data_dir_.AppendASCII("messaging/on_unload")); + ExtensionTestMessageListener listener("listening", false); + ASSERT_TRUE(extension); + ui_test_utils::NavigateToURL( + browser(), embedded_test_server()->GetURL("example.com", "/empty.html")); + EXPECT_TRUE(listener.WaitUntilSatisfied()); + ExtensionHost* background_host = + ProcessManager::Get(profile())->GetBackgroundHostForExtension( + extension->id()); + ASSERT_TRUE(background_host); + content::WebContents* background_contents = background_host->host_contents(); + ASSERT_TRUE(background_contents); + int message_count = -1; + ASSERT_TRUE(content::ExecuteScriptAndExtractInt( + background_contents, + "window.domAutomationController.send(window.messageCount);", + &message_count)); + // There shouldn't be any messages yet. + EXPECT_EQ(0, message_count); + + content::WebContentsDestroyedWatcher destroyed_watcher( + browser()->tab_strip_model()->GetActiveWebContents()); + chrome::CloseTab(browser()); + destroyed_watcher.Wait(); + base::RunLoop().RunUntilIdle(); + // The extension should have sent a message from its unload handler. + ASSERT_TRUE(content::ExecuteScriptAndExtractInt( + background_contents, + "window.domAutomationController.send(window.messageCount);", + &message_count)); + EXPECT_EQ(1, message_count); +} + } // namespace }; // namespace extensions
diff --git a/chrome/browser/extensions/extension_view_host.cc b/chrome/browser/extensions/extension_view_host.cc index ea544c71..301611e 100644 --- a/chrome/browser/extensions/extension_view_host.cc +++ b/chrome/browser/extensions/extension_view_host.cc
@@ -24,7 +24,7 @@ #include "content/public/browser/web_contents.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/runtime_data.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/base/resource/resource_bundle.h" #include "ui/events/keycodes/keyboard_codes.h"
diff --git a/chrome/browser/media_galleries/fileapi/file_path_watcher_util.cc b/chrome/browser/media_galleries/fileapi/file_path_watcher_util.cc index 129cbac..16295c9 100644 --- a/chrome/browser/media_galleries/fileapi/file_path_watcher_util.cc +++ b/chrome/browser/media_galleries/fileapi/file_path_watcher_util.cc
@@ -58,3 +58,15 @@ watch_started_callback, path_changed_callback)); } + +void StopFilePathWatchOnMediaTaskRunner( + std::unique_ptr<base::FilePathWatcher> watcher) { + MediaFileSystemBackend::AssertCurrentlyOnMediaSequence(); + if (watcher) { + const bool task_posted = content::BrowserThread::DeleteSoon( + content::BrowserThread::FILE, FROM_HERE, watcher.release()); + + // This will fail if the FILE thread has been stopped. + DCHECK(task_posted); + } +}
diff --git a/chrome/browser/media_galleries/fileapi/file_path_watcher_util.h b/chrome/browser/media_galleries/fileapi/file_path_watcher_util.h index 8e512534..cd3443d 100644 --- a/chrome/browser/media_galleries/fileapi/file_path_watcher_util.h +++ b/chrome/browser/media_galleries/fileapi/file_path_watcher_util.h
@@ -22,4 +22,9 @@ const FileWatchStartedCallback& watch_started_callback, const base::FilePathWatcher::Callback& path_changed_callback); +// Stops a file path watch started by StartFilePathWatchOnMediaTaskRunner(). +// Must be called from the MediaTaskRunner. +void StopFilePathWatchOnMediaTaskRunner( + std::unique_ptr<base::FilePathWatcher> watcher); + #endif // CHROME_BROWSER_MEDIA_GALLERIES_FILEAPI_FILE_PATH_WATCHER_UTIL_H_
diff --git a/chrome/browser/media_galleries/fileapi/iapps_data_provider.cc b/chrome/browser/media_galleries/fileapi/iapps_data_provider.cc index ec8cfd2..72e90365 100644 --- a/chrome/browser/media_galleries/fileapi/iapps_data_provider.cc +++ b/chrome/browser/media_galleries/fileapi/iapps_data_provider.cc
@@ -40,7 +40,9 @@ weak_factory_.GetWeakPtr())); } -IAppsDataProvider::~IAppsDataProvider() {} +IAppsDataProvider::~IAppsDataProvider() { + StopFilePathWatchOnMediaTaskRunner(std::move(library_watcher_)); +} bool IAppsDataProvider::valid() const { return is_valid_;
diff --git a/chrome/browser/media_galleries/fileapi/itunes_file_util_unittest.cc b/chrome/browser/media_galleries/fileapi/itunes_file_util_unittest.cc index 256b56e..ffe14bd 100644 --- a/chrome/browser/media_galleries/fileapi/itunes_file_util_unittest.cc +++ b/chrome/browser/media_galleries/fileapi/itunes_file_util_unittest.cc
@@ -189,6 +189,11 @@ profile_dir_.GetPath(), content::CreateAllowFileAccessOptions()); } + void TearDown() override { + MediaFileSystemBackend::MediaTaskRunner()->DeleteSoon( + FROM_HERE, itunes_data_provider_.release()); + } + protected: void TestNonexistentFolder(const std::string& path_append) { FileSystemOperation::FileEntryList contents;
diff --git a/chrome/browser/media_galleries/fileapi/picasa_data_provider.cc b/chrome/browser/media_galleries/fileapi/picasa_data_provider.cc index 04360a93..15275cc 100644 --- a/chrome/browser/media_galleries/fileapi/picasa_data_provider.cc +++ b/chrome/browser/media_galleries/fileapi/picasa_data_provider.cc
@@ -51,7 +51,9 @@ weak_factory_.GetWeakPtr())); } -PicasaDataProvider::~PicasaDataProvider() {} +PicasaDataProvider::~PicasaDataProvider() { + StopFilePathWatchOnMediaTaskRunner(std::move(temp_dir_watcher_)); +} void PicasaDataProvider::RefreshData(DataType needed_data, const ReadyCallback& ready_callback) {
diff --git a/chrome/browser/metrics/desktop_session_duration/desktop_session_duration_observer.h b/chrome/browser/metrics/desktop_session_duration/desktop_session_duration_observer.h index dcd5b701..a5b8c46 100644 --- a/chrome/browser/metrics/desktop_session_duration/desktop_session_duration_observer.h +++ b/chrome/browser/metrics/desktop_session_duration/desktop_session_duration_observer.h
@@ -10,7 +10,7 @@ #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" namespace metrics {
diff --git a/chrome/browser/metrics/perf/perf_provider_chromeos.cc b/chrome/browser/metrics/perf/perf_provider_chromeos.cc index f8305c7..f7b32db 100644 --- a/chrome/browser/metrics/perf/perf_provider_chromeos.cc +++ b/chrome/browser/metrics/perf/perf_provider_chromeos.cc
@@ -119,7 +119,7 @@ "perf record -a -e cycles -g -c 4000037"; const char kPerfRecordLBRCmd[] = - "perf record -a -e r2c4 -b -c 20011"; + "perf record -a -e r20c4 -b -c 200011"; const char kPerfRecordInstructionTLBMissesCmd[] = "perf record -a -e iTLB-misses -c 2003";
diff --git a/chrome/browser/metrics/perf/perf_provider_chromeos_unittest.cc b/chrome/browser/metrics/perf/perf_provider_chromeos_unittest.cc index 664945f..313108a 100644 --- a/chrome/browser/metrics/perf/perf_provider_chromeos_unittest.cc +++ b/chrome/browser/metrics/perf/perf_provider_chromeos_unittest.cc
@@ -34,7 +34,7 @@ const char kPerfRecordCallgraphCmd[] = "perf record -a -e cycles -g -c 4000037"; const char kPerfRecordLBRCmd[] = - "perf record -a -e r2c4 -b -c 20011"; + "perf record -a -e r20c4 -b -c 200011"; const char kPerfStatMemoryBandwidthCmd[] = "perf stat -a -e cycles -e instructions " "-e uncore_imc/data_reads/ -e uncore_imc/data_writes/ "
diff --git a/chrome/browser/page_load_metrics/metrics_web_contents_observer.h b/chrome/browser/page_load_metrics/metrics_web_contents_observer.h index 4a43b9d..5ecd66c 100644 --- a/chrome/browser/page_load_metrics/metrics_web_contents_observer.h +++ b/chrome/browser/page_load_metrics/metrics_web_contents_observer.h
@@ -18,7 +18,7 @@ #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h" #include "content/public/common/resource_type.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" namespace content { class NavigationHandle;
diff --git a/chrome/browser/page_load_metrics/observers/page_load_metrics_observer_test_harness.cc b/chrome/browser/page_load_metrics/observers/page_load_metrics_observer_test_harness.cc index c7cec4fa..fba8561 100644 --- a/chrome/browser/page_load_metrics/observers/page_load_metrics_observer_test_harness.cc +++ b/chrome/browser/page_load_metrics/observers/page_load_metrics_observer_test_harness.cc
@@ -13,7 +13,7 @@ #include "content/public/browser/navigation_entry.h" #include "content/public/browser/web_contents.h" #include "content/public/test/web_contents_tester.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" namespace page_load_metrics {
diff --git a/chrome/browser/page_load_metrics/observers/page_load_metrics_observer_test_harness.h b/chrome/browser/page_load_metrics/observers/page_load_metrics_observer_test_harness.h index 9c1e6c1..5ff0447 100644 --- a/chrome/browser/page_load_metrics/observers/page_load_metrics_observer_test_harness.h +++ b/chrome/browser/page_load_metrics/observers/page_load_metrics_observer_test_harness.h
@@ -11,7 +11,7 @@ #include "chrome/browser/page_load_metrics/page_load_tracker.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "content/public/test/web_contents_tester.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/base/page_transition_types.h" namespace page_load_metrics {
diff --git a/chrome/browser/page_load_metrics/observers/service_worker_page_load_metrics_observer.cc b/chrome/browser/page_load_metrics/observers/service_worker_page_load_metrics_observer.cc index e401315e..43fcb86 100644 --- a/chrome/browser/page_load_metrics/observers/service_worker_page_load_metrics_observer.cc +++ b/chrome/browser/page_load_metrics/observers/service_worker_page_load_metrics_observer.cc
@@ -49,7 +49,7 @@ } bool IsInboxSite(const GURL& url) { - return url.host() == "inbox.google.com"; + return url.host_piece() == "inbox.google.com"; } } // namespace
diff --git a/chrome/browser/page_load_metrics/page_load_metrics_observer.h b/chrome/browser/page_load_metrics/page_load_metrics_observer.h index e0480c2..bfcd594 100644 --- a/chrome/browser/page_load_metrics/page_load_metrics_observer.h +++ b/chrome/browser/page_load_metrics/page_load_metrics_observer.h
@@ -9,7 +9,7 @@ #include "base/optional.h" #include "chrome/common/page_load_metrics/page_load_timing.h" #include "content/public/browser/navigation_handle.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "url/gurl.h" namespace page_load_metrics {
diff --git a/chrome/browser/password_manager/password_manager_browsertest.cc b/chrome/browser/password_manager/password_manager_browsertest.cc index b53a42f..a17d1f5 100644 --- a/chrome/browser/password_manager/password_manager_browsertest.cc +++ b/chrome/browser/password_manager/password_manager_browsertest.cc
@@ -58,7 +58,7 @@ #include "net/test/embedded_test_server/http_response.h" #include "net/url_request/test_url_fetcher_factory.h" #include "testing/gmock/include/gmock/gmock.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/gfx/geometry/point.h"
diff --git a/chrome/browser/plugins/flash_permission_browsertest.cc b/chrome/browser/plugins/flash_permission_browsertest.cc index 3c230c0..5a934dd6 100644 --- a/chrome/browser/plugins/flash_permission_browsertest.cc +++ b/chrome/browser/plugins/flash_permission_browsertest.cc
@@ -14,7 +14,7 @@ #include "content/public/common/content_switches.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/ppapi_test_utils.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "url/gurl.h" class FlashPermissionBrowserTest : public PermissionsBrowserTest {
diff --git a/chrome/browser/plugins/plugin_power_saver_browsertest.cc b/chrome/browser/plugins/plugin_power_saver_browsertest.cc index 9fa28e0..bff1c242 100644 --- a/chrome/browser/plugins/plugin_power_saver_browsertest.cc +++ b/chrome/browser/plugins/plugin_power_saver_browsertest.cc
@@ -33,7 +33,7 @@ #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/embedded_test_server/http_request.h" #include "net/test/embedded_test_server/http_response.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/window_open_disposition.h" #include "ui/display/display.h"
diff --git a/chrome/browser/policy/configuration_policy_handler_list_factory.cc b/chrome/browser/policy/configuration_policy_handler_list_factory.cc index d81c768..48f48bd9 100644 --- a/chrome/browser/policy/configuration_policy_handler_list_factory.cc +++ b/chrome/browser/policy/configuration_policy_handler_list_factory.cc
@@ -45,6 +45,7 @@ #include "components/prefs/pref_value_map.h" #include "components/search_engines/default_search_policy_handler.h" #include "components/signin/core/common/signin_pref_names.h" +#include "components/spellcheck/spellcheck_build_features.h" #include "components/ssl_config/ssl_config_prefs.h" #include "components/sync/driver/sync_policy_handler.h" #include "components/translate/core/common/translate_pref_names.h" @@ -83,7 +84,7 @@ #include "chrome/browser/plugins/plugin_policy_handler.h" #endif -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) #include "components/spellcheck/browser/pref_names.h" #endif @@ -365,11 +366,11 @@ prefs::kComponentUpdatesEnabled, base::Value::TYPE_BOOLEAN }, -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) { key::kSpellCheckServiceEnabled, spellcheck::prefs::kSpellCheckUseSpellingService, base::Value::TYPE_BOOLEAN }, -#endif // defined(ENABLE_SPELLCHECK) +#endif // BUILDFLAG(ENABLE_SPELLCHECK) { key::kDisableScreenshots, prefs::kDisableScreenshots,
diff --git a/chrome/browser/policy/policy_browsertest.cc b/chrome/browser/policy/policy_browsertest.cc index 2e325e6..5ff50be 100644 --- a/chrome/browser/policy/policy_browsertest.cc +++ b/chrome/browser/policy/policy_browsertest.cc
@@ -180,7 +180,7 @@ #include "net/url_request/url_request_interceptor.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/page_transition_types.h" #include "ui/base/resource/resource_bundle.h"
diff --git a/chrome/browser/policy/policy_helpers.cc b/chrome/browser/policy/policy_helpers.cc index ed3be58..662f3b7 100644 --- a/chrome/browser/policy/policy_helpers.cc +++ b/chrome/browser/policy/policy_helpers.cc
@@ -49,7 +49,7 @@ if (url.GetOrigin() != GaiaUrls::GetInstance()->gaia_url().GetOrigin()) return false; - return url.path() == kServiceLoginAuth; + return url.path_piece() == kServiceLoginAuth; #endif }
diff --git a/chrome/browser/prerender/prerender_tab_helper.h b/chrome/browser/prerender/prerender_tab_helper.h index b105c70..788c3f1 100644 --- a/chrome/browser/prerender/prerender_tab_helper.h +++ b/chrome/browser/prerender/prerender_tab_helper.h
@@ -16,14 +16,6 @@ #include "content/public/browser/web_contents_user_data.h" #include "url/gurl.h" -namespace autofill { -struct PasswordForm; -} - -namespace password_manager { -class PasswordManager; -} - namespace prerender { class PrerenderManager;
diff --git a/chrome/browser/prerender/prerender_util.cc b/chrome/browser/prerender/prerender_util.cc index efdf28d..a9f380b 100644 --- a/chrome/browser/prerender/prerender_util.cc +++ b/chrome/browser/prerender/prerender_util.cc
@@ -80,7 +80,7 @@ return (url.path_piece().empty() || base::StartsWith(url.path_piece(), "/search", base::CompareCase::SENSITIVE) || - (url.path() == "/") || + (url.path_piece() == "/") || base::StartsWith(url.path_piece(), "/webhp", base::CompareCase::SENSITIVE)); }
diff --git a/chrome/browser/printing/print_view_manager_base.cc b/chrome/browser/printing/print_view_manager_base.cc index c8028f4..e559fdb 100644 --- a/chrome/browser/printing/print_view_manager_base.cc +++ b/chrome/browser/printing/print_view_manager_base.cc
@@ -193,16 +193,20 @@ #if defined(OS_WIN) print_job_->AppendPrintedPage(params.page_number); if (metafile_must_be_valid) { + // TODO(thestig): Figure out why rendering text with GDI results in random + // missing characters for some users. https://crbug.com/658606 + bool print_text_with_gdi = + document->settings().print_text_with_gdi() && + !document->settings().printer_is_xps() && + switches::GDITextPrintingEnabled(); scoped_refptr<base::RefCountedBytes> bytes = new base::RefCountedBytes( reinterpret_cast<const unsigned char*>(shared_buf->memory()), params.data_size); document->DebugDumpData(bytes.get(), FILE_PATH_LITERAL(".pdf")); - // TODO(thestig): Figure out why rendering text with GDI results in random - // missing characters for some users. https://crbug.com/658606 print_job_->StartPdfToEmfConversion( bytes, params.page_size, params.content_area, - false /* print_text_with_gdi? */); + print_text_with_gdi); } #else // Update the rendered document. It will send notifications to the listener.
diff --git a/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc b/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc index 2dcb1d2..0c6091e6 100644 --- a/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc +++ b/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc
@@ -70,6 +70,7 @@ #include "chrome/browser/undo/bookmark_undo_service_factory.h" #include "chrome/browser/web_data_service_factory.h" #include "chrome/common/features.h" +#include "components/spellcheck/spellcheck_build_features.h" #include "extensions/features/features.h" #include "printing/features/features.h" @@ -133,7 +134,7 @@ #include "chrome/browser/profile_resetter/triggered_profile_resetter_factory.h" #endif -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) #include "chrome/browser/spellchecker/spellcheck_factory.h" #endif @@ -326,7 +327,7 @@ if (SiteEngagementService::IsEnabled()) SiteEngagementServiceFactory::GetInstance(); -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) SpellcheckServiceFactory::GetInstance(); #endif suggestions::SuggestionsServiceFactory::GetInstance();
diff --git a/chrome/browser/referrer_policy_browsertest.cc b/chrome/browser/referrer_policy_browsertest.cc index 17db565..d41ca45 100644 --- a/chrome/browser/referrer_policy_browsertest.cc +++ b/chrome/browser/referrer_policy_browsertest.cc
@@ -28,7 +28,7 @@ #include "content/public/common/content_switches.h" #include "content/public/test/browser_test_utils.h" #include "net/test/url_request/url_request_mock_http_job.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" class ReferrerPolicyTest : public InProcessBrowserTest { public:
diff --git a/chrome/browser/renderer_context_menu/context_menu_content_type_factory.cc b/chrome/browser/renderer_context_menu/context_menu_content_type_factory.cc index f60f25c..057e015 100644 --- a/chrome/browser/renderer_context_menu/context_menu_content_type_factory.cc +++ b/chrome/browser/renderer_context_menu/context_menu_content_type_factory.cc
@@ -27,7 +27,7 @@ bool CheckInternalResourcesURL(const GURL& url) { return url.SchemeIs(content::kChromeUIScheme) && - (url.host() == chrome::kChromeUISyncResourcesHost); + (url.host_piece() == chrome::kChromeUISyncResourcesHost); } } // namespace
diff --git a/chrome/browser/renderer_context_menu/render_view_context_menu.cc b/chrome/browser/renderer_context_menu/render_view_context_menu.cc index a479ce1..3762746f 100644 --- a/chrome/browser/renderer_context_menu/render_view_context_menu.cc +++ b/chrome/browser/renderer_context_menu/render_view_context_menu.cc
@@ -80,6 +80,7 @@ #include "components/spellcheck/browser/pref_names.h" #include "components/spellcheck/browser/spellcheck_host_metrics.h" #include "components/spellcheck/common/spellcheck_common.h" +#include "components/spellcheck/spellcheck_build_features.h" #include "components/translate/core/browser/translate_download_manager.h" #include "components/translate/core/browser/translate_manager.h" #include "components/translate/core/browser/translate_prefs.h" @@ -121,7 +122,7 @@ #include "ui/gfx/path.h" #include "ui/gfx/text_elider.h" -#if !defined(USE_BROWSER_SPELLCHECKER) +#if !BUILDFLAG(USE_BROWSER_SPELLCHECKER) #include "chrome/browser/renderer_context_menu/spelling_options_submenu_observer.h" #endif @@ -534,7 +535,7 @@ bool RenderViewContextMenu::IsInternalResourcesURL(const GURL& url) { if (!url.SchemeIs(content::kChromeUIScheme)) return false; - return url.host() == chrome::kChromeUISyncResourcesHost; + return url.host_piece() == chrome::kChromeUISyncResourcesHost; } // static
diff --git a/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc b/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc index c0c02276..94092618 100644 --- a/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc +++ b/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc
@@ -53,8 +53,8 @@ #include "net/url_request/url_request.h" #include "net/url_request/url_request_filter.h" #include "net/url_request/url_request_interceptor.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/web/WebContextMenuData.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" #include "ui/base/models/menu_model.h" using content::WebContents;
diff --git a/chrome/browser/renderer_context_menu/spelling_menu_observer.cc b/chrome/browser/renderer_context_menu/spelling_menu_observer.cc index 0cbdbc70..ca6f1d2 100644 --- a/chrome/browser/renderer_context_menu/spelling_menu_observer.cc +++ b/chrome/browser/renderer_context_menu/spelling_menu_observer.cc
@@ -28,6 +28,7 @@ #include "components/spellcheck/browser/spelling_service_client.h" #include "components/spellcheck/common/spellcheck_common.h" #include "components/spellcheck/common/spellcheck_result.h" +#include "components/spellcheck/spellcheck_build_features.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" @@ -271,7 +272,7 @@ spellcheck->GetFeedbackSender()->AddedToDictionary(misspelling_hash_); } } -#if defined(USE_BROWSER_SPELLCHECKER) +#if BUILDFLAG(USE_BROWSER_SPELLCHECKER) spellcheck_platform::AddWord(misspelled_word_); #endif }
diff --git a/chrome/browser/renderer_host/chrome_extension_message_filter.cc b/chrome/browser/renderer_host/chrome_extension_message_filter.cc index b1b9fed..3b1ef45 100644 --- a/chrome/browser/renderer_host/chrome_extension_message_filter.cc +++ b/chrome/browser/renderer_host/chrome_extension_message_filter.cc
@@ -80,6 +80,8 @@ IPC_BEGIN_MESSAGE_MAP(ChromeExtensionMessageFilter, message) IPC_MESSAGE_HANDLER(ExtensionHostMsg_OpenChannelToExtension, OnOpenChannelToExtension) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_OpenChannelToExtensionSync, + OnOpenChannelToExtensionSync) IPC_MESSAGE_HANDLER(ExtensionHostMsg_OpenChannelToTab, OnOpenChannelToTab) IPC_MESSAGE_HANDLER(ExtensionHostMsg_OpenChannelToNativeApp, OnOpenChannelToNativeApp) @@ -138,9 +140,26 @@ BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind( - &ChromeExtensionMessageFilter::OpenChannelToExtensionOnUIThread, - this, render_process_id_, routing_id, port2_id, info, - channel_name, include_tls_channel_id)); + &ChromeExtensionMessageFilter::OpenChannelToExtensionOnUIThread, this, + render_process_id_, routing_id, port2_id, info, channel_name, + include_tls_channel_id)); +} + +void ChromeExtensionMessageFilter::OnOpenChannelToExtensionSync( + int routing_id, + const ExtensionMsg_ExternalConnectionInfo& info, + const std::string& channel_name, + bool include_tls_channel_id, + int* port_id) { + int port2_id = 0; + extensions::MessageService::AllocatePortIdPair(port_id, &port2_id); + + BrowserThread::PostTask( + BrowserThread::UI, FROM_HERE, + base::Bind( + &ChromeExtensionMessageFilter::OpenChannelToExtensionOnUIThread, this, + render_process_id_, routing_id, port2_id, info, channel_name, + include_tls_channel_id)); } void ChromeExtensionMessageFilter::OpenChannelToExtensionOnUIThread(
diff --git a/chrome/browser/renderer_host/chrome_extension_message_filter.h b/chrome/browser/renderer_host/chrome_extension_message_filter.h index 0ad57f3..ff79393 100644 --- a/chrome/browser/renderer_host/chrome_extension_message_filter.h +++ b/chrome/browser/renderer_host/chrome_extension_message_filter.h
@@ -58,6 +58,12 @@ const std::string& channel_name, bool include_tls_channel_id, int request_id); + void OnOpenChannelToExtensionSync( + int routing_id, + const ExtensionMsg_ExternalConnectionInfo& info, + const std::string& channel_name, + bool include_tls_channel_id, + int* port_id); void OpenChannelToExtensionOnUIThread( int source_process_id, int source_routing_id,
diff --git a/chrome/browser/renderer_host/chrome_render_widget_host_view_mac_history_swiper.mm b/chrome/browser/renderer_host/chrome_render_widget_host_view_mac_history_swiper.mm index 0165f04..b9a63a6 100644 --- a/chrome/browser/renderer_host/chrome_render_widget_host_view_mac_history_swiper.mm +++ b/chrome/browser/renderer_host/chrome_render_widget_host_view_mac_history_swiper.mm
@@ -10,7 +10,7 @@ #include "chrome/browser/ui/browser_finder.h" #import "chrome/browser/ui/cocoa/history_overlay_controller.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" namespace { // The horizontal distance required to cause the browser to perform a history
diff --git a/chrome/browser/renderer_host/chrome_render_widget_host_view_mac_history_swiper_unit_test.mm b/chrome/browser/renderer_host/chrome_render_widget_host_view_mac_history_swiper_unit_test.mm index 5169e7b..7bbdeb9 100644 --- a/chrome/browser/renderer_host/chrome_render_widget_host_view_mac_history_swiper_unit_test.mm +++ b/chrome/browser/renderer_host/chrome_render_widget_host_view_mac_history_swiper_unit_test.mm
@@ -8,7 +8,7 @@ #import "base/mac/sdk_forward_declarations.h" #import "chrome/browser/ui/cocoa/cocoa_test_helper.h" #include "testing/gtest/include/gtest/gtest.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #import "third_party/ocmock/OCMock/OCMock.h" #import "third_party/ocmock/ocmock_extensions.h"
diff --git a/chrome/browser/renderer_preferences_util.cc b/chrome/browser/renderer_preferences_util.cc index aa4f1c2..c20a01db 100644 --- a/chrome/browser/renderer_preferences_util.cc +++ b/chrome/browser/renderer_preferences_util.cc
@@ -16,6 +16,7 @@ #include "content/public/browser/web_contents.h" #include "content/public/common/renderer_preferences.h" #include "content/public/common/webrtc_ip_handling_policy.h" +#include "third_party/WebKit/public/public_features.h" #include "third_party/skia/include/core/SkColor.h" #if defined(OS_LINUX) || defined(OS_ANDROID) @@ -111,7 +112,7 @@ &prefs->webrtc_udp_max_port); #endif -#if defined(USE_DEFAULT_RENDER_THEME) +#if BUILDFLAG(USE_DEFAULT_RENDER_THEME) prefs->focus_ring_color = SkColorSetRGB(0x4D, 0x90, 0xFE); #if defined(OS_CHROMEOS) // This color is 0x544d90fe modulated with 0xffffff.
diff --git a/chrome/browser/resources/chromeos/arc_support/background.js b/chrome/browser/resources/chromeos/arc_support/background.js index 57383a0..c0b6716 100644 --- a/chrome/browser/resources/chromeos/arc_support/background.js +++ b/chrome/browser/resources/chromeos/arc_support/background.js
@@ -30,13 +30,6 @@ var currentDeviceId = null; /** - * Indicates that terms were accepted by user. - * @type {boolean} - * TODO: This should be a part of TermsOfServicePage. - */ -var termsAccepted = false; - -/** * Host window inner default width. * @const {number} */ @@ -280,8 +273,6 @@ /** Called when the TermsOfService page is shown. */ onShow() { - termsAccepted = false; - if (this.isManaged_ || this.state_ == LoadState.LOADED) { // Note: in managed case, because it does not show the contents of terms // of service, it is ok to show the content container immediately. @@ -367,8 +358,6 @@ /** Called when "AGREE" button is clicked. */ onAgree() { - termsAccepted = true; - sendNativeMessage('onAgreed', { isMetricsEnabled: this.metricsCheckbox_.isChecked(), isBackupRestoreEnabled: this.backupRestoreCheckbox_.isChecked(), @@ -469,16 +458,8 @@ appWindow.close(); } } else if (message.action == 'showPage') { - if (message.page != 'terms') { - // Explicit request to start not from start page. Assume terms are - // accepted in this case. - // TODO: this is only for controling "RETRY" button. Remove this. - termsAccepted = true; - } showPage(message.page); } else if (message.action == 'showErrorPage') { - // TODO: this is only for controling "RETRY" button. Remove this. - termsAccepted = true; showErrorPage(message.errorMessage, message.shouldShowSendFeedback); } else if (message.action == 'setWindowBounds') { setWindowBounds(); @@ -706,15 +687,7 @@ lsoView.addEventListener('contentload', onLsoViewContentLoad); var onRetry = function() { - if (termsAccepted) { - // Reuse the onAgree() in case that the user has already accepted - // the ToS. - termsPage.onAgree(); - } else { - // Here 'error' page should be visible. So switch to 'terms' page - // to show the progress page, which triggers reloading. - showPage('terms'); - } + sendNativeMessage('onRetryClicked'); }; var onSendFeedback = function() {
diff --git a/chrome/browser/resources/chromeos/sounds/spoken_feedback_toggle_countdown_high.wav b/chrome/browser/resources/chromeos/sounds/spoken_feedback_toggle_countdown_high.wav new file mode 100644 index 0000000..12661f5 --- /dev/null +++ b/chrome/browser/resources/chromeos/sounds/spoken_feedback_toggle_countdown_high.wav Binary files differ
diff --git a/chrome/browser/resources/chromeos/sounds/spoken_feedback_toggle_countdown_low.wav b/chrome/browser/resources/chromeos/sounds/spoken_feedback_toggle_countdown_low.wav new file mode 100644 index 0000000..e0f4f20 --- /dev/null +++ b/chrome/browser/resources/chromeos/sounds/spoken_feedback_toggle_countdown_low.wav Binary files differ
diff --git a/chrome/browser/resources/md_downloads/crisper.js b/chrome/browser/resources/md_downloads/crisper.js index 381f5c7..a369ad0b 100644 --- a/chrome/browser/resources/md_downloads/crisper.js +++ b/chrome/browser/resources/md_downloads/crisper.js
@@ -25,8 +25,9 @@ // <if expr="is_ios"> if(!("key"in KeyboardEvent.prototype)){Object.defineProperty(KeyboardEvent.prototype,"key",{get:function(){if(this.keyCode>=48&&this.keyCode<=57)return String.fromCharCode(this.keyCode);if(this.keyCode>=65&&this.keyCode<=90){var result=String.fromCharCode(this.keyCode).toLowerCase();if(this.shiftKey)result=result.toUpperCase();return result}switch(this.keyCode){case 8:return"Backspace";case 9:return"Tab";case 13:return"Enter";case 16:return"Shift";case 17:return"Control";case 18:return"Alt";case 27:return"Escape";case 32:return" ";case 33:return"PageUp";case 34:return"PageDown";case 35:return"End";case 36:return"Home";case 37:return"ArrowLeft";case 38:return"ArrowUp";case 39:return"ArrowRight";case 40:return"ArrowDown";case 45:return"Insert";case 46:return"Delete";case 91:return"Meta";case 112:return"F1";case 113:return"F2";case 114:return"F3";case 115:return"F4";case 116:return"F5";case 117:return"F6";case 118:return"F7";case 119:return"F8";case 120:return"F9";case 121:return"F10";case 122:return"F11";case 123:return"F12";case 187:return"=";case 189:return"-";case 219:return"[";case 221:return"]"}return"Unidentified"}})}else{window.console.log("KeyboardEvent.Key polyfill not required")} // </if> /* is_ios */ -Polymer.IronResizableBehavior={properties:{_parentResizable:{type:Object,observer:"_parentResizableChanged"},_notifyingDescendant:{type:Boolean,value:false}},listeners:{"iron-request-resize-notifications":"_onIronRequestResizeNotifications"},created:function(){this._interestedResizables=[];this._boundNotifyResize=this.notifyResize.bind(this)},attached:function(){this.fire("iron-request-resize-notifications",null,{node:this,bubbles:true,cancelable:true});if(!this._parentResizable){window.addEventListener("resize",this._boundNotifyResize);this.notifyResize()}},detached:function(){if(this._parentResizable){this._parentResizable.stopResizeNotificationsFor(this)}else{window.removeEventListener("resize",this._boundNotifyResize)}this._parentResizable=null},notifyResize:function(){if(!this.isAttached){return}this._interestedResizables.forEach(function(resizable){if(this.resizerShouldNotify(resizable)){this._notifyDescendant(resizable)}},this);this._fireResize()},assignParentResizable:function(parentResizable){this._parentResizable=parentResizable},stopResizeNotificationsFor:function(target){var index=this._interestedResizables.indexOf(target);if(index>-1){this._interestedResizables.splice(index,1);this.unlisten(target,"iron-resize","_onDescendantIronResize")}},resizerShouldNotify:function(element){return true},_onDescendantIronResize:function(event){if(this._notifyingDescendant){event.stopPropagation();return}if(!Polymer.Settings.useShadow){this._fireResize()}},_fireResize:function(){this.fire("iron-resize",null,{node:this,bubbles:false})},_onIronRequestResizeNotifications:function(event){var target=event.path?event.path[0]:event.target;if(target===this){return}if(this._interestedResizables.indexOf(target)===-1){this._interestedResizables.push(target);this.listen(target,"iron-resize","_onDescendantIronResize")}target.assignParentResizable(this);this._notifyDescendant(target);event.stopPropagation()},_parentResizableChanged:function(parentResizable){if(parentResizable){window.removeEventListener("resize",this._boundNotifyResize)}},_notifyDescendant:function(descendant){if(!this.isAttached){return}this._notifyingDescendant=true;descendant.notifyResize();this._notifyingDescendant=false}};(function(){"use strict";var KEY_IDENTIFIER={"U+0008":"backspace","U+0009":"tab","U+001B":"esc","U+0020":"space","U+007F":"del"};var KEY_CODE={8:"backspace",9:"tab",13:"enter",27:"esc",33:"pageup",34:"pagedown",35:"end",36:"home",32:"space",37:"left",38:"up",39:"right",40:"down",46:"del",106:"*"};var MODIFIER_KEYS={shift:"shiftKey",ctrl:"ctrlKey",alt:"altKey",meta:"metaKey"};var KEY_CHAR=/[a-z0-9*]/;var IDENT_CHAR=/U\+/;var ARROW_KEY=/^arrow/;var SPACE_KEY=/^space(bar)?/;var ESC_KEY=/^escape$/;function transformKey(key,noSpecialChars){var validKey="";if(key){var lKey=key.toLowerCase();if(lKey===" "||SPACE_KEY.test(lKey)){validKey="space"}else if(ESC_KEY.test(lKey)){validKey="esc"}else if(lKey.length==1){if(!noSpecialChars||KEY_CHAR.test(lKey)){validKey=lKey}}else if(ARROW_KEY.test(lKey)){validKey=lKey.replace("arrow","")}else if(lKey=="multiply"){validKey="*"}else{validKey=lKey}}return validKey}function transformKeyIdentifier(keyIdent){var validKey="";if(keyIdent){if(keyIdent in KEY_IDENTIFIER){validKey=KEY_IDENTIFIER[keyIdent]}else if(IDENT_CHAR.test(keyIdent)){keyIdent=parseInt(keyIdent.replace("U+","0x"),16);validKey=String.fromCharCode(keyIdent).toLowerCase()}else{validKey=keyIdent.toLowerCase()}}return validKey}function transformKeyCode(keyCode){var validKey="";if(Number(keyCode)){if(keyCode>=65&&keyCode<=90){validKey=String.fromCharCode(32+keyCode)}else if(keyCode>=112&&keyCode<=123){validKey="f"+(keyCode-112)}else if(keyCode>=48&&keyCode<=57){validKey=String(keyCode-48)}else if(keyCode>=96&&keyCode<=105){validKey=String(keyCode-96)}else{validKey=KEY_CODE[keyCode]}}return validKey}function normalizedKeyForEvent(keyEvent,noSpecialChars){if(keyEvent.key){return transformKey(keyEvent.key,noSpecialChars)}if(keyEvent.detail&&keyEvent.detail.key){return transformKey(keyEvent.detail.key,noSpecialChars)}return transformKeyIdentifier(keyEvent.keyIdentifier)||transformKeyCode(keyEvent.keyCode)||""}function keyComboMatchesEvent(keyCombo,event){var keyEvent=normalizedKeyForEvent(event,keyCombo.hasModifiers);return keyEvent===keyCombo.key&&(!keyCombo.hasModifiers||!!event.shiftKey===!!keyCombo.shiftKey&&!!event.ctrlKey===!!keyCombo.ctrlKey&&!!event.altKey===!!keyCombo.altKey&&!!event.metaKey===!!keyCombo.metaKey)}function parseKeyComboString(keyComboString){if(keyComboString.length===1){return{combo:keyComboString,key:keyComboString,event:"keydown"}}return keyComboString.split("+").reduce(function(parsedKeyCombo,keyComboPart){var eventParts=keyComboPart.split(":");var keyName=eventParts[0];var event=eventParts[1];if(keyName in MODIFIER_KEYS){parsedKeyCombo[MODIFIER_KEYS[keyName]]=true;parsedKeyCombo.hasModifiers=true}else{parsedKeyCombo.key=keyName;parsedKeyCombo.event=event||"keydown"}return parsedKeyCombo},{combo:keyComboString.split(":").shift()})}function parseEventString(eventString){return eventString.trim().split(" ").map(function(keyComboString){return parseKeyComboString(keyComboString)})}Polymer.IronA11yKeysBehavior={properties:{keyEventTarget:{type:Object,value:function(){return this}},stopKeyboardEventPropagation:{type:Boolean,value:false},_boundKeyHandlers:{type:Array,value:function(){return[]}},_imperativeKeyBindings:{type:Object,value:function(){return{}}}},observers:["_resetKeyEventListeners(keyEventTarget, _boundKeyHandlers)"],keyBindings:{},registered:function(){this._prepKeyBindings()},attached:function(){this._listenKeyEventListeners()},detached:function(){this._unlistenKeyEventListeners()},addOwnKeyBinding:function(eventString,handlerName){this._imperativeKeyBindings[eventString]=handlerName;this._prepKeyBindings();this._resetKeyEventListeners()},removeOwnKeyBindings:function(){this._imperativeKeyBindings={};this._prepKeyBindings();this._resetKeyEventListeners()},keyboardEventMatchesKeys:function(event,eventString){var keyCombos=parseEventString(eventString);for(var i=0;i<keyCombos.length;++i){if(keyComboMatchesEvent(keyCombos[i],event)){return true}}return false},_collectKeyBindings:function(){var keyBindings=this.behaviors.map(function(behavior){return behavior.keyBindings});if(keyBindings.indexOf(this.keyBindings)===-1){keyBindings.push(this.keyBindings)}return keyBindings},_prepKeyBindings:function(){this._keyBindings={};this._collectKeyBindings().forEach(function(keyBindings){for(var eventString in keyBindings){this._addKeyBinding(eventString,keyBindings[eventString])}},this);for(var eventString in this._imperativeKeyBindings){this._addKeyBinding(eventString,this._imperativeKeyBindings[eventString])}for(var eventName in this._keyBindings){this._keyBindings[eventName].sort(function(kb1,kb2){var b1=kb1[0].hasModifiers;var b2=kb2[0].hasModifiers;return b1===b2?0:b1?-1:1})}},_addKeyBinding:function(eventString,handlerName){parseEventString(eventString).forEach(function(keyCombo){this._keyBindings[keyCombo.event]=this._keyBindings[keyCombo.event]||[];this._keyBindings[keyCombo.event].push([keyCombo,handlerName])},this)},_resetKeyEventListeners:function(){this._unlistenKeyEventListeners();if(this.isAttached){this._listenKeyEventListeners()}},_listenKeyEventListeners:function(){if(!this.keyEventTarget){return}Object.keys(this._keyBindings).forEach(function(eventName){var keyBindings=this._keyBindings[eventName];var boundKeyHandler=this._onKeyBindingEvent.bind(this,keyBindings);this._boundKeyHandlers.push([this.keyEventTarget,eventName,boundKeyHandler]);this.keyEventTarget.addEventListener(eventName,boundKeyHandler)},this)},_unlistenKeyEventListeners:function(){var keyHandlerTuple;var keyEventTarget;var eventName;var boundKeyHandler;while(this._boundKeyHandlers.length){keyHandlerTuple=this._boundKeyHandlers.pop();keyEventTarget=keyHandlerTuple[0];eventName=keyHandlerTuple[1];boundKeyHandler=keyHandlerTuple[2];keyEventTarget.removeEventListener(eventName,boundKeyHandler)}},_onKeyBindingEvent:function(keyBindings,event){if(this.stopKeyboardEventPropagation){event.stopPropagation()}if(event.defaultPrevented){return}for(var i=0;i<keyBindings.length;i++){var keyCombo=keyBindings[i][0];var handlerName=keyBindings[i][1];if(keyComboMatchesEvent(keyCombo,event)){this._triggerKeyHandler(keyCombo,handlerName,event);if(event.defaultPrevented){return}}}},_triggerKeyHandler:function(keyCombo,handlerName,keyboardEvent){var detail=Object.create(keyCombo);detail.keyboardEvent=keyboardEvent;var event=new CustomEvent(keyCombo.event,{detail:detail,cancelable:true});this[handlerName].call(this,event);if(event.defaultPrevented){keyboardEvent.preventDefault()}}}})();Polymer.IronScrollTargetBehavior={properties:{scrollTarget:{type:HTMLElement,value:function(){return this._defaultScrollTarget}}},observers:["_scrollTargetChanged(scrollTarget, isAttached)"],_shouldHaveListener:true,_scrollTargetChanged:function(scrollTarget,isAttached){var eventTarget;if(this._oldScrollTarget){this._toggleScrollListener(false,this._oldScrollTarget);this._oldScrollTarget=null}if(!isAttached){return}if(scrollTarget==="document"){this.scrollTarget=this._doc}else if(typeof scrollTarget==="string"){this.scrollTarget=this.domHost?this.domHost.$[scrollTarget]:Polymer.dom(this.ownerDocument).querySelector("#"+scrollTarget)}else if(this._isValidScrollTarget()){this._boundScrollHandler=this._boundScrollHandler||this._scrollHandler.bind(this);this._oldScrollTarget=scrollTarget;this._toggleScrollListener(this._shouldHaveListener,scrollTarget)}},_scrollHandler:function scrollHandler(){},get _defaultScrollTarget(){return this._doc},get _doc(){return this.ownerDocument.documentElement},get _scrollTop(){if(this._isValidScrollTarget()){return this.scrollTarget===this._doc?window.pageYOffset:this.scrollTarget.scrollTop}return 0},get _scrollLeft(){if(this._isValidScrollTarget()){return this.scrollTarget===this._doc?window.pageXOffset:this.scrollTarget.scrollLeft}return 0},set _scrollTop(top){if(this.scrollTarget===this._doc){window.scrollTo(window.pageXOffset,top)}else if(this._isValidScrollTarget()){this.scrollTarget.scrollTop=top}},set _scrollLeft(left){if(this.scrollTarget===this._doc){window.scrollTo(left,window.pageYOffset)}else if(this._isValidScrollTarget()){this.scrollTarget.scrollLeft=left}},scroll:function(left,top){if(this.scrollTarget===this._doc){window.scrollTo(left,top)}else if(this._isValidScrollTarget()){this.scrollTarget.scrollLeft=left;this.scrollTarget.scrollTop=top}},get _scrollTargetWidth(){if(this._isValidScrollTarget()){return this.scrollTarget===this._doc?window.innerWidth:this.scrollTarget.offsetWidth}return 0},get _scrollTargetHeight(){if(this._isValidScrollTarget()){return this.scrollTarget===this._doc?window.innerHeight:this.scrollTarget.offsetHeight}return 0},_isValidScrollTarget:function(){return this.scrollTarget instanceof HTMLElement},_toggleScrollListener:function(yes,scrollTarget){if(!this._boundScrollHandler){return}var eventTarget=scrollTarget===this._doc?window:scrollTarget;if(yes){eventTarget.addEventListener("scroll",this._boundScrollHandler)}else{eventTarget.removeEventListener("scroll",this._boundScrollHandler)}},toggleScrollListener:function(yes){this._shouldHaveListener=yes;this._toggleScrollListener(yes,this.scrollTarget)}};(function(){var IOS=navigator.userAgent.match(/iP(?:hone|ad;(?: U;)? CPU) OS (\d+)/);var IOS_TOUCH_SCROLLING=IOS&&IOS[1]>=8;var DEFAULT_PHYSICAL_COUNT=3;var HIDDEN_Y="-10000px";var ITEM_WIDTH=0;var ITEM_HEIGHT=1;var SECRET_TABINDEX=-100;Polymer({is:"iron-list",properties:{items:{type:Array},maxPhysicalCount:{type:Number,value:500},as:{type:String,value:"item"},indexAs:{type:String,value:"index"},selectedAs:{type:String,value:"selected"},grid:{type:Boolean,value:false,reflectToAttribute:true},selectionEnabled:{type:Boolean,value:false},selectedItem:{type:Object,notify:true},selectedItems:{type:Object,notify:true},multiSelection:{type:Boolean,value:false}},observers:["_itemsChanged(items.*)","_selectionEnabledChanged(selectionEnabled)","_multiSelectionChanged(multiSelection)","_setOverflow(scrollTarget)"],behaviors:[Polymer.Templatizer,Polymer.IronResizableBehavior,Polymer.IronA11yKeysBehavior,Polymer.IronScrollTargetBehavior],keyBindings:{up:"_didMoveUp",down:"_didMoveDown",enter:"_didEnter"},_ratio:.5,_scrollerPaddingTop:0,_scrollPosition:0,_physicalSize:0,_physicalAverage:0,_physicalAverageCount:0,_physicalTop:0,_virtualCount:0,_physicalIndexForKey:null,_estScrollHeight:0,_scrollHeight:0,_viewportHeight:0,_viewportWidth:0,_physicalItems:null,_physicalSizes:null,_firstVisibleIndexVal:null,_lastVisibleIndexVal:null,_collection:null,_maxPages:2,_focusedItem:null,_focusedIndex:-1,_offscreenFocusedItem:null,_focusBackfillItem:null,_itemsPerRow:1,_itemWidth:0,_rowHeight:0,_templateCost:0,get _physicalBottom(){return this._physicalTop+this._physicalSize},get _scrollBottom(){return this._scrollPosition+this._viewportHeight},get _virtualEnd(){return this._virtualStart+this._physicalCount-1},get _hiddenContentSize(){var size=this.grid?this._physicalRows*this._rowHeight:this._physicalSize;return size-this._viewportHeight},get _maxScrollTop(){return this._estScrollHeight-this._viewportHeight+this._scrollerPaddingTop},_minVirtualStart:0,get _maxVirtualStart(){return Math.max(0,this._virtualCount-this._physicalCount)},_virtualStartVal:0,set _virtualStart(val){this._virtualStartVal=Math.min(this._maxVirtualStart,Math.max(this._minVirtualStart,val))},get _virtualStart(){return this._virtualStartVal||0},_physicalStartVal:0,set _physicalStart(val){this._physicalStartVal=val%this._physicalCount;if(this._physicalStartVal<0){this._physicalStartVal=this._physicalCount+this._physicalStartVal}this._physicalEnd=(this._physicalStart+this._physicalCount-1)%this._physicalCount},get _physicalStart(){return this._physicalStartVal||0},_physicalCountVal:0,set _physicalCount(val){this._physicalCountVal=val;this._physicalEnd=(this._physicalStart+this._physicalCount-1)%this._physicalCount},get _physicalCount(){return this._physicalCountVal},_physicalEnd:0,get _optPhysicalSize(){if(this.grid){return this._estRowsInView*this._rowHeight*this._maxPages}return this._viewportHeight*this._maxPages},get _isVisible(){return Boolean(this.offsetWidth||this.offsetHeight)},get firstVisibleIndex(){if(this._firstVisibleIndexVal===null){var physicalOffset=Math.floor(this._physicalTop+this._scrollerPaddingTop);this._firstVisibleIndexVal=this._iterateItems(function(pidx,vidx){physicalOffset+=this._getPhysicalSizeIncrement(pidx);if(physicalOffset>this._scrollPosition){return this.grid?vidx-vidx%this._itemsPerRow:vidx}if(this.grid&&this._virtualCount-1===vidx){return vidx-vidx%this._itemsPerRow}})||0}return this._firstVisibleIndexVal},get lastVisibleIndex(){if(this._lastVisibleIndexVal===null){if(this.grid){var lastIndex=this.firstVisibleIndex+this._estRowsInView*this._itemsPerRow-1;this._lastVisibleIndexVal=Math.min(this._virtualCount,lastIndex)}else{var physicalOffset=this._physicalTop;this._iterateItems(function(pidx,vidx){if(physicalOffset<this._scrollBottom){this._lastVisibleIndexVal=vidx}else{return true}physicalOffset+=this._getPhysicalSizeIncrement(pidx)})}}return this._lastVisibleIndexVal},get _defaultScrollTarget(){return this},get _virtualRowCount(){return Math.ceil(this._virtualCount/this._itemsPerRow)},get _estRowsInView(){return Math.ceil(this._viewportHeight/this._rowHeight)},get _physicalRows(){return Math.ceil(this._physicalCount/this._itemsPerRow)},ready:function(){this.addEventListener("focus",this._didFocus.bind(this),true)},attached:function(){if(this._physicalCount===0){this._debounceTemplate(this._render)}this.listen(this,"iron-resize","_resizeHandler")},detached:function(){this.unlisten(this,"iron-resize","_resizeHandler")},_setOverflow:function(scrollTarget){this.style.webkitOverflowScrolling=scrollTarget===this?"touch":"";this.style.overflow=scrollTarget===this?"auto":""},updateViewportBoundaries:function(){this._scrollerPaddingTop=this.scrollTarget===this?0:parseInt(window.getComputedStyle(this)["padding-top"],10);this._viewportWidth=this.$.items.offsetWidth;this._viewportHeight=this._scrollTargetHeight;this.grid&&this._updateGridMetrics()},_scrollHandler:function(){var scrollTop=Math.max(0,Math.min(this._maxScrollTop,this._scrollTop));var delta=scrollTop-this._scrollPosition;var isScrollingDown=delta>=0;this._scrollPosition=scrollTop;this._firstVisibleIndexVal=null;this._lastVisibleIndexVal=null;if(Math.abs(delta)>this._physicalSize){var idxAdjustment=Math.round(delta/this._physicalAverage)*this._itemsPerRow;this._physicalTop=this._physicalTop+delta;this._virtualStart=this._virtualStart+idxAdjustment;this._physicalStart=this._physicalStart+idxAdjustment;this._update()}else{var reusables=this._getReusables(isScrollingDown);if(isScrollingDown){this._physicalTop=reusables.physicalTop;this._virtualStart=this._virtualStart+reusables.indexes.length;this._physicalStart=this._physicalStart+reusables.indexes.length}else{this._virtualStart=this._virtualStart-reusables.indexes.length;this._physicalStart=this._physicalStart-reusables.indexes.length}if(reusables.indexes.length===0){this._increasePoolIfNeeded()}else{this._update(reusables.indexes,isScrollingDown?null:reusables.indexes)}}},_getReusables:function(fromTop){var ith,lastIth,offsetContent,physicalItemHeight;var idxs=[];var protectedOffsetContent=this._hiddenContentSize*this._ratio;var virtualStart=this._virtualStart;var virtualEnd=this._virtualEnd;var physicalCount=this._physicalCount;var physicalTop=this._physicalTop+this._scrollerPaddingTop;var scrollTop=this._scrollTop;var scrollBottom=this._scrollBottom;if(fromTop){ith=this._physicalStart;lastIth=this._physicalEnd;offsetContent=scrollTop-physicalTop}else{ith=this._physicalEnd;lastIth=this._physicalStart;offsetContent=this._physicalBottom-scrollBottom}while(true){physicalItemHeight=this._getPhysicalSizeIncrement(ith);offsetContent=offsetContent-physicalItemHeight;if(idxs.length>=physicalCount||offsetContent<=protectedOffsetContent){break}if(fromTop){if(virtualEnd+idxs.length+1>=this._virtualCount){break}if(physicalTop+physicalItemHeight>=scrollTop){break}idxs.push(ith);physicalTop=physicalTop+physicalItemHeight;ith=(ith+1)%physicalCount}else{if(virtualStart-idxs.length<=0){break}if(physicalTop+this._physicalSize-physicalItemHeight<=scrollBottom){break}idxs.push(ith);physicalTop=physicalTop-physicalItemHeight;ith=ith===0?physicalCount-1:ith-1}}return{indexes:idxs,physicalTop:physicalTop-this._scrollerPaddingTop}},_update:function(itemSet,movingUp){if(itemSet&&itemSet.length===0){return}this._manageFocus();this._assignModels(itemSet);this._updateMetrics(itemSet);if(movingUp){while(movingUp.length){var idx=movingUp.pop();this._physicalTop-=this._getPhysicalSizeIncrement(idx)}}this._positionItems();this._updateScrollerSize();this._increasePoolIfNeeded()},_createPool:function(size){var physicalItems=new Array(size);this._ensureTemplatized();for(var i=0;i<size;i++){var inst=this.stamp(null);physicalItems[i]=inst.root.querySelector("*");Polymer.dom(this).appendChild(inst.root)}return physicalItems},_increasePoolIfNeeded:function(){if(this._viewportHeight===0){return false}var self=this;var isClientFull=this._physicalBottom>=this._scrollBottom&&this._physicalTop<=this._scrollPosition;if(this._physicalSize>=this._optPhysicalSize&&isClientFull){return false}var maxPoolSize=Math.round(this._physicalCount*.5);if(!isClientFull){this._debounceTemplate(this._increasePool.bind(this,maxPoolSize));return true}this._yield(function(){self._increasePool(Math.min(maxPoolSize,Math.max(1,Math.round(50/self._templateCost))))});return true},_yield:function(cb){var g=window;var handle=g.requestIdleCallback?g.requestIdleCallback(cb):g.setTimeout(cb,16);Polymer.dom.addDebouncer({complete:function(){g.cancelIdleCallback?g.cancelIdleCallback(handle):g.clearTimeout(handle);cb()}})},_increasePool:function(missingItems){var nextPhysicalCount=Math.min(this._physicalCount+missingItems,this._virtualCount-this._virtualStart,Math.max(this.maxPhysicalCount,DEFAULT_PHYSICAL_COUNT));var prevPhysicalCount=this._physicalCount;var delta=nextPhysicalCount-prevPhysicalCount;var ts=window.performance.now();if(delta<=0){return}[].push.apply(this._physicalItems,this._createPool(delta));[].push.apply(this._physicalSizes,new Array(delta));this._physicalCount=prevPhysicalCount+delta;if(this._physicalStart>this._physicalEnd&&this._isIndexRendered(this._focusedIndex)&&this._getPhysicalIndex(this._focusedIndex)<this._physicalEnd){this._physicalStart=this._physicalStart+delta}this._update();this._templateCost=(window.performance.now()-ts)/delta},_render:function(){if(this.isAttached&&this._isVisible){if(this._physicalCount===0){this.updateViewportBoundaries();this._increasePool(DEFAULT_PHYSICAL_COUNT)}else{var reusables=this._getReusables(true);this._physicalTop=reusables.physicalTop;this._virtualStart=this._virtualStart+reusables.indexes.length;this._physicalStart=this._physicalStart+reusables.indexes.length;this._update(reusables.indexes);this._update()}}},_ensureTemplatized:function(){if(!this.ctor){var props={};props.__key__=true;props[this.as]=true;props[this.indexAs]=true;props[this.selectedAs]=true;props.tabIndex=true;this._instanceProps=props;this._userTemplate=Polymer.dom(this).querySelector("template");if(this._userTemplate){this.templatize(this._userTemplate)}else{console.warn("iron-list requires a template to be provided in light-dom")}}},_getStampedChildren:function(){return this._physicalItems},_forwardInstancePath:function(inst,path,value){if(path.indexOf(this.as+".")===0){this.notifyPath("items."+inst.__key__+"."+path.slice(this.as.length+1),value)}},_forwardParentProp:function(prop,value){if(this._physicalItems){this._physicalItems.forEach(function(item){item._templateInstance[prop]=value},this)}},_forwardParentPath:function(path,value){if(this._physicalItems){this._physicalItems.forEach(function(item){item._templateInstance.notifyPath(path,value,true)},this)}},_forwardItemPath:function(path,value){if(!this._physicalIndexForKey){return}var dot=path.indexOf(".");var key=path.substring(0,dot<0?path.length:dot);var idx=this._physicalIndexForKey[key];var offscreenItem=this._offscreenFocusedItem;var el=offscreenItem&&offscreenItem._templateInstance.__key__===key?offscreenItem:this._physicalItems[idx];if(!el||el._templateInstance.__key__!==key){return}if(dot>=0){path=this.as+"."+path.substring(dot+1);el._templateInstance.notifyPath(path,value,true)}else{var currentItem=el._templateInstance[this.as];if(Array.isArray(this.selectedItems)){for(var i=0;i<this.selectedItems.length;i++){if(this.selectedItems[i]===currentItem){this.set("selectedItems."+i,value);break}}}else if(this.selectedItem===currentItem){this.set("selectedItem",value)}el._templateInstance[this.as]=value}},_itemsChanged:function(change){if(change.path==="items"){this._virtualStart=0;this._physicalTop=0;this._virtualCount=this.items?this.items.length:0;this._collection=this.items?Polymer.Collection.get(this.items):null;this._physicalIndexForKey={};this._firstVisibleIndexVal=null;this._lastVisibleIndexVal=null;this._physicalCount=this._physicalCount||0;this._physicalItems=this._physicalItems||[];this._physicalSizes=this._physicalSizes||[];this._physicalStart=0;this._resetScrollPosition(0);this._removeFocusedItem();this._debounceTemplate(this._render)}else if(change.path==="items.splices"){this._adjustVirtualIndex(change.value.indexSplices);this._virtualCount=this.items?this.items.length:0;this._debounceTemplate(this._render)}else{this._forwardItemPath(change.path.split(".").slice(1).join("."),change.value)}},_adjustVirtualIndex:function(splices){splices.forEach(function(splice){splice.removed.forEach(this._removeItem,this);if(splice.index<this._virtualStart){var delta=Math.max(splice.addedCount-splice.removed.length,splice.index-this._virtualStart);this._virtualStart=this._virtualStart+delta;if(this._focusedIndex>=0){this._focusedIndex=this._focusedIndex+delta}}},this)},_removeItem:function(item){this.$.selector.deselect(item);if(this._focusedItem&&this._focusedItem._templateInstance[this.as]===item){this._removeFocusedItem()}},_iterateItems:function(fn,itemSet){var pidx,vidx,rtn,i;if(arguments.length===2&&itemSet){for(i=0;i<itemSet.length;i++){pidx=itemSet[i];vidx=this._computeVidx(pidx);if((rtn=fn.call(this,pidx,vidx))!=null){return rtn}}}else{pidx=this._physicalStart;vidx=this._virtualStart;for(;pidx<this._physicalCount;pidx++,vidx++){if((rtn=fn.call(this,pidx,vidx))!=null){return rtn}}for(pidx=0;pidx<this._physicalStart;pidx++,vidx++){if((rtn=fn.call(this,pidx,vidx))!=null){return rtn}}}},_computeVidx:function(pidx){if(pidx>=this._physicalStart){return this._virtualStart+(pidx-this._physicalStart)}return this._virtualStart+(this._physicalCount-this._physicalStart)+pidx},_assignModels:function(itemSet){this._iterateItems(function(pidx,vidx){var el=this._physicalItems[pidx];var inst=el._templateInstance;var item=this.items&&this.items[vidx];if(item!=null){inst[this.as]=item;inst.__key__=this._collection.getKey(item);inst[this.selectedAs]=this.$.selector.isSelected(item);inst[this.indexAs]=vidx;inst.tabIndex=this._focusedIndex===vidx?0:-1;this._physicalIndexForKey[inst.__key__]=pidx;el.removeAttribute("hidden")}else{inst.__key__=null;el.setAttribute("hidden","")}},itemSet)},_updateMetrics:function(itemSet){Polymer.dom.flush();var newPhysicalSize=0;var oldPhysicalSize=0;var prevAvgCount=this._physicalAverageCount;var prevPhysicalAvg=this._physicalAverage;this._iterateItems(function(pidx,vidx){oldPhysicalSize+=this._physicalSizes[pidx]||0;this._physicalSizes[pidx]=this._physicalItems[pidx].offsetHeight;newPhysicalSize+=this._physicalSizes[pidx];this._physicalAverageCount+=this._physicalSizes[pidx]?1:0},itemSet);if(this.grid){this._updateGridMetrics();this._physicalSize=Math.ceil(this._physicalCount/this._itemsPerRow)*this._rowHeight}else{this._physicalSize=this._physicalSize+newPhysicalSize-oldPhysicalSize}if(this._physicalAverageCount!==prevAvgCount){this._physicalAverage=Math.round((prevPhysicalAvg*prevAvgCount+newPhysicalSize)/this._physicalAverageCount)}},_updateGridMetrics:function(){this._itemWidth=this._physicalCount>0?this._physicalItems[0].getBoundingClientRect().width:200;this._rowHeight=this._physicalCount>0?this._physicalItems[0].offsetHeight:200;this._itemsPerRow=this._itemWidth?Math.floor(this._viewportWidth/this._itemWidth):this._itemsPerRow},_positionItems:function(){this._adjustScrollPosition();var y=this._physicalTop;if(this.grid){var totalItemWidth=this._itemsPerRow*this._itemWidth;var rowOffset=(this._viewportWidth-totalItemWidth)/2;this._iterateItems(function(pidx,vidx){var modulus=vidx%this._itemsPerRow;var x=Math.floor(modulus*this._itemWidth+rowOffset);this.translate3d(x+"px",y+"px",0,this._physicalItems[pidx]);if(this._shouldRenderNextRow(vidx)){y+=this._rowHeight}})}else{this._iterateItems(function(pidx,vidx){this.translate3d(0,y+"px",0,this._physicalItems[pidx]);y+=this._physicalSizes[pidx]})}},_getPhysicalSizeIncrement:function(pidx){if(!this.grid){return this._physicalSizes[pidx]}if(this._computeVidx(pidx)%this._itemsPerRow!==this._itemsPerRow-1){return 0}return this._rowHeight},_shouldRenderNextRow:function(vidx){return vidx%this._itemsPerRow===this._itemsPerRow-1},_adjustScrollPosition:function(){var deltaHeight=this._virtualStart===0?this._physicalTop:Math.min(this._scrollPosition+this._physicalTop,0);if(deltaHeight){this._physicalTop=this._physicalTop-deltaHeight;if(!IOS_TOUCH_SCROLLING&&this._physicalTop!==0){this._resetScrollPosition(this._scrollTop-deltaHeight)}}},_resetScrollPosition:function(pos){if(this.scrollTarget){this._scrollTop=pos;this._scrollPosition=this._scrollTop}},_updateScrollerSize:function(forceUpdate){if(this.grid){this._estScrollHeight=this._virtualRowCount*this._rowHeight}else{this._estScrollHeight=this._physicalBottom+Math.max(this._virtualCount-this._physicalCount-this._virtualStart,0)*this._physicalAverage}forceUpdate=forceUpdate||this._scrollHeight===0;forceUpdate=forceUpdate||this._scrollPosition>=this._estScrollHeight-this._physicalSize;forceUpdate=forceUpdate||this.grid&&this.$.items.style.height<this._estScrollHeight;if(forceUpdate||Math.abs(this._estScrollHeight-this._scrollHeight)>=this._optPhysicalSize){this.$.items.style.height=this._estScrollHeight+"px";this._scrollHeight=this._estScrollHeight}},scrollToItem:function(item){return this.scrollToIndex(this.items.indexOf(item))},scrollToIndex:function(idx){if(typeof idx!=="number"||idx<0||idx>this.items.length-1){return}Polymer.dom.flush();if(this._physicalCount===0){return}idx=Math.min(Math.max(idx,0),this._virtualCount-1);if(!this._isIndexRendered(idx)||idx>=this._maxVirtualStart){this._virtualStart=this.grid?idx-this._itemsPerRow*2:idx-1}this._manageFocus();this._assignModels();this._updateMetrics();this._physicalTop=Math.floor(this._virtualStart/this._itemsPerRow)*this._physicalAverage;var currentTopItem=this._physicalStart;var currentVirtualItem=this._virtualStart;var targetOffsetTop=0;var hiddenContentSize=this._hiddenContentSize;while(currentVirtualItem<idx&&targetOffsetTop<=hiddenContentSize){targetOffsetTop=targetOffsetTop+this._getPhysicalSizeIncrement(currentTopItem);currentTopItem=(currentTopItem+1)%this._physicalCount;currentVirtualItem++}this._updateScrollerSize(true);this._positionItems();this._resetScrollPosition(this._physicalTop+this._scrollerPaddingTop+targetOffsetTop);this._increasePoolIfNeeded();this._firstVisibleIndexVal=null;this._lastVisibleIndexVal=null},_resetAverage:function(){this._physicalAverage=0;this._physicalAverageCount=0},_resizeHandler:function(){var delta=Math.abs(this._viewportHeight-this._scrollTargetHeight);if(IOS&&delta>0&&delta<100){return}Polymer.dom.addDebouncer(this.debounce("_debounceTemplate",function(){this.updateViewportBoundaries();this._render();if(this._isVisible){this.toggleScrollListener(true);if(this._physicalCount>0){this._resetAverage();this.scrollToIndex(this.firstVisibleIndex)}}else{this.toggleScrollListener(false)}}.bind(this),1))},_getModelFromItem:function(item){var key=this._collection.getKey(item);var pidx=this._physicalIndexForKey[key];if(pidx!=null){return this._physicalItems[pidx]._templateInstance}return null},_getNormalizedItem:function(item){if(this._collection.getKey(item)===undefined){if(typeof item==="number"){item=this.items[item];if(!item){throw new RangeError("<item> not found")}return item}throw new TypeError("<item> should be a valid item")}return item},selectItem:function(item){item=this._getNormalizedItem(item);var model=this._getModelFromItem(item);if(!this.multiSelection&&this.selectedItem){this.deselectItem(this.selectedItem)}if(model){model[this.selectedAs]=true}this.$.selector.select(item);this.updateSizeForItem(item)},deselectItem:function(item){item=this._getNormalizedItem(item);var model=this._getModelFromItem(item);if(model){model[this.selectedAs]=false}this.$.selector.deselect(item);this.updateSizeForItem(item)},toggleSelectionForItem:function(item){item=this._getNormalizedItem(item);if(this.$.selector.isSelected(item)){this.deselectItem(item)}else{this.selectItem(item)}},clearSelection:function(){function unselect(item){var model=this._getModelFromItem(item);if(model){model[this.selectedAs]=false}}if(Array.isArray(this.selectedItems)){this.selectedItems.forEach(unselect,this)}else if(this.selectedItem){unselect.call(this,this.selectedItem)}this.$.selector.clearSelection()},_selectionEnabledChanged:function(selectionEnabled){var handler=selectionEnabled?this.listen:this.unlisten;handler.call(this,this,"tap","_selectionHandler")},_selectionHandler:function(e){var model=this.modelForElement(e.target);if(!model){return}var modelTabIndex,activeElTabIndex;var target=Polymer.dom(e).path[0];var activeEl=Polymer.dom(this.domHost?this.domHost.root:document).activeElement;var physicalItem=this._physicalItems[this._getPhysicalIndex(model[this.indexAs])];if(target.localName==="input"||target.localName==="button"||target.localName==="select"){ -return}modelTabIndex=model.tabIndex;model.tabIndex=SECRET_TABINDEX;activeElTabIndex=activeEl?activeEl.tabIndex:-1;model.tabIndex=modelTabIndex;if(activeEl&&physicalItem!==activeEl&&physicalItem.contains(activeEl)&&activeElTabIndex!==SECRET_TABINDEX){return}this.toggleSelectionForItem(model[this.as])},_multiSelectionChanged:function(multiSelection){this.clearSelection();this.$.selector.multi=multiSelection},updateSizeForItem:function(item){item=this._getNormalizedItem(item);var key=this._collection.getKey(item);var pidx=this._physicalIndexForKey[key];if(pidx!=null){this._updateMetrics([pidx]);this._positionItems()}},_manageFocus:function(){var fidx=this._focusedIndex;if(fidx>=0&&fidx<this._virtualCount){if(this._isIndexRendered(fidx)){this._restoreFocusedItem()}else{this._createFocusBackfillItem()}}else if(this._virtualCount>0&&this._physicalCount>0){this._focusedIndex=this._virtualStart;this._focusedItem=this._physicalItems[this._physicalStart]}},_isIndexRendered:function(idx){return idx>=this._virtualStart&&idx<=this._virtualEnd},_isIndexVisible:function(idx){return idx>=this.firstVisibleIndex&&idx<=this.lastVisibleIndex},_getPhysicalIndex:function(idx){return this._physicalIndexForKey[this._collection.getKey(this._getNormalizedItem(idx))]},_focusPhysicalItem:function(idx){if(idx<0||idx>=this._virtualCount){return}this._restoreFocusedItem();if(!this._isIndexRendered(idx)){this.scrollToIndex(idx)}var physicalItem=this._physicalItems[this._getPhysicalIndex(idx)];var model=physicalItem._templateInstance;var focusable;model.tabIndex=SECRET_TABINDEX;if(physicalItem.tabIndex===SECRET_TABINDEX){focusable=physicalItem}if(!focusable){focusable=Polymer.dom(physicalItem).querySelector('[tabindex="'+SECRET_TABINDEX+'"]')}model.tabIndex=0;this._focusedIndex=idx;focusable&&focusable.focus()},_removeFocusedItem:function(){if(this._offscreenFocusedItem){Polymer.dom(this).removeChild(this._offscreenFocusedItem)}this._offscreenFocusedItem=null;this._focusBackfillItem=null;this._focusedItem=null;this._focusedIndex=-1},_createFocusBackfillItem:function(){var fidx=this._focusedIndex;var pidx=this._getPhysicalIndex(fidx);if(this._offscreenFocusedItem||pidx==null||fidx<0){return}if(!this._focusBackfillItem){var stampedTemplate=this.stamp(null);this._focusBackfillItem=stampedTemplate.root.querySelector("*");Polymer.dom(this).appendChild(stampedTemplate.root)}this._offscreenFocusedItem=this._physicalItems[pidx];this._offscreenFocusedItem._templateInstance.tabIndex=0;this._physicalItems[pidx]=this._focusBackfillItem;this.translate3d(0,HIDDEN_Y,0,this._offscreenFocusedItem)},_restoreFocusedItem:function(){var pidx,fidx=this._focusedIndex;if(!this._offscreenFocusedItem||this._focusedIndex<0){return}this._assignModels();pidx=this._getPhysicalIndex(fidx);if(pidx!=null){this._focusBackfillItem=this._physicalItems[pidx];this._focusBackfillItem._templateInstance.tabIndex=-1;this._physicalItems[pidx]=this._offscreenFocusedItem;this._offscreenFocusedItem=null;this.translate3d(0,HIDDEN_Y,0,this._focusBackfillItem)}},_didFocus:function(e){var targetModel=this.modelForElement(e.target);var focusedModel=this._focusedItem?this._focusedItem._templateInstance:null;var hasOffscreenFocusedItem=this._offscreenFocusedItem!==null;var fidx=this._focusedIndex;if(!targetModel||!focusedModel){return}if(focusedModel===targetModel){if(!this._isIndexVisible(fidx)){this.scrollToIndex(fidx)}}else{this._restoreFocusedItem();focusedModel.tabIndex=-1;targetModel.tabIndex=0;fidx=targetModel[this.indexAs];this._focusedIndex=fidx;this._focusedItem=this._physicalItems[this._getPhysicalIndex(fidx)];if(hasOffscreenFocusedItem&&!this._offscreenFocusedItem){this._update()}}},_didMoveUp:function(){this._focusPhysicalItem(this._focusedIndex-1)},_didMoveDown:function(e){e.detail.keyboardEvent.preventDefault();this._focusPhysicalItem(this._focusedIndex+1)},_didEnter:function(e){this._focusPhysicalItem(this._focusedIndex);this._selectionHandler(e.detail.keyboardEvent)}})})(); +function importModules(moduleNames){return new Promise(function(resolve){define(moduleNames,function(){resolve(Array.from(arguments))})})}Polymer.IronResizableBehavior={properties:{_parentResizable:{type:Object,observer:"_parentResizableChanged"},_notifyingDescendant:{type:Boolean,value:false}},listeners:{"iron-request-resize-notifications":"_onIronRequestResizeNotifications"},created:function(){this._interestedResizables=[];this._boundNotifyResize=this.notifyResize.bind(this)},attached:function(){this.fire("iron-request-resize-notifications",null,{node:this,bubbles:true,cancelable:true});if(!this._parentResizable){window.addEventListener("resize",this._boundNotifyResize);this.notifyResize()}},detached:function(){if(this._parentResizable){this._parentResizable.stopResizeNotificationsFor(this)}else{window.removeEventListener("resize",this._boundNotifyResize)}this._parentResizable=null},notifyResize:function(){if(!this.isAttached){return}this._interestedResizables.forEach(function(resizable){if(this.resizerShouldNotify(resizable)){this._notifyDescendant(resizable)}},this);this._fireResize()},assignParentResizable:function(parentResizable){this._parentResizable=parentResizable},stopResizeNotificationsFor:function(target){var index=this._interestedResizables.indexOf(target);if(index>-1){this._interestedResizables.splice(index,1);this.unlisten(target,"iron-resize","_onDescendantIronResize")}},resizerShouldNotify:function(element){return true},_onDescendantIronResize:function(event){if(this._notifyingDescendant){event.stopPropagation();return}if(!Polymer.Settings.useShadow){this._fireResize()}},_fireResize:function(){this.fire("iron-resize",null,{node:this,bubbles:false})},_onIronRequestResizeNotifications:function(event){var target=event.path?event.path[0]:event.target;if(target===this){return}if(this._interestedResizables.indexOf(target)===-1){this._interestedResizables.push(target);this.listen(target,"iron-resize","_onDescendantIronResize")}target.assignParentResizable(this);this._notifyDescendant(target);event.stopPropagation()},_parentResizableChanged:function(parentResizable){if(parentResizable){window.removeEventListener("resize",this._boundNotifyResize)}},_notifyDescendant:function(descendant){if(!this.isAttached){return}this._notifyingDescendant=true;descendant.notifyResize();this._notifyingDescendant=false}};(function(){"use strict";var KEY_IDENTIFIER={"U+0008":"backspace","U+0009":"tab","U+001B":"esc","U+0020":"space","U+007F":"del"};var KEY_CODE={8:"backspace",9:"tab",13:"enter",27:"esc",33:"pageup",34:"pagedown",35:"end",36:"home",32:"space",37:"left",38:"up",39:"right",40:"down",46:"del",106:"*"};var MODIFIER_KEYS={shift:"shiftKey",ctrl:"ctrlKey",alt:"altKey",meta:"metaKey"};var KEY_CHAR=/[a-z0-9*]/;var IDENT_CHAR=/U\+/;var ARROW_KEY=/^arrow/;var SPACE_KEY=/^space(bar)?/;var ESC_KEY=/^escape$/;function transformKey(key,noSpecialChars){var validKey="";if(key){var lKey=key.toLowerCase();if(lKey===" "||SPACE_KEY.test(lKey)){validKey="space"}else if(ESC_KEY.test(lKey)){validKey="esc"}else if(lKey.length==1){if(!noSpecialChars||KEY_CHAR.test(lKey)){validKey=lKey}}else if(ARROW_KEY.test(lKey)){validKey=lKey.replace("arrow","")}else if(lKey=="multiply"){validKey="*"}else{validKey=lKey}}return validKey}function transformKeyIdentifier(keyIdent){var validKey="";if(keyIdent){if(keyIdent in KEY_IDENTIFIER){validKey=KEY_IDENTIFIER[keyIdent]}else if(IDENT_CHAR.test(keyIdent)){keyIdent=parseInt(keyIdent.replace("U+","0x"),16);validKey=String.fromCharCode(keyIdent).toLowerCase()}else{validKey=keyIdent.toLowerCase()}}return validKey}function transformKeyCode(keyCode){var validKey="";if(Number(keyCode)){if(keyCode>=65&&keyCode<=90){validKey=String.fromCharCode(32+keyCode)}else if(keyCode>=112&&keyCode<=123){validKey="f"+(keyCode-112)}else if(keyCode>=48&&keyCode<=57){validKey=String(keyCode-48)}else if(keyCode>=96&&keyCode<=105){validKey=String(keyCode-96)}else{validKey=KEY_CODE[keyCode]}}return validKey}function normalizedKeyForEvent(keyEvent,noSpecialChars){if(keyEvent.key){return transformKey(keyEvent.key,noSpecialChars)}if(keyEvent.detail&&keyEvent.detail.key){return transformKey(keyEvent.detail.key,noSpecialChars)}return transformKeyIdentifier(keyEvent.keyIdentifier)||transformKeyCode(keyEvent.keyCode)||""}function keyComboMatchesEvent(keyCombo,event){var keyEvent=normalizedKeyForEvent(event,keyCombo.hasModifiers);return keyEvent===keyCombo.key&&(!keyCombo.hasModifiers||!!event.shiftKey===!!keyCombo.shiftKey&&!!event.ctrlKey===!!keyCombo.ctrlKey&&!!event.altKey===!!keyCombo.altKey&&!!event.metaKey===!!keyCombo.metaKey)}function parseKeyComboString(keyComboString){if(keyComboString.length===1){return{combo:keyComboString,key:keyComboString,event:"keydown"}}return keyComboString.split("+").reduce(function(parsedKeyCombo,keyComboPart){var eventParts=keyComboPart.split(":");var keyName=eventParts[0];var event=eventParts[1];if(keyName in MODIFIER_KEYS){parsedKeyCombo[MODIFIER_KEYS[keyName]]=true;parsedKeyCombo.hasModifiers=true}else{parsedKeyCombo.key=keyName;parsedKeyCombo.event=event||"keydown"}return parsedKeyCombo},{combo:keyComboString.split(":").shift()})}function parseEventString(eventString){return eventString.trim().split(" ").map(function(keyComboString){return parseKeyComboString(keyComboString)})}Polymer.IronA11yKeysBehavior={properties:{keyEventTarget:{type:Object,value:function(){return this}},stopKeyboardEventPropagation:{type:Boolean,value:false},_boundKeyHandlers:{type:Array,value:function(){return[]}},_imperativeKeyBindings:{type:Object,value:function(){return{}}}},observers:["_resetKeyEventListeners(keyEventTarget, _boundKeyHandlers)"],keyBindings:{},registered:function(){this._prepKeyBindings()},attached:function(){this._listenKeyEventListeners()},detached:function(){this._unlistenKeyEventListeners()},addOwnKeyBinding:function(eventString,handlerName){this._imperativeKeyBindings[eventString]=handlerName;this._prepKeyBindings();this._resetKeyEventListeners()},removeOwnKeyBindings:function(){this._imperativeKeyBindings={};this._prepKeyBindings();this._resetKeyEventListeners()},keyboardEventMatchesKeys:function(event,eventString){var keyCombos=parseEventString(eventString);for(var i=0;i<keyCombos.length;++i){if(keyComboMatchesEvent(keyCombos[i],event)){return true}}return false},_collectKeyBindings:function(){var keyBindings=this.behaviors.map(function(behavior){return behavior.keyBindings});if(keyBindings.indexOf(this.keyBindings)===-1){keyBindings.push(this.keyBindings)}return keyBindings},_prepKeyBindings:function(){this._keyBindings={};this._collectKeyBindings().forEach(function(keyBindings){for(var eventString in keyBindings){this._addKeyBinding(eventString,keyBindings[eventString])}},this);for(var eventString in this._imperativeKeyBindings){this._addKeyBinding(eventString,this._imperativeKeyBindings[eventString])}for(var eventName in this._keyBindings){this._keyBindings[eventName].sort(function(kb1,kb2){var b1=kb1[0].hasModifiers;var b2=kb2[0].hasModifiers;return b1===b2?0:b1?-1:1})}},_addKeyBinding:function(eventString,handlerName){parseEventString(eventString).forEach(function(keyCombo){this._keyBindings[keyCombo.event]=this._keyBindings[keyCombo.event]||[];this._keyBindings[keyCombo.event].push([keyCombo,handlerName])},this)},_resetKeyEventListeners:function(){this._unlistenKeyEventListeners();if(this.isAttached){this._listenKeyEventListeners()}},_listenKeyEventListeners:function(){if(!this.keyEventTarget){return}Object.keys(this._keyBindings).forEach(function(eventName){var keyBindings=this._keyBindings[eventName];var boundKeyHandler=this._onKeyBindingEvent.bind(this,keyBindings);this._boundKeyHandlers.push([this.keyEventTarget,eventName,boundKeyHandler]);this.keyEventTarget.addEventListener(eventName,boundKeyHandler)},this)},_unlistenKeyEventListeners:function(){var keyHandlerTuple;var keyEventTarget;var eventName;var boundKeyHandler;while(this._boundKeyHandlers.length){keyHandlerTuple=this._boundKeyHandlers.pop();keyEventTarget=keyHandlerTuple[0];eventName=keyHandlerTuple[1];boundKeyHandler=keyHandlerTuple[2];keyEventTarget.removeEventListener(eventName,boundKeyHandler)}},_onKeyBindingEvent:function(keyBindings,event){if(this.stopKeyboardEventPropagation){event.stopPropagation()}if(event.defaultPrevented){return}for(var i=0;i<keyBindings.length;i++){var keyCombo=keyBindings[i][0];var handlerName=keyBindings[i][1];if(keyComboMatchesEvent(keyCombo,event)){this._triggerKeyHandler(keyCombo,handlerName,event);if(event.defaultPrevented){return}}}},_triggerKeyHandler:function(keyCombo,handlerName,keyboardEvent){var detail=Object.create(keyCombo);detail.keyboardEvent=keyboardEvent;var event=new CustomEvent(keyCombo.event,{detail:detail,cancelable:true});this[handlerName].call(this,event);if(event.defaultPrevented){keyboardEvent.preventDefault()}}}})();Polymer.IronScrollTargetBehavior={properties:{scrollTarget:{type:HTMLElement,value:function(){return this._defaultScrollTarget}}},observers:["_scrollTargetChanged(scrollTarget, isAttached)"],_shouldHaveListener:true,_scrollTargetChanged:function(scrollTarget,isAttached){var eventTarget;if(this._oldScrollTarget){this._toggleScrollListener(false,this._oldScrollTarget);this._oldScrollTarget=null}if(!isAttached){return}if(scrollTarget==="document"){this.scrollTarget=this._doc}else if(typeof scrollTarget==="string"){this.scrollTarget=this.domHost?this.domHost.$[scrollTarget]:Polymer.dom(this.ownerDocument).querySelector("#"+scrollTarget)}else if(this._isValidScrollTarget()){this._boundScrollHandler=this._boundScrollHandler||this._scrollHandler.bind(this);this._oldScrollTarget=scrollTarget;this._toggleScrollListener(this._shouldHaveListener,scrollTarget)}},_scrollHandler:function scrollHandler(){},get _defaultScrollTarget(){return this._doc},get _doc(){return this.ownerDocument.documentElement},get _scrollTop(){if(this._isValidScrollTarget()){return this.scrollTarget===this._doc?window.pageYOffset:this.scrollTarget.scrollTop}return 0},get _scrollLeft(){if(this._isValidScrollTarget()){return this.scrollTarget===this._doc?window.pageXOffset:this.scrollTarget.scrollLeft}return 0},set _scrollTop(top){if(this.scrollTarget===this._doc){window.scrollTo(window.pageXOffset,top)}else if(this._isValidScrollTarget()){this.scrollTarget.scrollTop=top}},set _scrollLeft(left){if(this.scrollTarget===this._doc){window.scrollTo(left,window.pageYOffset)}else if(this._isValidScrollTarget()){this.scrollTarget.scrollLeft=left}},scroll:function(left,top){if(this.scrollTarget===this._doc){window.scrollTo(left,top)}else if(this._isValidScrollTarget()){this.scrollTarget.scrollLeft=left;this.scrollTarget.scrollTop=top}},get _scrollTargetWidth(){if(this._isValidScrollTarget()){return this.scrollTarget===this._doc?window.innerWidth:this.scrollTarget.offsetWidth}return 0},get _scrollTargetHeight(){if(this._isValidScrollTarget()){return this.scrollTarget===this._doc?window.innerHeight:this.scrollTarget.offsetHeight}return 0},_isValidScrollTarget:function(){return this.scrollTarget instanceof HTMLElement},_toggleScrollListener:function(yes,scrollTarget){if(!this._boundScrollHandler){return}var eventTarget=scrollTarget===this._doc?window:scrollTarget;if(yes){eventTarget.addEventListener("scroll",this._boundScrollHandler)}else{eventTarget.removeEventListener("scroll",this._boundScrollHandler)}},toggleScrollListener:function(yes){this._shouldHaveListener=yes;this._toggleScrollListener(yes,this.scrollTarget)}};(function(){var IOS=navigator.userAgent.match(/iP(?:hone|ad;(?: U;)? CPU) OS (\d+)/);var IOS_TOUCH_SCROLLING=IOS&&IOS[1]>=8;var DEFAULT_PHYSICAL_COUNT=3;var HIDDEN_Y="-10000px";var ITEM_WIDTH=0;var ITEM_HEIGHT=1;var SECRET_TABINDEX=-100;Polymer({is:"iron-list",properties:{items:{type:Array},maxPhysicalCount:{type:Number,value:500},as:{type:String,value:"item"},indexAs:{type:String,value:"index"},selectedAs:{type:String,value:"selected"},grid:{type:Boolean,value:false,reflectToAttribute:true},selectionEnabled:{type:Boolean,value:false},selectedItem:{type:Object,notify:true},selectedItems:{type:Object,notify:true},multiSelection:{type:Boolean,value:false}},observers:["_itemsChanged(items.*)","_selectionEnabledChanged(selectionEnabled)","_multiSelectionChanged(multiSelection)","_setOverflow(scrollTarget)"],behaviors:[Polymer.Templatizer,Polymer.IronResizableBehavior,Polymer.IronA11yKeysBehavior,Polymer.IronScrollTargetBehavior],keyBindings:{up:"_didMoveUp",down:"_didMoveDown",enter:"_didEnter"},_ratio:.5,_scrollerPaddingTop:0,_scrollPosition:0,_physicalSize:0,_physicalAverage:0,_physicalAverageCount:0,_physicalTop:0,_virtualCount:0,_physicalIndexForKey:null,_estScrollHeight:0,_scrollHeight:0,_viewportHeight:0,_viewportWidth:0,_physicalItems:null,_physicalSizes:null,_firstVisibleIndexVal:null,_lastVisibleIndexVal:null,_collection:null,_maxPages:2,_focusedItem:null,_focusedIndex:-1,_offscreenFocusedItem:null,_focusBackfillItem:null,_itemsPerRow:1,_itemWidth:0,_rowHeight:0,_templateCost:0,get _physicalBottom(){return this._physicalTop+this._physicalSize},get _scrollBottom(){return this._scrollPosition+this._viewportHeight},get _virtualEnd(){return this._virtualStart+this._physicalCount-1},get _hiddenContentSize(){var size=this.grid?this._physicalRows*this._rowHeight:this._physicalSize;return size-this._viewportHeight},get _maxScrollTop(){return this._estScrollHeight-this._viewportHeight+this._scrollerPaddingTop},_minVirtualStart:0,get _maxVirtualStart(){return Math.max(0,this._virtualCount-this._physicalCount)},_virtualStartVal:0,set _virtualStart(val){this._virtualStartVal=Math.min(this._maxVirtualStart,Math.max(this._minVirtualStart,val))},get _virtualStart(){return this._virtualStartVal||0},_physicalStartVal:0,set _physicalStart(val){this._physicalStartVal=val%this._physicalCount;if(this._physicalStartVal<0){this._physicalStartVal=this._physicalCount+this._physicalStartVal}this._physicalEnd=(this._physicalStart+this._physicalCount-1)%this._physicalCount},get _physicalStart(){return this._physicalStartVal||0},_physicalCountVal:0,set _physicalCount(val){this._physicalCountVal=val;this._physicalEnd=(this._physicalStart+this._physicalCount-1)%this._physicalCount},get _physicalCount(){return this._physicalCountVal},_physicalEnd:0,get _optPhysicalSize(){if(this.grid){return this._estRowsInView*this._rowHeight*this._maxPages}return this._viewportHeight*this._maxPages},get _isVisible(){return Boolean(this.offsetWidth||this.offsetHeight)},get firstVisibleIndex(){if(this._firstVisibleIndexVal===null){var physicalOffset=Math.floor(this._physicalTop+this._scrollerPaddingTop);this._firstVisibleIndexVal=this._iterateItems(function(pidx,vidx){physicalOffset+=this._getPhysicalSizeIncrement(pidx);if(physicalOffset>this._scrollPosition){return this.grid?vidx-vidx%this._itemsPerRow:vidx}if(this.grid&&this._virtualCount-1===vidx){return vidx-vidx%this._itemsPerRow}})||0}return this._firstVisibleIndexVal},get lastVisibleIndex(){if(this._lastVisibleIndexVal===null){if(this.grid){var lastIndex=this.firstVisibleIndex+this._estRowsInView*this._itemsPerRow-1;this._lastVisibleIndexVal=Math.min(this._virtualCount,lastIndex)}else{var physicalOffset=this._physicalTop;this._iterateItems(function(pidx,vidx){if(physicalOffset<this._scrollBottom){this._lastVisibleIndexVal=vidx}else{return true}physicalOffset+=this._getPhysicalSizeIncrement(pidx)})}}return this._lastVisibleIndexVal},get _defaultScrollTarget(){return this},get _virtualRowCount(){return Math.ceil(this._virtualCount/this._itemsPerRow)},get _estRowsInView(){return Math.ceil(this._viewportHeight/this._rowHeight)},get _physicalRows(){return Math.ceil(this._physicalCount/this._itemsPerRow)},ready:function(){this.addEventListener("focus",this._didFocus.bind(this),true)},attached:function(){if(this._physicalCount===0){this._debounceTemplate(this._render)}this.listen(this,"iron-resize","_resizeHandler")},detached:function(){this.unlisten(this,"iron-resize","_resizeHandler")},_setOverflow:function(scrollTarget){this.style.webkitOverflowScrolling=scrollTarget===this?"touch":"";this.style.overflow=scrollTarget===this?"auto":""},updateViewportBoundaries:function(){this._scrollerPaddingTop=this.scrollTarget===this?0:parseInt(window.getComputedStyle(this)["padding-top"],10);this._viewportWidth=this.$.items.offsetWidth;this._viewportHeight=this._scrollTargetHeight;this.grid&&this._updateGridMetrics()},_scrollHandler:function(){var scrollTop=Math.max(0,Math.min(this._maxScrollTop,this._scrollTop));var delta=scrollTop-this._scrollPosition;var isScrollingDown=delta>=0;this._scrollPosition=scrollTop;this._firstVisibleIndexVal=null;this._lastVisibleIndexVal=null;if(Math.abs(delta)>this._physicalSize){var idxAdjustment=Math.round(delta/this._physicalAverage)*this._itemsPerRow;this._physicalTop=this._physicalTop+delta;this._virtualStart=this._virtualStart+idxAdjustment;this._physicalStart=this._physicalStart+idxAdjustment;this._update()}else{var reusables=this._getReusables(isScrollingDown);if(isScrollingDown){this._physicalTop=reusables.physicalTop;this._virtualStart=this._virtualStart+reusables.indexes.length;this._physicalStart=this._physicalStart+reusables.indexes.length}else{this._virtualStart=this._virtualStart-reusables.indexes.length;this._physicalStart=this._physicalStart-reusables.indexes.length}if(reusables.indexes.length===0){this._increasePoolIfNeeded()}else{this._update(reusables.indexes,isScrollingDown?null:reusables.indexes)}}},_getReusables:function(fromTop){var ith,lastIth,offsetContent,physicalItemHeight;var idxs=[];var protectedOffsetContent=this._hiddenContentSize*this._ratio;var virtualStart=this._virtualStart;var virtualEnd=this._virtualEnd;var physicalCount=this._physicalCount;var physicalTop=this._physicalTop+this._scrollerPaddingTop;var scrollTop=this._scrollTop;var scrollBottom=this._scrollBottom;if(fromTop){ith=this._physicalStart;lastIth=this._physicalEnd;offsetContent=scrollTop-physicalTop}else{ith=this._physicalEnd;lastIth=this._physicalStart;offsetContent=this._physicalBottom-scrollBottom}while(true){physicalItemHeight=this._getPhysicalSizeIncrement(ith);offsetContent=offsetContent-physicalItemHeight;if(idxs.length>=physicalCount||offsetContent<=protectedOffsetContent){break}if(fromTop){if(virtualEnd+idxs.length+1>=this._virtualCount){break}if(physicalTop+physicalItemHeight>=scrollTop){break}idxs.push(ith);physicalTop=physicalTop+physicalItemHeight;ith=(ith+1)%physicalCount}else{if(virtualStart-idxs.length<=0){break}if(physicalTop+this._physicalSize-physicalItemHeight<=scrollBottom){break}idxs.push(ith);physicalTop=physicalTop-physicalItemHeight;ith=ith===0?physicalCount-1:ith-1}}return{indexes:idxs,physicalTop:physicalTop-this._scrollerPaddingTop}},_update:function(itemSet,movingUp){if(itemSet&&itemSet.length===0){return}this._manageFocus();this._assignModels(itemSet);this._updateMetrics(itemSet);if(movingUp){while(movingUp.length){var idx=movingUp.pop();this._physicalTop-=this._getPhysicalSizeIncrement(idx)}}this._positionItems();this._updateScrollerSize();this._increasePoolIfNeeded()},_createPool:function(size){var physicalItems=new Array(size);this._ensureTemplatized();for(var i=0;i<size;i++){var inst=this.stamp(null);physicalItems[i]=inst.root.querySelector("*");Polymer.dom(this).appendChild(inst.root)}return physicalItems},_increasePoolIfNeeded:function(){if(this._viewportHeight===0){return false}var self=this;var isClientFull=this._physicalBottom>=this._scrollBottom&&this._physicalTop<=this._scrollPosition;if(this._physicalSize>=this._optPhysicalSize&&isClientFull){return false}var maxPoolSize=Math.round(this._physicalCount*.5);if(!isClientFull){this._debounceTemplate(this._increasePool.bind(this,maxPoolSize));return true}this._yield(function(){self._increasePool(Math.min(maxPoolSize,Math.max(1,Math.round(50/self._templateCost))))});return true},_yield:function(cb){var g=window;var handle=g.requestIdleCallback?g.requestIdleCallback(cb):g.setTimeout(cb,16);Polymer.dom.addDebouncer({complete:function(){g.cancelIdleCallback?g.cancelIdleCallback(handle):g.clearTimeout(handle);cb()}})},_increasePool:function(missingItems){var nextPhysicalCount=Math.min(this._physicalCount+missingItems,this._virtualCount-this._virtualStart,Math.max(this.maxPhysicalCount,DEFAULT_PHYSICAL_COUNT));var prevPhysicalCount=this._physicalCount;var delta=nextPhysicalCount-prevPhysicalCount;var ts=window.performance.now();if(delta<=0){return}[].push.apply(this._physicalItems,this._createPool(delta));[].push.apply(this._physicalSizes,new Array(delta));this._physicalCount=prevPhysicalCount+delta;if(this._physicalStart>this._physicalEnd&&this._isIndexRendered(this._focusedIndex)&&this._getPhysicalIndex(this._focusedIndex)<this._physicalEnd){this._physicalStart=this._physicalStart+delta}this._update();this._templateCost=(window.performance.now()-ts)/delta},_render:function(){if(this.isAttached&&this._isVisible){if(this._physicalCount===0){this.updateViewportBoundaries();this._increasePool(DEFAULT_PHYSICAL_COUNT)}else{var reusables=this._getReusables(true);this._physicalTop=reusables.physicalTop;this._virtualStart=this._virtualStart+reusables.indexes.length;this._physicalStart=this._physicalStart+reusables.indexes.length;this._update(reusables.indexes);this._update()}}},_ensureTemplatized:function(){if(!this.ctor){var props={};props.__key__=true;props[this.as]=true;props[this.indexAs]=true;props[this.selectedAs]=true;props.tabIndex=true;this._instanceProps=props;this._userTemplate=Polymer.dom(this).querySelector("template");if(this._userTemplate){this.templatize(this._userTemplate)}else{console.warn("iron-list requires a template to be provided in light-dom")}}},_getStampedChildren:function(){return this._physicalItems},_forwardInstancePath:function(inst,path,value){if(path.indexOf(this.as+".")===0){this.notifyPath("items."+inst.__key__+"."+path.slice(this.as.length+1),value)}},_forwardParentProp:function(prop,value){if(this._physicalItems){this._physicalItems.forEach(function(item){item._templateInstance[prop]=value},this)}},_forwardParentPath:function(path,value){if(this._physicalItems){this._physicalItems.forEach(function(item){item._templateInstance.notifyPath(path,value,true)},this)}},_forwardItemPath:function(path,value){if(!this._physicalIndexForKey){return}var dot=path.indexOf(".");var key=path.substring(0,dot<0?path.length:dot);var idx=this._physicalIndexForKey[key];var offscreenItem=this._offscreenFocusedItem;var el=offscreenItem&&offscreenItem._templateInstance.__key__===key?offscreenItem:this._physicalItems[idx];if(!el||el._templateInstance.__key__!==key){return}if(dot>=0){path=this.as+"."+path.substring(dot+1);el._templateInstance.notifyPath(path,value,true)}else{var currentItem=el._templateInstance[this.as];if(Array.isArray(this.selectedItems)){for(var i=0;i<this.selectedItems.length;i++){if(this.selectedItems[i]===currentItem){this.set("selectedItems."+i,value);break}}}else if(this.selectedItem===currentItem){this.set("selectedItem",value)}el._templateInstance[this.as]=value}},_itemsChanged:function(change){if(change.path==="items"){this._virtualStart=0;this._physicalTop=0;this._virtualCount=this.items?this.items.length:0;this._collection=this.items?Polymer.Collection.get(this.items):null;this._physicalIndexForKey={};this._firstVisibleIndexVal=null;this._lastVisibleIndexVal=null;this._physicalCount=this._physicalCount||0;this._physicalItems=this._physicalItems||[];this._physicalSizes=this._physicalSizes||[];this._physicalStart=0;this._resetScrollPosition(0);this._removeFocusedItem();this._debounceTemplate(this._render)}else if(change.path==="items.splices"){this._adjustVirtualIndex(change.value.indexSplices);this._virtualCount=this.items?this.items.length:0;this._debounceTemplate(this._render)}else{this._forwardItemPath(change.path.split(".").slice(1).join("."),change.value)}},_adjustVirtualIndex:function(splices){splices.forEach(function(splice){splice.removed.forEach(this._removeItem,this);if(splice.index<this._virtualStart){var delta=Math.max(splice.addedCount-splice.removed.length,splice.index-this._virtualStart);this._virtualStart=this._virtualStart+delta;if(this._focusedIndex>=0){this._focusedIndex=this._focusedIndex+delta}}},this)},_removeItem:function(item){this.$.selector.deselect(item);if(this._focusedItem&&this._focusedItem._templateInstance[this.as]===item){this._removeFocusedItem()}},_iterateItems:function(fn,itemSet){var pidx,vidx,rtn,i;if(arguments.length===2&&itemSet){for(i=0;i<itemSet.length;i++){pidx=itemSet[i];vidx=this._computeVidx(pidx);if((rtn=fn.call(this,pidx,vidx))!=null){return rtn}}}else{pidx=this._physicalStart;vidx=this._virtualStart;for(;pidx<this._physicalCount;pidx++,vidx++){if((rtn=fn.call(this,pidx,vidx))!=null){return rtn}}for(pidx=0;pidx<this._physicalStart;pidx++,vidx++){if((rtn=fn.call(this,pidx,vidx))!=null){return rtn}}}},_computeVidx:function(pidx){if(pidx>=this._physicalStart){return this._virtualStart+(pidx-this._physicalStart)}return this._virtualStart+(this._physicalCount-this._physicalStart)+pidx},_assignModels:function(itemSet){this._iterateItems(function(pidx,vidx){var el=this._physicalItems[pidx];var inst=el._templateInstance;var item=this.items&&this.items[vidx];if(item!=null){inst[this.as]=item;inst.__key__=this._collection.getKey(item);inst[this.selectedAs]=this.$.selector.isSelected(item);inst[this.indexAs]=vidx;inst.tabIndex=this._focusedIndex===vidx?0:-1;this._physicalIndexForKey[inst.__key__]=pidx;el.removeAttribute("hidden")}else{inst.__key__=null;el.setAttribute("hidden","")}},itemSet)},_updateMetrics:function(itemSet){Polymer.dom.flush();var newPhysicalSize=0;var oldPhysicalSize=0;var prevAvgCount=this._physicalAverageCount;var prevPhysicalAvg=this._physicalAverage;this._iterateItems(function(pidx,vidx){oldPhysicalSize+=this._physicalSizes[pidx]||0;this._physicalSizes[pidx]=this._physicalItems[pidx].offsetHeight;newPhysicalSize+=this._physicalSizes[pidx];this._physicalAverageCount+=this._physicalSizes[pidx]?1:0},itemSet);if(this.grid){this._updateGridMetrics();this._physicalSize=Math.ceil(this._physicalCount/this._itemsPerRow)*this._rowHeight}else{this._physicalSize=this._physicalSize+newPhysicalSize-oldPhysicalSize}if(this._physicalAverageCount!==prevAvgCount){this._physicalAverage=Math.round((prevPhysicalAvg*prevAvgCount+newPhysicalSize)/this._physicalAverageCount)}},_updateGridMetrics:function(){this._itemWidth=this._physicalCount>0?this._physicalItems[0].getBoundingClientRect().width:200;this._rowHeight=this._physicalCount>0?this._physicalItems[0].offsetHeight:200;this._itemsPerRow=this._itemWidth?Math.floor(this._viewportWidth/this._itemWidth):this._itemsPerRow},_positionItems:function(){this._adjustScrollPosition();var y=this._physicalTop;if(this.grid){var totalItemWidth=this._itemsPerRow*this._itemWidth;var rowOffset=(this._viewportWidth-totalItemWidth)/2;this._iterateItems(function(pidx,vidx){var modulus=vidx%this._itemsPerRow;var x=Math.floor(modulus*this._itemWidth+rowOffset);this.translate3d(x+"px",y+"px",0,this._physicalItems[pidx]);if(this._shouldRenderNextRow(vidx)){y+=this._rowHeight}})}else{this._iterateItems(function(pidx,vidx){this.translate3d(0,y+"px",0,this._physicalItems[pidx]);y+=this._physicalSizes[pidx]})}},_getPhysicalSizeIncrement:function(pidx){if(!this.grid){return this._physicalSizes[pidx]}if(this._computeVidx(pidx)%this._itemsPerRow!==this._itemsPerRow-1){return 0}return this._rowHeight},_shouldRenderNextRow:function(vidx){return vidx%this._itemsPerRow===this._itemsPerRow-1},_adjustScrollPosition:function(){var deltaHeight=this._virtualStart===0?this._physicalTop:Math.min(this._scrollPosition+this._physicalTop,0);if(deltaHeight){this._physicalTop=this._physicalTop-deltaHeight;if(!IOS_TOUCH_SCROLLING&&this._physicalTop!==0){this._resetScrollPosition(this._scrollTop-deltaHeight)}}},_resetScrollPosition:function(pos){if(this.scrollTarget){this._scrollTop=pos;this._scrollPosition=this._scrollTop}},_updateScrollerSize:function(forceUpdate){if(this.grid){this._estScrollHeight=this._virtualRowCount*this._rowHeight}else{this._estScrollHeight=this._physicalBottom+Math.max(this._virtualCount-this._physicalCount-this._virtualStart,0)*this._physicalAverage}forceUpdate=forceUpdate||this._scrollHeight===0;forceUpdate=forceUpdate||this._scrollPosition>=this._estScrollHeight-this._physicalSize;forceUpdate=forceUpdate||this.grid&&this.$.items.style.height<this._estScrollHeight;if(forceUpdate||Math.abs(this._estScrollHeight-this._scrollHeight)>=this._optPhysicalSize){this.$.items.style.height=this._estScrollHeight+"px";this._scrollHeight=this._estScrollHeight}},scrollToItem:function(item){return this.scrollToIndex(this.items.indexOf(item))},scrollToIndex:function(idx){if(typeof idx!=="number"||idx<0||idx>this.items.length-1){return}Polymer.dom.flush();if(this._physicalCount===0){return}idx=Math.min(Math.max(idx,0),this._virtualCount-1);if(!this._isIndexRendered(idx)||idx>=this._maxVirtualStart){this._virtualStart=this.grid?idx-this._itemsPerRow*2:idx-1}this._manageFocus();this._assignModels();this._updateMetrics();this._physicalTop=Math.floor(this._virtualStart/this._itemsPerRow)*this._physicalAverage;var currentTopItem=this._physicalStart;var currentVirtualItem=this._virtualStart;var targetOffsetTop=0;var hiddenContentSize=this._hiddenContentSize;while(currentVirtualItem<idx&&targetOffsetTop<=hiddenContentSize){targetOffsetTop=targetOffsetTop+this._getPhysicalSizeIncrement(currentTopItem);currentTopItem=(currentTopItem+1)%this._physicalCount;currentVirtualItem++}this._updateScrollerSize(true);this._positionItems();this._resetScrollPosition(this._physicalTop+this._scrollerPaddingTop+targetOffsetTop);this._increasePoolIfNeeded();this._firstVisibleIndexVal=null;this._lastVisibleIndexVal=null},_resetAverage:function(){this._physicalAverage=0;this._physicalAverageCount=0},_resizeHandler:function(){var delta=Math.abs(this._viewportHeight-this._scrollTargetHeight);if(IOS&&delta>0&&delta<100){return}Polymer.dom.addDebouncer(this.debounce("_debounceTemplate",function(){this.updateViewportBoundaries();this._render();if(this._isVisible){this.toggleScrollListener(true);if(this._physicalCount>0){this._resetAverage();this.scrollToIndex(this.firstVisibleIndex)}}else{this.toggleScrollListener(false)}}.bind(this),1))},_getModelFromItem:function(item){var key=this._collection.getKey(item);var pidx=this._physicalIndexForKey[key];if(pidx!=null){return this._physicalItems[pidx]._templateInstance}return null},_getNormalizedItem:function(item){if(this._collection.getKey(item)===undefined){if(typeof item==="number"){item=this.items[item];if(!item){throw new RangeError("<item> not found")}return item}throw new TypeError("<item> should be a valid item")}return item},selectItem:function(item){item=this._getNormalizedItem(item);var model=this._getModelFromItem(item);if(!this.multiSelection&&this.selectedItem){this.deselectItem(this.selectedItem)}if(model){model[this.selectedAs]=true}this.$.selector.select(item);this.updateSizeForItem(item)},deselectItem:function(item){item=this._getNormalizedItem(item);var model=this._getModelFromItem(item);if(model){model[this.selectedAs]=false}this.$.selector.deselect(item);this.updateSizeForItem(item)},toggleSelectionForItem:function(item){item=this._getNormalizedItem(item);if(this.$.selector.isSelected(item)){this.deselectItem(item)}else{this.selectItem(item)}},clearSelection:function(){function unselect(item){var model=this._getModelFromItem(item);if(model){model[this.selectedAs]=false}}if(Array.isArray(this.selectedItems)){this.selectedItems.forEach(unselect,this)}else if(this.selectedItem){unselect.call(this,this.selectedItem)}this.$.selector.clearSelection()},_selectionEnabledChanged:function(selectionEnabled){var handler=selectionEnabled?this.listen:this.unlisten;handler.call(this,this,"tap","_selectionHandler")},_selectionHandler:function(e){var model=this.modelForElement(e.target);if(!model){return}var modelTabIndex,activeElTabIndex;var target=Polymer.dom(e).path[0];var activeEl=Polymer.dom(this.domHost?this.domHost.root:document).activeElement;var physicalItem=this._physicalItems[this._getPhysicalIndex(model[this.indexAs])]; + +if(target.localName==="input"||target.localName==="button"||target.localName==="select"){return}modelTabIndex=model.tabIndex;model.tabIndex=SECRET_TABINDEX;activeElTabIndex=activeEl?activeEl.tabIndex:-1;model.tabIndex=modelTabIndex;if(activeEl&&physicalItem!==activeEl&&physicalItem.contains(activeEl)&&activeElTabIndex!==SECRET_TABINDEX){return}this.toggleSelectionForItem(model[this.as])},_multiSelectionChanged:function(multiSelection){this.clearSelection();this.$.selector.multi=multiSelection},updateSizeForItem:function(item){item=this._getNormalizedItem(item);var key=this._collection.getKey(item);var pidx=this._physicalIndexForKey[key];if(pidx!=null){this._updateMetrics([pidx]);this._positionItems()}},_manageFocus:function(){var fidx=this._focusedIndex;if(fidx>=0&&fidx<this._virtualCount){if(this._isIndexRendered(fidx)){this._restoreFocusedItem()}else{this._createFocusBackfillItem()}}else if(this._virtualCount>0&&this._physicalCount>0){this._focusedIndex=this._virtualStart;this._focusedItem=this._physicalItems[this._physicalStart]}},_isIndexRendered:function(idx){return idx>=this._virtualStart&&idx<=this._virtualEnd},_isIndexVisible:function(idx){return idx>=this.firstVisibleIndex&&idx<=this.lastVisibleIndex},_getPhysicalIndex:function(idx){return this._physicalIndexForKey[this._collection.getKey(this._getNormalizedItem(idx))]},_focusPhysicalItem:function(idx){if(idx<0||idx>=this._virtualCount){return}this._restoreFocusedItem();if(!this._isIndexRendered(idx)){this.scrollToIndex(idx)}var physicalItem=this._physicalItems[this._getPhysicalIndex(idx)];var model=physicalItem._templateInstance;var focusable;model.tabIndex=SECRET_TABINDEX;if(physicalItem.tabIndex===SECRET_TABINDEX){focusable=physicalItem}if(!focusable){focusable=Polymer.dom(physicalItem).querySelector('[tabindex="'+SECRET_TABINDEX+'"]')}model.tabIndex=0;this._focusedIndex=idx;focusable&&focusable.focus()},_removeFocusedItem:function(){if(this._offscreenFocusedItem){Polymer.dom(this).removeChild(this._offscreenFocusedItem)}this._offscreenFocusedItem=null;this._focusBackfillItem=null;this._focusedItem=null;this._focusedIndex=-1},_createFocusBackfillItem:function(){var fidx=this._focusedIndex;var pidx=this._getPhysicalIndex(fidx);if(this._offscreenFocusedItem||pidx==null||fidx<0){return}if(!this._focusBackfillItem){var stampedTemplate=this.stamp(null);this._focusBackfillItem=stampedTemplate.root.querySelector("*");Polymer.dom(this).appendChild(stampedTemplate.root)}this._offscreenFocusedItem=this._physicalItems[pidx];this._offscreenFocusedItem._templateInstance.tabIndex=0;this._physicalItems[pidx]=this._focusBackfillItem;this.translate3d(0,HIDDEN_Y,0,this._offscreenFocusedItem)},_restoreFocusedItem:function(){var pidx,fidx=this._focusedIndex;if(!this._offscreenFocusedItem||this._focusedIndex<0){return}this._assignModels();pidx=this._getPhysicalIndex(fidx);if(pidx!=null){this._focusBackfillItem=this._physicalItems[pidx];this._focusBackfillItem._templateInstance.tabIndex=-1;this._physicalItems[pidx]=this._offscreenFocusedItem;this._offscreenFocusedItem=null;this.translate3d(0,HIDDEN_Y,0,this._focusBackfillItem)}},_didFocus:function(e){var targetModel=this.modelForElement(e.target);var focusedModel=this._focusedItem?this._focusedItem._templateInstance:null;var hasOffscreenFocusedItem=this._offscreenFocusedItem!==null;var fidx=this._focusedIndex;if(!targetModel||!focusedModel){return}if(focusedModel===targetModel){if(!this._isIndexVisible(fidx)){this.scrollToIndex(fidx)}}else{this._restoreFocusedItem();focusedModel.tabIndex=-1;targetModel.tabIndex=0;fidx=targetModel[this.indexAs];this._focusedIndex=fidx;this._focusedItem=this._physicalItems[this._getPhysicalIndex(fidx)];if(hasOffscreenFocusedItem&&!this._offscreenFocusedItem){this._update()}}},_didMoveUp:function(){this._focusPhysicalItem(this._focusedIndex-1)},_didMoveDown:function(e){e.detail.keyboardEvent.preventDefault();this._focusPhysicalItem(this._focusedIndex+1)},_didEnter:function(e){this._focusPhysicalItem(this._focusedIndex);this._selectionHandler(e.detail.keyboardEvent)}})})(); // Copyright 2015 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. @@ -48,7 +49,7 @@ // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -var CrSearchFieldBehavior={properties:{label:{type:String,value:""},clearLabel:{type:String,value:""},showingSearch:{type:Boolean,value:false,notify:true,observer:"showingSearchChanged_",reflectToAttribute:true},lastValue_:{type:String,value:""}},getSearchInput:function(){},getValue:function(){return this.getSearchInput().value},setValue:function(value){this.getSearchInput().bindValue=value;this.onValueChanged_(value)},showAndFocus:function(){this.showingSearch=true;this.focus_()},focus_:function(){this.getSearchInput().focus()},onSearchTermSearch:function(){this.onValueChanged_(this.getValue())},onValueChanged_:function(newValue){if(newValue==this.lastValue_)return;this.lastValue_=newValue;this.fire("search-changed",newValue)},onSearchTermKeydown:function(e){if(e.key=="Escape")this.showingSearch=false},showingSearchChanged_:function(current,previous){if(previous==undefined)return;if(this.showingSearch){this.focus_();return}this.setValue("");this.getSearchInput().blur()}}; +var CrSearchFieldBehavior={properties:{label:{type:String,value:""},clearLabel:{type:String,value:""},showingSearch:{type:Boolean,value:false,notify:true,observer:"showingSearchChanged_",reflectToAttribute:true},lastValue_:{type:String,value:""}},getSearchInput:function(){},getValue:function(){return this.getSearchInput().value},setValue:function(value,opt_noEvent){this.getSearchInput().bindValue=value;this.onValueChanged_(value,!!opt_noEvent)},showAndFocus:function(){this.showingSearch=true;this.focus_()},focus_:function(){this.getSearchInput().focus()},onSearchTermSearch:function(){this.onValueChanged_(this.getValue(),false)},onValueChanged_:function(newValue,noEvent){if(newValue==this.lastValue_)return;this.lastValue_=newValue;if(!noEvent)this.fire("search-changed",newValue)},onSearchTermKeydown:function(e){if(e.key=="Escape")this.showingSearch=false},showingSearchChanged_:function(current,previous){if(previous==undefined)return;if(this.showingSearch){this.focus_();return}this.setValue("");this.getSearchInput().blur()}}; // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file.
diff --git a/chrome/browser/resources/md_history/app.crisper.js b/chrome/browser/resources/md_history/app.crisper.js index eb948b0..88c2cf5 100644 --- a/chrome/browser/resources/md_history/app.crisper.js +++ b/chrome/browser/resources/md_history/app.crisper.js
@@ -71,7 +71,7 @@ // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -Polymer({is:"history-list-container",properties:{selectedPage_:String,grouped:Boolean,groupedRange:{type:Number,observer:"groupedRangeChanged_"},queryState:Object,queryResult:Object},observers:["searchTermChanged_(queryState.searchTerm)"],listeners:{"history-list-scrolled":"closeMenu_","load-more-history":"loadMoreHistory_","toggle-menu":"toggleMenu_"},historyResult:function(info,results){this.initializeResults_(info,results);this.closeMenu_();if(info.term&&!this.queryState.incremental){Polymer.IronA11yAnnouncer.requestAvailability();this.fire("iron-announce",{text:md_history.HistoryItem.searchResultsTitle(results.length,info.term)})}if(this.selectedPage_=="grouped-list"){this.$$("#grouped-list").historyData=results;return}var list=this.$["infinite-list"];list.addNewResults(results,this.queryState.incremental);if(info.finished)list.disableResultLoading()},queryHistory:function(incremental){var queryState=this.queryState;var noResults=!this.queryResult||this.queryResult.results==null;if(queryState.queryingDisabled||!this.queryState.searchTerm&&noResults){return}var dialog=this.$.dialog.getIfExists();if(!incremental&&dialog&&dialog.open)dialog.close();this.set("queryState.querying",true);this.set("queryState.incremental",incremental);var lastVisitTime=0;if(incremental){var lastVisit=this.queryResult.results.slice(-1)[0];lastVisitTime=lastVisit?Math.floor(lastVisit.time):0}var maxResults=this.groupedRange==HistoryRange.ALL_TIME?RESULTS_PER_PAGE:0;chrome.send("queryHistory",[queryState.searchTerm,queryState.groupedOffset,queryState.range,lastVisitTime,maxResults])},historyDeleted:function(){if(this.getSelectedItemCount()>0)return;this.queryHistory(false)},getContentScrollTarget:function(){return this.getSelectedList_()},getSelectedItemCount:function(){return this.getSelectedList_().selectedPaths.size},unselectAllItems:function(count){var selectedList=this.getSelectedList_();if(selectedList)selectedList.unselectAllItems(count)},deleteSelectedWithPrompt:function(){if(!loadTimeData.getBoolean("allowDeletingHistory"))return;var browserService=md_history.BrowserService.getInstance();browserService.recordAction("RemoveSelected");if(this.queryState.searchTerm!="")browserService.recordAction("SearchResultRemove");this.$.dialog.get().showModal()},groupedRangeChanged_:function(range,oldRange){this.selectedPage_=range==HistoryRange.ALL_TIME?"infinite-list":"grouped-list";if(oldRange==undefined)return;this.queryHistory(false);this.fire("history-view-changed")},searchTermChanged_:function(){this.queryHistory(false);if(this.queryState.searchTerm)md_history.BrowserService.getInstance().recordAction("Search")},loadMoreHistory_:function(){this.queryHistory(true)},initializeResults_:function(info,results){if(results.length==0)return;var currentDate=results[0].dateRelativeDay;for(var i=0;i<results.length;i++){results[i].selected=false;results[i].readableTimestamp=info.term==""?results[i].dateTimeOfDay:results[i].dateShort;if(results[i].dateRelativeDay!=currentDate){currentDate=results[i].dateRelativeDay}}},onDialogConfirmTap_:function(){md_history.BrowserService.getInstance().recordAction("ConfirmRemoveSelected");this.getSelectedList_().deleteSelected();var dialog=assert(this.$.dialog.getIfExists());dialog.close()},onDialogCancelTap_:function(){md_history.BrowserService.getInstance().recordAction("CancelRemoveSelected");var dialog=assert(this.$.dialog.getIfExists());dialog.close()},closeMenu_:function(){var menu=this.$.sharedMenu.getIfExists();if(menu)menu.closeMenu()},toggleMenu_:function(e){var target=e.detail.target;var menu=this.$.sharedMenu.get();menu.toggleMenu(target,e.detail)},onMoreFromSiteTap_:function(){md_history.BrowserService.getInstance().recordAction("EntryMenuShowMoreFromSite");var menu=assert(this.$.sharedMenu.getIfExists());this.set("queryState.searchTerm",menu.itemData.item.domain);menu.closeMenu()},onRemoveFromHistoryTap_:function(){var browserService=md_history.BrowserService.getInstance();browserService.recordAction("EntryMenuRemoveFromHistory");var menu=assert(this.$.sharedMenu.getIfExists());var itemData=menu.itemData;browserService.deleteItems([itemData.item]).then(function(items){this.fire("unselect-all");this.getSelectedList_().removeItemsByPath([itemData.path]);var index=itemData.index;if(index==undefined)return;var browserService=md_history.BrowserService.getInstance();browserService.recordHistogram("HistoryPage.RemoveEntryPosition",Math.min(index,UMA_MAX_BUCKET_VALUE),UMA_MAX_BUCKET_VALUE);if(index<=UMA_MAX_SUBSET_BUCKET_VALUE){browserService.recordHistogram("HistoryPage.RemoveEntryPositionSubset",index,UMA_MAX_SUBSET_BUCKET_VALUE)}}.bind(this));menu.closeMenu()},getSelectedList_:function(){return this.$.content.selectedItem}});(function(){"use strict";Polymer({is:"iron-location",properties:{path:{type:String,notify:true,value:function(){return window.decodeURIComponent(window.location.pathname)}},query:{type:String,notify:true,value:function(){return window.decodeURIComponent(window.location.search.slice(1))}},hash:{type:String,notify:true,value:function(){return window.decodeURIComponent(window.location.hash.slice(1))}},dwellTime:{type:Number,value:2e3},urlSpaceRegex:{type:String,value:""},_urlSpaceRegExp:{computed:"_makeRegExp(urlSpaceRegex)"},_lastChangedAt:{type:Number},_initialized:{type:Boolean,value:false}},hostAttributes:{hidden:true},observers:["_updateUrl(path, query, hash)"],attached:function(){this.listen(window,"hashchange","_hashChanged");this.listen(window,"location-changed","_urlChanged");this.listen(window,"popstate","_urlChanged");this.listen(document.body,"click","_globalOnClick");this._lastChangedAt=window.performance.now()-(this.dwellTime-200);this._initialized=true;this._urlChanged()},detached:function(){this.unlisten(window,"hashchange","_hashChanged");this.unlisten(window,"location-changed","_urlChanged");this.unlisten(window,"popstate","_urlChanged");this.unlisten(document.body,"click","_globalOnClick");this._initialized=false},_hashChanged:function(){this.hash=window.decodeURIComponent(window.location.hash.substring(1))},_urlChanged:function(){this._dontUpdateUrl=true;this._hashChanged();this.path=window.decodeURIComponent(window.location.pathname);this.query=window.decodeURIComponent(window.location.search.substring(1));this._dontUpdateUrl=false;this._updateUrl()},_getUrl:function(){var partiallyEncodedPath=window.encodeURI(this.path).replace(/\#/g,"%23").replace(/\?/g,"%3F");var partiallyEncodedQuery="";if(this.query){partiallyEncodedQuery="?"+window.encodeURI(this.query).replace(/\#/g,"%23")}var partiallyEncodedHash="";if(this.hash){partiallyEncodedHash="#"+window.encodeURI(this.hash)}return partiallyEncodedPath+partiallyEncodedQuery+partiallyEncodedHash},_updateUrl:function(){if(this._dontUpdateUrl||!this._initialized){return}if(this.path===window.decodeURIComponent(window.location.pathname)&&this.query===window.decodeURIComponent(window.location.search.substring(1))&&this.hash===window.decodeURIComponent(window.location.hash.substring(1))){return}var newUrl=this._getUrl();var fullNewUrl=new URL(newUrl,window.location.protocol+"//"+window.location.host).href;var now=window.performance.now();var shouldReplace=this._lastChangedAt+this.dwellTime>now;this._lastChangedAt=now;if(shouldReplace){window.history.replaceState({},"",fullNewUrl)}else{window.history.pushState({},"",fullNewUrl)}this.fire("location-changed",{},{node:window})},_globalOnClick:function(event){if(event.defaultPrevented){return}var href=this._getSameOriginLinkHref(event);if(!href){return}event.preventDefault();if(href===window.location.href){return}window.history.pushState({},"",href);this.fire("location-changed",{},{node:window})},_getSameOriginLinkHref:function(event){if(event.button!==0){return null}if(event.metaKey||event.ctrlKey){return null}var eventPath=Polymer.dom(event).path;var anchor=null;for(var i=0;i<eventPath.length;i++){var element=eventPath[i];if(element.tagName==="A"&&element.href){anchor=element;break}}if(!anchor){return null}if(anchor.target==="_blank"){return null}if((anchor.target==="_top"||anchor.target==="_parent")&&window.top!==window){return null}var href=anchor.href;var url;if(document.baseURI!=null){url=new URL(href,document.baseURI)}else{url=new URL(href)}var origin;if(window.location.origin){origin=window.location.origin}else{origin=window.location.protocol+"//"+window.location.hostname;if(window.location.port){origin+=":"+window.location.port}}if(url.origin!==origin){return null}var normalizedHref=url.pathname+url.search+url.hash;if(this._urlSpaceRegExp&&!this._urlSpaceRegExp.test(normalizedHref)){return null}var fullNormalizedHref=new URL(normalizedHref,window.location.href).href;return fullNormalizedHref},_makeRegExp:function(urlSpaceRegex){return RegExp(urlSpaceRegex)}})})();"use strict";Polymer({is:"iron-query-params",properties:{paramsString:{type:String,notify:true,observer:"paramsStringChanged"},paramsObject:{type:Object,notify:true,value:function(){return{}}},_dontReact:{type:Boolean,value:false}},hostAttributes:{hidden:true},observers:["paramsObjectChanged(paramsObject.*)"],paramsStringChanged:function(){this._dontReact=true;this.paramsObject=this._decodeParams(this.paramsString);this._dontReact=false},paramsObjectChanged:function(){if(this._dontReact){return}this.paramsString=this._encodeParams(this.paramsObject)},_encodeParams:function(params){var encodedParams=[];for(var key in params){var value=params[key];if(value===""){encodedParams.push(encodeURIComponent(key))}else if(value){encodedParams.push(encodeURIComponent(key)+"="+encodeURIComponent(value.toString()))}}return encodedParams.join("&")},_decodeParams:function(paramString){var params={};paramString=(paramString||"").replace(/\+/g,"%20");var paramList=paramString.split("&");for(var i=0;i<paramList.length;i++){var param=paramList[i].split("=");if(param[0]){params[decodeURIComponent(param[0])]=decodeURIComponent(param[1]||"")}}return params}}); +Polymer({is:"history-list-container",properties:{selectedPage_:String,grouped:Boolean,groupedRange:{type:Number,observer:"groupedRangeChanged_"},queryState:Object,queryResult:Object},observers:["searchTermChanged_(queryState.searchTerm)"],listeners:{"history-list-scrolled":"closeMenu_","load-more-history":"loadMoreHistory_","toggle-menu":"toggleMenu_"},historyResult:function(info,results){this.initializeResults_(info,results);this.closeMenu_();if(info.term&&!this.queryState.incremental){Polymer.IronA11yAnnouncer.requestAvailability();this.fire("iron-announce",{text:md_history.HistoryItem.searchResultsTitle(results.length,info.term)})}if(this.selectedPage_=="grouped-list"){this.$$("#grouped-list").historyData=results;return}var list=this.$["infinite-list"];list.addNewResults(results,this.queryState.incremental);if(info.finished)list.disableResultLoading()},queryHistory:function(incremental){var queryState=this.queryState;var noResults=!this.queryResult||this.queryResult.results==null;if(queryState.queryingDisabled||!this.queryState.searchTerm&&noResults){return}var dialog=this.$.dialog.getIfExists();if(!incremental&&dialog&&dialog.open)dialog.close();this.set("queryState.querying",true);this.set("queryState.incremental",incremental);var lastVisitTime=0;if(incremental){var lastVisit=this.queryResult.results.slice(-1)[0];lastVisitTime=lastVisit?Math.floor(lastVisit.time):0}var maxResults=this.groupedRange==HistoryRange.ALL_TIME?RESULTS_PER_PAGE:0;chrome.send("queryHistory",[queryState.searchTerm,queryState.groupedOffset,queryState.range,lastVisitTime,maxResults])},historyDeleted:function(){if(this.getSelectedItemCount()>0)return;this.queryHistory(false)},getContentScrollTarget:function(){return this.getSelectedList_()},getSelectedItemCount:function(){return this.getSelectedList_().selectedPaths.size},unselectAllItems:function(count){var selectedList=this.getSelectedList_();if(selectedList)selectedList.unselectAllItems(count)},deleteSelectedWithPrompt:function(){if(!loadTimeData.getBoolean("allowDeletingHistory"))return;var browserService=md_history.BrowserService.getInstance();browserService.recordAction("RemoveSelected");if(this.queryState.searchTerm!="")browserService.recordAction("SearchResultRemove");this.$.dialog.get().showModal();this.$$(".action-button").focus()},groupedRangeChanged_:function(range,oldRange){this.selectedPage_=range==HistoryRange.ALL_TIME?"infinite-list":"grouped-list";if(oldRange==undefined)return;this.queryHistory(false);this.fire("history-view-changed")},searchTermChanged_:function(){this.queryHistory(false);if(this.queryState.searchTerm)md_history.BrowserService.getInstance().recordAction("Search")},loadMoreHistory_:function(){this.queryHistory(true)},initializeResults_:function(info,results){if(results.length==0)return;var currentDate=results[0].dateRelativeDay;for(var i=0;i<results.length;i++){results[i].selected=false;results[i].readableTimestamp=info.term==""?results[i].dateTimeOfDay:results[i].dateShort;if(results[i].dateRelativeDay!=currentDate){currentDate=results[i].dateRelativeDay}}},onDialogConfirmTap_:function(){md_history.BrowserService.getInstance().recordAction("ConfirmRemoveSelected");this.getSelectedList_().deleteSelected();var dialog=assert(this.$.dialog.getIfExists());dialog.close()},onDialogCancelTap_:function(){md_history.BrowserService.getInstance().recordAction("CancelRemoveSelected");var dialog=assert(this.$.dialog.getIfExists());dialog.close()},closeMenu_:function(){var menu=this.$.sharedMenu.getIfExists();if(menu)menu.closeMenu()},toggleMenu_:function(e){var target=e.detail.target;var menu=this.$.sharedMenu.get();menu.toggleMenu(target,e.detail)},onMoreFromSiteTap_:function(){md_history.BrowserService.getInstance().recordAction("EntryMenuShowMoreFromSite");var menu=assert(this.$.sharedMenu.getIfExists());this.set("queryState.searchTerm",menu.itemData.item.domain);menu.closeMenu()},onRemoveFromHistoryTap_:function(){var browserService=md_history.BrowserService.getInstance();browserService.recordAction("EntryMenuRemoveFromHistory");var menu=assert(this.$.sharedMenu.getIfExists());var itemData=menu.itemData;browserService.deleteItems([itemData.item]).then(function(items){this.fire("unselect-all");this.getSelectedList_().removeItemsByPath([itemData.path]);var index=itemData.index;if(index==undefined)return;var browserService=md_history.BrowserService.getInstance();browserService.recordHistogram("HistoryPage.RemoveEntryPosition",Math.min(index,UMA_MAX_BUCKET_VALUE),UMA_MAX_BUCKET_VALUE);if(index<=UMA_MAX_SUBSET_BUCKET_VALUE){browserService.recordHistogram("HistoryPage.RemoveEntryPositionSubset",index,UMA_MAX_SUBSET_BUCKET_VALUE)}}.bind(this));menu.closeMenu()},getSelectedList_:function(){return this.$.content.selectedItem},canDeleteHistory_:function(){return loadTimeData.getBoolean("allowDeletingHistory")}});(function(){"use strict";Polymer({is:"iron-location",properties:{path:{type:String,notify:true,value:function(){return window.decodeURIComponent(window.location.pathname)}},query:{type:String,notify:true,value:function(){return window.decodeURIComponent(window.location.search.slice(1))}},hash:{type:String,notify:true,value:function(){return window.decodeURIComponent(window.location.hash.slice(1))}},dwellTime:{type:Number,value:2e3},urlSpaceRegex:{type:String,value:""},_urlSpaceRegExp:{computed:"_makeRegExp(urlSpaceRegex)"},_lastChangedAt:{type:Number},_initialized:{type:Boolean,value:false}},hostAttributes:{hidden:true},observers:["_updateUrl(path, query, hash)"],attached:function(){this.listen(window,"hashchange","_hashChanged");this.listen(window,"location-changed","_urlChanged");this.listen(window,"popstate","_urlChanged");this.listen(document.body,"click","_globalOnClick");this._lastChangedAt=window.performance.now()-(this.dwellTime-200);this._initialized=true;this._urlChanged()},detached:function(){this.unlisten(window,"hashchange","_hashChanged");this.unlisten(window,"location-changed","_urlChanged");this.unlisten(window,"popstate","_urlChanged");this.unlisten(document.body,"click","_globalOnClick");this._initialized=false},_hashChanged:function(){this.hash=window.decodeURIComponent(window.location.hash.substring(1))},_urlChanged:function(){this._dontUpdateUrl=true;this._hashChanged();this.path=window.decodeURIComponent(window.location.pathname);this.query=window.decodeURIComponent(window.location.search.substring(1));this._dontUpdateUrl=false;this._updateUrl()},_getUrl:function(){var partiallyEncodedPath=window.encodeURI(this.path).replace(/\#/g,"%23").replace(/\?/g,"%3F");var partiallyEncodedQuery="";if(this.query){partiallyEncodedQuery="?"+window.encodeURI(this.query).replace(/\#/g,"%23")}var partiallyEncodedHash="";if(this.hash){partiallyEncodedHash="#"+window.encodeURI(this.hash)}return partiallyEncodedPath+partiallyEncodedQuery+partiallyEncodedHash},_updateUrl:function(){if(this._dontUpdateUrl||!this._initialized){return}if(this.path===window.decodeURIComponent(window.location.pathname)&&this.query===window.decodeURIComponent(window.location.search.substring(1))&&this.hash===window.decodeURIComponent(window.location.hash.substring(1))){return}var newUrl=this._getUrl();var fullNewUrl=new URL(newUrl,window.location.protocol+"//"+window.location.host).href;var now=window.performance.now();var shouldReplace=this._lastChangedAt+this.dwellTime>now;this._lastChangedAt=now;if(shouldReplace){window.history.replaceState({},"",fullNewUrl)}else{window.history.pushState({},"",fullNewUrl)}this.fire("location-changed",{},{node:window})},_globalOnClick:function(event){if(event.defaultPrevented){return}var href=this._getSameOriginLinkHref(event);if(!href){return}event.preventDefault();if(href===window.location.href){return}window.history.pushState({},"",href);this.fire("location-changed",{},{node:window})},_getSameOriginLinkHref:function(event){if(event.button!==0){return null}if(event.metaKey||event.ctrlKey){return null}var eventPath=Polymer.dom(event).path;var anchor=null;for(var i=0;i<eventPath.length;i++){var element=eventPath[i];if(element.tagName==="A"&&element.href){anchor=element;break}}if(!anchor){return null}if(anchor.target==="_blank"){return null}if((anchor.target==="_top"||anchor.target==="_parent")&&window.top!==window){return null}var href=anchor.href;var url;if(document.baseURI!=null){url=new URL(href,document.baseURI)}else{url=new URL(href)}var origin;if(window.location.origin){origin=window.location.origin}else{origin=window.location.protocol+"//"+window.location.hostname;if(window.location.port){origin+=":"+window.location.port}}if(url.origin!==origin){return null}var normalizedHref=url.pathname+url.search+url.hash;if(this._urlSpaceRegExp&&!this._urlSpaceRegExp.test(normalizedHref)){return null}var fullNormalizedHref=new URL(normalizedHref,window.location.href).href;return fullNormalizedHref},_makeRegExp:function(urlSpaceRegex){return RegExp(urlSpaceRegex)}})})();"use strict";Polymer({is:"iron-query-params",properties:{paramsString:{type:String,notify:true,observer:"paramsStringChanged"},paramsObject:{type:Object,notify:true,value:function(){return{}}},_dontReact:{type:Boolean,value:false}},hostAttributes:{hidden:true},observers:["paramsObjectChanged(paramsObject.*)"],paramsStringChanged:function(){this._dontReact=true;this.paramsObject=this._decodeParams(this.paramsString);this._dontReact=false},paramsObjectChanged:function(){if(this._dontReact){return}this.paramsString=this._encodeParams(this.paramsObject)},_encodeParams:function(params){var encodedParams=[];for(var key in params){var value=params[key];if(value===""){encodedParams.push(encodeURIComponent(key))}else if(value){encodedParams.push(encodeURIComponent(key)+"="+encodeURIComponent(value.toString()))}}return encodedParams.join("&")},_decodeParams:function(paramString){var params={};paramString=(paramString||"").replace(/\+/g,"%20");var paramList=paramString.split("&");for(var i=0;i<paramList.length;i++){var param=paramList[i].split("=");if(param[0]){params[decodeURIComponent(param[0])]=decodeURIComponent(param[1]||"")}}return params}}); // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -83,4 +83,4 @@ // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -cr.define("md_history",function(){var lazyLoadPromise=null;function ensureLazyLoaded(){if(!lazyLoadPromise){lazyLoadPromise=new Promise(function(resolve,reject){Polymer.Base.importHref("chrome://history/lazy_load.html",resolve,reject,true)})}return lazyLoadPromise}return{ensureLazyLoaded:ensureLazyLoaded}});Polymer({is:"history-app",behaviors:[Polymer.IronScrollTargetBehavior],properties:{showSidebarFooter:Boolean,hasSyncedResults:Boolean,selectedPage_:{type:String,observer:"selectedPageChanged_"},grouped_:{type:Boolean,reflectToAttribute:true},queryState_:{type:Object,value:function(){return{incremental:false,querying:true,queryingDisabled:false,_range:HistoryRange.ALL_TIME,searchTerm:"",groupedOffset:0,set range(val){this._range=Number(val)},get range(){return this._range}}}},queryResult_:{type:Object,value:function(){return{info:null,results:null,sessionList:null}}},hasDrawer_:Boolean,isUserSignedIn_:{type:Boolean,value:loadTimeData.getBoolean("isUserSignedIn")},toolbarShadow_:{type:Boolean,reflectToAttribute:true,notify:true},showMenuPromo_:{type:Boolean,value:function(){return loadTimeData.getBoolean("showMenuPromo")}}},listeners:{"cr-toolbar-menu-promo-close":"onCrToolbarMenuPromoClose_","cr-toolbar-menu-promo-shown":"onCrToolbarMenuPromoShown_","cr-toolbar-menu-tap":"onCrToolbarMenuTap_","delete-selected":"deleteSelected","history-checkbox-select":"checkboxSelected","history-close-drawer":"closeDrawer_","history-view-changed":"historyViewChanged_","opened-changed":"onOpenedChanged_","unselect-all":"unselectAll"},ready:function(){this.grouped_=loadTimeData.getBoolean("groupByDomain");cr.ui.decorate("command",cr.ui.Command);document.addEventListener("canExecute",this.onCanExecute_.bind(this));document.addEventListener("command",this.onCommand_.bind(this))},onFirstRender:function(){setTimeout(function(){chrome.send("metricsHandler:recordTime",["History.ResultsRenderedTime",window.performance.now()])});var searchField=this.$.toolbar.searchField;if(!searchField.narrow){searchField.getSearchInput().focus()}md_history.ensureLazyLoaded()},_scrollHandler:function(){if(this.scrollTarget)this.toolbarShadow_=this.scrollTarget.scrollTop!=0},onCrToolbarMenuPromoClose_:function(){this.showMenuPromo_=false},onCrToolbarMenuPromoShown_:function(){md_history.BrowserService.getInstance().menuPromoShown()},onCrToolbarMenuTap_:function(){var drawer=this.$$("#drawer");if(drawer)drawer.toggle()},onOpenedChanged_:function(e){if(e.detail.value)this.showMenuPromo_=false},checkboxSelected:function(e){var toolbar=this.$.toolbar;toolbar.count=this.$.history.getSelectedItemCount()},unselectAll:function(){var listContainer=this.$.history;var toolbar=this.$.toolbar;listContainer.unselectAllItems(toolbar.count);toolbar.count=0},deleteSelected:function(){this.$.history.deleteSelectedWithPrompt()},historyResult:function(info,results){this.set("queryState_.querying",false);this.set("queryResult_.info",info);this.set("queryResult_.results",results);var listContainer=this.$["history"];listContainer.historyResult(info,results)},focusToolbarSearchField:function(){this.$.toolbar.showSearchField()},onCanExecute_:function(e){e=e;switch(e.command.id){case"find-command":e.canExecute=true;break;case"slash-command":e.canExecute=!this.$.toolbar.searchField.isSearchFocused();break;case"delete-command":e.canExecute=this.$.toolbar.count>0;break}},onCommand_:function(e){if(e.command.id=="find-command"||e.command.id=="slash-command")this.focusToolbarSearchField();if(e.command.id=="delete-command")this.deleteSelected()},setForeignSessions:function(sessionList,isTabSyncEnabled){if(!isTabSyncEnabled){var syncedDeviceManagerElem=this.$$("history-synced-device-manager");if(syncedDeviceManagerElem){md_history.ensureLazyLoaded().then(function(){syncedDeviceManagerElem.tabSyncDisabled()})}return}this.set("queryResult_.sessionList",sessionList)},historyDeleted:function(){this.$.history.historyDeleted()},updateSignInState:function(isUserSignedIn){this.isUserSignedIn_=isUserSignedIn},syncedTabsSelected_:function(selectedPage){return selectedPage=="syncedTabs"},shouldShowSpinner_:function(querying,incremental,searchTerm){return querying&&!incremental&&searchTerm!=""},showSyncNotice_:function(hasSyncedResults,selectedPage){return hasSyncedResults&&selectedPage!="syncedTabs"},selectedPageChanged_:function(){this.unselectAll();this.historyViewChanged_()},historyViewChanged_:function(){requestAnimationFrame(function(){md_history.ensureLazyLoaded().then(function(){if(!this.$.content.selectedItem)return;this.scrollTarget=this.$.content.selectedItem.getContentScrollTarget();this._scrollHandler()}.bind(this))}.bind(this));this.recordHistoryPageView_()},getSelectedPage_:function(selectedPage,items){return selectedPage},closeDrawer_:function(){var drawer=this.$$("#drawer");if(drawer)drawer.close()},recordHistoryPageView_:function(){var histogramValue=HistoryPageViewHistogram.END;switch(this.selectedPage_){case"syncedTabs":histogramValue=this.isUserSignedIn_?HistoryPageViewHistogram.SYNCED_TABS:HistoryPageViewHistogram.SIGNIN_PROMO;break;default:switch(this.queryState_.range){case HistoryRange.ALL_TIME:histogramValue=HistoryPageViewHistogram.HISTORY;break;case HistoryRange.WEEK:histogramValue=HistoryPageViewHistogram.GROUPED_WEEK;break;case HistoryRange.MONTH:histogramValue=HistoryPageViewHistogram.GROUPED_MONTH;break}break}md_history.BrowserService.getInstance().recordHistogram("History.HistoryPageView",histogramValue,HistoryPageViewHistogram.END)}}); \ No newline at end of file +cr.define("md_history",function(){var lazyLoadPromise=null;function ensureLazyLoaded(){if(!lazyLoadPromise){lazyLoadPromise=new Promise(function(resolve,reject){Polymer.Base.importHref("chrome://history/lazy_load.html",resolve,reject,true)})}return lazyLoadPromise}return{ensureLazyLoaded:ensureLazyLoaded}});Polymer({is:"history-app",behaviors:[Polymer.IronScrollTargetBehavior],properties:{showSidebarFooter:Boolean,hasSyncedResults:Boolean,selectedPage_:{type:String,observer:"selectedPageChanged_"},grouped_:{type:Boolean,reflectToAttribute:true},queryState_:{type:Object,value:function(){return{incremental:false,querying:true,queryingDisabled:false,_range:HistoryRange.ALL_TIME,searchTerm:"",groupedOffset:0,set range(val){this._range=Number(val)},get range(){return this._range}}}},queryResult_:{type:Object,value:function(){return{info:null,results:null,sessionList:null}}},hasDrawer_:Boolean,isUserSignedIn_:{type:Boolean,value:loadTimeData.getBoolean("isUserSignedIn")},toolbarShadow_:{type:Boolean,reflectToAttribute:true,notify:true},showMenuPromo_:{type:Boolean,value:function(){return loadTimeData.getBoolean("showMenuPromo")}}},listeners:{"cr-toolbar-menu-promo-close":"onCrToolbarMenuPromoClose_","cr-toolbar-menu-promo-shown":"onCrToolbarMenuPromoShown_","cr-toolbar-menu-tap":"onCrToolbarMenuTap_","delete-selected":"deleteSelected","history-checkbox-select":"checkboxSelected","history-close-drawer":"closeDrawer_","history-view-changed":"historyViewChanged_","opened-changed":"onOpenedChanged_","unselect-all":"unselectAll"},boundOnCanExecute_:null,boundOnCommand_:null,attached:function(){this.grouped_=loadTimeData.getBoolean("groupByDomain");cr.ui.decorate("command",cr.ui.Command);this.boundOnCanExecute_=this.onCanExecute_.bind(this);this.boundOnCommand_=this.onCommand_.bind(this);document.addEventListener("canExecute",this.boundOnCanExecute_);document.addEventListener("command",this.boundOnCommand_)},detached:function(){document.removeEventListener("canExecute",this.boundOnCanExecute_);document.removeEventListener("command",this.boundOnCommand_)},onFirstRender:function(){setTimeout(function(){chrome.send("metricsHandler:recordTime",["History.ResultsRenderedTime",window.performance.now()])});var searchField=this.$.toolbar.searchField;if(!searchField.narrow){searchField.getSearchInput().focus()}md_history.ensureLazyLoaded()},_scrollHandler:function(){if(this.scrollTarget)this.toolbarShadow_=this.scrollTarget.scrollTop!=0},onCrToolbarMenuPromoClose_:function(){this.showMenuPromo_=false},onCrToolbarMenuPromoShown_:function(){md_history.BrowserService.getInstance().menuPromoShown()},onCrToolbarMenuTap_:function(){var drawer=this.$$("#drawer");if(drawer)drawer.toggle()},onOpenedChanged_:function(e){if(e.detail.value)this.showMenuPromo_=false},checkboxSelected:function(e){var toolbar=this.$.toolbar;toolbar.count=this.$.history.getSelectedItemCount()},unselectAll:function(){var listContainer=this.$.history;var toolbar=this.$.toolbar;listContainer.unselectAllItems(toolbar.count);toolbar.count=0},deleteSelected:function(){this.$.history.deleteSelectedWithPrompt()},historyResult:function(info,results){this.set("queryState_.querying",false);this.set("queryResult_.info",info);this.set("queryResult_.results",results);var listContainer=this.$["history"];listContainer.historyResult(info,results)},focusToolbarSearchField:function(){this.$.toolbar.showSearchField()},onCanExecute_:function(e){e=e;switch(e.command.id){case"find-command":e.canExecute=true;break;case"slash-command":e.canExecute=!this.$.toolbar.searchField.isSearchFocused();break;case"delete-command":e.canExecute=this.$.toolbar.count>0;break}},onCommand_:function(e){if(e.command.id=="find-command"||e.command.id=="slash-command")this.focusToolbarSearchField();if(e.command.id=="delete-command")this.deleteSelected()},setForeignSessions:function(sessionList,isTabSyncEnabled){if(!isTabSyncEnabled){var syncedDeviceManagerElem=this.$$("history-synced-device-manager");if(syncedDeviceManagerElem){md_history.ensureLazyLoaded().then(function(){syncedDeviceManagerElem.tabSyncDisabled()})}return}this.set("queryResult_.sessionList",sessionList)},historyDeleted:function(){this.$.history.historyDeleted()},updateSignInState:function(isUserSignedIn){this.isUserSignedIn_=isUserSignedIn},syncedTabsSelected_:function(selectedPage){return selectedPage=="syncedTabs"},shouldShowSpinner_:function(querying,incremental,searchTerm){return querying&&!incremental&&searchTerm!=""},showSyncNotice_:function(hasSyncedResults,selectedPage){return hasSyncedResults&&selectedPage!="syncedTabs"},selectedPageChanged_:function(){this.unselectAll();this.historyViewChanged_()},historyViewChanged_:function(){requestAnimationFrame(function(){md_history.ensureLazyLoaded().then(function(){if(!this.$.content.selectedItem)return;this.scrollTarget=this.$.content.selectedItem.getContentScrollTarget();this._scrollHandler()}.bind(this))}.bind(this));this.recordHistoryPageView_()},getSelectedPage_:function(selectedPage,items){return selectedPage},closeDrawer_:function(){var drawer=this.$$("#drawer");if(drawer)drawer.close()},recordHistoryPageView_:function(){var histogramValue=HistoryPageViewHistogram.END;switch(this.selectedPage_){case"syncedTabs":histogramValue=this.isUserSignedIn_?HistoryPageViewHistogram.SYNCED_TABS:HistoryPageViewHistogram.SIGNIN_PROMO;break;default:switch(this.queryState_.range){case HistoryRange.ALL_TIME:histogramValue=HistoryPageViewHistogram.HISTORY;break;case HistoryRange.WEEK:histogramValue=HistoryPageViewHistogram.GROUPED_WEEK;break;case HistoryRange.MONTH:histogramValue=HistoryPageViewHistogram.GROUPED_MONTH;break}break}md_history.BrowserService.getInstance().recordHistogram("History.HistoryPageView",histogramValue,HistoryPageViewHistogram.END)}}); \ No newline at end of file
diff --git a/chrome/browser/resources/md_history/app.js b/chrome/browser/resources/md_history/app.js index c0dbb18..0b287d5 100644 --- a/chrome/browser/resources/md_history/app.js +++ b/chrome/browser/resources/md_history/app.js
@@ -107,13 +107,28 @@ 'unselect-all': 'unselectAll', }, + /** @private {?function(!Event)} */ + boundOnCanExecute_: null, + + /** @private {?function(!Event)} */ + boundOnCommand_: null, + /** @override */ - ready: function() { + attached: function() { this.grouped_ = loadTimeData.getBoolean('groupByDomain'); cr.ui.decorate('command', cr.ui.Command); - document.addEventListener('canExecute', this.onCanExecute_.bind(this)); - document.addEventListener('command', this.onCommand_.bind(this)); + this.boundOnCanExecute_ = this.onCanExecute_.bind(this); + this.boundOnCommand_ = this.onCommand_.bind(this); + + document.addEventListener('canExecute', this.boundOnCanExecute_); + document.addEventListener('command', this.boundOnCommand_); + }, + + /** @override */ + detached: function() { + document.removeEventListener('canExecute', this.boundOnCanExecute_); + document.removeEventListener('command', this.boundOnCommand_); }, onFirstRender: function() {
diff --git a/chrome/browser/resources/md_history/app.vulcanized.html b/chrome/browser/resources/md_history/app.vulcanized.html index 30cf90a..4bcd3b7 100644 --- a/chrome/browser/resources/md_history/app.vulcanized.html +++ b/chrome/browser/resources/md_history/app.vulcanized.html
@@ -3557,7 +3557,7 @@ <paper-button class="cancel-button" on-tap="onDialogCancelTap_"> $i18n{cancel} </paper-button> - <paper-button class="action-button" on-tap="onDialogConfirmTap_" autofocus=""> + <paper-button class="action-button" on-tap="onDialogConfirmTap_"> $i18n{deleteConfirm} </paper-button> </div> @@ -3569,7 +3569,7 @@ <paper-item id="menuMoreButton" class="menu-item" on-tap="onMoreFromSiteTap_"> $i18n{moreFromSite} </paper-item> - <paper-item id="menuRemoveButton" class="menu-item" on-tap="onRemoveFromHistoryTap_"> + <paper-item id="menuRemoveButton" class="menu-item" disabled="[[!canDeleteHistory_()]]" on-tap="onRemoveFromHistoryTap_"> $i18n{removeFromHistory} </paper-item> </cr-shared-menu> @@ -3692,7 +3692,7 @@ } #clear-browsing-data iron-icon { - -webkit-margin-end: 24px; + -webkit-margin-end: 20px; color: var(--paper-grey-400); height: 20px; margin-bottom: 10px; @@ -3712,6 +3712,8 @@ iron-selector > a { font-family: var(--paper-font-subhead_-_font-family); -webkit-font-smoothing: var(--paper-font-subhead_-_-webkit-font-smoothing); font-size: var(--paper-font-subhead_-_font-size); font-weight: var(--paper-font-subhead_-_font-weight); line-height: var(--paper-font-subhead_-_line-height); + + -webkit-margin-end: 4px; -webkit-padding-start: 24px; align-items: center; box-sizing: border-box;
diff --git a/chrome/browser/resources/md_history/lazy_load.crisper.js b/chrome/browser/resources/md_history/lazy_load.crisper.js index 8a7adf9..b3f8a172e 100644 --- a/chrome/browser/resources/md_history/lazy_load.crisper.js +++ b/chrome/browser/resources/md_history/lazy_load.crisper.js
@@ -23,4 +23,4 @@ // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -Polymer({is:"cr-dialog","extends":"dialog",properties:{ignorePopstate:{type:Boolean,value:false}},ready:function(){window.addEventListener("popstate",function(){if(!this.ignorePopstate&&this.open)this.cancel()}.bind(this))},cancel:function(){this.fire("cancel");HTMLDialogElement.prototype.close.call(this,"")},close:function(opt_returnValue){HTMLDialogElement.prototype.close.call(this,"success")},getCloseButton:function(){return this.$.close}});Polymer({is:"app-drawer",properties:{opened:{type:Boolean,value:false,notify:true,reflectToAttribute:true},persistent:{type:Boolean,value:false,reflectToAttribute:true},align:{type:String,value:"left"},position:{type:String,readOnly:true,value:"left",reflectToAttribute:true},swipeOpen:{type:Boolean,value:false,reflectToAttribute:true},noFocusTrap:{type:Boolean,value:false}},observers:["resetLayout(position)","_resetPosition(align, isAttached)"],_translateOffset:0,_trackDetails:null,_drawerState:0,_boundEscKeydownHandler:null,_firstTabStop:null,_lastTabStop:null,ready:function(){this.setScrollDirection("y");this._setTransitionDuration("0s")},attached:function(){Polymer.RenderStatus.afterNextRender(this,function(){this._setTransitionDuration("");this._boundEscKeydownHandler=this._escKeydownHandler.bind(this);this._resetDrawerState();this.listen(this,"track","_track");this.addEventListener("transitionend",this._transitionend.bind(this));this.addEventListener("keydown",this._tabKeydownHandler.bind(this))})},detached:function(){document.removeEventListener("keydown",this._boundEscKeydownHandler)},open:function(){this.opened=true},close:function(){this.opened=false},toggle:function(){this.opened=!this.opened},getWidth:function(){return this.$.contentContainer.offsetWidth},resetLayout:function(){this.debounce("_resetLayout",function(){this.fire("app-drawer-reset-layout")},1)},_isRTL:function(){return window.getComputedStyle(this).direction==="rtl"},_resetPosition:function(){switch(this.align){case"start":this._setPosition(this._isRTL()?"right":"left");return;case"end":this._setPosition(this._isRTL()?"left":"right");return}this._setPosition(this.align)},_escKeydownHandler:function(event){var ESC_KEYCODE=27;if(event.keyCode===ESC_KEYCODE){event.preventDefault();this.close()}},_track:function(event){if(this.persistent){return}event.preventDefault();switch(event.detail.state){case"start":this._trackStart(event);break;case"track":this._trackMove(event);break;case"end":this._trackEnd(event);break}},_trackStart:function(event){this._drawerState=this._DRAWER_STATE.TRACKING;this._setTransitionDuration("0s");this.style.visibility="visible";var rect=this.$.contentContainer.getBoundingClientRect();if(this.position==="left"){this._translateOffset=rect.left}else{this._translateOffset=rect.right-window.innerWidth}this._trackDetails=[]},_trackMove:function(event){this._translateDrawer(event.detail.dx+this._translateOffset);this._trackDetails.push({dx:event.detail.dx,timeStamp:Date.now()})},_trackEnd:function(event){var x=event.detail.dx+this._translateOffset;var drawerWidth=this.getWidth();var isPositionLeft=this.position==="left";var isInEndState=isPositionLeft?x>=0||x<=-drawerWidth:x<=0||x>=drawerWidth;if(!isInEndState){var trackDetails=this._trackDetails;this._trackDetails=null;this._flingDrawer(event,trackDetails);if(this._drawerState===this._DRAWER_STATE.FLINGING){return}}var halfWidth=drawerWidth/2;if(event.detail.dx<-halfWidth){this.opened=this.position==="right"}else if(event.detail.dx>halfWidth){this.opened=this.position==="left"}if(isInEndState){this._resetDrawerState()}this._setTransitionDuration("");this._resetDrawerTranslate();this.style.visibility=""},_calculateVelocity:function(event,trackDetails){var now=Date.now();var timeLowerBound=now-100;var trackDetail;var min=0;var max=trackDetails.length-1;while(min<=max){var mid=min+max>>1;var d=trackDetails[mid];if(d.timeStamp>=timeLowerBound){trackDetail=d;max=mid-1}else{min=mid+1}}if(trackDetail){var dx=event.detail.dx-trackDetail.dx;var dt=now-trackDetail.timeStamp||1;return dx/dt}return 0},_flingDrawer:function(event,trackDetails){var velocity=this._calculateVelocity(event,trackDetails);if(Math.abs(velocity)<this._MIN_FLING_THRESHOLD){return}this._drawerState=this._DRAWER_STATE.FLINGING;var x=event.detail.dx+this._translateOffset;var drawerWidth=this.getWidth();var isPositionLeft=this.position==="left";var isVelocityPositive=velocity>0;var isClosingLeft=!isVelocityPositive&&isPositionLeft;var isClosingRight=isVelocityPositive&&!isPositionLeft;var dx;if(isClosingLeft){dx=-(x+drawerWidth)}else if(isClosingRight){dx=drawerWidth-x}else{dx=-x}if(isVelocityPositive){velocity=Math.max(velocity,this._MIN_TRANSITION_VELOCITY);this.opened=this.position==="left"}else{velocity=Math.min(velocity,-this._MIN_TRANSITION_VELOCITY);this.opened=this.position==="right"}this._setTransitionDuration(this._FLING_INITIAL_SLOPE*dx/velocity+"ms");this._setTransitionTimingFunction(this._FLING_TIMING_FUNCTION);this._resetDrawerTranslate()},_transitionend:function(event){var target=Polymer.dom(event).rootTarget;if(target===this.$.contentContainer||target===this.$.scrim){if(this._drawerState===this._DRAWER_STATE.FLINGING){this._setTransitionDuration("");this._setTransitionTimingFunction("");this.style.visibility=""}this._resetDrawerState()}},_setTransitionDuration:function(duration){this.$.contentContainer.style.transitionDuration=duration;this.$.scrim.style.transitionDuration=duration},_setTransitionTimingFunction:function(timingFunction){this.$.contentContainer.style.transitionTimingFunction=timingFunction;this.$.scrim.style.transitionTimingFunction=timingFunction},_translateDrawer:function(x){var drawerWidth=this.getWidth();if(this.position==="left"){x=Math.max(-drawerWidth,Math.min(x,0));this.$.scrim.style.opacity=1+x/drawerWidth}else{x=Math.max(0,Math.min(x,drawerWidth));this.$.scrim.style.opacity=1-x/drawerWidth}this.translate3d(x+"px","0","0",this.$.contentContainer)},_resetDrawerTranslate:function(){this.$.scrim.style.opacity="";this.transform("",this.$.contentContainer)},_resetDrawerState:function(){var oldState=this._drawerState;if(this.opened){this._drawerState=this.persistent?this._DRAWER_STATE.OPENED_PERSISTENT:this._DRAWER_STATE.OPENED}else{this._drawerState=this._DRAWER_STATE.CLOSED}if(oldState!==this._drawerState){if(this._drawerState===this._DRAWER_STATE.OPENED){this._setKeyboardFocusTrap();document.addEventListener("keydown",this._boundEscKeydownHandler);document.body.style.overflow="hidden"}else{document.removeEventListener("keydown",this._boundEscKeydownHandler);document.body.style.overflow=""}if(oldState!==this._DRAWER_STATE.INIT){this.fire("app-drawer-transitioned")}}},_setKeyboardFocusTrap:function(){if(this.noFocusTrap){return}var focusableElementsSelector=['a[href]:not([tabindex="-1"])','area[href]:not([tabindex="-1"])','input:not([disabled]):not([tabindex="-1"])','select:not([disabled]):not([tabindex="-1"])','textarea:not([disabled]):not([tabindex="-1"])','button:not([disabled]):not([tabindex="-1"])','iframe:not([tabindex="-1"])','[tabindex]:not([tabindex="-1"])','[contentEditable=true]:not([tabindex="-1"])'].join(",");var focusableElements=Polymer.dom(this).querySelectorAll(focusableElementsSelector);if(focusableElements.length>0){this._firstTabStop=focusableElements[0];this._lastTabStop=focusableElements[focusableElements.length-1]}else{this._firstTabStop=null;this._lastTabStop=null}var tabindex=this.getAttribute("tabindex");if(tabindex&&parseInt(tabindex,10)>-1){this.focus()}else if(this._firstTabStop){this._firstTabStop.focus()}},_tabKeydownHandler:function(event){if(this.noFocusTrap){return}var TAB_KEYCODE=9;if(this._drawerState===this._DRAWER_STATE.OPENED&&event.keyCode===TAB_KEYCODE){if(event.shiftKey){if(this._firstTabStop&&Polymer.dom(event).localTarget===this._firstTabStop){event.preventDefault();this._lastTabStop.focus()}}else{if(this._lastTabStop&&Polymer.dom(event).localTarget===this._lastTabStop){event.preventDefault();this._firstTabStop.focus()}}}},_MIN_FLING_THRESHOLD:.2,_MIN_TRANSITION_VELOCITY:1.2,_FLING_TIMING_FUNCTION:"cubic-bezier(0.667, 1, 0.667, 1)",_FLING_INITIAL_SLOPE:1.5,_DRAWER_STATE:{INIT:0,OPENED:1,OPENED_PERSISTENT:2,CLOSED:3,TRACKING:4,FLINGING:5}});Polymer({is:"paper-tab",behaviors:[Polymer.IronControlState,Polymer.IronButtonState,Polymer.PaperRippleBehavior],properties:{link:{type:Boolean,value:false,reflectToAttribute:true}},hostAttributes:{role:"tab"},listeners:{down:"_updateNoink",tap:"_onTap"},attached:function(){this._updateNoink()},get _parentNoink(){var parent=Polymer.dom(this).parentNode;return!!parent&&!!parent.noink},_updateNoink:function(){this.noink=!!this.noink||!!this._parentNoink},_onTap:function(event){if(this.link){var anchor=this.queryEffectiveChildren("a");if(!anchor){return}if(event.target===anchor){return}anchor.click()}}});Polymer.IronMenubarBehaviorImpl={hostAttributes:{role:"menubar"},keyBindings:{left:"_onLeftKey",right:"_onRightKey"},_onUpKey:function(event){this.focusedItem.click();event.detail.keyboardEvent.preventDefault()},_onDownKey:function(event){this.focusedItem.click();event.detail.keyboardEvent.preventDefault()},get _isRTL(){return window.getComputedStyle(this)["direction"]==="rtl"},_onLeftKey:function(event){if(this._isRTL){this._focusNext()}else{this._focusPrevious()}event.detail.keyboardEvent.preventDefault()},_onRightKey:function(event){if(this._isRTL){this._focusPrevious()}else{this._focusNext()}event.detail.keyboardEvent.preventDefault()},_onKeydown:function(event){if(this.keyboardEventMatchesKeys(event,"up down left right esc")){return}this._focusWithKeyboardEvent(event)}};Polymer.IronMenubarBehavior=[Polymer.IronMenuBehavior,Polymer.IronMenubarBehaviorImpl];Polymer({is:"paper-tabs",behaviors:[Polymer.IronResizableBehavior,Polymer.IronMenubarBehavior],properties:{noink:{type:Boolean,value:false,observer:"_noinkChanged"},noBar:{type:Boolean,value:false},noSlide:{type:Boolean,value:false},scrollable:{type:Boolean,value:false},fitContainer:{type:Boolean,value:false},disableDrag:{type:Boolean,value:false},hideScrollButtons:{type:Boolean,value:false},alignBottom:{type:Boolean,value:false},selectable:{type:String,value:"paper-tab"},autoselect:{type:Boolean,value:false},autoselectDelay:{type:Number,value:0},_step:{type:Number,value:10},_holdDelay:{type:Number,value:1},_leftHidden:{type:Boolean,value:false},_rightHidden:{type:Boolean,value:false},_previousTab:{type:Object}},hostAttributes:{role:"tablist"},listeners:{"iron-resize":"_onTabSizingChanged","iron-items-changed":"_onTabSizingChanged","iron-select":"_onIronSelect","iron-deselect":"_onIronDeselect"},keyBindings:{"left:keyup right:keyup":"_onArrowKeyup"},created:function(){this._holdJob=null;this._pendingActivationItem=undefined;this._pendingActivationTimeout=undefined;this._bindDelayedActivationHandler=this._delayedActivationHandler.bind(this);this.addEventListener("blur",this._onBlurCapture.bind(this),true)},ready:function(){this.setScrollDirection("y",this.$.tabsContainer)},detached:function(){this._cancelPendingActivation()},_noinkChanged:function(noink){var childTabs=Polymer.dom(this).querySelectorAll("paper-tab");childTabs.forEach(noink?this._setNoinkAttribute:this._removeNoinkAttribute)},_setNoinkAttribute:function(element){element.setAttribute("noink","")},_removeNoinkAttribute:function(element){element.removeAttribute("noink")},_computeScrollButtonClass:function(hideThisButton,scrollable,hideScrollButtons){if(!scrollable||hideScrollButtons){return"hidden"}if(hideThisButton){return"not-visible"}return""},_computeTabsContentClass:function(scrollable,fitContainer){return scrollable?"scrollable"+(fitContainer?" fit-container":""):" fit-container"},_computeSelectionBarClass:function(noBar,alignBottom){if(noBar){return"hidden"}else if(alignBottom){return"align-bottom"}return""},_onTabSizingChanged:function(){this.debounce("_onTabSizingChanged",function(){this._scroll();this._tabChanged(this.selectedItem)},10)},_onIronSelect:function(event){this._tabChanged(event.detail.item,this._previousTab);this._previousTab=event.detail.item;this.cancelDebouncer("tab-changed")},_onIronDeselect:function(event){this.debounce("tab-changed",function(){this._tabChanged(null,this._previousTab);this._previousTab=null},1)},_activateHandler:function(){this._cancelPendingActivation();Polymer.IronMenuBehaviorImpl._activateHandler.apply(this,arguments)},_scheduleActivation:function(item,delay){this._pendingActivationItem=item;this._pendingActivationTimeout=this.async(this._bindDelayedActivationHandler,delay)},_delayedActivationHandler:function(){var item=this._pendingActivationItem;this._pendingActivationItem=undefined;this._pendingActivationTimeout=undefined;item.fire(this.activateEvent,null,{bubbles:true,cancelable:true})},_cancelPendingActivation:function(){if(this._pendingActivationTimeout!==undefined){this.cancelAsync(this._pendingActivationTimeout);this._pendingActivationItem=undefined;this._pendingActivationTimeout=undefined}},_onArrowKeyup:function(event){if(this.autoselect){this._scheduleActivation(this.focusedItem,this.autoselectDelay)}},_onBlurCapture:function(event){if(event.target===this._pendingActivationItem){this._cancelPendingActivation()}},get _tabContainerScrollSize(){return Math.max(0,this.$.tabsContainer.scrollWidth-this.$.tabsContainer.offsetWidth)},_scroll:function(e,detail){if(!this.scrollable){return}var ddx=detail&&-detail.ddx||0;this._affectScroll(ddx)},_down:function(e){this.async(function(){if(this._defaultFocusAsync){this.cancelAsync(this._defaultFocusAsync);this._defaultFocusAsync=null}},1)},_affectScroll:function(dx){this.$.tabsContainer.scrollLeft+=dx;var scrollLeft=this.$.tabsContainer.scrollLeft;this._leftHidden=scrollLeft===0;this._rightHidden=scrollLeft===this._tabContainerScrollSize},_onLeftScrollButtonDown:function(){this._scrollToLeft();this._holdJob=setInterval(this._scrollToLeft.bind(this),this._holdDelay)},_onRightScrollButtonDown:function(){this._scrollToRight();this._holdJob=setInterval(this._scrollToRight.bind(this),this._holdDelay)},_onScrollButtonUp:function(){clearInterval(this._holdJob);this._holdJob=null},_scrollToLeft:function(){this._affectScroll(-this._step)},_scrollToRight:function(){this._affectScroll(this._step)},_tabChanged:function(tab,old){if(!tab){this.$.selectionBar.classList.remove("expand");this.$.selectionBar.classList.remove("contract");this._positionBar(0,0);return}var r=this.$.tabsContent.getBoundingClientRect();var w=r.width;var tabRect=tab.getBoundingClientRect();var tabOffsetLeft=tabRect.left-r.left;this._pos={width:this._calcPercent(tabRect.width,w),left:this._calcPercent(tabOffsetLeft,w)};if(this.noSlide||old==null){this.$.selectionBar.classList.remove("expand");this.$.selectionBar.classList.remove("contract");this._positionBar(this._pos.width,this._pos.left);return}var oldRect=old.getBoundingClientRect();var oldIndex=this.items.indexOf(old);var index=this.items.indexOf(tab);var m=5;this.$.selectionBar.classList.add("expand");var moveRight=oldIndex<index;var isRTL=this._isRTL;if(isRTL){moveRight=!moveRight}if(moveRight){this._positionBar(this._calcPercent(tabRect.left+tabRect.width-oldRect.left,w)-m,this._left)}else{this._positionBar(this._calcPercent(oldRect.left+oldRect.width-tabRect.left,w)-m,this._calcPercent(tabOffsetLeft,w)+m)}if(this.scrollable){this._scrollToSelectedIfNeeded(tabRect.width,tabOffsetLeft)}},_scrollToSelectedIfNeeded:function(tabWidth,tabOffsetLeft){var l=tabOffsetLeft-this.$.tabsContainer.scrollLeft;if(l<0){this.$.tabsContainer.scrollLeft+=l}else{l+=tabWidth-this.$.tabsContainer.offsetWidth;if(l>0){this.$.tabsContainer.scrollLeft+=l}}},_calcPercent:function(w,w0){return 100*w/w0},_positionBar:function(width,left){width=width||0;left=left||0;this._width=width;this._left=left;this.transform("translateX("+left+"%) scaleX("+width/100+")",this.$.selectionBar)},_onBarTransitionEnd:function(e){var cl=this.$.selectionBar.classList;if(cl.contains("expand")){cl.remove("expand");cl.add("contract");this._positionBar(this._pos.width,this._pos.left)}else if(cl.contains("contract")){cl.remove("contract")}}}); \ No newline at end of file +Polymer({is:"cr-dialog","extends":"dialog",properties:{closeText:String,ignorePopstate:{type:Boolean,value:false}},ready:function(){window.addEventListener("popstate",function(){if(!this.ignorePopstate&&this.open)this.cancel()}.bind(this))},cancel:function(){this.fire("cancel");HTMLDialogElement.prototype.close.call(this,"")},close:function(opt_returnValue){HTMLDialogElement.prototype.close.call(this,"success")},getCloseButton:function(){return this.$.close}});Polymer({is:"app-drawer",properties:{opened:{type:Boolean,value:false,notify:true,reflectToAttribute:true},persistent:{type:Boolean,value:false,reflectToAttribute:true},align:{type:String,value:"left"},position:{type:String,readOnly:true,value:"left",reflectToAttribute:true},swipeOpen:{type:Boolean,value:false,reflectToAttribute:true},noFocusTrap:{type:Boolean,value:false}},observers:["resetLayout(position)","_resetPosition(align, isAttached)"],_translateOffset:0,_trackDetails:null,_drawerState:0,_boundEscKeydownHandler:null,_firstTabStop:null,_lastTabStop:null,ready:function(){this.setScrollDirection("y");this._setTransitionDuration("0s")},attached:function(){Polymer.RenderStatus.afterNextRender(this,function(){this._setTransitionDuration("");this._boundEscKeydownHandler=this._escKeydownHandler.bind(this);this._resetDrawerState();this.listen(this,"track","_track");this.addEventListener("transitionend",this._transitionend.bind(this));this.addEventListener("keydown",this._tabKeydownHandler.bind(this))})},detached:function(){document.removeEventListener("keydown",this._boundEscKeydownHandler)},open:function(){this.opened=true},close:function(){this.opened=false},toggle:function(){this.opened=!this.opened},getWidth:function(){return this.$.contentContainer.offsetWidth},resetLayout:function(){this.debounce("_resetLayout",function(){this.fire("app-drawer-reset-layout")},1)},_isRTL:function(){return window.getComputedStyle(this).direction==="rtl"},_resetPosition:function(){switch(this.align){case"start":this._setPosition(this._isRTL()?"right":"left");return;case"end":this._setPosition(this._isRTL()?"left":"right");return}this._setPosition(this.align)},_escKeydownHandler:function(event){var ESC_KEYCODE=27;if(event.keyCode===ESC_KEYCODE){event.preventDefault();this.close()}},_track:function(event){if(this.persistent){return}event.preventDefault();switch(event.detail.state){case"start":this._trackStart(event);break;case"track":this._trackMove(event);break;case"end":this._trackEnd(event);break}},_trackStart:function(event){this._drawerState=this._DRAWER_STATE.TRACKING;this._setTransitionDuration("0s");this.style.visibility="visible";var rect=this.$.contentContainer.getBoundingClientRect();if(this.position==="left"){this._translateOffset=rect.left}else{this._translateOffset=rect.right-window.innerWidth}this._trackDetails=[]},_trackMove:function(event){this._translateDrawer(event.detail.dx+this._translateOffset);this._trackDetails.push({dx:event.detail.dx,timeStamp:Date.now()})},_trackEnd:function(event){var x=event.detail.dx+this._translateOffset;var drawerWidth=this.getWidth();var isPositionLeft=this.position==="left";var isInEndState=isPositionLeft?x>=0||x<=-drawerWidth:x<=0||x>=drawerWidth;if(!isInEndState){var trackDetails=this._trackDetails;this._trackDetails=null;this._flingDrawer(event,trackDetails);if(this._drawerState===this._DRAWER_STATE.FLINGING){return}}var halfWidth=drawerWidth/2;if(event.detail.dx<-halfWidth){this.opened=this.position==="right"}else if(event.detail.dx>halfWidth){this.opened=this.position==="left"}if(isInEndState){this._resetDrawerState()}this._setTransitionDuration("");this._resetDrawerTranslate();this.style.visibility=""},_calculateVelocity:function(event,trackDetails){var now=Date.now();var timeLowerBound=now-100;var trackDetail;var min=0;var max=trackDetails.length-1;while(min<=max){var mid=min+max>>1;var d=trackDetails[mid];if(d.timeStamp>=timeLowerBound){trackDetail=d;max=mid-1}else{min=mid+1}}if(trackDetail){var dx=event.detail.dx-trackDetail.dx;var dt=now-trackDetail.timeStamp||1;return dx/dt}return 0},_flingDrawer:function(event,trackDetails){var velocity=this._calculateVelocity(event,trackDetails);if(Math.abs(velocity)<this._MIN_FLING_THRESHOLD){return}this._drawerState=this._DRAWER_STATE.FLINGING;var x=event.detail.dx+this._translateOffset;var drawerWidth=this.getWidth();var isPositionLeft=this.position==="left";var isVelocityPositive=velocity>0;var isClosingLeft=!isVelocityPositive&&isPositionLeft;var isClosingRight=isVelocityPositive&&!isPositionLeft;var dx;if(isClosingLeft){dx=-(x+drawerWidth)}else if(isClosingRight){dx=drawerWidth-x}else{dx=-x}if(isVelocityPositive){velocity=Math.max(velocity,this._MIN_TRANSITION_VELOCITY);this.opened=this.position==="left"}else{velocity=Math.min(velocity,-this._MIN_TRANSITION_VELOCITY);this.opened=this.position==="right"}this._setTransitionDuration(this._FLING_INITIAL_SLOPE*dx/velocity+"ms");this._setTransitionTimingFunction(this._FLING_TIMING_FUNCTION);this._resetDrawerTranslate()},_transitionend:function(event){var target=Polymer.dom(event).rootTarget;if(target===this.$.contentContainer||target===this.$.scrim){if(this._drawerState===this._DRAWER_STATE.FLINGING){this._setTransitionDuration("");this._setTransitionTimingFunction("");this.style.visibility=""}this._resetDrawerState()}},_setTransitionDuration:function(duration){this.$.contentContainer.style.transitionDuration=duration;this.$.scrim.style.transitionDuration=duration},_setTransitionTimingFunction:function(timingFunction){this.$.contentContainer.style.transitionTimingFunction=timingFunction;this.$.scrim.style.transitionTimingFunction=timingFunction},_translateDrawer:function(x){var drawerWidth=this.getWidth();if(this.position==="left"){x=Math.max(-drawerWidth,Math.min(x,0));this.$.scrim.style.opacity=1+x/drawerWidth}else{x=Math.max(0,Math.min(x,drawerWidth));this.$.scrim.style.opacity=1-x/drawerWidth}this.translate3d(x+"px","0","0",this.$.contentContainer)},_resetDrawerTranslate:function(){this.$.scrim.style.opacity="";this.transform("",this.$.contentContainer)},_resetDrawerState:function(){var oldState=this._drawerState;if(this.opened){this._drawerState=this.persistent?this._DRAWER_STATE.OPENED_PERSISTENT:this._DRAWER_STATE.OPENED}else{this._drawerState=this._DRAWER_STATE.CLOSED}if(oldState!==this._drawerState){if(this._drawerState===this._DRAWER_STATE.OPENED){this._setKeyboardFocusTrap();document.addEventListener("keydown",this._boundEscKeydownHandler);document.body.style.overflow="hidden"}else{document.removeEventListener("keydown",this._boundEscKeydownHandler);document.body.style.overflow=""}if(oldState!==this._DRAWER_STATE.INIT){this.fire("app-drawer-transitioned")}}},_setKeyboardFocusTrap:function(){if(this.noFocusTrap){return}var focusableElementsSelector=['a[href]:not([tabindex="-1"])','area[href]:not([tabindex="-1"])','input:not([disabled]):not([tabindex="-1"])','select:not([disabled]):not([tabindex="-1"])','textarea:not([disabled]):not([tabindex="-1"])','button:not([disabled]):not([tabindex="-1"])','iframe:not([tabindex="-1"])','[tabindex]:not([tabindex="-1"])','[contentEditable=true]:not([tabindex="-1"])'].join(",");var focusableElements=Polymer.dom(this).querySelectorAll(focusableElementsSelector);if(focusableElements.length>0){this._firstTabStop=focusableElements[0];this._lastTabStop=focusableElements[focusableElements.length-1]}else{this._firstTabStop=null;this._lastTabStop=null}var tabindex=this.getAttribute("tabindex");if(tabindex&&parseInt(tabindex,10)>-1){this.focus()}else if(this._firstTabStop){this._firstTabStop.focus()}},_tabKeydownHandler:function(event){if(this.noFocusTrap){return}var TAB_KEYCODE=9;if(this._drawerState===this._DRAWER_STATE.OPENED&&event.keyCode===TAB_KEYCODE){if(event.shiftKey){if(this._firstTabStop&&Polymer.dom(event).localTarget===this._firstTabStop){event.preventDefault();this._lastTabStop.focus()}}else{if(this._lastTabStop&&Polymer.dom(event).localTarget===this._lastTabStop){event.preventDefault();this._firstTabStop.focus()}}}},_MIN_FLING_THRESHOLD:.2,_MIN_TRANSITION_VELOCITY:1.2,_FLING_TIMING_FUNCTION:"cubic-bezier(0.667, 1, 0.667, 1)",_FLING_INITIAL_SLOPE:1.5,_DRAWER_STATE:{INIT:0,OPENED:1,OPENED_PERSISTENT:2,CLOSED:3,TRACKING:4,FLINGING:5}});Polymer({is:"paper-tab",behaviors:[Polymer.IronControlState,Polymer.IronButtonState,Polymer.PaperRippleBehavior],properties:{link:{type:Boolean,value:false,reflectToAttribute:true}},hostAttributes:{role:"tab"},listeners:{down:"_updateNoink",tap:"_onTap"},attached:function(){this._updateNoink()},get _parentNoink(){var parent=Polymer.dom(this).parentNode;return!!parent&&!!parent.noink},_updateNoink:function(){this.noink=!!this.noink||!!this._parentNoink},_onTap:function(event){if(this.link){var anchor=this.queryEffectiveChildren("a");if(!anchor){return}if(event.target===anchor){return}anchor.click()}}});Polymer.IronMenubarBehaviorImpl={hostAttributes:{role:"menubar"},keyBindings:{left:"_onLeftKey",right:"_onRightKey"},_onUpKey:function(event){this.focusedItem.click();event.detail.keyboardEvent.preventDefault()},_onDownKey:function(event){this.focusedItem.click();event.detail.keyboardEvent.preventDefault()},get _isRTL(){return window.getComputedStyle(this)["direction"]==="rtl"},_onLeftKey:function(event){if(this._isRTL){this._focusNext()}else{this._focusPrevious()}event.detail.keyboardEvent.preventDefault()},_onRightKey:function(event){if(this._isRTL){this._focusPrevious()}else{this._focusNext()}event.detail.keyboardEvent.preventDefault()},_onKeydown:function(event){if(this.keyboardEventMatchesKeys(event,"up down left right esc")){return}this._focusWithKeyboardEvent(event)}};Polymer.IronMenubarBehavior=[Polymer.IronMenuBehavior,Polymer.IronMenubarBehaviorImpl];Polymer({is:"paper-tabs",behaviors:[Polymer.IronResizableBehavior,Polymer.IronMenubarBehavior],properties:{noink:{type:Boolean,value:false,observer:"_noinkChanged"},noBar:{type:Boolean,value:false},noSlide:{type:Boolean,value:false},scrollable:{type:Boolean,value:false},fitContainer:{type:Boolean,value:false},disableDrag:{type:Boolean,value:false},hideScrollButtons:{type:Boolean,value:false},alignBottom:{type:Boolean,value:false},selectable:{type:String,value:"paper-tab"},autoselect:{type:Boolean,value:false},autoselectDelay:{type:Number,value:0},_step:{type:Number,value:10},_holdDelay:{type:Number,value:1},_leftHidden:{type:Boolean,value:false},_rightHidden:{type:Boolean,value:false},_previousTab:{type:Object}},hostAttributes:{role:"tablist"},listeners:{"iron-resize":"_onTabSizingChanged","iron-items-changed":"_onTabSizingChanged","iron-select":"_onIronSelect","iron-deselect":"_onIronDeselect"},keyBindings:{"left:keyup right:keyup":"_onArrowKeyup"},created:function(){this._holdJob=null;this._pendingActivationItem=undefined;this._pendingActivationTimeout=undefined;this._bindDelayedActivationHandler=this._delayedActivationHandler.bind(this);this.addEventListener("blur",this._onBlurCapture.bind(this),true)},ready:function(){this.setScrollDirection("y",this.$.tabsContainer)},detached:function(){this._cancelPendingActivation()},_noinkChanged:function(noink){var childTabs=Polymer.dom(this).querySelectorAll("paper-tab");childTabs.forEach(noink?this._setNoinkAttribute:this._removeNoinkAttribute)},_setNoinkAttribute:function(element){element.setAttribute("noink","")},_removeNoinkAttribute:function(element){element.removeAttribute("noink")},_computeScrollButtonClass:function(hideThisButton,scrollable,hideScrollButtons){if(!scrollable||hideScrollButtons){return"hidden"}if(hideThisButton){return"not-visible"}return""},_computeTabsContentClass:function(scrollable,fitContainer){return scrollable?"scrollable"+(fitContainer?" fit-container":""):" fit-container"},_computeSelectionBarClass:function(noBar,alignBottom){if(noBar){return"hidden"}else if(alignBottom){return"align-bottom"}return""},_onTabSizingChanged:function(){this.debounce("_onTabSizingChanged",function(){this._scroll();this._tabChanged(this.selectedItem)},10)},_onIronSelect:function(event){this._tabChanged(event.detail.item,this._previousTab);this._previousTab=event.detail.item;this.cancelDebouncer("tab-changed")},_onIronDeselect:function(event){this.debounce("tab-changed",function(){this._tabChanged(null,this._previousTab);this._previousTab=null},1)},_activateHandler:function(){this._cancelPendingActivation();Polymer.IronMenuBehaviorImpl._activateHandler.apply(this,arguments)},_scheduleActivation:function(item,delay){this._pendingActivationItem=item;this._pendingActivationTimeout=this.async(this._bindDelayedActivationHandler,delay)},_delayedActivationHandler:function(){var item=this._pendingActivationItem;this._pendingActivationItem=undefined;this._pendingActivationTimeout=undefined;item.fire(this.activateEvent,null,{bubbles:true,cancelable:true})},_cancelPendingActivation:function(){if(this._pendingActivationTimeout!==undefined){this.cancelAsync(this._pendingActivationTimeout);this._pendingActivationItem=undefined;this._pendingActivationTimeout=undefined}},_onArrowKeyup:function(event){if(this.autoselect){this._scheduleActivation(this.focusedItem,this.autoselectDelay)}},_onBlurCapture:function(event){if(event.target===this._pendingActivationItem){this._cancelPendingActivation()}},get _tabContainerScrollSize(){return Math.max(0,this.$.tabsContainer.scrollWidth-this.$.tabsContainer.offsetWidth)},_scroll:function(e,detail){if(!this.scrollable){return}var ddx=detail&&-detail.ddx||0;this._affectScroll(ddx)},_down:function(e){this.async(function(){if(this._defaultFocusAsync){this.cancelAsync(this._defaultFocusAsync);this._defaultFocusAsync=null}},1)},_affectScroll:function(dx){this.$.tabsContainer.scrollLeft+=dx;var scrollLeft=this.$.tabsContainer.scrollLeft;this._leftHidden=scrollLeft===0;this._rightHidden=scrollLeft===this._tabContainerScrollSize},_onLeftScrollButtonDown:function(){this._scrollToLeft();this._holdJob=setInterval(this._scrollToLeft.bind(this),this._holdDelay)},_onRightScrollButtonDown:function(){this._scrollToRight();this._holdJob=setInterval(this._scrollToRight.bind(this),this._holdDelay)},_onScrollButtonUp:function(){clearInterval(this._holdJob);this._holdJob=null},_scrollToLeft:function(){this._affectScroll(-this._step)},_scrollToRight:function(){this._affectScroll(this._step)},_tabChanged:function(tab,old){if(!tab){this.$.selectionBar.classList.remove("expand");this.$.selectionBar.classList.remove("contract");this._positionBar(0,0);return}var r=this.$.tabsContent.getBoundingClientRect();var w=r.width;var tabRect=tab.getBoundingClientRect();var tabOffsetLeft=tabRect.left-r.left;this._pos={width:this._calcPercent(tabRect.width,w),left:this._calcPercent(tabOffsetLeft,w)};if(this.noSlide||old==null){this.$.selectionBar.classList.remove("expand");this.$.selectionBar.classList.remove("contract");this._positionBar(this._pos.width,this._pos.left);return}var oldRect=old.getBoundingClientRect();var oldIndex=this.items.indexOf(old);var index=this.items.indexOf(tab);var m=5;this.$.selectionBar.classList.add("expand");var moveRight=oldIndex<index;var isRTL=this._isRTL;if(isRTL){moveRight=!moveRight}if(moveRight){this._positionBar(this._calcPercent(tabRect.left+tabRect.width-oldRect.left,w)-m,this._left)}else{this._positionBar(this._calcPercent(oldRect.left+oldRect.width-tabRect.left,w)-m,this._calcPercent(tabOffsetLeft,w)+m)}if(this.scrollable){this._scrollToSelectedIfNeeded(tabRect.width,tabOffsetLeft)}},_scrollToSelectedIfNeeded:function(tabWidth,tabOffsetLeft){var l=tabOffsetLeft-this.$.tabsContainer.scrollLeft;if(l<0){this.$.tabsContainer.scrollLeft+=l}else{l+=tabWidth-this.$.tabsContainer.offsetWidth;if(l>0){this.$.tabsContainer.scrollLeft+=l}}},_calcPercent:function(w,w0){return 100*w/w0},_positionBar:function(width,left){width=width||0;left=left||0;this._width=width;this._left=left;this.transform("translateX("+left+"%) scaleX("+width/100+")",this.$.selectionBar)},_onBarTransitionEnd:function(e){var cl=this.$.selectionBar.classList;if(cl.contains("expand")){cl.remove("expand");cl.add("contract");this._positionBar(this._pos.width,this._pos.left)}else if(cl.contains("contract")){cl.remove("contract")}}}); \ No newline at end of file
diff --git a/chrome/browser/resources/md_history/lazy_load.vulcanized.html b/chrome/browser/resources/md_history/lazy_load.vulcanized.html index a890f69..9c958e04 100644 --- a/chrome/browser/resources/md_history/lazy_load.vulcanized.html +++ b/chrome/browser/resources/md_history/lazy_load.vulcanized.html
@@ -1097,7 +1097,7 @@ </style> <div class="title-container"> <content select=".title"></content> - <paper-icon-button icon="cr:clear" on-tap="cancel" id="close"> + <paper-icon-button icon="cr:clear" on-tap="cancel" id="close" aria-label$="[[closeText]]"> </paper-icon-button> </div> <div class="body-container">
diff --git a/chrome/browser/resources/md_history/list_container.html b/chrome/browser/resources/md_history/list_container.html index 35b952c..d28fac58 100644 --- a/chrome/browser/resources/md_history/list_container.html +++ b/chrome/browser/resources/md_history/list_container.html
@@ -50,8 +50,7 @@ <paper-button class="cancel-button" on-tap="onDialogCancelTap_"> $i18n{cancel} </paper-button> - <paper-button class="action-button" on-tap="onDialogConfirmTap_" - autofocus> + <paper-button class="action-button" on-tap="onDialogConfirmTap_"> $i18n{deleteConfirm} </paper-button> </div> @@ -65,6 +64,7 @@ $i18n{moreFromSite} </paper-item> <paper-item id="menuRemoveButton" class="menu-item" + disabled="[[!canDeleteHistory_()]]" on-tap="onRemoveFromHistoryTap_"> $i18n{removeFromHistory} </paper-item>
diff --git a/chrome/browser/resources/md_history/list_container.js b/chrome/browser/resources/md_history/list_container.js index a54bc2f..613fa14 100644 --- a/chrome/browser/resources/md_history/list_container.js +++ b/chrome/browser/resources/md_history/list_container.js
@@ -136,6 +136,9 @@ if (this.queryState.searchTerm != '') browserService.recordAction('SearchResultRemove'); this.$.dialog.get().showModal(); + + // TODO(dbeam): remove focus flicker caused by showModal() + focus(). + this.$$('.action-button').focus(); }, /** @@ -276,4 +279,9 @@ * @private */ getSelectedList_: function() { return this.$.content.selectedItem; }, + + /** @private */ + canDeleteHistory_: function() { + return loadTimeData.getBoolean('allowDeletingHistory'); + } });
diff --git a/chrome/browser/resources/md_history/side_bar.html b/chrome/browser/resources/md_history/side_bar.html index 0d0fd5a4..c4c8254 100644 --- a/chrome/browser/resources/md_history/side_bar.html +++ b/chrome/browser/resources/md_history/side_bar.html
@@ -34,7 +34,7 @@ } #clear-browsing-data iron-icon { - -webkit-margin-end: 24px; + -webkit-margin-end: 20px; color: var(--paper-grey-400); height: 20px; margin-bottom: 10px; @@ -54,6 +54,8 @@ iron-selector > a { @apply(--paper-font-subhead); + /* Ensure the focus outline appears correctly (crbug.com/655503). */ + -webkit-margin-end: 4px; -webkit-padding-start: 24px; align-items: center; box-sizing: border-box;
diff --git a/chrome/browser/resources/media_router/elements/route_details/route_details.css b/chrome/browser/resources/media_router/elements/route_details/route_details.css index eaff052..d2207455 100644 --- a/chrome/browser/resources/media_router/elements/route_details/route_details.css +++ b/chrome/browser/resources/media_router/elements/route_details/route_details.css
@@ -5,7 +5,7 @@ #custom-controller { display: inline-block; - height: 136px; + height: 142px; width: 100%; }
diff --git a/chrome/browser/resources/settings/people_page/password_prompt_dialog.html b/chrome/browser/resources/settings/people_page/password_prompt_dialog.html index 5f893f8..235d387 100644 --- a/chrome/browser/resources/settings/people_page/password_prompt_dialog.html +++ b/chrome/browser/resources/settings/people_page/password_prompt_dialog.html
@@ -17,7 +17,8 @@ } </style> - <dialog is="cr-dialog" id="dialog" on-close="onClose_"> + <dialog is="cr-dialog" id="dialog" on-close="onClose_" + close-text="$i18n{close}"> <div class="title">$i18n{passwordPromptTitle}</div> <div class="body">
diff --git a/chrome/browser/resources/settings/people_page/people_page.html b/chrome/browser/resources/settings/people_page/people_page.html index 75f851c1..a9fd8bfd 100644 --- a/chrome/browser/resources/settings/people_page/people_page.html +++ b/chrome/browser/resources/settings/people_page/people_page.html
@@ -200,13 +200,14 @@ <template is="dom-if" if="[[quickUnlockEnabled_]]"> <div class="settings-box two-line" actionable on-tap="onConfigureLockTap_"> - <div class="middle"> - <div>$i18n{lockScreenTitle}</div> + <div class="start"> + $i18n{lockScreenTitle} <div class="secondary"> [[getPasswordState_(hasPin, prefs.settings.enable_screen_lock.value)]] </div> </div> + <button class="subpage-arrow" is="paper-icon-button-light"></button> </div> </template>
diff --git a/chrome/browser/resources/settings/people_page/setup_pin_dialog.html b/chrome/browser/resources/settings/people_page/setup_pin_dialog.html index 3f222420..91beddf 100644 --- a/chrome/browser/resources/settings/people_page/setup_pin_dialog.html +++ b/chrome/browser/resources/settings/people_page/setup_pin_dialog.html
@@ -10,11 +10,11 @@ <style include="settings-shared"></style> <style> .warning { - color: var(--paper-grey-500); + color: var(--paper-grey-700); } .warning > iron-icon { - --iron-icon-fill-color: var(--paper-grey-500); + --iron-icon-fill-color: var(--paper-grey-700); } .error {
diff --git a/chrome/browser/resources/settings/people_page/setup_pin_dialog.js b/chrome/browser/resources/settings/people_page/setup_pin_dialog.js index 72b68c8..14da74e9 100644 --- a/chrome/browser/resources/settings/people_page/setup_pin_dialog.js +++ b/chrome/browser/resources/settings/people_page/setup_pin_dialog.js
@@ -141,11 +141,12 @@ }, /** - * Returns true if the PIN is ready to be changed to a new value. + * Returns true if the currently entered PIN is the same as the initially + * submitted PIN. * @private * @return {boolean} */ - canSubmit_: function() { + isPinConfirmed_: function() { return this.isPinLongEnough_(this.pinKeyboardValue_) && this.initialPin_ == this.pinKeyboardValue_; }, @@ -157,10 +158,17 @@ * @param {string} problemClass */ showProblem_: function(messageId, problemClass) { + var previousMessage = this.problemMessage_; + + // Update problem info. this.problemMessage_ = this.i18n(messageId); this.problemClass_ = problemClass; this.updateStyles(); - }, + + // If the problem message has changed, fire an alert. + if (previousMessage != this.problemMessage_) + this.$.problemDiv.setAttribute('role', 'alert'); + }, /** @private */ hideProblem_: function() { @@ -174,8 +182,8 @@ var isPinLongEnough = this.isPinLongEnough_(this.pinKeyboardValue_); var isWeak = isPinLongEnough && this.isPinWeak_(this.pinKeyboardValue_); - if (!isPinLongEnough && this.pinKeyboardValue_) - this.showProblem_('configurePinTooShort', 'error'); + if (!isPinLongEnough) + this.showProblem_('configurePinTooShort', 'warning'); else if (isWeak) this.showProblem_('configurePinWeakPin', 'warning'); else @@ -184,14 +192,12 @@ this.enableSubmit_ = isPinLongEnough; } else { - var canSubmit = this.canSubmit_(); - - if (!canSubmit && this.pinKeyboardValue_) - this.showProblem_('configurePinMismatched', 'error'); - else + if (this.isPinConfirmed_()) this.hideProblem_(); + else + this.showProblem_('configurePinMismatched', 'warning'); - this.enableSubmit_ = canSubmit; + this.enableSubmit_ = true; } }, @@ -208,8 +214,10 @@ } else { // onPinSubmit_ gets called if the user hits enter on the PIN keyboard. // The PIN is not guaranteed to be valid in that case. - if (!this.canSubmit_()) + if (!this.isPinConfirmed_()) { + this.showProblem_('configurePinMismatched', 'error'); return; + } function onSetModesCompleted(didSet) { if (!didSet) {
diff --git a/chrome/browser/resources/settings/route.js b/chrome/browser/resources/settings/route.js index 4718a1f..2b689e6 100644 --- a/chrome/browser/resources/settings/route.js +++ b/chrome/browser/resources/settings/route.js
@@ -184,7 +184,7 @@ r.EDIT_DICTIONARY = r.LANGUAGES.createChild('/editDictionary'); </if> - r.DOWNLOADS = r.ADVANCED.createSection('/downloadsDirectory', 'downloads'); + r.DOWNLOADS = r.ADVANCED.createSection('/downloads', 'downloads'); r.PRINTING = r.ADVANCED.createSection('/printing', 'printing'); r.CLOUD_PRINTERS = r.PRINTING.createChild('/cloudPrinters');
diff --git a/chrome/browser/resources/settings/settings_menu/settings_menu.html b/chrome/browser/resources/settings/settings_menu/settings_menu.html index b9865ea..912bbd3 100644 --- a/chrome/browser/resources/settings/settings_menu/settings_menu.html +++ b/chrome/browser/resources/settings/settings_menu/settings_menu.html
@@ -170,7 +170,7 @@ <iron-icon icon="settings:language"></iron-icon> $i18n{languagesPageTitle} </div> - <div data-path="/downloadsDirectory" on-tap="openPage_"> + <div data-path="/downloads" on-tap="openPage_"> <iron-icon icon="cr:file-download"></iron-icon> $i18n{downloadsPageTitle} </div>
diff --git a/chrome/browser/resources/settings/settings_page/settings_subpage.html b/chrome/browser/resources/settings/settings_page/settings_subpage.html index c0296af..af7d0c3b2 100644 --- a/chrome/browser/resources/settings/settings_page/settings_subpage.html +++ b/chrome/browser/resources/settings/settings_page/settings_subpage.html
@@ -42,7 +42,8 @@ } </style> <div class="settings-box first"> - <paper-icon-button icon="settings:arrow-back" on-tap="onTapBack_"> + <paper-icon-button icon="settings:arrow-back" on-tap="onTapBack_" + aria-label="$i18n{back}"> </paper-icon-button> <h1>[[pageTitle]]</h1> <template is="dom-if" if="[[searchLabel]]">
diff --git a/chrome/browser/resources/settings/settings_shared_css.html b/chrome/browser/resources/settings/settings_shared_css.html index 7fa95bc..0f852d06 100644 --- a/chrome/browser/resources/settings/settings_shared_css.html +++ b/chrome/browser/resources/settings/settings_shared_css.html
@@ -431,6 +431,7 @@ position: absolute; top: -5px; width: 10px; + z-index: -1; } /* Turns the arrow direction downwards, when the bubble is placed above
diff --git a/chrome/browser/resources/settings/site_settings/compiled_resources2.gyp b/chrome/browser/resources/settings/site_settings/compiled_resources2.gyp index 89395cf..fd7cab2 100644 --- a/chrome/browser/resources/settings/site_settings/compiled_resources2.gyp +++ b/chrome/browser/resources/settings/site_settings/compiled_resources2.gyp
@@ -68,6 +68,7 @@ { 'target_name': 'protocol_handlers', 'dependencies': [ + '<(DEPTH)/ui/webui/resources/cr_elements/cr_action_menu/compiled_resources2.gyp:cr_action_menu', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:web_ui_listener_behavior', 'site_settings_behavior', ],
diff --git a/chrome/browser/resources/settings/site_settings/protocol_handlers.html b/chrome/browser/resources/settings/site_settings/protocol_handlers.html index ab78ee8..265b2f1 100644 --- a/chrome/browser/resources/settings/site_settings/protocol_handlers.html +++ b/chrome/browser/resources/settings/site_settings/protocol_handlers.html
@@ -1,10 +1,9 @@ <link rel="import" href="chrome://resources/html/polymer.html"> <link rel="import" href="chrome://resources/cr_elements/icons.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button.html"> -<link rel="import" href="chrome://resources/polymer/v1_0/paper-item/paper-item.html"> -<link rel="import" href="chrome://resources/polymer/v1_0/paper-menu/paper-menu.html"> -<link rel="import" href="chrome://resources/polymer/v1_0/paper-menu-button/paper-menu-button.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-toggle-button/paper-toggle-button.html"> +<link rel="import" href="chrome://resources/cr_elements/cr_action_menu/cr_action_menu.html"> + <link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html"> <link rel="import" href="/i18n_setup.html"> <link rel="import" href="/settings_shared_css.html"> @@ -42,35 +41,33 @@ <div class="favicon-image" style$="[[computeSiteIcon(item.host)]]"> </div> <div class="middle" > - <div>[[item.host]]</div> - <div class="secondary" + <div class="protocol-host">[[item.host]]</div> + <div class="secondary protocol-default" hidden$="[[!isDefault_(index, protocol.default_handler)]]"> $i18n{handlerIsDefault} </div> </div> - <paper-menu-button> - <paper-icon-button icon="cr:more-vert" - class="dropdown-trigger"> - </paper-icon-button> - <paper-menu id="actionMenu" class="dropdown-content" actionable - on-iron-activate="onActionMenuIronActivate_" - attr-for-selected="menu-value"> - <paper-item menu-value$="[[menuActions_.SET_DEFAULT]]" - hidden$="[[isDefault_(index, protocol.default_handler)]]" - actionable> - $i18n{handlerSetDefault} - </paper-item> - <paper-item menu-value$="[[menuActions_.REMOVE]]" actionable> - $i18n{handlerRemove} - </paper-item> - </paper-menu> - </paper-menu-button> + <paper-icon-button icon="cr:more-vert" on-tap="showMenu_" + class="dropdown-trigger"> + </paper-icon-button> </div> </template> </div> </template> + + <dialog is="cr-action-menu"> + <button class="dropdown-item" role="option" on-tap="onDefaultTap_" + hidden$="[[isModelDefault_(actionMenuModel_)]]" + id="defaultButton"> + $i18n{handlerSetDefault} + </button> + <button class="dropdown-item" role="option" on-tap="onRemoveTap_" + id="removeButton"> + $i18n{handlerRemove} + </button> + </dialog> </template> <script src="protocol_handlers.js"></script> </dom-module>
diff --git a/chrome/browser/resources/settings/site_settings/protocol_handlers.js b/chrome/browser/resources/settings/site_settings/protocol_handlers.js index 404d3df..b175e83 100644 --- a/chrome/browser/resources/settings/site_settings/protocol_handlers.js +++ b/chrome/browser/resources/settings/site_settings/protocol_handlers.js
@@ -51,14 +51,10 @@ protocols: Array, /** - * The possible menu actions. - * @type {MenuActions} + * The targetted object for menu operations. + * @private {?Object} */ - menuActions_: { - type: Object, - value: MenuActions, - readOnly: true, - }, + actionMenuModel_: Object }, ready: function() { @@ -133,18 +129,50 @@ }, /** - * A handler when an action is selected in the action menu. - * @param {!{model: !{item: ProtocolHandlerEntry}, - * detail: !{selected: string}}} event + * The handler for when "Set Default" is selected in the action menu. * @private */ - onActionMenuIronActivate_: function(event) { - var protocol = event.model.item.protocol; - var url = event.model.item.spec; - if (event.detail.selected == MenuActions.SET_DEFAULT) { - this.browserProxy.setProtocolDefault(protocol, url); - } else if (event.detail.selected == MenuActions.REMOVE) { - this.browserProxy.removeProtocolHandler(protocol, url); - } + onDefaultTap_: function() { + var item = this.actionMenuModel_.item; + + this.$$('dialog[is=cr-action-menu]').close(); + this.actionMenuModel_ = null; + this.browserProxy.setProtocolDefault(item.protocol, item.spec); }, + + /** + * The handler for when "Remove" is selected in the action menu. + * @private + */ + onRemoveTap_: function() { + var item = this.actionMenuModel_.item; + + this.$$('dialog[is=cr-action-menu]').close(); + this.actionMenuModel_ = null; + this.browserProxy.removeProtocolHandler(item.protocol, item.spec); + }, + + /** + * Checks whether or not the selected actionMenuModel is the default handler + * for its protocol. + * @return {boolean} if actionMenuModel_ is default handler of its protocol. + */ + isModelDefault_: function() { + return !!this.actionMenuModel_ && (this.actionMenuModel_.index == + this.actionMenuModel_.protocol.default_handler); + }, + + /** + * A handler to show the action menu next to the clicked menu button. + * @param {!{model: !{protocol: HandlerEntry, item: ProtocolEntry, + * index: number}}} event + * @private + */ + showMenu_: function(event) { + this.actionMenuModel_ = event.model; + /** @type {!CrActionMenuElement} */ ( + this.$$('dialog[is=cr-action-menu]')).showAt( + /** @type {!Element} */ ( + Polymer.dom(/** @type {!Event} */ (event)).localTarget)); + } });
diff --git a/chrome/browser/resources/settings/site_settings/usb_devices.html b/chrome/browser/resources/settings/site_settings/usb_devices.html index a371110a..eed92587 100644 --- a/chrome/browser/resources/settings/site_settings/usb_devices.html +++ b/chrome/browser/resources/settings/site_settings/usb_devices.html
@@ -1,5 +1,6 @@ <link rel="import" href="chrome://resources/html/polymer.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button.html"> +<link rel="import" href="chrome://resources/cr_elements/cr_action_menu/cr_action_menu.html"> <link rel="import" href="/i18n_setup.html"> <link rel="import" href="/settings_shared_css.html">
diff --git a/chrome/browser/resources/vr_shell/vr_shell_ui.css b/chrome/browser/resources/vr_shell/vr_shell_ui.css index 043ed0a79..07daf35f 100644 --- a/chrome/browser/resources/vr_shell/vr_shell_ui.css +++ b/chrome/browser/resources/vr_shell/vr_shell_ui.css
@@ -12,6 +12,15 @@ position: absolute; top: 0; transform: scale(0.25, 0.25); + transform-origin: left top; + width: 400%; +} + +/* This class manages the position of elements on the texture page. + * Each UI element should have a bounding div of this class. */ +.ui-element { + float: left; + margin: 2px; } .webvr-message-box { @@ -19,16 +28,11 @@ display: flex; flex-direction: column; justify-content: center; - position: absolute; } -/* Permanent security warning for WebVR. This uses a fixed-size absolutely - * positioned DIV, the rectangle must match kWebVrWarningPermanentRect - * in vr_shell.cc for use as a GL textured quad. */ +/* Permanent security warning for WebVR. */ #webvr-not-secure-permanent { height: 128px; - left: 0; - top: 0; width: 512px; } @@ -64,13 +68,9 @@ white-space: nowrap; } -/* Transient security warning for WebVR. This uses a fixed-size absolutely - * positioned DIV, the rectangle must match kWebVrWarningTransientRect - * in vr_shell.cc for use as a GL textured quad. */ +/* Transient security warning for WebVR. */ #webvr-not-secure-transient { height: 256px; - left: 0; - top: 128px; width: 512px; } @@ -89,18 +89,12 @@ line-height: 1.4; max-height: 210px; min-height: 160px; + overflow: hidden; padding: 20px; text-align: center; width: 512px; } -.round-button { - height: 136px; - left: 512px; - position: absolute; - width: 96px; -} - .round-button .button { background-color: #eee; background-position: center; @@ -108,45 +102,31 @@ background-size: contain; border-radius: 50%; height: 96px; + margin: auto auto; opacity: 0.8; - position: absolute; - top: 0; transition: opacity 150ms ease-in-out; width: 96px; } .round-button .caption { - bottom: 0; color: white; font-size: 24px; - left: 50%; + max-width: 192px; opacity: 0; - position: absolute; - transform: translateX(-50%); + overflow: hidden; + text-align: center; transition: opacity 150ms ease-in-out; - z-index: 100; -} - -#back { - top: 0; + white-space: nowrap; } #back .button { background-image: url(../../../../ui/webui/resources/images/vr_back.svg); } -#reload { - top: 138px; -} - #reload .button { background-image: url(../../../../ui/webui/resources/images/vr_reload.svg); } -#forward { - top: 276px; -} - #forward .button { background-image: url(../../../../ui/webui/resources/images/vr_back.svg); transform: scaleX(-1); @@ -155,47 +135,45 @@ #reload-ui-button { background-color: #555; color: white; - font-size: 16; - height: 24px; - left: 610px; - opacity: 1; - position: absolute; - text-align: center; - top: 0; - width: 96px; + font-size: 24px; + padding: 12px; } #omni { --tranX: 0; --tranY: -0.5; --tranZ: -1.0; + align-items: center; background-color: rgba(255, 255, 255, 0.9); border-radius: 100px; box-sizing: border-box; + display: flex; height: 104px; - left: 0; + justify-content: center; + margin-bottom: 60px; + margin-top: 0; opacity: 1; - position: absolute; - top: 402px; transition: opacity 250ms ease, margin-top 250ms ease; white-space: nowrap; - width: 504px; + width: 512px; } -#omni #connection-security { - left: 35px; - position: absolute; - top: 50%; - transform: translateY(-50%); +#omni-content { + align-items: center; + display: flex; + max-width: 448px; +} + +#omni .connection-security { + height: 50px; + margin-right: 10px; + width: 50px; } #omni #url { color: #252525; font-size: 34px; - left: 80px; - position: absolute; - top: 50%; - transform: translateY(-50%); + overflow: hidden; white-space: nowrap; } @@ -204,6 +182,7 @@ } #omni.hide { + margin-bottom: 0; margin-top: 60px; opacity: 0; } @@ -213,8 +192,7 @@ } #omni.idle { - background-color: #ECECEC; - box-shadow: 0 2px 24px 0 rgba(0, 0, 0, 0.1); + background-color: #ececec; } #omni.idle #domain {
diff --git a/chrome/browser/resources/vr_shell/vr_shell_ui.html b/chrome/browser/resources/vr_shell/vr_shell_ui.html index 2efc4fa..4c295d2 100644 --- a/chrome/browser/resources/vr_shell/vr_shell_ui.html +++ b/chrome/browser/resources/vr_shell/vr_shell_ui.html
@@ -19,40 +19,44 @@ </head> <body> <div id="ui"> - <div id="webvr-not-secure-permanent" class="webvr-message-box"> + <div id="webvr-not-secure-permanent" class="webvr-message-box ui-element"> <div class="webvr-box"> <img class="webvr-not-secure-icon" width="36" height="36" src="../../../../ui/webui/resources/images/i_circle.svg"> <div class="webvr-string">$i18n{insecureWebVrContentPermanent}</div> </div> </div> - <div id="webvr-not-secure-transient" class="webvr-message-box"> + <div id="webvr-not-secure-transient" class="webvr-message-box ui-element"> <div> <div>$i18n{insecureWebVrContentTransient}</div> </div> </div> - - <div id="omni"> - <img id="connection-security" - src="../../../../ui/webui/resources/images/i_circle.svg"> - <div id="url"> - <span id="domain"></span><span id="path"></span> + <div class="ui-element"> + <div id="omni" class="idle"> + <div id="omni-content"> + <img id="omni-insecure-icon" class="connection-security" + src="../../../../ui/webui/resources/images/i_circle.svg"> + <img id="omni-secure-icon" class="connection-security" + src="../../../../ui/webui/resources/images/lock.svg"> + <div id="url"> + <span id="domain"></span><span id="path"></span> + </div> + </div> </div> </div> - - <div class="round-button" id="back"> + <div id="back" class="round-button ui-element"> <div class="button"></div> <div class="caption">$i18n{back}</div> </div> - <div class="round-button" id="reload"> + <div id="reload" class="round-button ui-element"> <div class="button"></div> <div class="caption">$i18n{reload}</div> </div> - <div class="round-button" id="forward"> + <div id="forward" class="round-button ui-element"> <div class="button"></div> <div class="caption">$i18n{forward}</div> </div> - <div id="reload-ui-button">Reload UI</div> + <div id="reload-ui-button" class="ui-element">Reload UI</div> </div> </body>
diff --git a/chrome/browser/resources/vr_shell/vr_shell_ui.js b/chrome/browser/resources/vr_shell/vr_shell_ui.js index c00c8182..1d363bf 100644 --- a/chrome/browser/resources/vr_shell/vr_shell_ui.js +++ b/chrome/browser/resources/vr_shell/vr_shell_ui.js
@@ -44,21 +44,20 @@ class DomUiElement { constructor(domId) { let domElement = document.querySelector(domId); - let style = window.getComputedStyle(domElement); - // Pull copy rectangle from DOM element properties. - let pixelX = Math.round(domElement.offsetLeft / scaleFactor); - let pixelY = Math.round(domElement.offsetTop / scaleFactor); - let pixelWidth = Math.round( - parseInt(style.getPropertyValue('width')) / scaleFactor); - let pixelHeight = Math.round( - parseInt(style.getPropertyValue('height')) / scaleFactor); + // Pull copy rectangle from the position of the element. + let rect = domElement.getBoundingClientRect(); + let pixelX = Math.floor(rect.left); + let pixelY = Math.floor(rect.top); + let pixelWidth = Math.ceil(rect.right) - pixelX; + let pixelHeight = Math.ceil(rect.bottom) - pixelY; let element = new api.UiElement(pixelX, pixelY, pixelWidth, pixelHeight); element.setSize(scaleFactor * pixelWidth / 1000, scaleFactor * pixelHeight / 1000); // Pull additional custom properties from CSS. + let style = window.getComputedStyle(domElement); element.setTranslation( getStyleFloat(style, '--tranX'), getStyleFloat(style, '--tranY'), @@ -252,7 +251,7 @@ class Omnibox { constructor(contentQuadId) { - this.setSecure(false); + this.setSecureOrigin(false); this.domUiElement = new DomUiElement('#omni'); let update = new api.UiElementUpdate(); update.setVisible(false); @@ -275,10 +274,11 @@ omnibox.querySelector('#path').innerHTML = path; } - setSecure(secure) { - let image = secure ? 'lock.svg' : 'i_circle.svg'; - let path = '../../../../ui/webui/resources/images/' + image; - document.querySelector('#connection-security').src = path; + setSecureOrigin(secure) { + document.querySelector('#omni-secure-icon').style.display = + (secure ? 'block' : 'none'); + document.querySelector('#omni-insecure-icon').style.display = + (!secure ? 'block' : 'none'); } }; @@ -304,6 +304,7 @@ setSecureOrigin(secure) { this.secureOriginWarnings.setSecureOrigin(secure); + this.omnibox.setSecureOrigin(secure); } setReloadUiEnabled(enabled) {
diff --git a/chrome/browser/safe_browsing/browser_feature_extractor.cc b/chrome/browser/safe_browsing/browser_feature_extractor.cc index 392dda7..aee391d 100644 --- a/chrome/browser/safe_browsing/browser_feature_extractor.cc +++ b/chrome/browser/safe_browsing/browser_feature_extractor.cc
@@ -212,7 +212,7 @@ // be cautious. url_index = index; } else if (index < url_index) { - if (entry->GetURL().host() == request_url.host()) { + if (entry->GetURL().host_piece() == request_url.host_piece()) { first_host_index = index; } else { // We have found the possibly phishing url, but we are no longer on the
diff --git a/chrome/browser/safe_browsing/mock_permission_report_sender.cc b/chrome/browser/safe_browsing/mock_permission_report_sender.cc index b6a8c0c..46510c9 100644 --- a/chrome/browser/safe_browsing/mock_permission_report_sender.cc +++ b/chrome/browser/safe_browsing/mock_permission_report_sender.cc
@@ -17,9 +17,12 @@ MockPermissionReportSender::~MockPermissionReportSender() { } -void MockPermissionReportSender::Send(const GURL& report_uri, - base::StringPiece content_type, - base::StringPiece report) { +void MockPermissionReportSender::Send( + const GURL& report_uri, + base::StringPiece content_type, + base::StringPiece report, + const base::Callback<void()>& success_callback, + const base::Callback<void(const GURL&, int)>& error_callback) { latest_report_uri_ = report_uri; report.CopyToString(&latest_report_); content_type.CopyToString(&latest_content_type_);
diff --git a/chrome/browser/safe_browsing/mock_permission_report_sender.h b/chrome/browser/safe_browsing/mock_permission_report_sender.h index e8d6b76c..00d4bcc 100644 --- a/chrome/browser/safe_browsing/mock_permission_report_sender.h +++ b/chrome/browser/safe_browsing/mock_permission_report_sender.h
@@ -17,9 +17,12 @@ ~MockPermissionReportSender() override; - void Send(const GURL& report_uri, - base::StringPiece content_type, - base::StringPiece report) override; + void Send( + const GURL& report_uri, + base::StringPiece content_type, + base::StringPiece report, + const base::Callback<void()>& success_callback, + const base::Callback<void(const GURL&, int)>& error_callback) override; const GURL& latest_report_uri();
diff --git a/chrome/browser/safe_browsing/permission_reporter.cc b/chrome/browser/safe_browsing/permission_reporter.cc index fee2d35..8356864 100644 --- a/chrome/browser/safe_browsing/permission_reporter.cc +++ b/chrome/browser/safe_browsing/permission_reporter.cc
@@ -170,8 +170,9 @@ std::string serialized_report; BuildReport(report_info, &serialized_report); permission_report_sender_->Send(GURL(kPermissionActionReportingUploadUrl), - "application/octet-stream", - serialized_report); + "application/octet-stream", serialized_report, + base::Closure(), + base::Callback<void(const GURL&, int)>()); } // static
diff --git a/chrome/browser/safe_browsing/safe_browsing_blocking_page.cc b/chrome/browser/safe_browsing/safe_browsing_blocking_page.cc index 41f222e..02986de 100644 --- a/chrome/browser/safe_browsing/safe_browsing_blocking_page.cc +++ b/chrome/browser/safe_browsing/safe_browsing_blocking_page.cc
@@ -690,8 +690,11 @@ l10n_util::GetStringUTF8(IDS_SAFE_BROWSING_PRIVACY_POLICY_PAGE).c_str()); load_time_data->SetString( security_interstitials::kOptInLink, - l10n_util::GetStringFUTF16(IDS_SAFE_BROWSING_MALWARE_REPORTING_AGREE, - base::UTF8ToUTF16(privacy_link))); + l10n_util::GetStringFUTF16( + ChooseOptInTextResource(*profile()->GetPrefs(), + IDS_SAFE_BROWSING_MALWARE_REPORTING_AGREE, + IDS_SAFE_BROWSING_SCOUT_REPORTING_AGREE), + base::UTF8ToUTF16(privacy_link))); load_time_data->SetBoolean( security_interstitials::kBoxChecked, IsExtendedReportingEnabled(*profile()->GetPrefs()));
diff --git a/chrome/browser/safe_browsing/safe_browsing_database.cc b/chrome/browser/safe_browsing/safe_browsing_database.cc index 586ee45..bd87b89b 100644 --- a/chrome/browser/safe_browsing/safe_browsing_database.cc +++ b/chrome/browser/safe_browsing/safe_browsing_database.cc
@@ -27,6 +27,7 @@ #include "build/build_config.h" #include "chrome/browser/safe_browsing/safe_browsing_store_file.h" #include "components/safe_browsing_db/prefix_set.h" +#include "components/safe_browsing_db/v4_protocol_manager_util.h" #include "content/public/browser/browser_thread.h" #include "crypto/sha2.h" #include "net/base/ip_address.h" @@ -958,12 +959,9 @@ bool SafeBrowsingDatabaseNew::ContainsMalwareIP(const std::string& ip_address) { net::IPAddress address; - if (!address.AssignFromIPLiteral(ip_address)) + if (!V4ProtocolManagerUtil::GetIPV6AddressFromString(ip_address, &address)) { return false; - if (address.IsIPv4()) - address = net::ConvertIPv4ToIPv4MappedIPv6(address); - if (!address.IsIPv6()) - return false; // better safe than sorry. + } std::unique_ptr<ReadTransaction> txn = state_manager_.BeginReadTransaction(); const IPBlacklist* ip_blacklist = txn->ip_blacklist();
diff --git a/chrome/browser/safe_browsing/safe_browsing_service.cc b/chrome/browser/safe_browsing/safe_browsing_service.cc index 7fa4cbaa..a5aa510 100644 --- a/chrome/browser/safe_browsing/safe_browsing_service.cc +++ b/chrome/browser/safe_browsing/safe_browsing_service.cc
@@ -639,6 +639,9 @@ prefs_map_[pref_service] = std::move(registrar); RefreshState(); + // Initialize SafeBrowsing prefs on startup. + InitializeSafeBrowsingPrefs(pref_service); + // Record the current pref state. UMA_HISTOGRAM_BOOLEAN("SafeBrowsing.Pref.General", pref_service->GetBoolean(prefs::kSafeBrowsingEnabled));
diff --git a/chrome/browser/search/iframe_source.cc b/chrome/browser/search/iframe_source.cc index e9dd3b64..925c97e 100644 --- a/chrome/browser/search/iframe_source.cc +++ b/chrome/browser/search/iframe_source.cc
@@ -40,9 +40,8 @@ const net::URLRequest* request) const { const std::string& path = request->url().path(); return InstantIOContext::ShouldServiceRequest(request) && - request->url().SchemeIs(chrome::kChromeSearchScheme) && - request->url().host() == GetSource() && - ServesPath(path); + request->url().SchemeIs(chrome::kChromeSearchScheme) && + request->url().host_piece() == GetSource() && ServesPath(path); } bool IframeSource::ShouldDenyXFrameOptions() const {
diff --git a/chrome/browser/search/local_ntp_source.cc b/chrome/browser/search/local_ntp_source.cc index 172f9a19..b192b0b 100644 --- a/chrome/browser/search/local_ntp_source.cc +++ b/chrome/browser/search/local_ntp_source.cc
@@ -252,7 +252,7 @@ bool LocalNtpSource::ShouldServiceRequest( const net::URLRequest* request) const { - DCHECK(request->url().host() == chrome::kChromeSearchLocalNtpHost); + DCHECK(request->url().host_piece() == chrome::kChromeSearchLocalNtpHost); if (!InstantIOContext::ShouldServiceRequest(request)) return false;
diff --git a/chrome/browser/search/search.cc b/chrome/browser/search/search.cc index 1d975cc..44f7ccdc0 100644 --- a/chrome/browser/search/search.cc +++ b/chrome/browser/search/search.cc
@@ -291,8 +291,8 @@ bool ShouldUseProcessPerSiteForInstantURL(const GURL& url, Profile* profile) { return ShouldAssignURLToInstantRenderer(url, profile) && - (url.host() == chrome::kChromeSearchLocalNtpHost || - url.host() == chrome::kChromeSearchRemoteNtpHost); + (url.host_piece() == chrome::kChromeSearchLocalNtpHost || + url.host_piece() == chrome::kChromeSearchRemoteNtpHost); } bool IsNTPURL(const GURL& url, Profile* profile) {
diff --git a/chrome/browser/sessions/session_common_utils.cc b/chrome/browser/sessions/session_common_utils.cc index 75973b7..a46d983c 100644 --- a/chrome/browser/sessions/session_common_utils.cc +++ b/chrome/browser/sessions/session_common_utils.cc
@@ -10,6 +10,6 @@ bool ShouldTrackURLForRestore(const GURL& url) { return url.is_valid() && !(url.SchemeIs(content::kChromeUIScheme) && - (url.host() == chrome::kChromeUIQuitHost || - url.host() == chrome::kChromeUIRestartHost)); + (url.host_piece() == chrome::kChromeUIQuitHost || + url.host_piece() == chrome::kChromeUIRestartHost)); }
diff --git a/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc b/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc index 1b219b8..04f44b5 100644 --- a/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc +++ b/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc
@@ -20,6 +20,7 @@ #include "components/data_use_measurement/core/data_use_user_data.h" #include "components/spellcheck/browser/spellcheck_platform.h" #include "components/spellcheck/common/spellcheck_common.h" +#include "components/spellcheck/spellcheck_build_features.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_process_host.h" #include "net/base/load_flags.h" @@ -116,7 +117,7 @@ void SpellcheckHunspellDictionary::Load() { DCHECK_CURRENTLY_ON(BrowserThread::UI); -#if defined(USE_BROWSER_SPELLCHECKER) +#if BUILDFLAG(USE_BROWSER_SPELLCHECKER) if (spellcheck_platform::SpellCheckerAvailable() && spellcheck_platform::PlatformSupportsLanguage(language_)) { use_browser_spellchecker_ = true;
diff --git a/chrome/browser/spellchecker/spellcheck_message_filter.cc b/chrome/browser/spellchecker/spellcheck_message_filter.cc index 3a51d9d..43c9a36 100644 --- a/chrome/browser/spellchecker/spellcheck_message_filter.cc +++ b/chrome/browser/spellchecker/spellcheck_message_filter.cc
@@ -17,6 +17,7 @@ #include "components/spellcheck/browser/spelling_service_client.h" #include "components/spellcheck/common/spellcheck_marker.h" #include "components/spellcheck/common/spellcheck_messages.h" +#include "components/spellcheck/spellcheck_build_features.h" #include "content/public/browser/render_process_host.h" #include "net/url_request/url_fetcher.h" @@ -37,7 +38,7 @@ message.type() == SpellCheckHostMsg_NotifyChecked::ID || message.type() == SpellCheckHostMsg_RespondDocumentMarkers::ID) *thread = BrowserThread::UI; -#if !defined(USE_BROWSER_SPELLCHECKER) +#if !BUILDFLAG(USE_BROWSER_SPELLCHECKER) if (message.type() == SpellCheckHostMsg_CallSpellingService::ID) *thread = BrowserThread::UI; #endif @@ -52,7 +53,7 @@ OnNotifyChecked) IPC_MESSAGE_HANDLER(SpellCheckHostMsg_RespondDocumentMarkers, OnRespondDocumentMarkers) -#if !defined(USE_BROWSER_SPELLCHECKER) +#if !BUILDFLAG(USE_BROWSER_SPELLCHECKER) IPC_MESSAGE_HANDLER(SpellCheckHostMsg_CallSpellingService, OnCallSpellingService) #endif @@ -106,7 +107,7 @@ render_process_id_, markers); } -#if !defined(USE_BROWSER_SPELLCHECKER) +#if !BUILDFLAG(USE_BROWSER_SPELLCHECKER) void SpellCheckMessageFilter::OnCallSpellingService( int route_id, int identifier,
diff --git a/chrome/browser/spellchecker/spellcheck_message_filter.h b/chrome/browser/spellchecker/spellcheck_message_filter.h index 6e02fdc..84347aff 100644 --- a/chrome/browser/spellchecker/spellcheck_message_filter.h +++ b/chrome/browser/spellchecker/spellcheck_message_filter.h
@@ -11,6 +11,7 @@ #include "base/compiler_specific.h" #include "components/spellcheck/browser/spelling_service_client.h" +#include "components/spellcheck/spellcheck_build_features.h" #include "content/public/browser/browser_message_filter.h" class SpellCheckMarker; @@ -36,7 +37,7 @@ void OnSpellCheckerRequestDictionary(); void OnNotifyChecked(const base::string16& word, bool misspelled); void OnRespondDocumentMarkers(const std::vector<uint32_t>& markers); -#if !defined(USE_BROWSER_SPELLCHECKER) +#if !BUILDFLAG(USE_BROWSER_SPELLCHECKER) void OnCallSpellingService(int route_id, int identifier, const base::string16& text,
diff --git a/chrome/browser/spellchecker/spellcheck_message_filter_unittest.cc b/chrome/browser/spellchecker/spellcheck_message_filter_unittest.cc index ad933ea..7781c26 100644 --- a/chrome/browser/spellchecker/spellcheck_message_filter_unittest.cc +++ b/chrome/browser/spellchecker/spellcheck_message_filter_unittest.cc
@@ -15,6 +15,7 @@ #include "chrome/test/base/testing_profile.h" #include "components/spellcheck/common/spellcheck_marker.h" #include "components/spellcheck/common/spellcheck_messages.h" +#include "components/spellcheck/spellcheck_build_features.h" #include "content/public/test/test_browser_thread_bundle.h" #include "ipc/ipc_message.h" #include "testing/gtest/include/gtest/gtest.h" @@ -34,7 +35,7 @@ return spellcheck_.get(); } -#if !defined(USE_BROWSER_SPELLCHECKER) +#if !BUILDFLAG(USE_BROWSER_SPELLCHECKER) void OnTextCheckComplete(int route_id, int identifier, const std::vector<SpellCheckMarker>& markers, @@ -63,7 +64,7 @@ SpellCheckHostMsg_RequestDictionary::ID, SpellCheckHostMsg_NotifyChecked::ID, SpellCheckHostMsg_RespondDocumentMarkers::ID, -#if !defined(USE_BROWSER_SPELLCHECKER) +#if !BUILDFLAG(USE_BROWSER_SPELLCHECKER) SpellCheckHostMsg_CallSpellingService::ID, #endif }; @@ -80,7 +81,7 @@ } } -#if !defined(USE_BROWSER_SPELLCHECKER) +#if !BUILDFLAG(USE_BROWSER_SPELLCHECKER) TEST(SpellCheckMessageFilterTest, OnTextCheckCompleteTestCustomDictionary) { static const std::string kCustomWord = "Helllo"; static const int kRouteId = 0;
diff --git a/chrome/browser/spellchecker/spellcheck_service.cc b/chrome/browser/spellchecker/spellcheck_service.cc index 7de1e82..e60a310 100644 --- a/chrome/browser/spellchecker/spellcheck_service.cc +++ b/chrome/browser/spellchecker/spellcheck_service.cc
@@ -24,6 +24,7 @@ #include "components/spellcheck/common/spellcheck_bdict_language.h" #include "components/spellcheck/common/spellcheck_common.h" #include "components/spellcheck/common/spellcheck_messages.h" +#include "components/spellcheck/spellcheck_build_features.h" #include "components/user_prefs/user_prefs.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" @@ -53,7 +54,7 @@ dictionaries_pref.Init(spellcheck::prefs::kSpellCheckDictionaries, prefs); std::string first_of_dictionaries; -#if defined(USE_BROWSER_SPELLCHECKER) +#if BUILDFLAG(USE_BROWSER_SPELLCHECKER) // Ensure that the renderer always knows the platform spellchecking language. // This language is used for initialization of the text iterator. If the // iterator is not initialized, then the context menu does not show spellcheck @@ -80,7 +81,7 @@ } single_dictionary_pref.SetValue(""); -#endif // defined(USE_BROWSER_SPELLCHECKER) +#endif // BUILDFLAG(USE_BROWSER_SPELLCHECKER) std::string language_code; std::string country_code;
diff --git a/chrome/browser/ssl/cert_report_helper.cc b/chrome/browser/ssl/cert_report_helper.cc index a9622b1..e4d77ad 100644 --- a/chrome/browser/ssl/cert_report_helper.cc +++ b/chrome/browser/ssl/cert_report_helper.cc
@@ -85,7 +85,10 @@ load_time_data->SetString( security_interstitials::kOptInLink, - l10n_util::GetStringFUTF16(IDS_SAFE_BROWSING_MALWARE_REPORTING_AGREE, + l10n_util::GetStringFUTF16(safe_browsing::ChooseOptInTextResource( + *GetProfile(web_contents_)->GetPrefs(), + IDS_SAFE_BROWSING_MALWARE_REPORTING_AGREE, + IDS_SAFE_BROWSING_SCOUT_REPORTING_AGREE), base::UTF8ToUTF16(privacy_link))); }
diff --git a/chrome/browser/ssl/chrome_expect_ct_reporter.cc b/chrome/browser/ssl/chrome_expect_ct_reporter.cc index 8a50a200..d10a652 100644 --- a/chrome/browser/ssl/chrome_expect_ct_reporter.cc +++ b/chrome/browser/ssl/chrome_expect_ct_reporter.cc
@@ -116,8 +116,7 @@ net::URLRequestContext* request_context) : report_sender_( new net::ReportSender(request_context, - net::ReportSender::DO_NOT_SEND_COOKIES, - base::Bind(RecordUMAOnFailure))) {} + net::ReportSender::DO_NOT_SEND_COOKIES)) {} ChromeExpectCTReporter::~ChromeExpectCTReporter() {} @@ -177,5 +176,6 @@ UMA_HISTOGRAM_BOOLEAN("SSL.ExpectCTReportSendingAttempt", true); report_sender_->Send(report_uri, "application/json; charset=utf-8", - serialized_report); + serialized_report, base::Closure(), + base::Bind(RecordUMAOnFailure)); }
diff --git a/chrome/browser/ssl/chrome_expect_ct_reporter_unittest.cc b/chrome/browser/ssl/chrome_expect_ct_reporter_unittest.cc index dcbbea6..8a0cf82 100644 --- a/chrome/browser/ssl/chrome_expect_ct_reporter_unittest.cc +++ b/chrome/browser/ssl/chrome_expect_ct_reporter_unittest.cc
@@ -38,19 +38,24 @@ : ReportSender(nullptr, net::ReportSender::DO_NOT_SEND_COOKIES) {} ~TestCertificateReportSender() override {} - void Send(const GURL& report_uri, - base::StringPiece content_type, - base::StringPiece serialized_report) override { + void Send( + const GURL& report_uri, + base::StringPiece content_type, + base::StringPiece serialized_report, + const base::Callback<void()>& success_callback, + const base::Callback<void(const GURL&, int)>& error_callback) override { latest_report_uri_ = report_uri; serialized_report.CopyToString(&latest_serialized_report_); content_type.CopyToString(&latest_content_type_); } - const GURL& latest_report_uri() { return latest_report_uri_; } + const GURL& latest_report_uri() const { return latest_report_uri_; } - const std::string& latest_content_type() { return latest_content_type_; } + const std::string& latest_content_type() const { + return latest_content_type_; + } - const std::string& latest_serialized_report() { + const std::string& latest_serialized_report() const { return latest_serialized_report_; }
diff --git a/chrome/browser/subresource_filter/subresource_filter_browsertest.cc b/chrome/browser/subresource_filter/subresource_filter_browsertest.cc index 28c822b..e691fa7 100644 --- a/chrome/browser/subresource_filter/subresource_filter_browsertest.cc +++ b/chrome/browser/subresource_filter/subresource_filter_browsertest.cc
@@ -7,7 +7,6 @@ #include "base/command_line.h" #include "base/files/file_path.h" -#include "base/memory/ptr_util.h" #include "base/path_service.h" #include "base/run_loop.h" #include "chrome/browser/browser_process.h" @@ -16,7 +15,7 @@ #include "chrome/common/chrome_paths.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" -#include "components/subresource_filter/core/browser/ruleset_distributor.h" +#include "components/subresource_filter/content/browser/content_ruleset_service_delegate.h" #include "components/subresource_filter/core/browser/ruleset_service.h" #include "components/subresource_filter/core/browser/subresource_filter_features.h" #include "components/subresource_filter/core/browser/subresource_filter_features_test_support.h" @@ -32,33 +31,30 @@ namespace { -void CloseFile(base::File) {} - -class RulesetDistributionListener : public RulesetDistributor { +class RulesetDistributionListener { public: - RulesetDistributionListener() {} - ~RulesetDistributionListener() override {} - - void AwaitDistribution() { - base::RunLoop run_loop; - quit_closure_ = run_loop.QuitClosure(); - run_loop.Run(); + RulesetDistributionListener() + : delegate_(static_cast<ContentRulesetServiceDelegate*>( + g_browser_process->subresource_filter_ruleset_service() + ->delegate())) { + delegate_->SetRulesetPublishedCallbackForTesting(run_loop_.QuitClosure()); } + ~RulesetDistributionListener() { + delegate_->SetRulesetPublishedCallbackForTesting(base::Closure()); + } + + void AwaitDistribution() { run_loop_.Run(); } + private: - void PublishNewVersion(base::File file) override { - content::BrowserThread::PostTask( - content::BrowserThread::FILE, FROM_HERE, - base::Bind(&CloseFile, base::Passed(&file))); - if (!quit_closure_.is_null()) - quit_closure_.Run(); - } - - base::Closure quit_closure_; + ContentRulesetServiceDelegate* delegate_; + base::RunLoop run_loop_; DISALLOW_COPY_AND_ASSIGN(RulesetDistributionListener); }; +void CloseFile(base::File) {} + } // namespace using subresource_filter::testing::ScopedSubresourceFilterFeatureToggle; @@ -140,15 +136,13 @@ ASSERT_NO_FATAL_FAILURE( ruleset_creator_.CreateRulesetToDisallowURLsWithPathSuffix( suffix, &test_ruleset_pair)); - RulesetDistributionListener* listener = new RulesetDistributionListener(); - g_browser_process->subresource_filter_ruleset_service() - ->RegisterDistributor(base::WrapUnique(listener)); subresource_filter::UnindexedRulesetInfo unindexed_ruleset_info; unindexed_ruleset_info.content_version = test_ruleset_content_version; unindexed_ruleset_info.ruleset_path = test_ruleset_pair.unindexed.path; + RulesetDistributionListener distribution_listener; g_browser_process->subresource_filter_ruleset_service() ->IndexAndStoreAndPublishRulesetIfNeeded(unindexed_ruleset_info); - listener->AwaitDistribution(); + distribution_listener.AwaitDistribution(); } private:
diff --git a/chrome/browser/sync/chrome_sync_client.cc b/chrome/browser/sync/chrome_sync_client.cc index 7551d44..05a808c 100644 --- a/chrome/browser/sync/chrome_sync_client.cc +++ b/chrome/browser/sync/chrome_sync_client.cc
@@ -54,6 +54,7 @@ #include "components/password_manager/sync/browser/password_model_worker.h" #include "components/search_engines/search_engine_data_type_controller.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" +#include "components/spellcheck/spellcheck_build_features.h" #include "components/sync/base/report_unrecoverable_error.h" #include "components/sync/driver/glue/browser_thread_model_worker.h" #include "components/sync/driver/glue/ui_model_worker.h" @@ -93,7 +94,7 @@ #include "chrome/browser/supervised_user/supervised_user_whitelist_service.h" #endif -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) #include "chrome/browser/spellchecker/spellcheck_factory.h" #include "chrome/browser/spellchecker/spellcheck_service.h" #endif @@ -365,7 +366,7 @@ return base::WeakPtr<history::TypedUrlSyncableService>(); return history->GetTypedUrlSyncableService()->AsWeakPtr(); } -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) case syncer::DICTIONARY: return SpellcheckServiceFactory::GetForContext(profile_)-> GetCustomDictionary()->AsWeakPtr();
diff --git a/chrome/browser/sync/sessions/sessions_sync_manager_unittest.cc b/chrome/browser/sync/sessions/sessions_sync_manager_unittest.cc index 886c2a4..c2023ae 100644 --- a/chrome/browser/sync/sessions/sessions_sync_manager_unittest.cc +++ b/chrome/browser/sync/sessions/sessions_sync_manager_unittest.cc
@@ -549,11 +549,17 @@ int GetEntryCount() const override { return entries_.size(); } SessionID::id_type GetWindowId() const override { - return SessionID::id_type(); + return window_id_; + } + void SetWindowId(SessionID::id_type window_id) { + window_id_ = window_id; } SessionID::id_type GetSessionId() const override { - return SessionID::id_type(); + return tab_id_; + } + void SetSessionId(SessionID::id_type id) { + tab_id_ = id; } bool IsBeingDestroyed() const override { return false; } @@ -594,6 +600,8 @@ int current_entry_index_; bool is_supervised_; int sync_id_; + SessionID::id_type tab_id_ = 0; + SessionID::id_type window_id_ = 0; std::vector<std::unique_ptr<const sessions::SerializedNavigationEntry>> blocked_navigations_; std::vector<std::unique_ptr<content::NavigationEntry>> entries_; @@ -988,7 +996,9 @@ ASSERT_EQ(1U, windows.size()); SyncedTabDelegateFake t1_override, t2_override; t1_override.SetSyncId(1); // No WebContents by default. + t1_override.SetSessionId(kNewTabId); t2_override.SetSyncId(2); // No WebContents by default. + t2_override.SetSessionId(t2_entity.session().tab().tab_id()); SyncedWindowDelegateOverride window_override(*windows.begin()); window_override.OverrideTabAt(1, &t1_override, kNewTabId); window_override.OverrideTabAt(2, &t2_override, @@ -1006,12 +1016,15 @@ new syncer::SyncErrorFactoryMock())); // There should be two changes, one for the fully associated tab, and - // one for the tab_id update to t1. t2 shouldn't need to be updated. - ASSERT_EQ(2U, FilterOutLocalHeaderChanges(&out)->size()); + // one each for the tab_id updates to t1 and t2. + ASSERT_EQ(3U, FilterOutLocalHeaderChanges(&out)->size()); EXPECT_EQ(SyncChange::ACTION_UPDATE, out[0].change_type()); EXPECT_EQ(SyncChange::ACTION_UPDATE, out[1].change_type()); + EXPECT_EQ(SyncChange::ACTION_UPDATE, out[2].change_type()); EXPECT_EQ(kNewTabId, out[1].sync_data().GetSpecifics().session().tab().tab_id()); + EXPECT_EQ(t2_entity.session().tab().tab_id(), + out[2].sync_data().GetSpecifics().session().tab().tab_id()); // Verify TabLinks. SessionsSyncManager::TabLinksMap tab_map = manager()->local_tab_map_; @@ -1021,10 +1034,6 @@ EXPECT_EQ(1, tab_map.find(kNewTabId)->second->tab_node_id()); int t0_tab_id = out[0].sync_data().GetSpecifics().session().tab().tab_id(); EXPECT_EQ(0, tab_map.find(t0_tab_id)->second->tab_node_id()); - // TODO(tim): Once bug 337057 is fixed, we can issue an OnLocalTabModified - // from here (using an override similar to above) to return a new tab id - // and verify that we don't see any node creations in the SyncChangeProcessor - // (similar to how SessionsSyncManagerTest.OnLocalTabModified works.) } // Ensure model association updates the window ID for tabs whose window's ID has @@ -1050,6 +1059,7 @@ // SyncedTabDelegateFake is a placeholder (no WebContents) by default. SyncedTabDelegateFake t0_override; t0_override.SetSyncId(t0_entity.session().tab_node_id()); + t0_override.SetWindowId(kNewWindowId); // Set up the window override with the new window ID and placeholder tab. const std::set<const SyncedWindowDelegate*>& windows = @@ -1307,10 +1317,10 @@ tag, tab_nums1, &tabs)); // Update associator with the session's meta node, window, and tabs. - manager()->UpdateTrackerWithForeignSession(meta, base::Time()); + manager()->UpdateTrackerWithSpecifics(meta, base::Time()); for (std::vector<sync_pb::SessionSpecifics>::iterator iter = tabs.begin(); iter != tabs.end(); ++iter) { - manager()->UpdateTrackerWithForeignSession(*iter, base::Time()); + manager()->UpdateTrackerWithSpecifics(*iter, base::Time()); } ASSERT_TRUE(manager()->GetAllForeignSessions(&foreign_sessions)); ASSERT_EQ(1U, foreign_sessions.size()); @@ -2070,13 +2080,9 @@ // Tabs are ordered by sessionid in tab_map, so should be able to traverse // the tree based on order of tabs created SessionsSyncManager::TabLinksMap::iterator iter = tab_map.begin(); - ASSERT_EQ(2, iter->second->tab()->GetEntryCount()); - EXPECT_EQ(GURL("http://foo1"), iter->second->tab()->GetVirtualURLAtIndex(0)); - EXPECT_EQ(GURL("http://foo2"), iter->second->tab()->GetVirtualURLAtIndex(1)); + EXPECT_EQ(GURL("http://foo2"), iter->second->url()); iter++; - ASSERT_EQ(2, iter->second->tab()->GetEntryCount()); - EXPECT_EQ(GURL("http://bar1"), iter->second->tab()->GetVirtualURLAtIndex(0)); - EXPECT_EQ(GURL("http://bar2"), iter->second->tab()->GetVirtualURLAtIndex(1)); + EXPECT_EQ(GURL("http://bar2"), iter->second->url()); } TEST_F(SessionsSyncManagerTest, ForeignSessionModifiedTime) {
diff --git a/chrome/browser/sync/test/integration/bookmarks_helper.cc b/chrome/browser/sync/test/integration/bookmarks_helper.cc index 2fc3a42c..2bf99e1f 100644 --- a/chrome/browser/sync/test/integration/bookmarks_helper.cc +++ b/chrome/browser/sync/test/integration/bookmarks_helper.cc
@@ -235,8 +235,6 @@ model->GetFavicon(node); observer.WaitForGetFavicon(); } - EXPECT_TRUE(node->is_favicon_loaded()); - EXPECT_FALSE(model->GetFavicon(node).IsEmpty()); return FaviconData(model->GetFavicon(node), node->icon_url()); } @@ -906,6 +904,18 @@ return "Waiting for matching models"; } +BookmarksMatchVerifierChecker::BookmarksMatchVerifierChecker() + : MultiClientStatusChangeChecker( + sync_datatype_helper::test()->GetSyncServices()) {} + +bool BookmarksMatchVerifierChecker::IsExitConditionSatisfied() { + return bookmarks_helper::AllModelsMatchVerifier(); +} + +std::string BookmarksMatchVerifierChecker::GetDebugMessage() const { + return "Waiting for model to match verifier"; +} + BookmarksTitleChecker::BookmarksTitleChecker(int profile_index, const std::string& title, int expected_count)
diff --git a/chrome/browser/sync/test/integration/bookmarks_helper.h b/chrome/browser/sync/test/integration/bookmarks_helper.h index ae9fd7f..115de8e 100644 --- a/chrome/browser/sync/test/integration/bookmarks_helper.h +++ b/chrome/browser/sync/test/integration/bookmarks_helper.h
@@ -227,6 +227,16 @@ std::string GetDebugMessage() const override; }; +// Checker used to block until bookmarks match the verifier bookmark model. +class BookmarksMatchVerifierChecker : public MultiClientStatusChangeChecker { + public: + BookmarksMatchVerifierChecker(); + + // StatusChangeChecker implementation. + bool IsExitConditionSatisfied() override; + std::string GetDebugMessage() const override; +}; + // Checker used to block until the actual number of bookmarks with the given // title match the expected count. // TODO(pvalenzuela): Remove this class and instead use
diff --git a/chrome/browser/sync/test/integration/single_client_sessions_sync_test.cc b/chrome/browser/sync/test/integration/single_client_sessions_sync_test.cc index 18da86c..ed25ef1 100644 --- a/chrome/browser/sync/test/integration/single_client_sessions_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_sessions_sync_test.cc
@@ -10,11 +10,13 @@ #include "chrome/browser/sync/test/integration/sync_test.h" #include "chrome/browser/sync/test/integration/typed_urls_helper.h" #include "chrome/browser/sync/test/integration/updated_progress_marker_checker.h" +#include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "components/browser_sync/profile_sync_service.h" #include "components/history/core/browser/history_types.h" #include "components/sessions/core/session_types.h" #include "components/sync/base/time.h" +#include "components/sync/driver/sync_driver_switches.h" #include "components/sync/test/fake_server/fake_server_verifier.h" #include "components/sync/test/fake_server/sessions_hierarchy.h" @@ -36,6 +38,18 @@ SingleClientSessionsSyncTest() : SyncTest(SINGLE_CLIENT) {} ~SingleClientSessionsSyncTest() override {} + void SetUpCommandLine(base::CommandLine* cl) override { + // This is a hacky override of the switches set in + // SyncTest::SetUpCommandLine() to avoid the switch that speeds up nudge + // delays. CookieJarMismatch asserts exact histogram counts assuming that + // sync is relatively slow, so we preserve that assumption. + if (!cl->HasSwitch(switches::kDisableBackgroundNetworking)) + cl->AppendSwitch(switches::kDisableBackgroundNetworking); + + if (!cl->HasSwitch(switches::kSyncShortInitialRetryOverride)) + cl->AppendSwitch(switches::kSyncShortInitialRetryOverride); + } + private: DISALLOW_COPY_AND_ASSIGN(SingleClientSessionsSyncTest); };
diff --git a/chrome/browser/sync/test/integration/sync_test.cc b/chrome/browser/sync/test/integration/sync_test.cc index eb8f850..0800d650 100644 --- a/chrome/browser/sync/test/integration/sync_test.cc +++ b/chrome/browser/sync/test/integration/sync_test.cc
@@ -307,6 +307,9 @@ if (!cl->HasSwitch(switches::kSyncShortInitialRetryOverride)) cl->AppendSwitch(switches::kSyncShortInitialRetryOverride); + + if (!cl->HasSwitch(switches::kSyncShortNudgeDelayForTest)) + cl->AppendSwitch(switches::kSyncShortNudgeDelayForTest); } void SyncTest::AddOptionalTypesToCommandLine(base::CommandLine* cl) {}
diff --git a/chrome/browser/sync/test/integration/two_client_bookmarks_sync_test.cc b/chrome/browser/sync/test/integration/two_client_bookmarks_sync_test.cc index 6db9fda..f04b7a1 100644 --- a/chrome/browser/sync/test/integration/two_client_bookmarks_sync_test.cc +++ b/chrome/browser/sync/test/integration/two_client_bookmarks_sync_test.cc
@@ -109,30 +109,26 @@ ASSERT_NE(nullptr, AddURL(0, "Google", google_url)); ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); ASSERT_NE(nullptr, AddURL(1, "Yahoo", GURL("http://www.yahoo.com"))); - ASSERT_TRUE(GetClient(1)->AwaitMutualSyncCycleCompletion(GetClient(0))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); const BookmarkNode* new_folder = AddFolder(0, 2, "New Folder"); Move(0, GetUniqueNodeByURL(0, google_url), new_folder, 0); SetTitle(0, GetBookmarkBarNode(0)->GetChild(0), "Yahoo!!"); ASSERT_NE(nullptr, AddURL(0, GetBookmarkBarNode(0), 1, "CNN", GURL("http://www.cnn.com"))); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); ASSERT_NE(nullptr, AddURL(1, "Facebook", GURL("http://www.facebook.com"))); - ASSERT_TRUE(GetClient(1)->AwaitMutualSyncCycleCompletion(GetClient(0))); - ASSERT_TRUE(AllModelsMatchVerifier()); + + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); SortChildren(1, GetBookmarkBarNode(1)); - ASSERT_TRUE(GetClient(1)->AwaitMutualSyncCycleCompletion(GetClient(0))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); DisableVerifier(); SetTitle(0, GetUniqueNodeByURL(0, google_url), "Google++"); SetTitle(1, GetUniqueNodeByURL(1, google_url), "Google--"); - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); } IN_PROC_BROWSER_TEST_F(TwoClientBookmarksSyncTest, SimultaneousURLChanges) { @@ -150,12 +146,10 @@ DisableVerifier(); ASSERT_NE(nullptr, SetURL(0, GetUniqueNodeByURL(0, initial_url), second_url)); ASSERT_NE(nullptr, SetURL(1, GetUniqueNodeByURL(1, initial_url), third_url)); - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); SetTitle(0, GetBookmarkBarNode(0)->GetChild(0), "Google1"); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); } // Test Scribe ID - 370558. @@ -164,8 +158,7 @@ ASSERT_TRUE(AllModelsMatchVerifier()); ASSERT_NE(nullptr, AddFolder(0, kGenericFolderName)); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 370559. @@ -175,26 +168,22 @@ ASSERT_TRUE(AllModelsMatchVerifier()); ASSERT_NE(nullptr, AddURL(0, kGenericURLTitle, GURL(kGenericURL))); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 370489. IN_PROC_BROWSER_TEST_F(TwoClientBookmarksSyncTest, SC_AddFirstBMWithFavicon) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; ASSERT_TRUE(AllModelsMatchVerifier()); - const GURL page_url(kGenericURL); const GURL icon_url("http://www.google.com/favicon.ico"); const BookmarkNode* bookmark = AddURL(0, kGenericURLTitle, page_url); - ASSERT_NE(nullptr, bookmark); ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); SetFavicon(0, bookmark, icon_url, CreateFavicon(SK_ColorWHITE), bookmarks_helper::FROM_UI); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test that the history service logic for not losing the hidpi versions of @@ -223,19 +212,16 @@ ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); SetFavicon(0, bookmark0, icon_url1, CreateFavicon(SK_ColorWHITE), bookmarks_helper::FROM_UI); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); const BookmarkNode* bookmark1 = GetUniqueNodeByURL(1, page_url); SetFavicon(1, bookmark1, icon_url1, CreateFavicon(SK_ColorBLUE), bookmarks_helper::FROM_UI); - ASSERT_TRUE(GetClient(1)->AwaitMutualSyncCycleCompletion(GetClient(0))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); SetFavicon(0, bookmark0, icon_url2, CreateFavicon(SK_ColorGREEN), bookmarks_helper::FROM_UI); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test that if sync does not modify a favicon bitmap's data that it does not @@ -269,8 +255,7 @@ ExpireFavicon(0, bookmark0); CheckFaviconExpired(0, icon_url); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); // Change the bookmark's title for profile 1. Changing the title will cause // the bookmark's favicon data to be synced from profile 1 to profile 0 even @@ -279,8 +264,7 @@ ASSERT_NE(kNewTitle, kGenericURLTitle); const BookmarkNode* bookmark1 = GetUniqueNodeByURL(1, page_url); SetTitle(1, bookmark1, kNewTitle); - ASSERT_TRUE(GetClient(1)->AwaitMutualSyncCycleCompletion(GetClient(0))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); // The favicon for profile 0 should still be expired. CheckFaviconExpired(0, icon_url); @@ -308,15 +292,13 @@ SetFavicon(0, bookmark01, icon_url, CreateFavicon(SK_ColorWHITE), bookmarks_helper::FROM_UI); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); // Set |page_url2| with the new (blue) favicon at |icon_url|. The sync favicon // for both |page_url1| and |page_url2| should be updated to the blue one. SetFavicon(0, bookmark02, icon_url, CreateFavicon(SK_ColorBLUE), bookmarks_helper::FROM_UI); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); // Set the title for |page_url1|. This should not revert either of the // bookmark favicons back to white. @@ -324,8 +306,7 @@ ASSERT_STRNE(kGenericURLTitle, kNewTitle); const BookmarkNode* bookmark11 = GetUniqueNodeByURL(1, page_url1); SetTitle(1, bookmark11, std::string(kNewTitle)); - ASSERT_TRUE(GetClient(1)->AwaitMutualSyncCycleCompletion(GetClient(0))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 370560. @@ -336,8 +317,7 @@ ASSERT_NE(nullptr, AddURL(0, "FTP UR", GURL("ftp://user:password@host:1234/path"))); ASSERT_NE(nullptr, AddURL(0, "File UR", GURL("file://host/path"))); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 370561. @@ -349,8 +329,7 @@ const BookmarkNode* folder = AddFolder(0, kGenericFolderName); ASSERT_NE(nullptr, folder); ASSERT_NE(nullptr, AddURL(0, folder, 0, kGenericURLTitle, GURL(kGenericURL))); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 370562. @@ -365,8 +344,7 @@ ASSERT_NE(nullptr, AddURL(0, i, title, url)); ASSERT_NE(nullptr, AddURL(0, GetOtherNode(0), i, title, url)); } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 370563. @@ -398,8 +376,7 @@ GURL url = GURL(IndexedURL(i)); ASSERT_NE(nullptr, AddURL(0, GetOtherNode(0), i, title, url)); } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 370641. @@ -412,8 +389,7 @@ GURL url1 = GURL(IndexedURL(1)); ASSERT_NE(nullptr, AddURL(0, kGenericURLTitle, url0)); ASSERT_NE(nullptr, AddURL(0, kGenericURLTitle, url1)); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 370639 - Add bookmarks with different name and same URL. @@ -426,8 +402,7 @@ std::string title1 = IndexedURLTitle(1); ASSERT_NE(nullptr, AddURL(0, title0, GURL(kGenericURL))); ASSERT_NE(nullptr, AddURL(0, title1, GURL(kGenericURL))); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 371817. @@ -438,13 +413,11 @@ std::string title = IndexedURLTitle(1); const BookmarkNode* bookmark = AddURL(0, title, GURL(kGenericURL)); ASSERT_NE(nullptr, bookmark); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); std::string new_title = IndexedURLTitle(2); SetTitle(0, bookmark, new_title); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 371822. @@ -455,13 +428,11 @@ GURL url = GURL(IndexedURL(1)); const BookmarkNode* bookmark = AddURL(0, kGenericURLTitle, url); ASSERT_NE(nullptr, bookmark); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); GURL new_url = GURL(IndexedURL(2)); ASSERT_NE(nullptr, SetURL(0, bookmark, new_url)); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } @@ -474,17 +445,14 @@ std::string title = IndexedURLTitle(1); const BookmarkNode* bookmark = AddURL(0, title, GURL(kGenericURL)); ASSERT_NE(nullptr, bookmark); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); std::string new_title = IndexedURLTitle(2); SetTitle(0, bookmark, new_title); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); SetTitle(0, bookmark, title); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 371823 - Renaming the same bookmark URL twice. @@ -496,17 +464,14 @@ GURL url = GURL(IndexedURL(1)); const BookmarkNode* bookmark = AddURL(0, kGenericURLTitle, url); ASSERT_NE(nullptr, bookmark); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); GURL new_url = GURL(IndexedURL(2)); ASSERT_NE(nullptr, SetURL(0, bookmark, new_url)); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); ASSERT_NE(nullptr, SetURL(0, bookmark, url)); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 371824. @@ -517,13 +482,11 @@ std::string title = IndexedFolderName(1); const BookmarkNode* folder = AddFolder(0, title); ASSERT_NE(nullptr, AddURL(0, folder, 0, kGenericURLTitle, GURL(kGenericURL))); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); std::string new_title = IndexedFolderName(2); SetTitle(0, folder, new_title); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 371825. @@ -533,13 +496,11 @@ std::string title = IndexedFolderName(1); const BookmarkNode* folder = AddFolder(0, title); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); std::string new_title = IndexedFolderName(2); SetTitle(0, folder, new_title); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 371826. @@ -561,13 +522,11 @@ ASSERT_NE(nullptr, AddFolder(0, folder, i, title)); } } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); std::string new_title = IndexedFolderName(2); SetTitle(0, folder, new_title); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 371827. @@ -595,13 +554,11 @@ ASSERT_NE(nullptr, AddFolder(0, subfolder, i, title)); } } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); std::string new_title = IndexedSubfolderName(2); SetTitle(0, subfolder, new_title); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 371828. @@ -613,16 +570,14 @@ std::string title = IndexedURLTitle(1); const BookmarkNode* bookmark = AddURL(0, title, url); ASSERT_NE(nullptr, bookmark); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); GURL new_url = GURL(IndexedURL(2)); std::string new_title = IndexedURLTitle(2); bookmark = SetURL(0, bookmark, new_url); ASSERT_NE(nullptr, bookmark); SetTitle(0, bookmark, new_title); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 371832. @@ -632,12 +587,10 @@ ASSERT_TRUE(AllModelsMatchVerifier()); ASSERT_NE(nullptr, AddURL(0, kGenericURLTitle, GURL(kGenericURL))); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); Remove(0, GetBookmarkBarNode(0), 0); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 371833. @@ -651,12 +604,10 @@ GURL url = GURL(IndexedURL(i)); ASSERT_NE(nullptr, AddURL(0, i, title, url)); } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); Remove(0, GetBookmarkBarNode(0), 0); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 371835. @@ -672,12 +623,10 @@ GURL url = GURL(IndexedURL(i)); ASSERT_NE(nullptr, AddURL(0, folder, i, title, url)); } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); Remove(0, folder, 0); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 371836. @@ -693,12 +642,10 @@ GURL url = GURL(IndexedURL(i)); ASSERT_NE(nullptr, AddURL(0, folder, i, title, url)); } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); Remove(0, folder, folder->child_count() - 1); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 371856. @@ -714,12 +661,10 @@ GURL url = GURL(IndexedURL(i)); ASSERT_NE(nullptr, AddURL(0, folder, i, title, url)); } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); Remove(0, folder, 4); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 371857. @@ -735,15 +680,13 @@ GURL url = GURL(IndexedURL(i)); ASSERT_NE(nullptr, AddURL(0, folder, i, title, url)); } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); int child_count = folder->child_count(); for (int i = 0; i < child_count; ++i) { Remove(0, folder, 0); } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 371858. @@ -753,12 +696,10 @@ ASSERT_TRUE(AllModelsMatchVerifier()); ASSERT_NE(nullptr, AddFolder(0, kGenericFolderName)); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); Remove(0, GetBookmarkBarNode(0), 0); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 371869. @@ -778,12 +719,10 @@ ASSERT_NE(nullptr, AddFolder(0, i, title)); } } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); Remove(0, GetBookmarkBarNode(0), 0); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 371879. @@ -810,12 +749,10 @@ GURL url = GURL(IndexedURL(i)); ASSERT_NE(nullptr, AddURL(0, folder, i, title, url)); } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); Remove(0, GetBookmarkBarNode(0), 1); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 371880. @@ -861,12 +798,10 @@ } } } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); Remove(0, GetBookmarkBarNode(0), 1); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 371882. @@ -895,12 +830,10 @@ ASSERT_NE(nullptr, AddFolder(0, subfolder, i, title)); } } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); Remove(0, folder, 0); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 371931. @@ -917,12 +850,10 @@ const BookmarkNode* bookmark1 = AddURL(0, 1, title1, url1); ASSERT_NE(nullptr, bookmark0); ASSERT_NE(nullptr, bookmark1); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); Move(0, bookmark0, GetBookmarkBarNode(0), 2); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 371933. @@ -935,12 +866,10 @@ GURL url = GURL(IndexedURL(i)); ASSERT_NE(nullptr, AddURL(0, i, title, url)); } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); ReverseChildOrder(0, GetBookmarkBarNode(0)); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 371954. @@ -964,8 +893,7 @@ GURL url = GURL(IndexedURL(i)); ASSERT_NE(nullptr, AddURL(0, i, title, url)); } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); int num_bookmarks_to_move = GetBookmarkBarNode(0)->child_count() - 2; @@ -998,8 +926,7 @@ GURL url = GURL(IndexedURL(i)); ASSERT_NE(nullptr, AddURL(0, folder, i, title, url)); } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); int num_bookmarks_to_move = folder->child_count() - 2; for (int i = 0; i < num_bookmarks_to_move; ++i) { @@ -1030,15 +957,13 @@ GURL url = GURL(IndexedURL(i + 3)); ASSERT_NE(nullptr, AddURL(0, subfolder, i, title, url)); } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); for (int i = 0; i < 3; ++i) { GURL url = GURL(IndexedURL(i)); Move(0, GetUniqueNodeByURL(0, url), subfolder, i + 10); } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 371964. @@ -1062,15 +987,13 @@ GURL url = GURL(IndexedURL(i + 3)); ASSERT_NE(nullptr, AddURL(0, subfolder, i, title, url)); } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); for (int i = 0; i < 3; ++i) { GURL url = GURL(IndexedURL(i + 3)); Move(0, GetUniqueNodeByURL(0, url), folder, i + 4); } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 371967. @@ -1099,8 +1022,7 @@ GURL url = GURL(IndexedURL(i + 10)); ASSERT_NE(nullptr, AddURL(0, folder_L10, i, title, url)); } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); GURL url10 = GURL(IndexedURL(10)); Move(0, GetUniqueNodeByURL( @@ -1109,8 +1031,7 @@ Move(0, GetUniqueNodeByURL(0, url11), folder_L0, 0); GURL url12 = GURL(IndexedURL(12)); Move(0, GetUniqueNodeByURL(0, url12), folder_L0, 1); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 371968. @@ -1140,8 +1061,7 @@ GURL url = GURL(IndexedURL(i + 10)); ASSERT_NE(nullptr, AddURL(0, folder_L0, 0, title, url)); } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); GURL url10 = GURL(IndexedURL(10)); Move(0, GetUniqueNodeByURL(0, url10), folder_L10, folder_L10->child_count()); @@ -1149,8 +1069,7 @@ Move(0, GetUniqueNodeByURL(0, url11), folder_L10, 0); GURL url12 = GURL(IndexedURL(12)); Move(0, GetUniqueNodeByURL(0, url12), folder_L10, 1); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 371980. @@ -1177,12 +1096,10 @@ folder = AddFolder( 0, GetBookmarkBarNode(0)->child_count(), kGenericFolderName); ASSERT_NE(nullptr, folder); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); Move(0, folder, folder_L5, folder_L5->child_count()); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 371997. @@ -1213,12 +1130,10 @@ GURL url = GURL(IndexedURL(i)); ASSERT_NE(nullptr, AddURL(0, folder, i, title, url)); } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); Move(0, folder, folder_L5, folder_L5->child_count()); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 372006. @@ -1249,12 +1164,10 @@ GURL url = GURL(IndexedURL(i)); ASSERT_NE(nullptr, AddURL(0, folder, i, title, url)); } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); Move(0, folder, GetBookmarkBarNode(0), GetBookmarkBarNode(0)->child_count()); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 372026. @@ -1273,12 +1186,10 @@ ASSERT_NE(nullptr, AddURL(0, folder, j, title, url)); } } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); ReverseChildOrder(0, GetBookmarkBarNode(0)); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 372028. @@ -1297,12 +1208,10 @@ ASSERT_NE(nullptr, AddURL(0, folder, j, title, url)); } } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); ReverseChildOrder(0, GetBookmarkBarNode(0)); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } // Test Scribe ID - 373379. @@ -1320,8 +1229,7 @@ GURL url1 = GURL(IndexedURL(2*i+1)); ASSERT_NE(nullptr, AddURL(1, title1, url1)); } - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); ASSERT_FALSE(ContainsDuplicateBookmarks(0)); } @@ -1340,8 +1248,7 @@ ASSERT_NE(nullptr, AddURL(0, title, url)); ASSERT_NE(nullptr, AddURL(1, title, url)); } - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); } // Test Scribe ID - 373506. @@ -1371,8 +1278,7 @@ ASSERT_NE(nullptr, AddURL(1, folder1, 2, "bOOKMARK 2", GURL(kGenericURL))); ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); ASSERT_FALSE(ContainsDuplicateBookmarks(0)); } @@ -1399,8 +1305,7 @@ } ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); ASSERT_FALSE(ContainsDuplicateBookmarks(0)); } @@ -1424,8 +1329,7 @@ } ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); ASSERT_FALSE(ContainsDuplicateBookmarks(0)); } @@ -1443,8 +1347,7 @@ } ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); ASSERT_FALSE(ContainsDuplicateBookmarks(0)); } @@ -1467,8 +1370,7 @@ ASSERT_NE(nullptr, AddURL(1, folder1, i, title1, url1)); } ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); ASSERT_FALSE(ContainsDuplicateBookmarks(0)); } @@ -1509,8 +1411,7 @@ ASSERT_NE(nullptr, AddURL(1, title, url)); } ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); ASSERT_FALSE(ContainsDuplicateBookmarks(0)); } @@ -1535,8 +1436,7 @@ } } ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); ASSERT_FALSE(ContainsDuplicateBookmarks(0)); } @@ -1559,8 +1459,7 @@ } ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); ASSERT_FALSE(ContainsDuplicateBookmarks(0)); ASSERT_FALSE(ContainsDuplicateBookmarks(1)); } @@ -1591,8 +1490,7 @@ AddURL(1, folder1, 4, IndexedURLTitle(1), GURL(IndexedURL(1)))); ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); ASSERT_FALSE(ContainsDuplicateBookmarks(0)); } @@ -1622,8 +1520,7 @@ AddURL(1, folder1, 3, IndexedURLTitle(8), GURL(IndexedURL(8)))); ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); ASSERT_FALSE(ContainsDuplicateBookmarks(0)); } @@ -1647,8 +1544,7 @@ } ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); ASSERT_FALSE(ContainsDuplicateBookmarks(0)); } @@ -1676,8 +1572,7 @@ } ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); for (int i = 1; i < 5 ; ++i) { ASSERT_EQ(i, CountBookmarksWithTitlesMatching(1, IndexedURLTitle(i))); @@ -1695,8 +1590,7 @@ ASSERT_FALSE(AllModelsMatch()); ASSERT_TRUE(GetClient(1)->EnableSyncForDatatype(syncer::BOOKMARKS)); - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); } // TCM ID - 7343544. @@ -1713,8 +1607,7 @@ ASSERT_FALSE(AllModelsMatch()); ASSERT_TRUE(GetClient(1)->EnableSyncForAllDatatypes()); - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); } // TCM ID - 3662298 - Test adding duplicate folder - Both with different BMs @@ -1737,8 +1630,7 @@ } ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); ASSERT_FALSE(ContainsDuplicateBookmarks(0)); } @@ -1788,8 +1680,7 @@ GURL url = GURL(IndexedURL(i)); ASSERT_NE(nullptr, AddURL(0, folder0, i, title, url)); } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); ASSERT_FALSE(ContainsDuplicateBookmarks(0)); DisableVerifier(); @@ -1797,8 +1688,7 @@ SetTitle(0, GetUniqueNodeByURL(0, url), "Title++"); SetTitle(1, GetUniqueNodeByURL(1, url), "Title--"); - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); ASSERT_FALSE(ContainsDuplicateBookmarks(0)); } @@ -1815,8 +1705,7 @@ GURL url = GURL(IndexedURL(i)); ASSERT_NE(nullptr, AddURL(0, folder0, i, title, url)); } - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); ASSERT_FALSE(ContainsDuplicateBookmarks(0)); DisableVerifier(); @@ -1826,8 +1715,7 @@ ASSERT_TRUE(SetURL( 1, GetUniqueNodeByURL(1, url), GURL("http://www.google.com/11"))); - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); ASSERT_FALSE(ContainsDuplicateBookmarks(0)); } @@ -1876,29 +1764,25 @@ } ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); ASSERT_FALSE(ContainsDuplicateBookmarks(0)); // Simultaneously rename folder A on both clients. SetTitle(0, folderA[0], "Folder A++"); SetTitle(1, folderA[1], "Folder A--"); - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); ASSERT_FALSE(ContainsDuplicateBookmarks(0)); // Simultaneously rename folder B on both clients. SetTitle(0, folderB[0], "Folder B++"); SetTitle(1, folderB[1], "Folder B--"); - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); ASSERT_FALSE(ContainsDuplicateBookmarks(0)); // Simultaneously rename folder C on both clients. SetTitle(0, folderC[0], "Folder C++"); SetTitle(1, folderC[1], "Folder C--"); - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); ASSERT_FALSE(ContainsDuplicateBookmarks(0)); } @@ -1971,8 +1855,7 @@ ASSERT_NE(nullptr, AddURL(0, IndexedURLTitle(1), GURL(IndexedURL(1)))); ASSERT_NE(nullptr, AddFolder(0, IndexedFolderName(0))); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); } IN_PROC_BROWSER_TEST_F(TwoClientBookmarksSyncTest, @@ -1984,8 +1867,7 @@ ASSERT_NE(nullptr, AddURL(0, 0, IndexedURLTitle(0), GURL(IndexedURL(0)))); ASSERT_NE(nullptr, AddURL(0, 1, IndexedURLTitle(1), GURL(IndexedURL(1)))); ASSERT_NE(nullptr, AddURL(0, 2, IndexedURLTitle(2), GURL(IndexedURL(2)))); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); // Set a passphrase and enable encryption on Client 0. Client 1 will not // understand the bookmark updates. @@ -2008,14 +1890,12 @@ ASSERT_TRUE(PassphraseRequiredChecker(GetSyncService(1)).Wait()); ASSERT_TRUE(GetSyncService(1)->SetDecryptionPassphrase(kValidPassphrase)); ASSERT_TRUE(PassphraseAcceptedChecker(GetSyncService(1)).Wait()); - ASSERT_TRUE(AwaitQuiescence()); - EXPECT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); ASSERT_EQ(0, GetClient(1)->GetLastCycleSnapshot().num_encryption_conflicts()); // Ensure everything is syncing normally by appending a final bookmark. ASSERT_NE(nullptr, AddURL(1, 5, IndexedURLTitle(5), GURL(IndexedURL(5)))); - ASSERT_TRUE(GetClient(1)->AwaitMutualSyncCycleCompletion(GetClient(0))); - EXPECT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); ASSERT_EQ(0, GetClient(1)->GetLastCycleSnapshot().num_encryption_conflicts()); } @@ -2055,8 +1935,7 @@ Move(1, node, node->parent(), rand_pos); } - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); // Now make changes to client 1 first. for (size_t i = 0; i < num_bookmarks; ++i) { @@ -2076,8 +1955,7 @@ Move(0, node, node->parent(), rand_pos); } - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); } // Trigger the server side creation of Synced Bookmarks. Ensure both clients @@ -2093,8 +1971,7 @@ // Add a bookmark on Client 0 and ensure it syncs over. This will also trigger // both clients downloading the new Synced Bookmarks folder. ASSERT_NE(nullptr, AddURL(0, "Google", GURL("http://www.google.com"))); - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); // Now add a bookmark within the Synced Bookmarks folder and ensure it syncs // over. @@ -2102,8 +1979,7 @@ ASSERT_TRUE(synced_bookmarks); ASSERT_NE(nullptr, AddURL(0, synced_bookmarks, 0, "Google2", GURL("http://www.google2.com"))); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); } IN_PROC_BROWSER_TEST_F(TwoClientBookmarksSyncTest, @@ -2147,8 +2023,7 @@ ASSERT_TRUE( AddURL(0, GetBookmarkBarNode(0), 2, "Gmai", GURL("http://gmail.com"))); - ASSERT_TRUE(AwaitQuiescence()); - ASSERT_TRUE(AllModelsMatch()); + ASSERT_TRUE(BookmarksMatchChecker().Wait()); // Remove all RemoveAll(0); @@ -2192,8 +2067,7 @@ // Verify that adding a bookmark is observed by the second Profile. GURL google_url("http://www.google.com"); ASSERT_NE(nullptr, AddURL(0, "Google", google_url)); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); ASSERT_EQ(1, bar_node0->child_count()); ASSERT_EQ(1, bar_node1->child_count()); @@ -2213,8 +2087,7 @@ // Now add another user bookmark and wait for it to sync. ASSERT_NE(nullptr, AddURL(0, "Google 2", google_url)); - ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1))); - ASSERT_TRUE(AllModelsMatchVerifier()); + ASSERT_TRUE(BookmarksMatchVerifierChecker().Wait()); EXPECT_FALSE(GetSyncService(0)->HasUnrecoverableError()); EXPECT_FALSE(GetSyncService(1)->HasUnrecoverableError());
diff --git a/chrome/browser/sync/test/integration/two_client_uss_sync_test.cc b/chrome/browser/sync/test/integration/two_client_uss_sync_test.cc index c1a597d..8a6f76c0 100644 --- a/chrome/browser/sync/test/integration/two_client_uss_sync_test.cc +++ b/chrome/browser/sync/test/integration/two_client_uss_sync_test.cc
@@ -303,6 +303,9 @@ // Write conflicting entities. model0->WriteItem(kKey1, kValue1); + // Wait for the server to see the first commit to avoid a race condition where + // both clients commit without seeing each other's update. + ASSERT_TRUE(ServerCountMatchStatusChecker(syncer::PREFERENCES, 1).Wait()); model1->WriteItem(kKey1, kValue2); // Wait for them to be resolved to kResolutionValue by the custom conflict
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index e0e3069..a224de2 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -1498,6 +1498,8 @@ "views/website_settings/chosen_object_row.cc", "views/website_settings/chosen_object_row.h", "views/website_settings/chosen_object_row_observer.h", + "views/website_settings/non_accessible_image_view.cc", + "views/website_settings/non_accessible_image_view.h", "views/website_settings/permission_prompt_impl.cc", "views/website_settings/permission_prompt_impl.h", "views/website_settings/permission_selector_row.cc",
diff --git a/chrome/browser/ui/ash/chrome_shell_delegate.cc b/chrome/browser/ui/ash/chrome_shell_delegate.cc index 96f7ad8..ebb7170 100644 --- a/chrome/browser/ui/ash/chrome_shell_delegate.cc +++ b/chrome/browser/ui/ash/chrome_shell_delegate.cc
@@ -303,6 +303,11 @@ return ash::A11Y_ALERT_NONE; } + void PlaySpokenFeedbackToggleCountdown(int tick_count) override { + DCHECK(AccessibilityManager::Get()); + AccessibilityManager::Get()->PlaySpokenFeedbackToggleCountdown(tick_count); + } + void PlayEarcon(int sound_key) override { DCHECK(AccessibilityManager::Get()); AccessibilityManager::Get()->PlayEarcon(
diff --git a/chrome/browser/ui/ash/launcher/chrome_launcher_controller_impl_unittest.cc b/chrome/browser/ui/ash/launcher/chrome_launcher_controller_impl_unittest.cc index 2a2dd5e..70c4baf 100644 --- a/chrome/browser/ui/ash/launcher/chrome_launcher_controller_impl_unittest.cc +++ b/chrome/browser/ui/ash/launcher/chrome_launcher_controller_impl_unittest.cc
@@ -3569,10 +3569,12 @@ "AppList, Chrome, Play Store"); // Arc is managed and enabled, Play Store pin should be available. + // Note: SHOWING_TERMS_OF_SERVICE here means that opt-in flow starts. profile()->GetTestingPrefService()->SetManagedPref( prefs::kArcEnabled, new base::FundamentalValue(true)); base::RunLoop().RunUntilIdle(); - ValidateArcState(true, true, arc::ArcAuthService::State::FETCHING_CODE, + ValidateArcState(true, true, + arc::ArcAuthService::State::SHOWING_TERMS_OF_SERVICE, "AppList, Chrome, Play Store"); // Arc is managed and disabled, Play Store pin should not be available. @@ -3590,7 +3592,8 @@ // Arc is not managed and enabled, Play Store pin should be available. EnableArc(true); - ValidateArcState(true, false, arc::ArcAuthService::State::FETCHING_CODE, + ValidateArcState(true, false, + arc::ArcAuthService::State::SHOWING_TERMS_OF_SERVICE, "AppList, Chrome, Play Store"); // User disables Arc. Arc is not managed and disabled, Play Store pin should @@ -3601,7 +3604,8 @@ // Even if re-enable it again, Play Store pin does not appear automatically. EnableArc(true); - ValidateArcState(true, false, arc::ArcAuthService::State::FETCHING_CODE, + ValidateArcState(true, false, + arc::ArcAuthService::State::SHOWING_TERMS_OF_SERVICE, "AppList, Chrome"); }
diff --git a/chrome/browser/ui/ash/system_tray_delegate_chromeos.cc b/chrome/browser/ui/ash/system_tray_delegate_chromeos.cc index 534ed5de..c366ef5b 100644 --- a/chrome/browser/ui/ash/system_tray_delegate_chromeos.cc +++ b/chrome/browser/ui/ash/system_tray_delegate_chromeos.cc
@@ -19,7 +19,6 @@ #include "ash/common/system/chromeos/bluetooth/bluetooth_observer.h" #include "ash/common/system/chromeos/power/power_status.h" #include "ash/common/system/chromeos/session/logout_button_observer.h" -#include "ash/common/system/chromeos/shutdown_policy_observer.h" #include "ash/common/system/date/clock_observer.h" #include "ash/common/system/ime/ime_observer.h" #include "ash/common/system/tray/system_tray_notifier.h" @@ -55,7 +54,6 @@ #include "chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.h" #include "chrome/browser/chromeos/profiles/multiprofiles_intro_dialog.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" -#include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/supervised_user/supervised_user_service.h" @@ -140,6 +138,12 @@ UserAddingScreen::Get()->Start(); } +bool IsSessionInSecondaryLoginScreen() { + return ash::WmShell::Get() + ->GetSessionStateDelegate() + ->IsInSecondaryLoginScreen(); +} + } // namespace SystemTrayDelegateChromeOS::SystemTrayDelegateChromeOS() @@ -175,8 +179,6 @@ base::Unretained(this))); user_manager::UserManager::Get()->AddSessionStateObserver(this); - shutdown_policy_handler_.reset( - new ShutdownPolicyHandler(CrosSettings::Get(), this)); } void SystemTrayDelegateChromeOS::Initialize() { @@ -321,19 +323,27 @@ GetUpdateInfo(UpgradeDetector::GetInstance(), info); } -bool SystemTrayDelegateChromeOS::ShouldShowSettings() { - ash::WmShell* wm_shell = ash::WmShell::Get(); +bool SystemTrayDelegateChromeOS::ShouldShowSettings() const { + // Show setting button only when the user flow allows and it's not in the + // multi-profile login screen. return ChromeUserManager::Get()->GetCurrentUserFlow()->ShouldShowSettings() && - !wm_shell->GetSessionStateDelegate()->IsInSecondaryLoginScreen(); + !IsSessionInSecondaryLoginScreen(); +} + +bool SystemTrayDelegateChromeOS::ShouldShowNotificationTray() const { + // Show notification tray only when the user flow allows and it's not in the + // multi-profile login screen. + return ChromeUserManager::Get() + ->GetCurrentUserFlow() + ->ShouldShowNotificationTray() && + !IsSessionInSecondaryLoginScreen(); } void SystemTrayDelegateChromeOS::ShowEnterpriseInfo() { // TODO(mash): Refactor out SessionStateDelegate and move to SystemTrayClient. ash::LoginStatus status = GetUserLoginStatus(); - ash::WmShell* wm_shell = ash::WmShell::Get(); if (status == ash::LoginStatus::NOT_LOGGED_IN || - status == ash::LoginStatus::LOCKED || - wm_shell->GetSessionStateDelegate()->IsInSecondaryLoginScreen()) { + status == ash::LoginStatus::LOCKED || IsSessionInSecondaryLoginScreen()) { scoped_refptr<chromeos::HelpAppLauncher> help_app( new chromeos::HelpAppLauncher(nullptr /* parent_window */)); help_app->ShowHelpTopic(chromeos::HelpAppLauncher::HELP_ENTERPRISE); @@ -466,7 +476,7 @@ dialog->ShowInContainer(SystemTrayClient::GetDialogParentContainerId()); } -bool SystemTrayDelegateChromeOS::IsBluetoothDiscovering() { +bool SystemTrayDelegateChromeOS::IsBluetoothDiscovering() const { return bluetooth_adapter_ && bluetooth_adapter_->IsDiscovering(); } @@ -593,21 +603,6 @@ custodian_info_changed_observers_.RemoveObserver(observer); } -void SystemTrayDelegateChromeOS::AddShutdownPolicyObserver( - ash::ShutdownPolicyObserver* observer) { - shutdown_policy_observers_.AddObserver(observer); -} - -void SystemTrayDelegateChromeOS::RemoveShutdownPolicyObserver( - ash::ShutdownPolicyObserver* observer) { - shutdown_policy_observers_.RemoveObserver(observer); -} - -void SystemTrayDelegateChromeOS::ShouldRebootOnShutdown( - const ash::RebootOnShutdownCallback& callback) { - shutdown_policy_handler_->CheckIfRebootOnShutdown(callback); -} - ash::VPNDelegate* SystemTrayDelegateChromeOS::GetVPNDelegate() const { return vpn_delegate_.get(); } @@ -981,13 +976,6 @@ OnAccessibilityModeChanged(details.notify); } -void SystemTrayDelegateChromeOS::OnShutdownPolicyChanged( - bool reboot_on_shutdown) { - // Notify all observers. - for (ash::ShutdownPolicyObserver& observer : shutdown_policy_observers_) - observer.OnShutdownPolicyChanged(reboot_on_shutdown); -} - void SystemTrayDelegateChromeOS::ImeMenuActivationChanged(bool is_active) { GetSystemTrayNotifier()->NotifyRefreshIMEMenu(is_active); }
diff --git a/chrome/browser/ui/ash/system_tray_delegate_chromeos.h b/chrome/browser/ui/ash/system_tray_delegate_chromeos.h index 90f776c7..25e8163 100644 --- a/chrome/browser/ui/ash/system_tray_delegate_chromeos.h +++ b/chrome/browser/ui/ash/system_tray_delegate_chromeos.h
@@ -23,7 +23,6 @@ #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "chrome/browser/chromeos/accessibility/accessibility_manager.h" -#include "chrome/browser/chromeos/settings/shutdown_policy_handler.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/supervised_user/supervised_user_service_observer.h" #include "chrome/browser/ui/browser_list_observer.h" @@ -65,7 +64,6 @@ public extensions::AppWindowRegistry::Observer, public user_manager::UserManager::UserSessionStateObserver, public SupervisedUserServiceObserver, - public ShutdownPolicyHandler::Delegate, public input_method::InputMethodManager::ImeMenuObserver { public: SystemTrayDelegateChromeOS(); @@ -87,7 +85,8 @@ bool IsUserSupervised() const override; bool IsUserChild() const override; void GetSystemUpdateInfo(ash::UpdateInfo* info) const override; - bool ShouldShowSettings() override; + bool ShouldShowSettings() const override; + bool ShouldShowNotificationTray() const override; void ShowEnterpriseInfo() override; void ShowUserLogin() override; void SignOut() override; @@ -96,7 +95,7 @@ void BluetoothStartDiscovering() override; void BluetoothStopDiscovering() override; void ConnectToBluetoothDevice(const std::string& address) override; - bool IsBluetoothDiscovering() override; + bool IsBluetoothDiscovering() const override; void GetCurrentIME(ash::IMEInfo* info) override; void GetAvailableIMEList(ash::IMEInfoList* list) override; void GetCurrentIMEProperties(ash::IMEPropertyInfoList* list) override; @@ -118,12 +117,6 @@ ash::CustodianInfoTrayObserver* observer) override; void RemoveCustodianInfoTrayObserver( ash::CustodianInfoTrayObserver* observer) override; - void AddShutdownPolicyObserver( - ash::ShutdownPolicyObserver* observer) override; - void RemoveShutdownPolicyObserver( - ash::ShutdownPolicyObserver* observer) override; - void ShouldRebootOnShutdown( - const ash::RebootOnShutdownCallback& callback) override; ash::VPNDelegate* GetVPNDelegate() const override; std::unique_ptr<ash::SystemTrayItem> CreateRotationLockTrayItem( ash::SystemTray* tray) override; @@ -221,9 +214,6 @@ void OnAccessibilityStatusChanged( const AccessibilityStatusEventDetails& details); - // Overridden from ShutdownPolicyObserver::Delegate. - void OnShutdownPolicyChanged(bool reboot_on_shutdown) override; - // input_method::InputMethodManager::ImeMenuObserver: void ImeMenuActivationChanged(bool is_active) override; void ImeMenuListChanged() override; @@ -256,14 +246,11 @@ std::unique_ptr<ash::CastConfigDelegate> cast_config_delegate_; std::unique_ptr<ash::NetworkingConfigDelegate> networking_config_delegate_; std::unique_ptr<AccessibilityStatusSubscription> accessibility_subscription_; - std::unique_ptr<ShutdownPolicyHandler> shutdown_policy_handler_; std::unique_ptr<ash::VPNDelegate> vpn_delegate_; base::ObserverList<ash::CustodianInfoTrayObserver> custodian_info_changed_observers_; - base::ObserverList<ash::ShutdownPolicyObserver> shutdown_policy_observers_; - base::WeakPtrFactory<SystemTrayDelegateChromeOS> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(SystemTrayDelegateChromeOS);
diff --git a/chrome/browser/ui/blocked_content/popup_blocker_browsertest.cc b/chrome/browser/ui/blocked_content/popup_blocker_browsertest.cc index eca68b7..6a01a1d 100644 --- a/chrome/browser/ui/blocked_content/popup_blocker_browsertest.cc +++ b/chrome/browser/ui/blocked_content/popup_blocker_browsertest.cc
@@ -338,8 +338,16 @@ } // Verify that when you unblock popup, the popup shows in history and omnibox. +// TODO(crbug.com/663333) Flaky on Linux. +#if defined(OS_LINUX) +#define MAYBE_UnblockedPopupShowsInHistoryAndOmnibox \ + DISABLED_UnblockedPopupShowsInHistoryAndOmnibox +#else +#define MAYBE_UnblockedPopupShowsInHistoryAndOmnibox \ + UnblockedPopupShowsInHistoryAndOmnibox +#endif IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest, - UnblockedPopupShowsInHistoryAndOmnibox) { + MAYBE_UnblockedPopupShowsInHistoryAndOmnibox) { base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kDisablePopupBlocking); GURL url(embedded_test_server()->GetURL(
diff --git a/chrome/browser/ui/browser.cc b/chrome/browser/ui/browser.cc index 29fbcd6..46bba57 100644 --- a/chrome/browser/ui/browser.cc +++ b/chrome/browser/ui/browser.cc
@@ -1550,12 +1550,12 @@ const content::NavigationEntry* entry = source->GetController().GetActiveEntry(); if (entry) { - GURL url = entry->GetURL(); - GURL virtual_url = entry->GetVirtualURL(); + const GURL& url = entry->GetURL(); + const GURL& virtual_url = entry->GetVirtualURL(); if ((url.SchemeIs(content::kChromeUIScheme) && - url.host() == chrome::kChromeUINewTabHost) || + url.host_piece() == chrome::kChromeUINewTabHost) || (virtual_url.SchemeIs(content::kChromeUIScheme) && - virtual_url.host() == chrome::kChromeUINewTabHost)) { + virtual_url.host_piece() == chrome::kChromeUINewTabHost)) { return true; } } @@ -2057,7 +2057,7 @@ // schemes, e.g. https://mail.google.com if you have the Gmail app // installed. if ((web_contents->GetURL().SchemeIs(extensions::kExtensionScheme) && - web_contents->GetURL().host() == extension->id()) || + web_contents->GetURL().host_piece() == extension->id()) || (extensions::TabHelper::FromWebContents(web_contents) ->extension_app() == extension)) { tab_strip_model_->CloseWebContentsAt(i, TabStripModel::CLOSE_NONE);
diff --git a/chrome/browser/ui/browser_focus_uitest.cc b/chrome/browser/ui/browser_focus_uitest.cc index d4805c4..9ce91d1 100644 --- a/chrome/browser/ui/browser_focus_uitest.cc +++ b/chrome/browser/ui/browser_focus_uitest.cc
@@ -678,7 +678,13 @@ EXPECT_FALSE(IsViewFocused(VIEW_ID_OMNIBOX)); } -IN_PROC_BROWSER_TEST_F(BrowserFocusTest, FocusOnNavigate) { +// Flaky on Windows (http://crbug.com/665296). +#if defined(OS_WIN) +#define MAYBE_FocusOnNavigate DISABLED_FocusOnNavigate +#else +#define MAYBE_FocusOnNavigate FocusOnNavigate +#endif +IN_PROC_BROWSER_TEST_F(BrowserFocusTest, MAYBE_FocusOnNavigate) { ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser())); ui_test_utils::BrowserActivationWaiter waiter(browser()); waiter.WaitForActivation();
diff --git a/chrome/browser/ui/browser_navigator.cc b/chrome/browser/ui/browser_navigator.cc index df7d5b13..75dee0c 100644 --- a/chrome/browser/ui/browser_navigator.cc +++ b/chrome/browser/ui/browser_navigator.cc
@@ -634,33 +634,33 @@ // chrome://extensions is on the list because it redirects to // chrome://settings. if (url.scheme() == content::kChromeUIScheme && - (url.host() == chrome::kChromeUISettingsHost || - url.host() == chrome::kChromeUIMdSettingsHost || - url.host() == chrome::kChromeUISettingsFrameHost || - url.host() == chrome::kChromeUIHelpHost || - url.host() == chrome::kChromeUIHistoryHost || - url.host() == chrome::kChromeUIExtensionsHost || - url.host() == chrome::kChromeUIBookmarksHost || + (url.host_piece() == chrome::kChromeUISettingsHost || + url.host_piece() == chrome::kChromeUIMdSettingsHost || + url.host_piece() == chrome::kChromeUISettingsFrameHost || + url.host_piece() == chrome::kChromeUIHelpHost || + url.host_piece() == chrome::kChromeUIHistoryHost || + url.host_piece() == chrome::kChromeUIExtensionsHost || + url.host_piece() == chrome::kChromeUIBookmarksHost || #if !defined(OS_CHROMEOS) - url.host() == chrome::kChromeUIChromeSigninHost || + url.host_piece() == chrome::kChromeUIChromeSigninHost || #endif - url.host() == chrome::kChromeUIUberHost || - url.host() == chrome::kChromeUIThumbnailHost || - url.host() == chrome::kChromeUIThumbnailHost2 || - url.host() == chrome::kChromeUIThumbnailListHost || - url.host() == chrome::kChromeUISuggestionsHost || + url.host_piece() == chrome::kChromeUIUberHost || + url.host_piece() == chrome::kChromeUIThumbnailHost || + url.host_piece() == chrome::kChromeUIThumbnailHost2 || + url.host_piece() == chrome::kChromeUIThumbnailListHost || + url.host_piece() == chrome::kChromeUISuggestionsHost || #if defined(OS_CHROMEOS) - url.host() == chrome::kChromeUIVoiceSearchHost || + url.host_piece() == chrome::kChromeUIVoiceSearchHost || #endif - url.host() == chrome::kChromeUIDevicesHost)) { + url.host_piece() == chrome::kChromeUIDevicesHost)) { return false; } if (url.scheme() == chrome::kChromeSearchScheme && - (url.host() == chrome::kChromeUIThumbnailHost || - url.host() == chrome::kChromeUIThumbnailHost2 || - url.host() == chrome::kChromeUIThumbnailListHost || - url.host() == chrome::kChromeUISuggestionsHost)) { + (url.host_piece() == chrome::kChromeUIThumbnailHost || + url.host_piece() == chrome::kChromeUIThumbnailHost2 || + url.host_piece() == chrome::kChromeUIThumbnailListHost || + url.host_piece() == chrome::kChromeUISuggestionsHost)) { return false; } @@ -670,8 +670,8 @@ &rewritten_url, browser_context, &reverse_on_redirect); // Some URLs are mapped to uber subpages. Do not allow them in incognito. - return !(rewritten_url.scheme() == content::kChromeUIScheme && - rewritten_url.host() == chrome::kChromeUIUberHost); + return !(rewritten_url.scheme_piece() == content::kChromeUIScheme && + rewritten_url.host_piece() == chrome::kChromeUIUberHost); } } // namespace chrome
diff --git a/chrome/browser/ui/cocoa/browser_window_command_handler.mm b/chrome/browser/ui/cocoa/browser_window_command_handler.mm index 7c5478f..7e62c7e 100644 --- a/chrome/browser/ui/cocoa/browser_window_command_handler.mm +++ b/chrome/browser/ui/cocoa/browser_window_command_handler.mm
@@ -8,6 +8,7 @@ #import "base/mac/foundation_util.h" #include "chrome/app/chrome_command_ids.h" #import "chrome/browser/app_controller_mac.h" +#include "chrome/browser/media/router/media_router_feature.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/bookmarks/bookmark_utils.h" #include "chrome/browser/ui/browser_commands.h" @@ -162,6 +163,13 @@ [menuItem setHidden:browser->is_type_tabbed() || browser->is_devtools()]; break; } + case IDC_ROUTE_MEDIA: { + // Hide this menu option if Media Router is disabled. + NSMenuItem* menuItem = base::mac::ObjCCast<NSMenuItem>(item); + [menuItem + setHidden:!media_router::MediaRouterEnabled(browser->profile())]; + break; + } default: break; }
diff --git a/chrome/browser/ui/cocoa/browser_window_controller_private.mm b/chrome/browser/ui/cocoa/browser_window_controller_private.mm index 24c805e..1c36955 100644 --- a/chrome/browser/ui/cocoa/browser_window_controller_private.mm +++ b/chrome/browser/ui/cocoa/browser_window_controller_private.mm
@@ -917,8 +917,7 @@ [infoBarContainerController_ setInfobarArrowX:[self locationBarBridge]->GetPageInfoBubblePoint().x]; - if (!NSIsEmptyRect(output.downloadShelfFrame)) - [[downloadShelfController_ view] setFrame:output.downloadShelfFrame]; + [[downloadShelfController_ view] setFrame:output.downloadShelfFrame]; [self layoutTabContentArea:output.contentAreaFrame];
diff --git a/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field.h b/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field.h index 142f9c13..f17405bd 100644 --- a/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field.h +++ b/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field.h
@@ -84,6 +84,9 @@ // Called when -insertText: is invoked on the editor. virtual void OnInsertText() = 0; + // Called before a -drawRect: operation. + virtual void OnBeforeDrawRect() = 0; + // Called after the completion of a -drawRect: operation. virtual void OnDidDrawRect() = 0;
diff --git a/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field.mm b/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field.mm index bd327b43..a295203 100644 --- a/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field.mm +++ b/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field.mm
@@ -196,6 +196,12 @@ [editor mouseDown:theEvent]; } +- (void)mouseUp:(NSEvent*)theEvent { + const NSRect bounds([self bounds]); + AutocompleteTextFieldCell* cell = [self cell]; + [cell mouseUp:theEvent inRect:bounds ofView:self]; +} + - (void)rightMouseDown:(NSEvent*)event { if (observer_) observer_->OnMouseDown([event buttonNumber]); @@ -316,7 +322,7 @@ // Reload the decoration tooltips. [currentToolTips_ removeAllObjects]; - [[self cell] updateToolTipsInRect:[self bounds] ofView:self]; + [[self cell] updateMouseTrackingAndToolTipsInRect:[self bounds] ofView:self]; } // NOTE(shess): http://crbug.com/19116 describes a weird bug which
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 7fa83f06..b8f6543 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
@@ -24,6 +24,9 @@ std::vector<LocationBarDecoration*> leftDecorations_; std::vector<LocationBarDecoration*> rightDecorations_; + // Decorations with tracking areas attached to the AutocompleteTextField. + std::vector<LocationBarDecoration*> mouseTrackingDecorations_; + // If YES then the text field will not draw a focus ring or show the insertion // pointer. BOOL hideFocusState_; @@ -44,6 +47,9 @@ // Line height used for text in this cell. - (CGFloat)lineHeight; +// Remove all of the tracking areas. +- (void)clearTrackingArea; + // Clear |leftDecorations_| and |rightDecorations_|. - (void)clearDecorations; @@ -95,15 +101,22 @@ inRect:(NSRect)cellFrame ofView:(AutocompleteTextField*)controlView; +// Called by |AutocompleteTextField| to pass the mouse up event to the omnibox +// decorations. +- (void)mouseUp:(NSEvent*)theEvent + inRect:(NSRect)cellFrame + ofView:(AutocompleteTextField*)controlView; + // Overridden from StyledTextFieldCell to include decorations adjacent // to the text area which don't handle mouse clicks themselves. // Keyword-search bubble, for instance. - (NSRect)textCursorFrameForFrame:(NSRect)cellFrame; -// Setup decoration tooltips on |controlView| by calling -// |-addToolTip:forRect:|. -- (void)updateToolTipsInRect:(NSRect)cellFrame - ofView:(AutocompleteTextField*)controlView; +// Setup decoration tooltips and mouse tracking on |controlView| by calling +// |-addToolTip:forRect:| and |SetupTrackingArea()|. +- (void)updateMouseTrackingAndToolTipsInRect:(NSRect)cellFrame + ofView: + (AutocompleteTextField*)controlView; // Gets and sets |hideFocusState|. This allows the text field to have focus but // to appear unfocused. @@ -115,3 +128,11 @@ - (void)handleFocusEvent:(NSEvent*)event ofView:(AutocompleteTextField*)controlView; @end + +// Methods which are either only for testing, or only public for testing. +@interface AutocompleteTextFieldCell (TestingAPI) + +// Returns |mouseTrackingDecorations_|. +- (const std::vector<LocationBarDecoration*>&)mouseTrackingDecorations; + +@end
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 814d8963..1a70f22 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
@@ -18,6 +18,7 @@ #import "extensions/common/feature_switch.h" #import "third_party/mozilla/NSPasteboard+Utils.h" #import "ui/base/cocoa/appkit_utils.h" +#import "ui/base/cocoa/tracking_area.h" #import "ui/base/cocoa/nsview_additions.h" #include "ui/base/cocoa/scoped_cg_context_smooth_fonts.h" #include "ui/base/material_design/material_design_controller.h" @@ -182,9 +183,17 @@ return 17; } +- (void)clearTrackingArea { + for (auto& decoration : mouseTrackingDecorations_) + decoration->RemoveTrackingArea(); + + mouseTrackingDecorations_.clear(); +} + - (void)clearDecorations { leftDecorations_.clear(); rightDecorations_.clear(); + [self clearTrackingArea]; } - (void)addLeftDecoration:(LocationBarDecoration*)decoration { @@ -458,6 +467,8 @@ if (!decoration || !decoration->AcceptsMousePress()) return NO; + decoration->OnMouseDown(); + NSRect decorationRect = [self frameForDecoration:decoration inFrame:cellFrame]; @@ -517,6 +528,15 @@ point.y - decorationRect.origin.y)); } +- (void)mouseUp:(NSEvent*)theEvent + inRect:(NSRect)cellFrame + ofView:(AutocompleteTextField*)controlView { + LocationBarDecoration* decoration = + [self decorationForEvent:theEvent inRect:cellFrame ofView:controlView]; + if (decoration) + decoration->OnMouseUp(); +} + // Returns the file path for file |name| if saved at NSURL |base|. static NSString* PathWithBaseURLAndName(NSURL* base, NSString* name) { NSString* filteredName = @@ -623,15 +643,22 @@ return NSDragOperationCopy; } -- (void)updateToolTipsInRect:(NSRect)cellFrame - ofView:(AutocompleteTextField*)controlView { +- (void)updateMouseTrackingAndToolTipsInRect:(NSRect)cellFrame + ofView: + (AutocompleteTextField*)controlView { std::vector<LocationBarDecoration*> decorations; std::vector<NSRect> decorationFrames; NSRect textFrame; CalculatePositionsInFrame(cellFrame, leftDecorations_, rightDecorations_, &decorations, &decorationFrames, &textFrame); + [self clearTrackingArea]; for (size_t i = 0; i < decorations.size(); ++i) { + CrTrackingArea* trackingArea = + decorations[i]->SetupTrackingArea(decorationFrames[i], controlView); + if (trackingArea) + mouseTrackingDecorations_.push_back(decorations[i]); + NSString* tooltip = decorations[i]->GetToolTip(); if ([tooltip length] > 0) [controlView addToolTip:tooltip forRect:decorationFrames[i]]; @@ -666,3 +693,11 @@ } @end + +@implementation AutocompleteTextFieldCell (TestingAPI) + +- (const std::vector<LocationBarDecoration*>&)mouseTrackingDecorations { + return mouseTrackingDecorations_; +} + +@end
diff --git a/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell_unittest.mm b/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell_unittest.mm index 5d7520e..9b7d1c1e 100644 --- a/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell_unittest.mm +++ b/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell_unittest.mm
@@ -264,7 +264,8 @@ EXPECT_LT(NSMinX(textFrame), NSMinX(decoration1Rect)); } -// Verify -[AutocompleteTextFieldCell updateToolTipsInRect:ofView:]. +// Verify -[AutocompleteTextFieldCell +// updateMouseTrackingAndToolTipsInRect:ofView:]. TEST_F(AutocompleteTextFieldCellTest, UpdateToolTips) { NSString* tooltip = @"tooltip"; @@ -292,7 +293,7 @@ id controlView = [OCMockObject mockForClass:[AutocompleteTextField class]]; [[controlView expect] addToolTip:tooltip forRect:leftDecorationRect]; - [cell updateToolTipsInRect:bounds ofView:controlView]; + [cell updateMouseTrackingAndToolTipsInRect:bounds ofView:controlView]; EXPECT_OCMOCK_VERIFY(controlView); }
diff --git a/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_editor.mm b/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_editor.mm index 3f0aad3..68dd493 100644 --- a/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_editor.mm +++ b/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_editor.mm
@@ -589,6 +589,9 @@ } - (void)drawRect:(NSRect)rect { + AutocompleteTextFieldObserver* observer = [self observer]; + if (observer) + observer->OnBeforeDrawRect(); [super drawRect:rect]; autocomplete_text_field::DrawGrayTextAutocompletion( [self textStorage], @@ -596,7 +599,6 @@ [[self delegate] suggestColor], self, [self bounds]); - AutocompleteTextFieldObserver* observer = [self observer]; if (observer) observer->OnDidDrawRect(); }
diff --git a/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_unittest.mm b/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_unittest.mm index 0d304d8e..4ca3df8 100644 --- a/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_unittest.mm +++ b/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_unittest.mm
@@ -574,6 +574,8 @@ .WillRepeatedly(Return(true)); AutocompleteTextFieldCell* cell = [field_ cell]; + [cell updateMouseTrackingAndToolTipsInRect:[field_ frame] ofView:field_]; + const NSRect iconFrame = [cell frameForDecoration:&mock_left_decoration_ inFrame:[field_ bounds]]; const NSPoint location = NSMakePoint(NSMidX(iconFrame), NSMidY(iconFrame)); @@ -621,6 +623,8 @@ .WillRepeatedly(Return(true)); AutocompleteTextFieldCell* cell = [field_ cell]; + [cell updateMouseTrackingAndToolTipsInRect:[field_ frame] ofView:field_]; + const NSRect bounds = [field_ bounds]; const NSRect iconFrame = [cell frameForDecoration:&mock_right_decoration_ inFrame:bounds]; @@ -797,6 +801,34 @@ EXPECT_TRUE([FieldEditor() shouldDrawInsertionPoint]); } +// Verify that the tracking areas are added properly. +TEST_F(AutocompleteTextFieldTest, UpdateTrackingAreas) { + AutocompleteTextFieldCell* cell = [field_ cell]; + + mock_left_decoration_.SetVisible(true); + mock_right_decoration_.SetVisible(true); + + EXPECT_CALL(mock_left_decoration_, AcceptsMousePress()) + .WillOnce(Return(true)) + .WillRepeatedly(Return(true)); + EXPECT_CALL(mock_right_decoration_, AcceptsMousePress()) + .WillOnce(Return(false)) + .WillRepeatedly(Return(false)); + [cell updateMouseTrackingAndToolTipsInRect:[field_ bounds] ofView:field_]; + + EXPECT_EQ([cell mouseTrackingDecorations].size(), 1.0); + + [cell clearTrackingArea]; + EXPECT_TRUE([cell mouseTrackingDecorations].empty()); + + EXPECT_CALL(mock_right_decoration_, AcceptsMousePress()) + .WillOnce(Return(true)) + .WillRepeatedly(Return(true)); + + [cell updateMouseTrackingAndToolTipsInRect:[field_ bounds] ofView:field_]; + EXPECT_EQ([cell mouseTrackingDecorations].size(), 2.0); +} + // Verify that clicking a decoration that accepts mouse clicks does not focus // the Omnibox. TEST_F(AutocompleteTextFieldObserverTest, @@ -816,6 +848,7 @@ .WillRepeatedly(testing::Return(true)); interactive_decoration.SetVisible(true); [cell addLeftDecoration:&interactive_decoration]; + [cell updateMouseTrackingAndToolTipsInRect:[field_ frame] ofView:field_]; EXPECT_CALL(interactive_decoration, OnMousePressed(_, _)) .WillRepeatedly(testing::Return(true)); @@ -827,6 +860,7 @@ EXPECT_CALL(field_observer_, OnSetFocus(false)).Times(testing::AnyNumber()); EXPECT_CALL(field_observer_, OnKillFocus()).Times(testing::AnyNumber()); EXPECT_CALL(field_observer_, OnDidEndEditing()).Times(testing::AnyNumber()); + EXPECT_CALL(field_observer_, OnBeforeDrawRect()).Times(testing::AnyNumber()); EXPECT_CALL(field_observer_, OnDidDrawRect()).Times(testing::AnyNumber()); // Ensure the field is currently not first responder.
diff --git a/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_unittest_helper.h b/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_unittest_helper.h index 6b6ccb1..1f2ae05 100644 --- a/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_unittest_helper.h +++ b/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_unittest_helper.h
@@ -50,6 +50,7 @@ MOCK_METHOD0(OnDidChange, void()); MOCK_METHOD0(OnDidEndEditing, void()); MOCK_METHOD0(OnInsertText, void()); + MOCK_METHOD0(OnBeforeDrawRect, void()); MOCK_METHOD0(OnDidDrawRect, void()); MOCK_METHOD1(OnDoCommandBySelector, bool(SEL cmd)); MOCK_METHOD1(OnSetFocus, void(bool control_down));
diff --git a/chrome/browser/ui/cocoa/location_bar/bubble_decoration.h b/chrome/browser/ui/cocoa/location_bar/bubble_decoration.h index 17ba200..1df5c1a 100644 --- a/chrome/browser/ui/cocoa/location_bar/bubble_decoration.h +++ b/chrome/browser/ui/cocoa/location_bar/bubble_decoration.h
@@ -33,6 +33,7 @@ // Implement |LocationBarDecoration|. CGFloat GetWidthForSpace(CGFloat width) override; + NSRect GetBackgroundFrame(NSRect frame) override; void DrawInFrame(NSRect frame, NSView* control_view) override; NSFont* GetFont() const override;
diff --git a/chrome/browser/ui/cocoa/location_bar/bubble_decoration.mm b/chrome/browser/ui/cocoa/location_bar/bubble_decoration.mm index 714e4b2..8f8db5a 100644 --- a/chrome/browser/ui/cocoa/location_bar/bubble_decoration.mm +++ b/chrome/browser/ui/cocoa/location_bar/bubble_decoration.mm
@@ -31,6 +31,12 @@ // Inset for the image frame. const CGFloat kImageFrameYInset = 4.0; +// Inset for the background frame. +const CGFloat kBackgroundFrameYInset = 2.0; + +// Left margin for the background frame. +const CGFloat kBackgroundFrameLeftMargin = 1.0; + } // namespace BubbleDecoration::BubbleDecoration() : retina_baseline_offset_(0) { @@ -93,6 +99,13 @@ return kOmittedWidth; } +NSRect BubbleDecoration::GetBackgroundFrame(NSRect frame) { + NSRect background_frame = NSInsetRect(frame, 0.0, kBackgroundFrameYInset); + background_frame.origin.x += kBackgroundFrameLeftMargin; + background_frame.size.width -= kDividerPadding; + return background_frame; +} + void BubbleDecoration::DrawInFrame(NSRect frame, NSView* control_view) { const NSRect decoration_frame = NSInsetRect(frame, 0.0, kImageFrameYInset); CGFloat text_offset = NSMinX(decoration_frame);
diff --git a/chrome/browser/ui/cocoa/location_bar/content_setting_decoration.mm b/chrome/browser/ui/cocoa/location_bar/content_setting_decoration.mm index fd005bf7..2d29915 100644 --- a/chrome/browser/ui/cocoa/location_bar/content_setting_decoration.mm +++ b/chrome/browser/ui/cocoa/location_bar/content_setting_decoration.mm
@@ -59,15 +59,14 @@ // Padding for the animated text with respect to the image. const CGFloat kTextMarginPadding = 4; -const CGFloat kIconMarginPadding = 2; +const CGFloat kIconMarginPadding = 4; const CGFloat kBorderPadding = 3; -// Padding between the divider between the omnibox text and the divider. The -// desired value for each side is 8px. We get 5px on the left side by -// subtracting kBorderPadding from 8px. -const CGFloat kRightDividerPadding = 8.0; -const CGFloat kLeftDividerPadding = 5.0; -const CGFloat kDividerPadding = kLeftDividerPadding + kRightDividerPadding; +// Padding between the divider and the decoration on the right. +const CGFloat kDividerPadding = 1; + +// Padding between the divider and the text. +const CGFloat kTextDividerPadding = 2; // Color of the vector graphic icons. Used when the location is not dark. // SkColorSetARGB(0xCC, 0xFF, 0xFF 0xFF); @@ -383,17 +382,20 @@ NSRect remainder = frame; remainder.origin.x = NSMaxX(icon_rect) + kTextMarginPadding; remainder.size.width = - NSMaxX(background_rect) - NSMinX(remainder) - kLeftDividerPadding; + NSMaxX(background_rect) - NSMinX(remainder) - kTextDividerPadding; DrawAttributedString(animated_text_, remainder); - NSBezierPath* line = [NSBezierPath bezierPath]; - [line setLineWidth:1]; - [line moveToPoint:NSMakePoint(NSMaxX(background_rect) - kLeftDividerPadding, - NSMinY(background_rect))]; - [line lineToPoint:NSMakePoint(NSMaxX(background_rect) - kLeftDividerPadding, - NSMaxY(background_rect))]; - [GetDividerColor(owner_->IsLocationBarDark()) set]; - [line stroke]; + // Draw the divider if available. + if (state() == LocationBarDecorationState::NORMAL) { + NSBezierPath* line = [NSBezierPath bezierPath]; + [line setLineWidth:1]; + [line moveToPoint:NSMakePoint(NSMaxX(background_rect) - kDividerPadding, + NSMinY(background_rect))]; + [line lineToPoint:NSMakePoint(NSMaxX(background_rect) - kDividerPadding, + NSMaxY(background_rect))]; + [GetDividerColor(owner_->IsLocationBarDark()) set]; + [line stroke]; + } } else { // No animation, draw the image as normal. ImageDecoration::DrawInFrame(frame, control_view);
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 754a080..11de3a0 100644 --- a/chrome/browser/ui/cocoa/location_bar/location_bar_decoration.h +++ b/chrome/browser/ui/cocoa/location_bar/location_bar_decoration.h
@@ -12,6 +12,9 @@ #include "third_party/skia/include/core/SkColor.h" #include "ui/gfx/vector_icons_public.h" +@class DecorationMouseTrackingDelegate; +@class CrTrackingArea; + // Base class for decorations at the left and right of the location // bar. For instance, the location icon. @@ -22,6 +25,8 @@ // Decorations are more like Cocoa cells, except implemented in C++ to // allow more similarity to the other platform implementations. +enum class LocationBarDecorationState { NORMAL, HOVER, PRESSED }; + class LocationBarDecoration { public: LocationBarDecoration(); @@ -36,6 +41,9 @@ // or |kOmittedWidth| if it should be omitted. virtual CGFloat GetWidthForSpace(CGFloat width); + // Returns a NSRect derived from |frame| for the background to fill. + virtual NSRect GetBackgroundFrame(NSRect frame); + // Draw the decoration in the frame provided. The frame will be // generated from an earlier call to |GetWidthForSpace()|. virtual void DrawInFrame(NSRect frame, NSView* control_view); @@ -50,6 +58,10 @@ // Returns the tooltip for this decoration, return |nil| for no tooltip. virtual NSString* GetToolTip(); + // Methods to set up and remove the tracking area from the |control_view|. + CrTrackingArea* SetupTrackingArea(NSRect frame, NSView* control_view); + void RemoveTrackingArea(); + // Decorations which do not accept mouse events are treated like the // field's background for purposes of selecting text. When such // decorations are adjacent to the text area, they will show the @@ -57,6 +69,11 @@ // an arrow cursor when the mouse is over them. virtual bool AcceptsMousePress(); + // Returns true if the decoration should display a background if it's + // hovered or pressed. The default value is equivalent to the value returned + // from AcceptsMousePress(). + virtual bool HasHoverAndPressEffect(); + // Determine if the item can act as a drag source. virtual bool IsDraggable(); @@ -72,10 +89,19 @@ // The pasteboard to drag. virtual NSPasteboard* GetDragPasteboard(); - // Called on mouse down. Return |false| to indicate that the press - // was not processed and should be handled by the cell. + // Called on mouse down, when the decoration isn't being dragged. Return + // |false| to indicate that the press was not processed and should be + // handled by the cell. virtual bool OnMousePressed(NSRect frame, NSPoint location); + // Mouse events called on mouse down/up. + void OnMouseDown(); + void OnMouseUp(); + + // Called by |tracking_delegate_| when the mouse enters/exits the decoration. + void OnMouseEntered(); + void OnMouseExited(); + // Called to get the right-click menu, return |nil| for no menu. virtual NSMenu* GetMenu(); @@ -108,6 +134,8 @@ // to the private DecorationAccessibilityView helper class. void OnAccessibilityViewAction(); + LocationBarDecorationState state() { return state_; } + // Width returned by |GetWidthForSpace()| when the item should be // omitted for this width; static const CGFloat kOmittedWidth; @@ -130,9 +158,26 @@ NSColor* GetDividerColor(bool location_bar_is_dark) const; private: + // Called when the state of the decoration is updated. + void UpdateDecorationState(); + bool visible_ = false; base::scoped_nsobject<NSView> accessibility_view_; + // The decoration's tracking area. Only set if the decoration accepts a mouse + // press. + base::scoped_nsobject<CrTrackingArea> tracking_area_; + + // The view that |tracking_area_| is added to. + NSView* tracking_area_owner_; + + // Delegate object that handles mouseEntered: and mouseExited: events from + // the tracking area. + base::scoped_nsobject<DecorationMouseTrackingDelegate> tracking_delegate_; + + // The state of the decoration. + LocationBarDecorationState state_; + DISALLOW_COPY_AND_ASSIGN(LocationBarDecoration); };
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 1786369..d8556da 100644 --- a/chrome/browser/ui/cocoa/location_bar/location_bar_decoration.mm +++ b/chrome/browser/ui/cocoa/location_bar/location_bar_decoration.mm
@@ -7,6 +7,8 @@ #include "base/logging.h" #include "base/mac/scoped_nsobject.h" #include "chrome/browser/ui/cocoa/omnibox/omnibox_view_mac.h" +#include "skia/ext/skia_utils_mac.h" +#import "ui/base/cocoa/tracking_area.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/font.h" #include "ui/gfx/image/image_skia_util_mac.h" @@ -14,10 +16,19 @@ namespace { -// Color values for the Material bubble decoration divider. -const CGFloat kMaterialDividerAlpha = 38.0; -const CGFloat kMaterialDividerGrayScale = 0.0; -const CGFloat kMaterialDividerIncognitoGrayScale = 1.0; +// Color values for the bubble decoration divider. +const CGFloat kDividerAlpha = 38.0; +const CGFloat kDividerGrayScale = 0.0; +const CGFloat kDividerIncognitoGrayScale = 1.0; + +// Color values for the hover and pressed background. +const SkColor kHoverBackgroundColor = 0x14000000; +const SkColor kHoverDarkBackgroundColor = 0x1E000000; +const SkColor kPressedBackgroundColor = 0x1E000000; +const SkColor kPressedDarkBackgroundColor = 0x3D000000; + +// Amount of inset for the background frame. +const CGFloat kBackgroundFrameYInset = 2.0; } // namespace @@ -82,10 +93,41 @@ @end +@interface DecorationMouseTrackingDelegate : NSObject { + LocationBarDecoration* owner_; // weak +} + +- (id)initWithOwner:(LocationBarDecoration*)owner; +- (void)mouseEntered:(NSEvent*)event; +- (void)mouseExited:(NSEvent*)event; + +@end + +@implementation DecorationMouseTrackingDelegate + +- (id)initWithOwner:(LocationBarDecoration*)owner { + if ((self = [super init])) { + owner_ = owner; + } + + return self; +} + +- (void)mouseEntered:(NSEvent*)event { + owner_->OnMouseEntered(); +} + +- (void)mouseExited:(NSEvent*)event { + owner_->OnMouseExited(); +} + +@end + const CGFloat LocationBarDecoration::kOmittedWidth = 0.0; const SkColor LocationBarDecoration::kMaterialDarkModeTextColor = 0xCCFFFFFF; -LocationBarDecoration::LocationBarDecoration() { +LocationBarDecoration::LocationBarDecoration() + : tracking_area_owner_(nil), state_(LocationBarDecorationState::NORMAL) { accessibility_view_.reset( [[DecorationAccessibilityView alloc] initWithOwner:this]); [accessibility_view_.get() setHidden:YES]; @@ -117,14 +159,38 @@ return kOmittedWidth; } +NSRect LocationBarDecoration::GetBackgroundFrame(NSRect frame) { + return NSInsetRect(frame, 0.0, kBackgroundFrameYInset); +} + void LocationBarDecoration::DrawInFrame(NSRect frame, NSView* control_view) { NOTREACHED(); } void LocationBarDecoration::DrawWithBackgroundInFrame(NSRect frame, NSView* control_view) { - // TODO(spqchan): Draw the hovered/pressed background. - // See crbug.com/588377. + // Draw the background if available. + if (state_ != LocationBarDecorationState::NORMAL && + HasHoverAndPressEffect()) { + bool in_dark_mode = [[control_view window] inIncognitoModeWithSystemTheme]; + + SkColor background_color; + if (state_ == LocationBarDecorationState::HOVER) { + background_color = + in_dark_mode ? kHoverDarkBackgroundColor : kHoverBackgroundColor; + } else { + background_color = + in_dark_mode ? kPressedBackgroundColor : kPressedDarkBackgroundColor; + } + + [skia::SkColorToSRGBNSColor(background_color) setFill]; + + NSBezierPath* path = [NSBezierPath bezierPath]; + [path appendBezierPathWithRoundedRect:GetBackgroundFrame(frame) + xRadius:2 + yRadius:2]; + [path fill]; + } DrawInFrame(frame, control_view); } @@ -132,10 +198,56 @@ return nil; } +CrTrackingArea* LocationBarDecoration::SetupTrackingArea(NSRect frame, + NSView* control_view) { + if (!AcceptsMousePress() || !control_view) + return nil; + + if (control_view == tracking_area_owner_ && tracking_area_.get() && + NSEqualRects([tracking_area_ rect], frame)) { + return tracking_area_.get(); + } + + if (tracking_area_owner_) + [tracking_area_owner_ removeTrackingArea:tracking_area_.get()]; + + if (!tracking_delegate_) { + tracking_delegate_.reset( + [[DecorationMouseTrackingDelegate alloc] initWithOwner:this]); + } + + tracking_area_.reset([[CrTrackingArea alloc] + initWithRect:frame + options:NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow + owner:tracking_delegate_.get() + userInfo:nil]); + + [control_view addTrackingArea:tracking_area_.get()]; + tracking_area_owner_ = control_view; + + state_ = [tracking_area_ mouseInsideTrackingAreaForView:control_view] + ? LocationBarDecorationState::HOVER + : LocationBarDecorationState::NORMAL; + + return tracking_area_.get(); +} + +void LocationBarDecoration::RemoveTrackingArea() { + DCHECK(tracking_area_owner_); + DCHECK(tracking_area_); + [tracking_area_owner_ removeTrackingArea:tracking_area_.get()]; + tracking_area_owner_ = nullptr; + tracking_area_.reset(); +} + bool LocationBarDecoration::AcceptsMousePress() { return false; } +bool LocationBarDecoration::HasHoverAndPressEffect() { + return AcceptsMousePress(); +} + bool LocationBarDecoration::IsDraggable() { return false; } @@ -156,6 +268,34 @@ return false; } +void LocationBarDecoration::OnMouseDown() { + state_ = LocationBarDecorationState::PRESSED; + UpdateDecorationState(); +} + +void LocationBarDecoration::OnMouseUp() { + DCHECK(tracking_area_owner_); + state_ = [tracking_area_ mouseInsideTrackingAreaForView:tracking_area_owner_] + ? LocationBarDecorationState::HOVER + : LocationBarDecorationState::NORMAL; + UpdateDecorationState(); +} + +void LocationBarDecoration::OnMouseEntered() { + state_ = LocationBarDecorationState::HOVER; + UpdateDecorationState(); +} + +void LocationBarDecoration::OnMouseExited() { + state_ = LocationBarDecorationState::NORMAL; + UpdateDecorationState(); +} + +void LocationBarDecoration::UpdateDecorationState() { + DCHECK(tracking_area_owner_); + [tracking_area_owner_ setNeedsDisplay:YES]; +} + NSMenu* LocationBarDecoration::GetMenu() { return nil; } @@ -224,10 +364,10 @@ NSColor* LocationBarDecoration::GetDividerColor( bool location_bar_is_dark) const { - CGFloat gray_scale = location_bar_is_dark ? kMaterialDividerIncognitoGrayScale - : kMaterialDividerGrayScale; - return [NSColor colorWithCalibratedWhite:gray_scale - alpha:kMaterialDividerAlpha / 255.0]; + CGFloat gray_scale = + location_bar_is_dark ? kDividerIncognitoGrayScale : kDividerGrayScale; + return + [NSColor colorWithCalibratedWhite:gray_scale alpha:kDividerAlpha / 255.0]; } gfx::VectorIconId LocationBarDecoration::GetMaterialVectorIconId() const {
diff --git a/chrome/browser/ui/cocoa/location_bar/location_icon_decoration.h b/chrome/browser/ui/cocoa/location_bar/location_icon_decoration.h index 7630f2c..cc4a62f 100644 --- a/chrome/browser/ui/cocoa/location_bar/location_icon_decoration.h +++ b/chrome/browser/ui/cocoa/location_bar/location_icon_decoration.h
@@ -29,8 +29,10 @@ // Show the page info panel on click. bool OnMousePressed(NSRect frame, NSPoint location) override; bool AcceptsMousePress() override; + bool HasHoverAndPressEffect() override; NSString* GetToolTip() override; NSPoint GetBubblePointInFrame(NSRect frame) override; + NSRect GetBackgroundFrame(NSRect frame) override; private: NSRect drag_frame_;
diff --git a/chrome/browser/ui/cocoa/location_bar/location_icon_decoration.mm b/chrome/browser/ui/cocoa/location_bar/location_icon_decoration.mm index d8a2469..1c9d350 100644 --- a/chrome/browser/ui/cocoa/location_bar/location_icon_decoration.mm +++ b/chrome/browser/ui/cocoa/location_bar/location_icon_decoration.mm
@@ -18,6 +18,7 @@ #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/web_contents.h" +#include "skia/ext/skia_utils_mac.h" #import "third_party/mozilla/NSPasteboard+Utils.h" #include "ui/base/l10n/l10n_util_mac.h" #include "ui/gfx/image/image.h" @@ -30,6 +31,10 @@ // icon. Determined with Pixie.app. const CGFloat kBubblePointYOffset = 2.0; +// Insets for the background frame. +const CGFloat kBackgroundFrameXInset = 1.0; +const CGFloat kBackgroundFrameYInset = 2.0; + LocationIconDecoration::LocationIconDecoration(LocationBarViewMac* owner) : drag_frame_(NSZeroRect), owner_(owner) { } @@ -97,10 +102,19 @@ NSMaxY(draw_frame) - kBubblePointYOffset); } +NSRect LocationIconDecoration::GetBackgroundFrame(NSRect frame) { + return NSInsetRect(frame, kBackgroundFrameXInset, kBackgroundFrameYInset); +} + bool LocationIconDecoration::AcceptsMousePress() { return true; } +bool LocationIconDecoration::HasHoverAndPressEffect() { + // The search icon should not show a hover/pressed background. + return !owner_->GetOmniboxView()->IsEditingOrEmpty(); +} + bool LocationIconDecoration::OnMousePressed(NSRect frame, NSPoint location) { // TODO(macourteau): this code (for displaying the page info bubble) should be // pulled out into LocationBarViewMac (or maybe even further), as other
diff --git a/chrome/browser/ui/cocoa/location_bar/security_state_bubble_decoration.mm b/chrome/browser/ui/cocoa/location_bar/security_state_bubble_decoration.mm index c6fe3ee..6ec3fd95 100644 --- a/chrome/browser/ui/cocoa/location_bar/security_state_bubble_decoration.mm +++ b/chrome/browser/ui/cocoa/location_bar/security_state_bubble_decoration.mm
@@ -227,19 +227,21 @@ [text drawInRect:text_rect]; // Draw the divider. - NSBezierPath* line = [NSBezierPath bezierPath]; - [line setLineWidth:line_width]; - [line moveToPoint:NSMakePoint(NSMaxX(decoration_frame) - DividerPadding(), - NSMinY(decoration_frame))]; - [line lineToPoint:NSMakePoint(NSMaxX(decoration_frame) - DividerPadding(), - NSMaxY(decoration_frame))]; + if (state() == LocationBarDecorationState::NORMAL) { + NSBezierPath* line = [NSBezierPath bezierPath]; + [line setLineWidth:line_width]; + [line moveToPoint:NSMakePoint(NSMaxX(decoration_frame) - DividerPadding(), + NSMinY(decoration_frame))]; + [line lineToPoint:NSMakePoint(NSMaxX(decoration_frame) - DividerPadding(), + NSMaxY(decoration_frame))]; - NSColor* divider_color = GetDividerColor(in_dark_mode); - CGFloat divider_alpha = - [divider_color alphaComponent] * GetAnimationProgress(); - divider_color = [divider_color colorWithAlphaComponent:divider_alpha]; - [divider_color set]; - [line stroke]; + NSColor* divider_color = GetDividerColor(in_dark_mode); + CGFloat divider_alpha = + [divider_color alphaComponent] * GetAnimationProgress(); + divider_color = [divider_color colorWithAlphaComponent:divider_alpha]; + [divider_color set]; + [line stroke]; + } } }
diff --git a/chrome/browser/ui/cocoa/omnibox/omnibox_view_mac.h b/chrome/browser/ui/cocoa/omnibox/omnibox_view_mac.h index 15f2c319..39d2deb8 100644 --- a/chrome/browser/ui/cocoa/omnibox/omnibox_view_mac.h +++ b/chrome/browser/ui/cocoa/omnibox/omnibox_view_mac.h
@@ -112,6 +112,7 @@ void OnDidChange() override; void OnDidEndEditing() override; void OnInsertText() override; + void OnBeforeDrawRect() override; void OnDidDrawRect() override; bool OnDoCommandBySelector(SEL cmd) override; void OnSetFocus(bool control_down) override; @@ -232,6 +233,9 @@ // painted. Used to measure omnibox responsiveness with a histogram. base::TimeTicks insert_char_time_; + // The time when OnBeforeDrawRect() was called. + base::TimeTicks draw_rect_start_time_; + DISALLOW_COPY_AND_ASSIGN(OmniboxViewMac); };
diff --git a/chrome/browser/ui/cocoa/omnibox/omnibox_view_mac.mm b/chrome/browser/ui/cocoa/omnibox/omnibox_view_mac.mm index c030fe98..e98ba38 100644 --- a/chrome/browser/ui/cocoa/omnibox/omnibox_view_mac.mm +++ b/chrome/browser/ui/cocoa/omnibox/omnibox_view_mac.mm
@@ -772,10 +772,16 @@ insert_char_time_ = base::TimeTicks::Now(); } +void OmniboxViewMac::OnBeforeDrawRect() { + draw_rect_start_time_ = base::TimeTicks::Now(); +} + void OmniboxViewMac::OnDidDrawRect() { + base::TimeTicks now = base::TimeTicks::Now(); + UMA_HISTOGRAM_TIMES("Omnibox.PaintTime", now - draw_rect_start_time_); if (!insert_char_time_.is_null()) { UMA_HISTOGRAM_TIMES("Omnibox.CharTypedToRepaintLatency", - base::TimeTicks::Now() - insert_char_time_); + now - insert_char_time_); insert_char_time_ = base::TimeTicks(); } }
diff --git a/chrome/browser/ui/cocoa/tabs/tab_strip_controller.mm b/chrome/browser/ui/cocoa/tabs/tab_strip_controller.mm index a8499d1..46ee02b 100644 --- a/chrome/browser/ui/cocoa/tabs/tab_strip_controller.mm +++ b/chrome/browser/ui/cocoa/tabs/tab_strip_controller.mm
@@ -1756,8 +1756,9 @@ // No placeholder, return the end of the strip. if (placeholderTab_ == nil) return count; - - double placeholderX = placeholderFrame_.origin.x; + BOOL isRTL = cocoa_l10n_util::ShouldDoExperimentalRTLLayout(); + double placeholderX = + isRTL ? NSMaxX(placeholderFrame_) : placeholderFrame_.origin.x; int index = 0; int location = 0; while (index < count) { @@ -1778,7 +1779,8 @@ index++; continue; } - if (placeholderX <= NSMinX([curr frame])) + if (isRTL ? placeholderX >= NSMaxX([curr frame]) + : placeholderX <= NSMinX([curr frame])) break; index++; location++; @@ -2259,8 +2261,8 @@ customWindowControls_.reset( [[CustomWindowControlsView alloc] initWithFrame:frame]); [customWindowControls_ - setAutoresizingMask:isRTL ? NSViewMaxXMargin | NSViewHeightSizable - : NSViewMinXMargin | NSViewHeightSizable]; + setAutoresizingMask:isRTL ? NSViewMinXMargin | NSViewHeightSizable + : NSViewMaxXMargin | NSViewHeightSizable]; // Add the traffic light buttons. The horizontal layout was determined by // manual inspection on Yosemite.
diff --git a/chrome/browser/ui/extensions/hosted_app_browser_controller.cc b/chrome/browser/ui/extensions/hosted_app_browser_controller.cc index 34b798e..1726f82 100644 --- a/chrome/browser/ui/extensions/hosted_app_browser_controller.cc +++ b/chrome/browser/ui/extensions/hosted_app_browser_controller.cc
@@ -26,10 +26,10 @@ bool IsSameOriginOrMoreSecure(const GURL& app_url, const GURL& page_url) { const std::string www("www."); - return (app_url.scheme() == page_url.scheme() || - page_url.scheme() == url::kHttpsScheme) && - (app_url.host() == page_url.host() || - www + app_url.host() == page_url.host()) && + return (app_url.scheme_piece() == page_url.scheme_piece() || + page_url.scheme_piece() == url::kHttpsScheme) && + (app_url.host_piece() == page_url.host_piece() || + www + app_url.host() == page_url.host_piece()) && app_url.port() == page_url.port(); }
diff --git a/chrome/browser/ui/javascript_dialogs/javascript_dialog_tab_helper.cc b/chrome/browser/ui/javascript_dialogs/javascript_dialog_tab_helper.cc index 1dfd9f4..66c838b 100644 --- a/chrome/browser/ui/javascript_dialogs/javascript_dialog_tab_helper.cc +++ b/chrome/browser/ui/javascript_dialogs/javascript_dialog_tab_helper.cc
@@ -77,10 +77,22 @@ message_length); } - if (IsEnabled()) { - content::WebContents* parent_web_contents = - WebContentsObserver::web_contents(); + content::WebContents* parent_web_contents = + WebContentsObserver::web_contents(); + bool foremost = IsWebContentsForemost(parent_web_contents); + switch (message_type) { + case content::JAVASCRIPT_MESSAGE_TYPE_ALERT: + UMA_HISTOGRAM_BOOLEAN("JSDialogs.IsForemost.Alert", foremost); + break; + case content::JAVASCRIPT_MESSAGE_TYPE_CONFIRM: + UMA_HISTOGRAM_BOOLEAN("JSDialogs.IsForemost.Confirm", foremost); + break; + case content::JAVASCRIPT_MESSAGE_TYPE_PROMPT: + UMA_HISTOGRAM_BOOLEAN("JSDialogs.IsForemost.Prompt", foremost); + break; + } + if (IsEnabled()) { if (!IsWebContentsForemost(parent_web_contents) && message_type == content::JAVASCRIPT_MESSAGE_TYPE_PROMPT) { // Don't allow "prompt" dialogs to steal the user's focus. TODO(avi):
diff --git a/chrome/browser/ui/search_engines/search_engine_tab_helper.cc b/chrome/browser/ui/search_engines/search_engine_tab_helper.cc index 9304c7d9..6ac56a4 100644 --- a/chrome/browser/ui/search_engines/search_engine_tab_helper.cc +++ b/chrome/browser/ui/search_engines/search_engine_tab_helper.cc
@@ -18,10 +18,10 @@ #include "content/public/browser/favicon_status.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_entry.h" +#include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" -#include "content/public/common/frame_navigate_params.h" #include "content/public/common/url_fetcher.h" using content::NavigationController; @@ -83,10 +83,9 @@ SearchEngineTabHelper::~SearchEngineTabHelper() { } -void SearchEngineTabHelper::DidNavigateMainFrame( - const content::LoadCommittedDetails& /*details*/, - const content::FrameNavigateParams& params) { - GenerateKeywordIfNecessary(params); +void SearchEngineTabHelper::DidFinishNavigation( + content::NavigationHandle* handle) { + GenerateKeywordIfNecessary(handle); } bool SearchEngineTabHelper::OnMessageReceived(const IPC::Message& message) { @@ -156,8 +155,8 @@ } void SearchEngineTabHelper::GenerateKeywordIfNecessary( - const content::FrameNavigateParams& params) { - if (!params.searchable_form_url.is_valid()) + content::NavigationHandle* handle) { + if (!handle->IsInMainFrame() || !handle->GetSearchableFormURL().is_valid()) return; Profile* profile = @@ -190,7 +189,7 @@ } TemplateURL* current_url; - GURL url = params.searchable_form_url; + GURL url = handle->GetSearchableFormURL(); if (!url_service->CanAddAutogeneratedKeyword(keyword, url, ¤t_url)) return; @@ -215,9 +214,11 @@ // latter. // TODO(sky): Need a way to set the favicon that doesn't involve generating // its url. - data.favicon_url = current_favicon.is_valid() ? - current_favicon : TemplateURL::GenerateFaviconURL(params.referrer.url); + data.favicon_url = + current_favicon.is_valid() + ? current_favicon + : TemplateURL::GenerateFaviconURL(handle->GetReferrer().url); data.safe_for_autoreplace = true; - data.input_encodings.push_back(params.searchable_form_encoding); + data.input_encodings.push_back(handle->GetSearchableFormEncoding()); url_service->Add(base::MakeUnique<TemplateURL>(data)); }
diff --git a/chrome/browser/ui/search_engines/search_engine_tab_helper.h b/chrome/browser/ui/search_engines/search_engine_tab_helper.h index c4f97663..b69b8ce 100644 --- a/chrome/browser/ui/search_engines/search_engine_tab_helper.h +++ b/chrome/browser/ui/search_engines/search_engine_tab_helper.h
@@ -23,9 +23,8 @@ ~SearchEngineTabHelper() override; // content::WebContentsObserver overrides. - void DidNavigateMainFrame( - const content::LoadCommittedDetails& details, - const content::FrameNavigateParams& params) override; + void DidFinishNavigation(content::NavigationHandle* handle) override; + bool OnMessageReceived(const IPC::Message& message) override; bool OnMessageReceived(const IPC::Message& message, content::RenderFrameHost* rfh) override; @@ -38,8 +37,7 @@ void OnPageHasOSDD(const GURL& page_url, const GURL& osdd_url); // If params has a searchable form, this tries to create a new keyword. - void GenerateKeywordIfNecessary( - const content::FrameNavigateParams& params); + void GenerateKeywordIfNecessary(content::NavigationHandle* handle); DISALLOW_COPY_AND_ASSIGN(SearchEngineTabHelper); };
diff --git a/chrome/browser/ui/startup/startup_tab_provider.cc b/chrome/browser/ui/startup/startup_tab_provider.cc index 7270275..5d4206c 100644 --- a/chrome/browser/ui/startup/startup_tab_provider.cc +++ b/chrome/browser/ui/startup/startup_tab_provider.cc
@@ -97,9 +97,9 @@ if (is_first_run) { tabs.reserve(first_run_tabs.size()); for (GURL url : first_run_tabs) { - if (url.host() == kNewTabUrlHost) + if (url.host_piece() == kNewTabUrlHost) url = GURL(chrome::kChromeUINewTabURL); - else if (url.host() == kWelcomePageUrlHost) + else if (url.host_piece() == kWelcomePageUrlHost) url = GetWelcomePageUrl(); tabs.emplace_back(url, false); }
diff --git a/chrome/browser/ui/tabs/tab_strip_model.cc b/chrome/browser/ui/tabs/tab_strip_model.cc index abc8082..b29c2094 100644 --- a/chrome/browser/ui/tabs/tab_strip_model.cc +++ b/chrome/browser/ui/tabs/tab_strip_model.cc
@@ -1099,7 +1099,7 @@ for (int i = 0; i < count(); ++i) { if (i == index) continue; - if (GetWebContentsAt(i)->GetURL().host() == domain) + if (GetWebContentsAt(i)->GetURL().host_piece() == domain) indices->push_back(i); } } @@ -1135,7 +1135,7 @@ bool TabStripModel::IsNewTabAtEndOfTabStrip(WebContents* contents) const { const GURL& url = contents->GetURL(); return url.SchemeIs(content::kChromeUIScheme) && - url.host() == chrome::kChromeUINewTabHost && + url.host_piece() == chrome::kChromeUINewTabHost && contents == GetWebContentsAtImpl(count() - 1) && contents->GetController().GetEntryCount() == 1; }
diff --git a/chrome/browser/ui/views/download/download_feedback_dialog_view.cc b/chrome/browser/ui/views/download/download_feedback_dialog_view.cc index ba04c8d..0f7874a 100644 --- a/chrome/browser/ui/views/download/download_feedback_dialog_view.cc +++ b/chrome/browser/ui/views/download/download_feedback_dialog_view.cc
@@ -75,11 +75,14 @@ : profile_(profile), navigator_(navigator), callback_(callback), - explanation_box_view_(new views::MessageBoxView( - views::MessageBoxView::InitParams(l10n_util::GetStringUTF16( - IDS_FEEDBACK_SERVICE_DIALOG_EXPLANATION)))), - link_view_(new views::Link(l10n_util::GetStringUTF16( - IDS_SAFE_BROWSING_PRIVACY_POLICY_PAGE))), + explanation_box_view_( + new views::MessageBoxView(views::MessageBoxView::InitParams( + l10n_util::GetStringUTF16(safe_browsing::ChooseOptInTextResource( + *profile->GetPrefs(), + IDS_FEEDBACK_SERVICE_DIALOG_EXPLANATION, + IDS_FEEDBACK_SERVICE_DIALOG_EXPLANATION_SCOUT))))), + link_view_(new views::Link( + l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_PRIVACY_POLICY_PAGE))), title_text_(l10n_util::GetStringUTF16(IDS_FEEDBACK_SERVICE_DIALOG_TITLE)), ok_button_text_(l10n_util::GetStringUTF16( IDS_FEEDBACK_SERVICE_DIALOG_OK_BUTTON_LABEL)),
diff --git a/chrome/browser/ui/views/extensions/extension_installed_bubble_view.cc b/chrome/browser/ui/views/extensions/extension_installed_bubble_view.cc index 8555bd0..242b3a4 100644 --- a/chrome/browser/ui/views/extensions/extension_installed_bubble_view.cc +++ b/chrome/browser/ui/views/extensions/extension_installed_bubble_view.cc
@@ -157,8 +157,8 @@ } void ExtensionInstalledBubbleView::CloseBubble() { - // This function should only be called once. - CHECK(!GetWidget()->IsClosed()); + if (GetWidget()->IsClosed()) + return; if (controller_->anchor_position() == ExtensionInstalledBubble::ANCHOR_PAGE_ACTION) { BrowserView* browser_view = @@ -261,8 +261,7 @@ chrome::ShowBrowserSignin( browser(), signin_metrics::AccessPoint::ACCESS_POINT_EXTENSION_INSTALL_BUBBLE); - // Showing the sign-in UI will cause the bubble to close. - CHECK(GetWidget()->IsClosed()); + CloseBubble(); } void ExtensionInstalledBubbleView::LinkClicked(views::Link* source, @@ -274,8 +273,7 @@ chrome::NavigateParams params( chrome::GetSingletonTabNavigateParams(browser(), GURL(configure_url))); chrome::Navigate(¶ms); - // Navigating will cause the bubble to close. - CHECK(GetWidget()->IsClosed()); + CloseBubble(); } gfx::Size ExtensionInstalledBubbleView::GetIconSize() const {
diff --git a/chrome/browser/ui/views/omnibox/omnibox_view_views.cc b/chrome/browser/ui/views/omnibox/omnibox_view_views.cc index 53d627b6..2d79a20 100644 --- a/chrome/browser/ui/views/omnibox/omnibox_view_views.cc +++ b/chrome/browser/ui/views/omnibox/omnibox_view_views.cc
@@ -301,7 +301,10 @@ } void OmniboxViewViews::OnPaint(gfx::Canvas* canvas) { - Textfield::OnPaint(canvas); + { + SCOPED_UMA_HISTOGRAM_TIMER("Omnibox.PaintTime"); + Textfield::OnPaint(canvas); + } if (!insert_char_time_.is_null()) { UMA_HISTOGRAM_TIMES("Omnibox.CharTypedToRepaintLatency", base::TimeTicks::Now() - insert_char_time_);
diff --git a/chrome/browser/ui/views/toolbar/toolbar_action_view.cc b/chrome/browser/ui/views/toolbar/toolbar_action_view.cc index 9968433..c447979 100644 --- a/chrome/browser/ui/views/toolbar/toolbar_action_view.cc +++ b/chrome/browser/ui/views/toolbar/toolbar_action_view.cc
@@ -110,6 +110,7 @@ std::unique_ptr<views::InkDropImpl> ink_drop = CustomButton::CreateDefaultInkDropImpl(); ink_drop->SetShowHighlightOnHover(!delegate_->ShownInsideMenu()); + ink_drop->SetShowHighlightOnFocus(true); return std::move(ink_drop); }
diff --git a/chrome/browser/ui/views/website_settings/non_accessible_image_view.cc b/chrome/browser/ui/views/website_settings/non_accessible_image_view.cc new file mode 100644 index 0000000..d0638d8 --- /dev/null +++ b/chrome/browser/ui/views/website_settings/non_accessible_image_view.cc
@@ -0,0 +1,12 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/views/website_settings/non_accessible_image_view.h" + +#include "ui/accessibility/ax_enums.h" +#include "ui/accessibility/ax_node_data.h" + +void NonAccessibleImageView::GetAccessibleNodeData(ui::AXNodeData* node_data) { + node_data->AddStateFlag(ui::AX_STATE_INVISIBLE); +}
diff --git a/chrome/browser/ui/views/website_settings/non_accessible_image_view.h b/chrome/browser/ui/views/website_settings/non_accessible_image_view.h new file mode 100644 index 0000000..80eb9956 --- /dev/null +++ b/chrome/browser/ui/views/website_settings/non_accessible_image_view.h
@@ -0,0 +1,23 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_VIEWS_WEBSITE_SETTINGS_NON_ACCESSIBLE_IMAGE_VIEW_H_ +#define CHROME_BROWSER_UI_VIEWS_WEBSITE_SETTINGS_NON_ACCESSIBLE_IMAGE_VIEW_H_ + +#include "base/macros.h" +#include "ui/views/controls/image_view.h" + +class NonAccessibleImageView : public views::ImageView { + public: + NonAccessibleImageView() {} + ~NonAccessibleImageView() override {} + + private: + // Overridden from views::ImageView. + void GetAccessibleNodeData(ui::AXNodeData* node_data) override; + + DISALLOW_COPY_AND_ASSIGN(NonAccessibleImageView); +}; + +#endif // CHROME_BROWSER_UI_VIEWS_WEBSITE_SETTINGS_NON_ACCESSIBLE_IMAGE_VIEW_H_
diff --git a/chrome/browser/ui/views/website_settings/permission_selector_row.cc b/chrome/browser/ui/views/website_settings/permission_selector_row.cc index a57926080..00f49fbc 100644 --- a/chrome/browser/ui/views/website_settings/permission_selector_row.cc +++ b/chrome/browser/ui/views/website_settings/permission_selector_row.cc
@@ -7,6 +7,7 @@ #include "base/i18n/rtl.h" #include "base/macros.h" #include "base/strings/utf_string_conversions.h" +#include "chrome/browser/ui/views/website_settings/non_accessible_image_view.h" #include "chrome/browser/ui/views/website_settings/website_settings_popup_view.h" #include "chrome/browser/ui/website_settings/permission_menu_model.h" #include "chrome/browser/ui/website_settings/website_settings_ui.h" @@ -28,7 +29,7 @@ namespace { // Minimum distance between the label and its corresponding menu. const int kMinSeparationBetweenLabelAndMenu = 16; -} +} // namespace namespace internal { @@ -251,7 +252,7 @@ layout->StartRow(1, column_set_id); // Create the permission icon. - icon_ = new views::ImageView(); + icon_ = new NonAccessibleImageView(); const gfx::Image& image = WebsiteSettingsUI::GetPermissionIcon(permission); icon_->SetImage(image.ToImageSkia()); layout->AddView(icon_,
diff --git a/chrome/browser/ui/views/website_settings/website_settings_popup_view.cc b/chrome/browser/ui/views/website_settings/website_settings_popup_view.cc index 63f5e57..6d73f9d 100644 --- a/chrome/browser/ui/views/website_settings/website_settings_popup_view.cc +++ b/chrome/browser/ui/views/website_settings/website_settings_popup_view.cc
@@ -25,6 +25,7 @@ #include "chrome/browser/ui/layout_constants.h" #include "chrome/browser/ui/views/collected_cookies_views.h" #include "chrome/browser/ui/views/website_settings/chosen_object_row.h" +#include "chrome/browser/ui/views/website_settings/non_accessible_image_view.h" #include "chrome/browser/ui/views/website_settings/permission_selector_row.h" #include "chrome/browser/ui/website_settings/website_settings.h" #include "chrome/common/pref_names.h" @@ -369,7 +370,7 @@ SetLayoutManager(new views::BoxLayout(views::BoxLayout::kHorizontal, kSpacing, kSpacing, kSpacing)); set_margins(gfx::Insets()); - views::ImageView* icon_view = new views::ImageView(); + views::ImageView* icon_view = new NonAccessibleImageView(); ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); icon_view->SetImage(rb.GetImageSkiaNamed(icon)); AddChildView(icon_view); @@ -619,7 +620,7 @@ info.is_incognito = Profile::FromBrowserContext(web_contents()->GetBrowserContext()) ->IsOffTheRecord(); - views::ImageView* icon = new views::ImageView(); + views::ImageView* icon = new NonAccessibleImageView(); const gfx::Image& image = WebsiteSettingsUI::GetPermissionIcon(info); icon->SetImage(image.ToImageSkia()); layout->AddView(
diff --git a/chrome/browser/ui/website_settings/website_settings.cc b/chrome/browser/ui/website_settings/website_settings.cc index f880bcb..d474389 100644 --- a/chrome/browser/ui/website_settings/website_settings.cc +++ b/chrome/browser/ui/website_settings/website_settings.cc
@@ -193,60 +193,6 @@ } } -// Returns true if any of the given statuses match |status|. -bool CertificateTransparencyStatusMatchAny( - const std::vector<net::ct::SCTVerifyStatus>& sct_verify_statuses, - net::ct::SCTVerifyStatus status) { - for (const auto& verify_status : sct_verify_statuses) { - if (verify_status == status) - return true; - } - return false; -} - -int GetSiteIdentityDetailsMessageByCTInfo( - const std::vector<net::ct::SCTVerifyStatus>& sct_verify_statuses, - bool is_ev) { - // No SCTs - no CT information. - if (sct_verify_statuses.empty()) - return (is_ev ? IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV_NO_CT - : IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_NO_CT); - - // Any valid SCT. - if (CertificateTransparencyStatusMatchAny(sct_verify_statuses, - net::ct::SCT_STATUS_OK)) - return (is_ev ? IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV_CT_VERIFIED - : IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_CT_VERIFIED); - - // Any invalid SCT. - if (CertificateTransparencyStatusMatchAny( - sct_verify_statuses, net::ct::SCT_STATUS_INVALID_TIMESTAMP) || - CertificateTransparencyStatusMatchAny( - sct_verify_statuses, net::ct::SCT_STATUS_INVALID_SIGNATURE)) - return (is_ev ? IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV_CT_INVALID - : IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_CT_INVALID); - - // All SCTs are from unknown logs. - return (is_ev ? IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV_CT_UNVERIFIED - : IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_CT_UNVERIFIED); -} - -// This function will return SITE_IDENTITY_STATUS_CERT or -// SITE_IDENTITY_STATUS_EV_CERT depending on |is_ev| unless all SCTs -// failed verification, in which case it will return -// SITE_IDENTITY_STATUS_ERROR. -WebsiteSettings::SiteIdentityStatus GetSiteIdentityStatusByCTInfo( - const std::vector<net::ct::SCTVerifyStatus>& sct_verify_statuses, - bool is_ev) { - if (sct_verify_statuses.empty() || - CertificateTransparencyStatusMatchAny(sct_verify_statuses, - net::ct::SCT_STATUS_OK)) - return is_ev ? WebsiteSettings::SITE_IDENTITY_STATUS_EV_CERT - : WebsiteSettings::SITE_IDENTITY_STATUS_CERT; - - return WebsiteSettings::SITE_IDENTITY_STATUS_CT_ERROR; -} - base::string16 GetSimpleSiteName(const GURL& url) { return url_formatter::FormatUrlForSecurityDisplay( url, url_formatter::SchemeDisplay::OMIT_HTTP_AND_HTTPS); @@ -497,9 +443,7 @@ } site_identity_details_.assign(l10n_util::GetStringFUTF16( - GetSiteIdentityDetailsMessageByCTInfo( - security_info.sct_verify_statuses, false /* not EV */), - issuer_name)); + IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_VERIFIED, issuer_name)); site_identity_details_ += ASCIIToUTF16("\n\n"); if (security_info.cert_status & @@ -514,10 +458,10 @@ NOTREACHED() << "Need to specify string for this warning"; } } else { + // No major or minor errors. if (security_info.cert_status & net::CERT_STATUS_IS_EV) { // EV HTTPS page. - site_identity_status_ = GetSiteIdentityStatusByCTInfo( - security_info.sct_verify_statuses, true); + site_identity_status_ = SITE_IDENTITY_STATUS_EV_CERT; DCHECK(!certificate_->subject().organization_names.empty()); organization_name_ = UTF8ToUTF16(certificate_->subject().organization_names[0]); @@ -540,15 +484,12 @@ } DCHECK(!certificate_->subject().organization_names.empty()); site_identity_details_.assign(l10n_util::GetStringFUTF16( - GetSiteIdentityDetailsMessageByCTInfo( - security_info.sct_verify_statuses, true /* is EV */), + IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV_VERIFIED, UTF8ToUTF16(certificate_->subject().organization_names[0]), - locality, - UTF8ToUTF16(certificate_->issuer().GetDisplayName()))); + locality, UTF8ToUTF16(certificate_->issuer().GetDisplayName()))); } else { // Non-EV OK HTTPS page. - site_identity_status_ = GetSiteIdentityStatusByCTInfo( - security_info.sct_verify_statuses, false); + site_identity_status_ = SITE_IDENTITY_STATUS_CERT; base::string16 issuer_name( UTF8ToUTF16(certificate_->issuer().GetDisplayName())); if (issuer_name.empty()) { @@ -557,9 +498,7 @@ } site_identity_details_.assign(l10n_util::GetStringFUTF16( - GetSiteIdentityDetailsMessageByCTInfo( - security_info.sct_verify_statuses, false /* not EV */), - issuer_name)); + IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_VERIFIED, issuer_name)); } switch (security_info.sha1_deprecation_status) { case SecurityStateModel::DEPRECATED_SHA1_MINOR: @@ -749,7 +688,6 @@ site_connection_status_ == SITE_CONNECTION_STATUS_INSECURE_ACTIVE_SUBRESOURCE || site_identity_status_ == SITE_IDENTITY_STATUS_ERROR || - site_identity_status_ == SITE_IDENTITY_STATUS_CT_ERROR || site_identity_status_ == SITE_IDENTITY_STATUS_CERT_REVOCATION_UNKNOWN || site_identity_status_ == SITE_IDENTITY_STATUS_ADMIN_PROVIDED_CERT || site_identity_status_ ==
diff --git a/chrome/browser/ui/website_settings/website_settings.h b/chrome/browser/ui/website_settings/website_settings.h index acd35cf..ae1aceb 100644 --- a/chrome/browser/ui/website_settings/website_settings.h +++ b/chrome/browser/ui/website_settings/website_settings.h
@@ -68,9 +68,6 @@ SITE_IDENTITY_STATUS_NO_CERT, // An error occured while verifying the site identity. SITE_IDENTITY_STATUS_ERROR, - // The website provided a valid certificate but all signed - // certificate timestamps failed to validate. - SITE_IDENTITY_STATUS_CT_ERROR, // The site is a trusted internal chrome page. SITE_IDENTITY_STATUS_INTERNAL_PAGE, // The profile has accessed data using an administrator-provided
diff --git a/chrome/browser/ui/website_settings/website_settings_ui.cc b/chrome/browser/ui/website_settings/website_settings_ui.cc index 1cdd003..0b3bf2a9 100644 --- a/chrome/browser/ui/website_settings/website_settings_ui.cc +++ b/chrome/browser/ui/website_settings/website_settings_ui.cc
@@ -166,7 +166,6 @@ case WebsiteSettings::SITE_IDENTITY_STATUS_CERT: case WebsiteSettings::SITE_IDENTITY_STATUS_EV_CERT: case WebsiteSettings::SITE_IDENTITY_STATUS_CERT_REVOCATION_UNKNOWN: - case WebsiteSettings::SITE_IDENTITY_STATUS_CT_ERROR: case WebsiteSettings::SITE_IDENTITY_STATUS_ADMIN_PROVIDED_CERT: switch (connection_status) { case WebsiteSettings:: @@ -345,7 +344,6 @@ resource_id = IDR_PAGEINFO_WARNING_MAJOR; break; case WebsiteSettings::SITE_IDENTITY_STATUS_ERROR: - case WebsiteSettings::SITE_IDENTITY_STATUS_CT_ERROR: resource_id = IDR_PAGEINFO_BAD; break; case WebsiteSettings::SITE_IDENTITY_STATUS_ADMIN_PROVIDED_CERT:
diff --git a/chrome/browser/ui/website_settings/website_settings_unittest.cc b/chrome/browser/ui/website_settings/website_settings_unittest.cc index d577c4e..dca9b4b0 100644 --- a/chrome/browser/ui/website_settings/website_settings_unittest.cc +++ b/chrome/browser/ui/website_settings/website_settings_unittest.cc
@@ -677,172 +677,6 @@ website_settings()->site_identity_status())); } -// All SCTs are from unknown logs. -TEST_F(WebsiteSettingsTest, UnknownSCTs) { - security_info_.security_level = SecurityStateModel::SECURE; - security_info_.scheme_is_cryptographic = true; - security_info_.certificate = cert(); - security_info_.cert_status = 0; - security_info_.security_bits = 81; // No error if > 80. - int status = 0; - status = SetSSLVersion(status, net::SSL_CONNECTION_VERSION_TLS1); - status = SetSSLCipherSuite(status, CR_TLS_RSA_WITH_AES_256_CBC_SHA256); - security_info_.connection_status = status; - - security_info_.sct_verify_statuses.push_back(net::ct::SCT_STATUS_LOG_UNKNOWN); - security_info_.sct_verify_statuses.push_back(net::ct::SCT_STATUS_LOG_UNKNOWN); - - SetDefaultUIExpectations(mock_ui()); - EXPECT_CALL(*mock_ui(), SetSelectedTab(WebsiteSettingsUI::TAB_ID_CONNECTION)); - - EXPECT_EQ(WebsiteSettings::SITE_CONNECTION_STATUS_ENCRYPTED, - website_settings()->site_connection_status()); - EXPECT_EQ(WebsiteSettings::SITE_IDENTITY_STATUS_CT_ERROR, - website_settings()->site_identity_status()); - EXPECT_EQ(IDR_PAGEINFO_BAD, WebsiteSettingsUI::GetIdentityIconID( - website_settings()->site_identity_status())); -} - -// All SCTs are invalid. -TEST_F(WebsiteSettingsTest, InvalidSCTs) { - security_info_.security_level = SecurityStateModel::SECURE; - security_info_.scheme_is_cryptographic = true; - security_info_.certificate = cert(); - security_info_.cert_status = 0; - security_info_.security_bits = 81; // No error if > 80. - int status = 0; - status = SetSSLVersion(status, net::SSL_CONNECTION_VERSION_TLS1); - status = SetSSLCipherSuite(status, CR_TLS_RSA_WITH_AES_256_CBC_SHA256); - security_info_.connection_status = status; - - security_info_.sct_verify_statuses.push_back( - net::ct::SCT_STATUS_INVALID_TIMESTAMP); - security_info_.sct_verify_statuses.push_back( - net::ct::SCT_STATUS_INVALID_SIGNATURE); - - SetDefaultUIExpectations(mock_ui()); - EXPECT_CALL(*mock_ui(), SetSelectedTab(WebsiteSettingsUI::TAB_ID_CONNECTION)); - - EXPECT_EQ(WebsiteSettings::SITE_CONNECTION_STATUS_ENCRYPTED, - website_settings()->site_connection_status()); - EXPECT_EQ(WebsiteSettings::SITE_IDENTITY_STATUS_CT_ERROR, - website_settings()->site_identity_status()); - EXPECT_EQ(IDR_PAGEINFO_BAD, WebsiteSettingsUI::GetIdentityIconID( - website_settings()->site_identity_status())); -} - -// All SCTs are valid. -TEST_F(WebsiteSettingsTest, ValidSCTs) { - security_info_.security_level = SecurityStateModel::SECURE; - security_info_.scheme_is_cryptographic = true; - security_info_.certificate = cert(); - security_info_.cert_status = 0; - security_info_.security_bits = 81; // No error if > 80. - int status = 0; - status = SetSSLVersion(status, net::SSL_CONNECTION_VERSION_TLS1); - status = SetSSLCipherSuite(status, CR_TLS_RSA_WITH_AES_256_CBC_SHA256); - security_info_.connection_status = status; - - security_info_.sct_verify_statuses.push_back(net::ct::SCT_STATUS_OK); - security_info_.sct_verify_statuses.push_back(net::ct::SCT_STATUS_OK); - - SetDefaultUIExpectations(mock_ui()); - EXPECT_CALL(*mock_ui(), - SetSelectedTab(WebsiteSettingsUI::TAB_ID_PERMISSIONS)); - - EXPECT_EQ(WebsiteSettings::SITE_CONNECTION_STATUS_ENCRYPTED, - website_settings()->site_connection_status()); - EXPECT_EQ(WebsiteSettings::SITE_IDENTITY_STATUS_CERT, - website_settings()->site_identity_status()); - EXPECT_EQ(IDR_PAGEINFO_GOOD, WebsiteSettingsUI::GetIdentityIconID( - website_settings()->site_identity_status())); -} - -// All SCTs are valid for an EV cert. -TEST_F(WebsiteSettingsTest, ValidSCTsEV) { - scoped_refptr<net::X509Certificate> ev_cert = - net::X509Certificate::CreateFromBytes( - reinterpret_cast<const char*>(google_der), sizeof(google_der)); - - security_info_.security_level = SecurityStateModel::SECURE; - security_info_.scheme_is_cryptographic = true; - security_info_.certificate = ev_cert; - security_info_.cert_status = net::CERT_STATUS_IS_EV; - security_info_.security_bits = 81; // No error if > 80. - int status = 0; - status = SetSSLVersion(status, net::SSL_CONNECTION_VERSION_TLS1); - status = SetSSLCipherSuite(status, CR_TLS_RSA_WITH_AES_256_CBC_SHA256); - security_info_.connection_status = status; - - security_info_.sct_verify_statuses.push_back(net::ct::SCT_STATUS_OK); - security_info_.sct_verify_statuses.push_back(net::ct::SCT_STATUS_OK); - - SetDefaultUIExpectations(mock_ui()); - EXPECT_CALL(*mock_ui(), - SetSelectedTab(WebsiteSettingsUI::TAB_ID_PERMISSIONS)); - - EXPECT_EQ(WebsiteSettings::SITE_CONNECTION_STATUS_ENCRYPTED, - website_settings()->site_connection_status()); - EXPECT_EQ(WebsiteSettings::SITE_IDENTITY_STATUS_EV_CERT, - website_settings()->site_identity_status()); - EXPECT_EQ(IDR_PAGEINFO_GOOD, WebsiteSettingsUI::GetIdentityIconID( - website_settings()->site_identity_status())); -} - -// A mix of unknown and invalid SCTs. -TEST_F(WebsiteSettingsTest, UnknownAndInvalidSCTs) { - security_info_.security_level = SecurityStateModel::SECURE; - security_info_.scheme_is_cryptographic = true; - security_info_.certificate = cert(); - security_info_.cert_status = 0; - security_info_.security_bits = 81; // No error if > 80. - int status = 0; - status = SetSSLVersion(status, net::SSL_CONNECTION_VERSION_TLS1); - status = SetSSLCipherSuite(status, CR_TLS_RSA_WITH_AES_256_CBC_SHA256); - security_info_.connection_status = status; - - security_info_.sct_verify_statuses.push_back(net::ct::SCT_STATUS_LOG_UNKNOWN); - security_info_.sct_verify_statuses.push_back( - net::ct::SCT_STATUS_INVALID_SIGNATURE); - - SetDefaultUIExpectations(mock_ui()); - EXPECT_CALL(*mock_ui(), SetSelectedTab(WebsiteSettingsUI::TAB_ID_CONNECTION)); - - EXPECT_EQ(WebsiteSettings::SITE_CONNECTION_STATUS_ENCRYPTED, - website_settings()->site_connection_status()); - EXPECT_EQ(WebsiteSettings::SITE_IDENTITY_STATUS_CT_ERROR, - website_settings()->site_identity_status()); - EXPECT_EQ(IDR_PAGEINFO_BAD, WebsiteSettingsUI::GetIdentityIconID( - website_settings()->site_identity_status())); -} - -// At least one SCT is valid and one is from an unknown log. -TEST_F(WebsiteSettingsTest, ValidAndUnknownSCTs) { - security_info_.security_level = SecurityStateModel::SECURE; - security_info_.scheme_is_cryptographic = true; - security_info_.certificate = cert(); - security_info_.cert_status = 0; - security_info_.security_bits = 81; // No error if > 80. - int status = 0; - status = SetSSLVersion(status, net::SSL_CONNECTION_VERSION_TLS1); - status = SetSSLCipherSuite(status, CR_TLS_RSA_WITH_AES_256_CBC_SHA256); - security_info_.connection_status = status; - - security_info_.sct_verify_statuses.push_back(net::ct::SCT_STATUS_OK); - security_info_.sct_verify_statuses.push_back(net::ct::SCT_STATUS_LOG_UNKNOWN); - - SetDefaultUIExpectations(mock_ui()); - EXPECT_CALL(*mock_ui(), - SetSelectedTab(WebsiteSettingsUI::TAB_ID_PERMISSIONS)); - - EXPECT_EQ(WebsiteSettings::SITE_CONNECTION_STATUS_ENCRYPTED, - website_settings()->site_connection_status()); - EXPECT_EQ(WebsiteSettings::SITE_IDENTITY_STATUS_CERT, - website_settings()->site_identity_status()); - EXPECT_EQ(IDR_PAGEINFO_GOOD, WebsiteSettingsUI::GetIdentityIconID( - website_settings()->site_identity_status())); -} - #if !defined(OS_ANDROID) TEST_F(WebsiteSettingsTest, NoInfoBar) { SetDefaultUIExpectations(mock_ui());
diff --git a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc index 4d43555..7f3886a 100644 --- a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc +++ b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc
@@ -279,21 +279,21 @@ #endif // defined(OS_WIN) bool IsAboutUI(const GURL& url) { - return (url.host() == chrome::kChromeUIChromeURLsHost || - url.host() == chrome::kChromeUICreditsHost || - url.host() == chrome::kChromeUIDNSHost + return (url.host_piece() == chrome::kChromeUIChromeURLsHost || + url.host_piece() == chrome::kChromeUICreditsHost || + url.host_piece() == chrome::kChromeUIDNSHost #if !defined(OS_ANDROID) - || url.host() == chrome::kChromeUITermsHost + || url.host_piece() == chrome::kChromeUITermsHost #endif #if defined(OS_LINUX) || defined(OS_OPENBSD) - || url.host() == chrome::kChromeUILinuxProxyConfigHost || - url.host() == chrome::kChromeUISandboxHost + || url.host_piece() == chrome::kChromeUILinuxProxyConfigHost || + url.host_piece() == chrome::kChromeUISandboxHost #endif #if defined(OS_CHROMEOS) - || url.host() == chrome::kChromeUIOSCreditsHost + || url.host_piece() == chrome::kChromeUIOSCreditsHost #endif #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) - || url.host() == chrome::kChromeUIDiscardsHost + || url.host_piece() == chrome::kChromeUIDiscardsHost #endif ); // NOLINT } @@ -320,65 +320,65 @@ // All platform builds of Chrome will need to have a cloud printing // dialog as backup. It's just that on Chrome OS, it's the only // print dialog. - if (url.host() == chrome::kChromeUIBluetoothInternalsHost) + if (url.host_piece() == chrome::kChromeUIBluetoothInternalsHost) return &NewWebUI<BluetoothInternalsUI>; - if (url.host() == chrome::kChromeUIComponentsHost) + if (url.host_piece() == chrome::kChromeUIComponentsHost) return &NewWebUI<ComponentsUI>; if (url.spec() == chrome::kChromeUIConstrainedHTMLTestURL) return &NewWebUI<ConstrainedWebDialogUI>; - if (url.host() == chrome::kChromeUICrashesHost) + if (url.host_piece() == chrome::kChromeUICrashesHost) return &NewWebUI<CrashesUI>; - if (url.host() == chrome::kChromeUIDeviceLogHost) + if (url.host_piece() == chrome::kChromeUIDeviceLogHost) return &NewWebUI<chromeos::DeviceLogUI>; - if (url.host() == chrome::kChromeUIDomainReliabilityInternalsHost) + if (url.host_piece() == chrome::kChromeUIDomainReliabilityInternalsHost) return &NewWebUI<DomainReliabilityInternalsUI>; - if (url.host() == chrome::kChromeUIFlagsHost) + if (url.host_piece() == chrome::kChromeUIFlagsHost) return &NewWebUI<FlagsUI>; - if (url.host() == chrome::kChromeUIGCMInternalsHost) + if (url.host_piece() == chrome::kChromeUIGCMInternalsHost) return &NewWebUI<GCMInternalsUI>; - if (url.host() == chrome::kChromeUIHistoryFrameHost) + if (url.host_piece() == chrome::kChromeUIHistoryFrameHost) return &NewWebUI<HistoryUI>; - if (url.host() == chrome::kChromeUIInstantHost) + if (url.host_piece() == chrome::kChromeUIInstantHost) return &NewWebUI<InstantUI>; - if (url.host() == chrome::kChromeUIInterstitialHost) + if (url.host_piece() == chrome::kChromeUIInterstitialHost) return &NewWebUI<InterstitialUI>; - if (url.host() == chrome::kChromeUIInvalidationsHost) + if (url.host_piece() == chrome::kChromeUIInvalidationsHost) return &NewWebUI<InvalidationsUI>; - if (url.host() == chrome::kChromeUILocalStateHost) + if (url.host_piece() == chrome::kChromeUILocalStateHost) return &NewWebUI<LocalStateUI>; - if (url.host() == chrome::kChromeUINetExportHost) + if (url.host_piece() == chrome::kChromeUINetExportHost) return &NewWebUI<NetExportUI>; - if (url.host() == chrome::kChromeUINetInternalsHost) + if (url.host_piece() == chrome::kChromeUINetInternalsHost) return &NewWebUI<NetInternalsUI>; - if (url.host() == chrome::kChromeUIOmniboxHost) + if (url.host_piece() == chrome::kChromeUIOmniboxHost) return &NewWebUI<OmniboxUI>; - if (url.host() == chrome::kChromeUIPasswordManagerInternalsHost) + if (url.host_piece() == chrome::kChromeUIPasswordManagerInternalsHost) return &NewWebUI<PasswordManagerInternalsUI>; - if (url.host() == chrome::kChromeUIPredictorsHost) + if (url.host_piece() == chrome::kChromeUIPredictorsHost) return &NewWebUI<PredictorsUI>; - if (url.host() == chrome::kChromeUIProfilerHost) + if (url.host_piece() == chrome::kChromeUIProfilerHost) return &NewWebUI<ProfilerUI>; - if (url.host() == chrome::kChromeUISignInInternalsHost) + if (url.host_piece() == chrome::kChromeUISignInInternalsHost) return &NewWebUI<SignInInternalsUI>; - if (url.host() == chrome::kChromeUISuggestionsHost) + if (url.host_piece() == chrome::kChromeUISuggestionsHost) return &NewWebUI<suggestions::SuggestionsUI>; - if (url.host() == chrome::kChromeUISupervisedUserInternalsHost) + if (url.host_piece() == chrome::kChromeUISupervisedUserInternalsHost) return &NewWebUI<SupervisedUserInternalsUI>; - if (url.host() == chrome::kChromeUISupervisedUserPassphrasePageHost) + if (url.host_piece() == chrome::kChromeUISupervisedUserPassphrasePageHost) return &NewWebUI<ConstrainedWebDialogUI>; - if (url.host() == chrome::kChromeUISyncInternalsHost) + if (url.host_piece() == chrome::kChromeUISyncInternalsHost) return &NewWebUI<SyncInternalsUI>; - if (url.host() == chrome::kChromeUISyncResourcesHost) + if (url.host_piece() == chrome::kChromeUISyncResourcesHost) return &NewWebUI<WebDialogUI>; - if (url.host() == chrome::kChromeUITaskSchedulerInternalsHost) + if (url.host_piece() == chrome::kChromeUITaskSchedulerInternalsHost) return &NewWebUI<TaskSchedulerInternalsUI>; - if (url.host() == chrome::kChromeUITranslateInternalsHost) + if (url.host_piece() == chrome::kChromeUITranslateInternalsHost) return &NewWebUI<TranslateInternalsUI>; - if (url.host() == chrome::kChromeUIUsbInternalsHost) + if (url.host_piece() == chrome::kChromeUIUsbInternalsHost) return &NewWebUI<UsbInternalsUI>; - if (url.host() == chrome::kChromeUIUserActionsHost) + if (url.host_piece() == chrome::kChromeUIUserActionsHost) return &NewWebUI<UserActionsUI>; - if (url.host() == chrome::kChromeUIVersionHost) + if (url.host_piece() == chrome::kChromeUIVersionHost) return &NewWebUI<VersionUI>; /**************************************************************************** @@ -387,134 +387,133 @@ #if !defined(OS_ANDROID) #if !defined(OS_CHROMEOS) // AppLauncherPage is not needed on Android or ChromeOS. - if (url.host() == chrome::kChromeUIAppLauncherPageHost && - profile && extensions::ExtensionSystem::Get(profile)-> - extension_service()) { + if (url.host_piece() == chrome::kChromeUIAppLauncherPageHost && profile && + extensions::ExtensionSystem::Get(profile)->extension_service()) { return &NewWebUI<AppLauncherPageUI>; } #endif // !defined(OS_CHROMEOS) // Bookmarks are part of NTP on Android. - if (url.host() == chrome::kChromeUIBookmarksHost) { + if (url.host_piece() == chrome::kChromeUIBookmarksHost) { return MdBookmarksUI::IsEnabled() ? &NewWebUI<MdBookmarksUI> : &NewWebUI<BookmarksUI>; } // Downloads list on Android uses the built-in download manager. - if (url.host() == chrome::kChromeUIDownloadsHost) + if (url.host_piece() == chrome::kChromeUIDownloadsHost) return &NewWebUI<MdDownloadsUI>; // Material Design feedback. Feedback is implemented separately in // Android. - if (url.host() == chrome::kChromeUIFeedbackHost && + if (url.host_piece() == chrome::kChromeUIFeedbackHost && ::switches::MdFeedbackEnabled()) { return &NewWebUI<MdFeedbackUI>; } // Help is implemented with native UI elements on Android. - if (url.host() == chrome::kChromeUIHelpFrameHost) + if (url.host_piece() == chrome::kChromeUIHelpFrameHost) return &NewWebUI<HelpUI>; // Identity API is not available on Android. - if (url.host() == chrome::kChromeUIIdentityInternalsHost) + if (url.host_piece() == chrome::kChromeUIIdentityInternalsHost) return &NewWebUI<IdentityInternalsUI>; - if (url.host() == chrome::kChromeUINewTabHost) + if (url.host_piece() == chrome::kChromeUINewTabHost) return &NewWebUI<NewTabUI>; - if (url.host() == chrome::kChromeUIMdSettingsHost) + if (url.host_piece() == chrome::kChromeUIMdSettingsHost) return &NewWebUI<settings::MdSettingsUI>; // If the material design extensions page is enabled, it gets its own host. // Otherwise, it's handled by the uber settings page. - if (url.host() == chrome::kChromeUIExtensionsHost && + if (url.host_piece() == chrome::kChromeUIExtensionsHost && base::FeatureList::IsEnabled(features::kMaterialDesignExtensions)) { return &NewWebUI<extensions::ExtensionsUI>; } // Material Design history is on its own host, rather than on an Uber page. if (MdHistoryUI::IsEnabled(profile) && - url.host() == chrome::kChromeUIHistoryHost) { + url.host_piece() == chrome::kChromeUIHistoryHost) { return &NewWebUI<MdHistoryUI>; } // Material Design Settings gets its own host, if enabled. if (base::FeatureList::IsEnabled(features::kMaterialDesignSettings) && - url.host() == chrome::kChromeUISettingsHost) { + url.host_piece() == chrome::kChromeUISettingsHost) { return &NewWebUI<settings::MdSettingsUI>; } - if (url.host() == chrome::kChromeUIQuotaInternalsHost) + if (url.host_piece() == chrome::kChromeUIQuotaInternalsHost) return &NewWebUI<QuotaInternalsUI>; // Settings are implemented with native UI elements on Android. // Handle chrome://settings if settings in a window and about in settings // are enabled. - if (url.host() == chrome::kChromeUISettingsFrameHost || - (url.host() == chrome::kChromeUISettingsHost && + if (url.host_piece() == chrome::kChromeUISettingsFrameHost || + (url.host_piece() == chrome::kChromeUISettingsHost && ::switches::AboutInSettingsEnabled())) { return &NewWebUI<options::OptionsUI>; } - if (url.host() == chrome::kChromeUISyncFileSystemInternalsHost) + if (url.host_piece() == chrome::kChromeUISyncFileSystemInternalsHost) return &NewWebUI<SyncFileSystemInternalsUI>; - if (url.host() == chrome::kChromeUISystemInfoHost) + if (url.host_piece() == chrome::kChromeUISystemInfoHost) return &NewWebUI<SystemInfoUI>; // Uber frame is not used on Android. - if (url.host() == chrome::kChromeUIUberFrameHost) + if (url.host_piece() == chrome::kChromeUIUberFrameHost) return &NewWebUI<UberFrameUI>; // Uber page is not used on Android. - if (url.host() == chrome::kChromeUIUberHost) + if (url.host_piece() == chrome::kChromeUIUberHost) return &NewWebUI<UberUI>; #endif // !defined(OS_ANDROID) #if defined(OS_WIN) - if (url.host() == chrome::kChromeUIConflictsHost) + if (url.host_piece() == chrome::kChromeUIConflictsHost) return &NewWebUI<ConflictsUI>; - if (url.host() == chrome::kChromeUIMetroFlowHost) + if (url.host_piece() == chrome::kChromeUIMetroFlowHost) return &NewWebUI<SetAsDefaultBrowserUI>; #endif #if defined(OS_CHROMEOS) - if (url.host() == chrome::kChromeUIBluetoothPairingHost) + if (url.host_piece() == chrome::kChromeUIBluetoothPairingHost) return &NewWebUI<chromeos::BluetoothPairingUI>; - if (url.host() == chrome::kChromeUICertificateManagerHost) + if (url.host_piece() == chrome::kChromeUICertificateManagerHost) return &NewWebUI<chromeos::CertificateManagerDialogUI>; - if (url.host() == chrome::kChromeUIChooseMobileNetworkHost) + if (url.host_piece() == chrome::kChromeUIChooseMobileNetworkHost) return &NewWebUI<chromeos::ChooseMobileNetworkUI>; - if (url.host() == chrome::kChromeUICryptohomeHost) + if (url.host_piece() == chrome::kChromeUICryptohomeHost) return &NewWebUI<chromeos::CryptohomeUI>; - if (url.host() == chrome::kChromeUIDriveInternalsHost) + if (url.host_piece() == chrome::kChromeUIDriveInternalsHost) return &NewWebUI<chromeos::DriveInternalsUI>; - if (url.host() == chrome::kChromeUIFirstRunHost) + if (url.host_piece() == chrome::kChromeUIFirstRunHost) return &NewWebUI<chromeos::FirstRunUI>; - if (url.host() == chrome::kChromeUIKeyboardOverlayHost) + if (url.host_piece() == chrome::kChromeUIKeyboardOverlayHost) return &NewWebUI<KeyboardOverlayUI>; - if (url.host() == chrome::kChromeUIMobileSetupHost) + if (url.host_piece() == chrome::kChromeUIMobileSetupHost) return &NewWebUI<MobileSetupUI>; - if (url.host() == chrome::kChromeUINetworkHost) + if (url.host_piece() == chrome::kChromeUINetworkHost) return &NewWebUI<chromeos::NetworkUI>; - if (url.host() == chrome::kChromeUIOobeHost) + if (url.host_piece() == chrome::kChromeUIOobeHost) return &NewWebUI<chromeos::OobeUI>; - if (url.host() == chrome::kChromeUIPowerHost) + if (url.host_piece() == chrome::kChromeUIPowerHost) return &NewWebUI<chromeos::PowerUI>; - if (url.host() == proximity_auth::kChromeUIProximityAuthHost) + if (url.host_piece() == proximity_auth::kChromeUIProximityAuthHost) return &NewWebUI<proximity_auth::ProximityAuthUI>; - if (url.host() == chrome::kChromeUIProxySettingsHost) + if (url.host_piece() == chrome::kChromeUIProxySettingsHost) return &NewWebUI<chromeos::ProxySettingsUI>; - if (url.host() == chrome::kChromeUISetTimeHost) + if (url.host_piece() == chrome::kChromeUISetTimeHost) return &NewWebUI<chromeos::SetTimeUI>; - if (url.host() == chrome::kChromeUISimUnlockHost) + if (url.host_piece() == chrome::kChromeUISimUnlockHost) return &NewWebUI<chromeos::SimUnlockUI>; - if (url.host() == chrome::kChromeUISlowHost) + if (url.host_piece() == chrome::kChromeUISlowHost) return &NewWebUI<chromeos::SlowUI>; - if (url.host() == chrome::kChromeUISlowTraceHost) + if (url.host_piece() == chrome::kChromeUISlowTraceHost) return &NewWebUI<chromeos::SlowTraceController>; - if (url.host() == chrome::kChromeUIVoiceSearchHost) + if (url.host_piece() == chrome::kChromeUIVoiceSearchHost) return &NewWebUI<VoiceSearchUI>; #if !defined(OFFICIAL_BUILD) if (!base::SysInfo::IsRunningOnChromeOS()) { - if (url.host() == chrome::kChromeUIDeviceEmulatorHost) + if (url.host_piece() == chrome::kChromeUIDeviceEmulatorHost) return &NewWebUI<DeviceEmulatorUI>; } #endif // !defined(OFFICIAL_BUILD) #endif // defined(OS_CHROMEOS) #if defined(OS_ANDROID) - if (url.host() == chrome::kChromeUIOfflineInternalsHost) + if (url.host_piece() == chrome::kChromeUIOfflineInternalsHost) return &NewWebUI<OfflineInternalsUI>; - if (url.host() == chrome::kChromeUIPopularSitesInternalsHost) + if (url.host_piece() == chrome::kChromeUIPopularSitesInternalsHost) return &NewWebUI<PopularSitesInternalsUI>; - if (url.host() == chrome::kChromeUISnippetsInternalsHost && + if (url.host_piece() == chrome::kChromeUISnippetsInternalsHost && !profile->IsOffTheRecord()) return &NewWebUI<SnippetsInternalsUI>; #if defined(ENABLE_VR_SHELL) || defined(ENABLE_WEBVR) - if (url.host() == chrome::kChromeUIVrShellUIHost) + if (url.host_piece() == chrome::kChromeUIVrShellUIHost) return &NewWebUI<VrShellUIUI>; #endif #else @@ -524,25 +523,25 @@ // chrome://inspect isn't supported on Android nor iOS. Page debugging is // handled by a remote devtools on the host machine, and other elements, i.e. // extensions aren't supported. - if (url.host() == chrome::kChromeUIInspectHost) + if (url.host_piece() == chrome::kChromeUIInspectHost) return &NewWebUI<InspectUI>; #endif #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) - if (url.host() == chrome::kChromeUIChromeSigninHost) + if (url.host_piece() == chrome::kChromeUIChromeSigninHost) return &NewWebUI<InlineLoginUI>; - if (url.host() == chrome::kChromeUIMdUserManagerHost) + if (url.host_piece() == chrome::kChromeUIMdUserManagerHost) return &NewWebUI<MDUserManagerUI>; - if (url.host() == chrome::kChromeUISigninErrorHost) + if (url.host_piece() == chrome::kChromeUISigninErrorHost) return &NewWebUI<SigninErrorUI>; - if (url.host() == chrome::kChromeUISyncConfirmationHost) + if (url.host_piece() == chrome::kChromeUISyncConfirmationHost) return &NewWebUI<SyncConfirmationUI>; - if (url.host() == chrome::kChromeUIProfileSigninConfirmationHost) + if (url.host_piece() == chrome::kChromeUIProfileSigninConfirmationHost) return &NewWebUI<ProfileSigninConfirmationUI>; - if (url.host() == chrome::kChromeUIWelcomeHost) + if (url.host_piece() == chrome::kChromeUIWelcomeHost) return &NewWebUI<WelcomeUI>; #endif #if defined(OS_WIN) - if (url.host() == chrome::kChromeUIWelcomeWin10Host) + if (url.host_piece() == chrome::kChromeUIWelcomeWin10Host) return &NewWebUI<WelcomeWin10UI>; #endif // defined(OS_WIN) @@ -550,68 +549,68 @@ * Other #defines and special logics. ***************************************************************************/ #if !defined(DISABLE_NACL) - if (url.host() == chrome::kChromeUINaClHost) + if (url.host_piece() == chrome::kChromeUINaClHost) return &NewWebUI<NaClUI>; #endif #if (defined(OS_LINUX) && defined(TOOLKIT_VIEWS)) || defined(USE_AURA) - if (url.host() == chrome::kChromeUITabModalConfirmDialogHost) { + if (url.host_piece() == chrome::kChromeUITabModalConfirmDialogHost) { return &NewWebUI<ConstrainedWebDialogUI>; } #endif #if (defined(USE_NSS_CERTS) || defined(USE_OPENSSL_CERTS)) && defined(USE_AURA) - if (url.host() == chrome::kChromeUICertificateViewerHost) + if (url.host_piece() == chrome::kChromeUICertificateViewerHost) return &NewWebUI<CertificateViewerUI>; #if defined(OS_CHROMEOS) - if (url.host() == chrome::kChromeUICertificateViewerDialogHost) + if (url.host_piece() == chrome::kChromeUICertificateViewerDialogHost) return &NewWebUI<CertificateViewerModalDialogUI>; #endif #endif // (USE_NSS_CERTS || USE_OPENSSL_CERTS) && USE_AURA - if (url.host() == chrome::kChromeUIPolicyHost) + if (url.host_piece() == chrome::kChromeUIPolicyHost) return &NewWebUI<PolicyUI>; - if (url.host() == chrome::kChromeUIMdPolicyHost && + if (url.host_piece() == chrome::kChromeUIMdPolicyHost && switches::MdPolicyPageEnabled()) { return &NewWebUI<PolicyMaterialDesignUI>; } #if BUILDFLAG(ENABLE_APP_LIST) - if (url.host() == chrome::kChromeUIAppListStartPageHost) + if (url.host_piece() == chrome::kChromeUIAppListStartPageHost) return &NewWebUI<app_list::StartPageUI>; #endif #if BUILDFLAG(ENABLE_EXTENSIONS) - if (url.host() == chrome::kChromeUIExtensionsFrameHost) + if (url.host_piece() == chrome::kChromeUIExtensionsFrameHost) return &NewWebUI<extensions::ExtensionsUI>; #endif #if defined(ENABLE_PLUGINS) - if (url.host() == chrome::kChromeUIFlashHost) + if (url.host_piece() == chrome::kChromeUIFlashHost) return &NewWebUI<FlashUI>; - if (url.host() == chrome::kChromeUIPluginsHost) + if (url.host_piece() == chrome::kChromeUIPluginsHost) return &NewWebUI<PluginsUI>; #endif #if BUILDFLAG(ENABLE_PRINT_PREVIEW) - if (url.host() == chrome::kChromeUIPrintHost && + if (url.host_piece() == chrome::kChromeUIPrintHost && !profile->GetPrefs()->GetBoolean(prefs::kPrintPreviewDisabled)) { return &NewWebUI<PrintPreviewUI>; } #endif #if BUILDFLAG(ENABLE_SERVICE_DISCOVERY) - if (url.host() == chrome::kChromeUIDevicesHost) { + if (url.host_piece() == chrome::kChromeUIDevicesHost) { return &NewWebUI<LocalDiscoveryUI>; } #endif #if defined(ENABLE_WEBRTC) - if (url.host() == chrome::kChromeUIWebRtcLogsHost) + if (url.host_piece() == chrome::kChromeUIWebRtcLogsHost) return &NewWebUI<WebRtcLogsUI>; #endif #if defined(ENABLE_MEDIA_ROUTER) #if !defined(OS_ANDROID) - if (url.host() == chrome::kChromeUIMediaRouterHost && + if (url.host_piece() == chrome::kChromeUIMediaRouterHost && media_router::MediaRouterEnabled(profile)) { return &NewWebUI<media_router::MediaRouterUI>; } #endif #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_CHROMEOS) - if (url.host() == chrome::kChromeUICastHost && + if (url.host_piece() == chrome::kChromeUICastHost && media_router::MediaRouterEnabled(profile)) { return &NewWebUI<CastUI>; } @@ -621,12 +620,12 @@ return &NewWebUI<AboutUI>; if (dom_distiller::IsEnableDomDistillerSet() && - url.host() == dom_distiller::kChromeUIDomDistillerHost) { + url.host_piece() == dom_distiller::kChromeUIDomDistillerHost) { return &NewWebUI<dom_distiller::DomDistillerUi>; } if (SiteEngagementService::IsEnabled() && - url.host() == chrome::kChromeUISiteEngagementHost) { + url.host_piece() == chrome::kChromeUISiteEngagementHost) { return &NewWebUI<SiteEngagementUI>; } @@ -754,8 +753,8 @@ #if !defined(OS_ANDROID) // Bookmarks are part of NTP on Android. // The bookmark manager is a chrome extension, so we have to check for it // before we check for extension scheme. - if (page_url.host() == extension_misc::kBookmarkManagerId || - page_url.host() == chrome::kChromeUIBookmarksHost) { + if (page_url.host_piece() == extension_misc::kBookmarkManagerId || + page_url.host_piece() == chrome::kChromeUIBookmarksHost) { return BookmarksUI::GetFaviconResourceBytes(scale_factor); } @@ -769,52 +768,52 @@ if (!content::HasWebUIScheme(page_url)) return NULL; - if (page_url.host() == chrome::kChromeUIComponentsHost) + if (page_url.host_piece() == chrome::kChromeUIComponentsHost) return ComponentsUI::GetFaviconResourceBytes(scale_factor); #if defined(OS_WIN) - if (page_url.host() == chrome::kChromeUIConflictsHost) + if (page_url.host_piece() == chrome::kChromeUIConflictsHost) return ConflictsUI::GetFaviconResourceBytes(scale_factor); #endif - if (page_url.host() == chrome::kChromeUICrashesHost) + if (page_url.host_piece() == chrome::kChromeUICrashesHost) return CrashesUI::GetFaviconResourceBytes(scale_factor); - if (page_url.host() == chrome::kChromeUIFlagsHost) + if (page_url.host_piece() == chrome::kChromeUIFlagsHost) return FlagsUI::GetFaviconResourceBytes(scale_factor); - if (page_url.host() == chrome::kChromeUIHistoryHost) + if (page_url.host_piece() == chrome::kChromeUIHistoryHost) return HistoryUI::GetFaviconResourceBytes(scale_factor); #if !defined(OS_ANDROID) #if !defined(OS_CHROMEOS) // The Apps launcher page is not available on android or ChromeOS. - if (page_url.host() == chrome::kChromeUIAppLauncherPageHost) + if (page_url.host_piece() == chrome::kChromeUIAppLauncherPageHost) return AppLauncherPageUI::GetFaviconResourceBytes(scale_factor); #endif // Flash is not available on android. - if (page_url.host() == chrome::kChromeUIFlashHost) + if (page_url.host_piece() == chrome::kChromeUIFlashHost) return FlashUI::GetFaviconResourceBytes(scale_factor); // Android uses the native download manager. - if (page_url.host() == chrome::kChromeUIDownloadsHost) + if (page_url.host_piece() == chrome::kChromeUIDownloadsHost) return MdDownloadsUI::GetFaviconResourceBytes(scale_factor); // Android doesn't use the Options/Settings pages. - if (page_url.host() == chrome::kChromeUISettingsHost || - page_url.host() == chrome::kChromeUISettingsFrameHost || - page_url.host() == chrome::kChromeUIMdSettingsHost) + if (page_url.host_piece() == chrome::kChromeUISettingsHost || + page_url.host_piece() == chrome::kChromeUISettingsFrameHost || + page_url.host_piece() == chrome::kChromeUIMdSettingsHost) return settings_utils::GetFaviconResourceBytes(scale_factor); #if BUILDFLAG(ENABLE_EXTENSIONS) - if (page_url.host() == chrome::kChromeUIExtensionsHost || - page_url.host() == chrome::kChromeUIExtensionsFrameHost) + if (page_url.host_piece() == chrome::kChromeUIExtensionsHost || + page_url.host_piece() == chrome::kChromeUIExtensionsFrameHost) return extensions::ExtensionsUI::GetFaviconResourceBytes(scale_factor); #endif // Android doesn't use the plugins pages. - if (page_url.host() == chrome::kChromeUIPluginsHost) + if (page_url.host_piece() == chrome::kChromeUIPluginsHost) return PluginsUI::GetFaviconResourceBytes(scale_factor); #endif
diff --git a/chrome/browser/ui/webui/chromeos/login/oobe_ui.cc b/chrome/browser/ui/webui/chromeos/login/oobe_ui.cc index 96beb8b..58120102 100644 --- a/chrome/browser/ui/webui/chromeos/login/oobe_ui.cc +++ b/chrome/browser/ui/webui/chromeos/login/oobe_ui.cc
@@ -539,8 +539,7 @@ new ShutdownPolicyHandler(CrosSettings::Get(), this)); // Trigger an initial update. - shutdown_policy_handler_->CheckIfRebootOnShutdown( - base::Bind(&OobeUI::OnShutdownPolicyChanged, base::Unretained(this))); + shutdown_policy_handler_->NotifyDelegateWithShutdownPolicy(); } void OobeUI::OnScreenAssetsLoaded(const std::string& async_assets_load_id) {
diff --git a/chrome/browser/ui/webui/chromeos/login/oobe_ui.h b/chrome/browser/ui/webui/chromeos/login/oobe_ui.h index 853fce7..9d6ce003 100644 --- a/chrome/browser/ui/webui/chromeos/login/oobe_ui.h +++ b/chrome/browser/ui/webui/chromeos/login/oobe_ui.h
@@ -118,7 +118,7 @@ GaiaScreenHandler* GetGaiaScreenActor(); UserBoardView* GetUserBoardScreenActor(); - // ShutdownPolicyObserver::Delegate + // ShutdownPolicyHandler::Delegate void OnShutdownPolicyChanged(bool reboot_on_shutdown) override; // Collects localized strings from the owned handlers.
diff --git a/chrome/browser/ui/webui/interstitials/interstitial_ui_browsertest.cc b/chrome/browser/ui/webui/interstitials/interstitial_ui_browsertest.cc index 806313378..eba2e01 100644 --- a/chrome/browser/ui/webui/interstitials/interstitial_ui_browsertest.cc +++ b/chrome/browser/ui/webui/interstitials/interstitial_ui_browsertest.cc
@@ -32,34 +32,55 @@ } }; -// The following test is disabled due to flakiness: -// https://crbug.com/405869, -// https://crbug.com/400503. -IN_PROC_BROWSER_TEST_F(InterstitialUITest, DISABLED_OpenInterstitial) { +IN_PROC_BROWSER_TEST_F(InterstitialUITest, HomePage) { TestInterstitial( GURL("chrome://interstitials"), "Interstitials"); +} + +IN_PROC_BROWSER_TEST_F(InterstitialUITest, InvalidURLShouldOpenHomePage) { // Invalid path should open the main page: TestInterstitial( GURL("chrome://interstitials/--invalid--"), "Interstitials"); +} + +IN_PROC_BROWSER_TEST_F(InterstitialUITest, SSLInterstitial) { TestInterstitial( GURL("chrome://interstitials/ssl"), "Privacy error"); +} + +IN_PROC_BROWSER_TEST_F(InterstitialUITest, MalwareInterstitial) { TestInterstitial( GURL("chrome://interstitials/safebrowsing?type=malware"), "Security error"); +} + +IN_PROC_BROWSER_TEST_F(InterstitialUITest, PhishingInterstitial) { TestInterstitial( GURL("chrome://interstitials/safebrowsing?type=phishing"), "Security error"); +} + +IN_PROC_BROWSER_TEST_F(InterstitialUITest, ClientsideMalwareInterstitial) { TestInterstitial( GURL("chrome://interstitials/safebrowsing?type=clientside_malware"), "Security error"); +} + +IN_PROC_BROWSER_TEST_F(InterstitialUITest, ClientsidePhishingInterstitial) { TestInterstitial( GURL("chrome://interstitials/safebrowsing?type=clientside_phishing"), "Security error"); +} + +IN_PROC_BROWSER_TEST_F(InterstitialUITest, CaptivePortalInterstitial) { TestInterstitial(GURL("chrome://interstitials/captiveportal"), "Connect to network"); +} + +IN_PROC_BROWSER_TEST_F(InterstitialUITest, CaptivePortalInterstitialWifi) { TestInterstitial(GURL("chrome://interstitials/captiveportal?is_wifi=1"), "Connect to Wi-Fi"); }
diff --git a/chrome/browser/ui/webui/options/browser_options_handler.cc b/chrome/browser/ui/webui/options/browser_options_handler.cc index e88c707..b8efb488 100644 --- a/chrome/browser/ui/webui/options/browser_options_handler.cc +++ b/chrome/browser/ui/webui/options/browser_options_handler.cc
@@ -83,6 +83,7 @@ #include "components/prefs/scoped_user_pref_update.h" #include "components/proximity_auth/switches.h" #include "components/proxy_config/proxy_config_pref_names.h" +#include "components/safe_browsing_db/safe_browsing_prefs.h" #include "components/search_engines/template_url.h" #include "components/search_engines/template_url_service.h" #include "components/signin/core/browser/signin_manager.h" @@ -362,8 +363,6 @@ IDS_RESET_PROFILE_SETTINGS_DESCRIPTION }, { "resetProfileSettingsSectionTitle", IDS_RESET_PROFILE_SETTINGS_SECTION_TITLE }, - { "safeBrowsingEnableExtendedReporting", - IDS_OPTIONS_SAFEBROWSING_ENABLE_EXTENDED_REPORTING }, { "safeBrowsingEnableProtection", IDS_OPTIONS_SAFEBROWSING_ENABLEPROTECTION }, { "sectionTitleAppearance", IDS_APPEARANCE_GROUP_NAME }, @@ -582,6 +581,13 @@ RegisterCloudPrintValues(values); #endif + Profile* profile = Profile::FromWebUI(web_ui()); + values->SetString( + "safeBrowsingEnableExtendedReporting", + l10n_util::GetStringUTF16(safe_browsing::ChooseOptInTextResource( + *profile->GetPrefs(), + IDS_OPTIONS_SAFEBROWSING_ENABLE_EXTENDED_REPORTING, + IDS_OPTIONS_SAFEBROWSING_ENABLE_SCOUT_REPORTING))); values->SetString("syncLearnMoreURL", chrome::kSyncLearnMoreURL); base::string16 omnibox_url = base::ASCIIToUTF16(chrome::kOmniboxLearnMoreURL); values->SetString( @@ -600,7 +606,6 @@ supervised_user_dashboard)); #if defined(OS_CHROMEOS) - Profile* profile = Profile::FromWebUI(web_ui()); std::string username = profile->GetProfileUserName(); if (username.empty()) { const user_manager::User* user =
diff --git a/chrome/browser/ui/webui/options/options_ui.cc b/chrome/browser/ui/webui/options/options_ui.cc index 0797fe6..8a7a21c 100644 --- a/chrome/browser/ui/webui/options/options_ui.cc +++ b/chrome/browser/ui/webui/options/options_ui.cc
@@ -511,7 +511,7 @@ load_start_time_ = base::Time::Now(); if (render_frame_host->GetRenderViewHost() == web_ui()->GetWebContents()->GetRenderViewHost() && - validated_url.host() == chrome::kChromeUISettingsFrameHost) { + validated_url.host_piece() == chrome::kChromeUISettingsFrameHost) { for (size_t i = 0; i < handlers_.size(); ++i) handlers_[i]->PageLoadStarted(); }
diff --git a/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.cc b/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.cc index 4eb854f..7fa0ec8 100644 --- a/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.cc +++ b/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.cc
@@ -11,6 +11,7 @@ #include "base/memory/ptr_util.h" #include "base/path_service.h" #include "base/strings/string_util.h" +#include "base/threading/sequenced_task_runner_handle.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/printing/printer_pref_manager_factory.h" @@ -83,6 +84,8 @@ base::PathService::Get(chrome::DIR_CHROMEOS_PPD_CACHE, &ppd_cache_path)); ppd_provider_ = chromeos::printing::PpdProvider::Create( google_apis::GetAPIKey(), g_browser_process->system_request_context(), + content::BrowserThread::GetTaskRunnerForThread( + content::BrowserThread::FILE), chromeos::printing::PpdCache::Create(ppd_cache_path)); } @@ -268,9 +271,20 @@ CHECK_EQ(2U, args->GetSize()); CHECK(args->GetString(0, &js_callback)); CHECK(args->GetString(1, &manufacturer)); - ppd_provider_->QueryAvailable( - base::Bind(&CupsPrintersHandler::QueryAvailableModelsDone, - weak_factory_.GetWeakPtr(), js_callback, manufacturer)); + // Special case the "asked with no manufacturer case" since the UI sometimes + // triggers this and it should yield a trivial (empty) result + if (manufacturer.empty()) { + base::SequencedTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::Bind(&CupsPrintersHandler::QueryAvailableModelsDone, + weak_factory_.GetWeakPtr(), js_callback, manufacturer, + chromeos::printing::PpdProvider::SUCCESS, + chromeos::printing::PpdProvider::AvailablePrintersMap())); + } else { + ppd_provider_->QueryAvailable( + base::Bind(&CupsPrintersHandler::QueryAvailableModelsDone, + weak_factory_.GetWeakPtr(), js_callback, manufacturer)); + } } void CupsPrintersHandler::HandleSelectPPDFile(const base::ListValue* args) {
diff --git a/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc b/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc index 13bcfe07..dceffa0 100644 --- a/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc +++ b/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc
@@ -26,6 +26,7 @@ #include "components/autofill/core/common/autofill_constants.h" #include "components/google/core/browser/google_util.h" #include "components/password_manager/core/browser/password_manager_constants.h" +#include "components/safe_browsing_db/safe_browsing_prefs.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/web_ui_data_source.h" #include "ui/base/l10n/l10n_util.h" @@ -67,7 +68,9 @@ void AddCommonStrings(content::WebUIDataSource* html_source, Profile* profile) { LocalizedString localized_strings[] = { {"add", IDS_ADD}, + {"back", IDS_ACCNAME_BACK}, {"cancel", IDS_CANCEL}, + {"close", IDS_CLOSE}, {"confirm", IDS_CONFIRM}, {"disable", IDS_DISABLE}, {"learnMore", IDS_LEARN_MORE}, @@ -1261,7 +1264,8 @@ #endif } -void AddPrivacyStrings(content::WebUIDataSource* html_source) { +void AddPrivacyStrings(content::WebUIDataSource* html_source, + Profile* profile) { LocalizedString localized_strings[] = { {"privacyPageTitle", IDS_SETTINGS_PRIVACY}, {"linkDoctorPref", IDS_SETTINGS_LINKDOCTOR_PREF}, @@ -1270,8 +1274,6 @@ IDS_SETTINGS_NETWORK_PREDICTION_ENABLED_DESCRIPTION}, {"safeBrowsingEnableProtection", IDS_SETTINGS_SAFEBROWSING_ENABLEPROTECTION}, - {"safeBrowsingEnableExtendedReporting", - IDS_SETTINGS_SAFEBROWSING_ENABLE_EXTENDED_REPORTING}, {"spellingPref", IDS_SETTINGS_SPELLING_PREF}, {"spellingDescription", IDS_SETTINGS_SPELLING_DESCRIPTION}, #if defined(OS_CHROMEOS) @@ -1296,6 +1298,12 @@ AddLocalizedStringsBulk(html_source, localized_strings, arraysize(localized_strings)); + html_source->AddLocalizedString( + "safeBrowsingEnableExtendedReporting", + safe_browsing::ChooseOptInTextResource( + *profile->GetPrefs(), + IDS_SETTINGS_SAFEBROWSING_ENABLE_EXTENDED_REPORTING, + IDS_SETTINGS_SAFEBROWSING_ENABLE_SCOUT_REPORTING)); html_source->AddString("improveBrowsingExperience", l10n_util::GetStringFUTF16( IDS_SETTINGS_IMPROVE_BROWSING_EXPERIENCE, @@ -1756,7 +1764,7 @@ AddPasswordsAndFormsStrings(html_source); AddPeopleStrings(html_source); AddPrintingStrings(html_source); - AddPrivacyStrings(html_source); + AddPrivacyStrings(html_source, profile); AddResetStrings(html_source); AddSearchEnginesStrings(html_source); AddSearchInSettingsStrings(html_source);
diff --git a/chrome/browser/usb/web_usb_detector.cc b/chrome/browser/usb/web_usb_detector.cc index 07c3a3b1..8bf90dd 100644 --- a/chrome/browser/usb/web_usb_detector.cc +++ b/chrome/browser/usb/web_usb_detector.cc
@@ -67,7 +67,7 @@ Browser* GetBrowser() { chrome::ScopedTabbedBrowserDisplayer browser_displayer( - ProfileManager::GetActiveUserProfile()); + ProfileManager::GetLastUsedProfileAllowedByPolicy()); DCHECK(browser_displayer.browser()); return browser_displayer.browser(); }
diff --git a/chrome/common/chrome_paths.cc b/chrome/common/chrome_paths.cc index dcb04ae..fbb022e 100644 --- a/chrome/common/chrome_paths.cc +++ b/chrome/common/chrome_paths.cc
@@ -433,7 +433,8 @@ case chrome::DIR_CHROMEOS_PPD_CACHE: if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; - cur = cur.Append(FILE_PATH_LITERAL("ppd_cache")); + cur = cur.Append(FILE_PATH_LITERAL("PpdCache")); + create_dir = true; break; #endif #if BUILDFLAG(ENABLE_SUPERVISED_USERS)
diff --git a/chrome/common/chrome_switches.cc b/chrome/common/chrome_switches.cc index 7336c23..d7f9792 100644 --- a/chrome/common/chrome_switches.cc +++ b/chrome/common/chrome_switches.cc
@@ -1183,7 +1183,7 @@ #if defined(OS_WIN) // Disables using GDI to print text as simply text. Fallback to printing text -// as paths. +// as paths. Overrides --enable-gdi-text-printing. const char kDisableGDITextPrinting[] = "disable-gdi-text-printing"; // Disables per monitor DPI for supported Windows versions. @@ -1193,6 +1193,9 @@ // Fallback to XPS. By default connector uses CDD. const char kEnableCloudPrintXps[] = "enable-cloud-print-xps"; +// Enables using GDI to print text as simply text. +const char kEnableGDITextPrinting[] = "enable-gdi-text-printing"; + // Enables per monitor DPI for supported Windows versions. const char kEnablePerMonitorDpi[] = "enable-per-monitor-dpi"; @@ -1307,6 +1310,15 @@ } #endif +#if defined(OS_WIN) +bool GDITextPrintingEnabled() { + const auto& command_line = *base::CommandLine::ForCurrentProcess(); + if (command_line.HasSwitch(kDisableGDITextPrinting)) + return false; + return command_line.HasSwitch(kEnableGDITextPrinting); +} +#endif + // ----------------------------------------------------------------------------- // DO NOT ADD YOUR VERY NICE FLAGS TO THE BOTTOM OF THIS FILE. //
diff --git a/chrome/common/chrome_switches.h b/chrome/common/chrome_switches.h index 850dacc9..0387b38 100644 --- a/chrome/common/chrome_switches.h +++ b/chrome/common/chrome_switches.h
@@ -357,6 +357,7 @@ extern const char kDisableGDITextPrinting[]; extern const char kDisablePerMonitorDpi[]; extern const char kEnableCloudPrintXps[]; +extern const char kEnableGDITextPrinting[]; extern const char kEnablePerMonitorDpi[]; extern const char kEnableProfileShortcutManager[]; extern const char kHideIcons[]; @@ -394,13 +395,16 @@ bool ExtensionsDisabled(const base::CommandLine& command_line); bool MdFeedbackEnabled(); bool MdPolicyPageEnabled(); -bool PdfMaterialUIEnabled(); bool SettingsWindowEnabled(); #if defined(OS_CHROMEOS) bool PowerOverlayEnabled(); #endif +#if defined(OS_WIN) +bool GDITextPrintingEnabled(); +#endif + // DON'T ADD RANDOM STUFF HERE. Put it in the main section above in // alphabetical order, or in one of the ifdefs (also in order in each section).
diff --git a/chrome/common/search/search_urls.cc b/chrome/common/search/search_urls.cc index 03694ab..eb32d38 100644 --- a/chrome/common/search/search_urls.cc +++ b/chrome/common/search/search_urls.cc
@@ -11,16 +11,17 @@ namespace { bool MatchesOrigin(const GURL& my_url, const GURL& other_url) { - return my_url.host() == other_url.host() && + return my_url.host_piece() == other_url.host_piece() && my_url.port() == other_url.port() && - (my_url.scheme() == other_url.scheme() || + (my_url.scheme_piece() == other_url.scheme_piece() || (my_url.SchemeIs(url::kHttpsScheme) && other_url.SchemeIs(url::kHttpScheme))); } } // namespace bool MatchesOriginAndPath(const GURL& my_url, const GURL& other_url) { - return MatchesOrigin(my_url, other_url) && my_url.path() == other_url.path(); + return MatchesOrigin(my_url, other_url) && + my_url.path_piece() == other_url.path_piece(); } } // namespace search
diff --git a/chrome/common/service_process_util.h b/chrome/common/service_process_util.h index 2c20ec0..c264742 100644 --- a/chrome/common/service_process_util.h +++ b/chrome/common/service_process_util.h
@@ -9,8 +9,10 @@ #include <string> #include "base/callback_forward.h" +#include "base/memory/ref_counted.h" #include "base/memory/shared_memory.h" #include "base/process/process.h" +#include "base/single_thread_task_runner.h" #include "build/build_config.h" #include "mojo/edk/embedder/named_platform_handle.h" #include "mojo/edk/embedder/scoped_platform_handle.h" @@ -27,7 +29,6 @@ namespace base { class CommandLine; -class SingleThreadTaskRunner; } // Return the IPC channel to connect to the service process. @@ -91,7 +92,7 @@ // process (in the same thread that called SignalReady). It can be NULL. // |task_runner| must be of type IO and is the loop that POSIX uses // to monitor the service process. - bool SignalReady(base::SingleThreadTaskRunner* task_runner, + bool SignalReady(scoped_refptr<base::SingleThreadTaskRunner> task_runner, const base::Closure& terminate_task); // Signal that the service process is stopped.
diff --git a/chrome/common/service_process_util_posix.cc b/chrome/common/service_process_util_posix.cc index 9bd3783c..b372856 100644 --- a/chrome/common/service_process_util_posix.cc +++ b/chrome/common/service_process_util_posix.cc
@@ -6,14 +6,12 @@ #include <string.h> -#include <memory> +#include <utility> #include "base/bind.h" #include "base/location.h" #include "base/posix/eintr_wrapper.h" -#include "base/single_thread_task_runner.h" #include "base/synchronization/waitable_event.h" -#include "build/build_config.h" #include "chrome/common/multi_process_lock.h" namespace { @@ -89,6 +87,7 @@ void ServiceProcessState::StateData::SignalReady(base::WaitableEvent* signal, bool* success) { + DCHECK(task_runner->BelongsToCurrentThread()); DCHECK_EQ(g_signal_socket, -1); DCHECK(!signal->IsSignaled()); *success = base::MessageLoopForIO::current()->WatchFileDescriptor( @@ -137,6 +136,11 @@ } ServiceProcessState::StateData::~StateData() { + // StateData is destroyed on the thread that called SignalReady() (if any) to + // satisfy the requirement that base::FilePathWatcher is destroyed in sequence + // with base::FilePathWatcher::Watch(). + DCHECK(!task_runner || task_runner->BelongsToCurrentThread()); + if (sockets[0] != -1) { if (IGNORE_EINTR(close(sockets[0]))) { DPLOG(ERROR) << "close"; @@ -157,20 +161,16 @@ void ServiceProcessState::CreateState() { DCHECK(!state_); - state_ = new StateData; - - // Explicitly adding a reference here (and removing it in TearDownState) - // because StateData is refcounted on Mac and Linux so that methods can - // be called on other threads. - // It is not refcounted on Windows at this time. - state_->AddRef(); + state_ = new StateData(); } -bool ServiceProcessState::SignalReady(base::SingleThreadTaskRunner* task_runner, - const base::Closure& terminate_task) { +bool ServiceProcessState::SignalReady( + scoped_refptr<base::SingleThreadTaskRunner> task_runner, + const base::Closure& terminate_task) { + DCHECK(task_runner); DCHECK(state_); -#if defined(OS_POSIX) && !defined(OS_MACOSX) +#if !defined(OS_MACOSX) state_->running_lock.reset(TakeServiceRunningLock(true)); if (state_->running_lock.get() == NULL) { return false; @@ -187,16 +187,18 @@ base::WaitableEvent::InitialState::NOT_SIGNALED); bool success = false; - task_runner->PostTask(FROM_HERE, - base::Bind(&ServiceProcessState::StateData::SignalReady, - state_, &signal_ready, &success)); + state_->task_runner = std::move(task_runner); + state_->task_runner->PostTask( + FROM_HERE, base::Bind(&ServiceProcessState::StateData::SignalReady, + base::Unretained(state_), &signal_ready, &success)); signal_ready.Wait(); return success; } void ServiceProcessState::TearDownState() { - if (state_) { - state_->Release(); - state_ = NULL; - } + if (state_ && state_->task_runner) + state_->task_runner->DeleteSoon(FROM_HERE, state_); + else + delete state_; + state_ = nullptr; }
diff --git a/chrome/common/service_process_util_posix.h b/chrome/common/service_process_util_posix.h index 2a5339e..be6ec48 100644 --- a/chrome/common/service_process_util_posix.h +++ b/chrome/common/service_process_util_posix.h
@@ -12,7 +12,9 @@ #include <memory> #include "base/callback.h" +#include "base/memory/ref_counted.h" #include "base/message_loop/message_loop.h" +#include "base/single_thread_task_runner.h" #include "build/build_config.h" #if defined(OS_POSIX) && !defined(OS_MACOSX) @@ -57,9 +59,9 @@ base::Closure terminate_task_; }; -struct ServiceProcessState::StateData - : public base::RefCountedThreadSafe<ServiceProcessState::StateData> { +struct ServiceProcessState::StateData { StateData(); + ~StateData(); // WatchFileDescriptor needs to be set up by the thread that is going // to be monitoring it. @@ -70,8 +72,7 @@ base::ScopedCFTypeRef<CFDictionaryRef> launchd_conf; base::FilePathWatcher executable_watcher; -#endif // OS_MACOSX -#if defined(OS_POSIX) && !defined(OS_MACOSX) +#else std::unique_ptr<MultiProcessLock> initializing_lock; std::unique_ptr<MultiProcessLock> running_lock; #endif @@ -81,9 +82,9 @@ struct sigaction old_action; bool set_action; - protected: - friend class base::RefCountedThreadSafe<ServiceProcessState::StateData>; - virtual ~StateData(); + // The SingleThreadTaskRunner on which SignalReady and the destructor are + // invoked. + scoped_refptr<base::SingleThreadTaskRunner> task_runner; }; #endif // CHROME_COMMON_SERVICE_PROCESS_UTIL_POSIX_H_
diff --git a/chrome/common/service_process_util_win.cc b/chrome/common/service_process_util_win.cc index 06711f7..8bedaf7 100644 --- a/chrome/common/service_process_util_win.cc +++ b/chrome/common/service_process_util_win.cc
@@ -135,8 +135,9 @@ return true; } -bool ServiceProcessState::SignalReady(base::SingleThreadTaskRunner* task_runner, - const base::Closure& terminate_task) { +bool ServiceProcessState::SignalReady( + scoped_refptr<base::SingleThreadTaskRunner> task_runner, + const base::Closure& terminate_task) { DCHECK(state_); DCHECK(state_->ready_event.IsValid()); if (!SetEvent(state_->ready_event.Get())) {
diff --git a/chrome/renderer/BUILD.gn b/chrome/renderer/BUILD.gn index 637b99d9..ba34e32 100644 --- a/chrome/renderer/BUILD.gn +++ b/chrome/renderer/BUILD.gn
@@ -4,6 +4,7 @@ import("//build/config/features.gni") import("//chrome/common/features.gni") +import("//components/spellcheck/spellcheck_build_features.gni") import("//extensions/features/features.gni") import("//tools/grit/grit_rule.gni") @@ -105,6 +106,7 @@ "//components/printing/renderer", "//components/rappor/public/interfaces", "//components/resources:components_resources", + "//components/spellcheck:build_features", "//components/startup_metric_utils/common:interfaces", "//components/subresource_filter/content/renderer", "//components/translate/content/renderer",
diff --git a/chrome/renderer/DEPS b/chrome/renderer/DEPS index 3485904..5430ede9 100644 --- a/chrome/renderer/DEPS +++ b/chrome/renderer/DEPS
@@ -26,8 +26,8 @@ "+components/printing/renderer", "+components/rappor/public/interfaces", "+components/signin/core/common", - "+components/spellcheck/common", - "+components/spellcheck/renderer", + "+components/spellcheck", + "-components/spellcheck/browser", # Allow all spellcheck but browser. "+components/startup_metric_utils/common", "+components/strings/grit", "+components/subresource_filter/content/renderer",
diff --git a/chrome/renderer/chrome_content_renderer_client.cc b/chrome/renderer/chrome_content_renderer_client.cc index 87067102..0f8c180a 100644 --- a/chrome/renderer/chrome_content_renderer_client.cc +++ b/chrome/renderer/chrome_content_renderer_client.cc
@@ -76,6 +76,7 @@ #include "components/password_manager/content/renderer/credential_manager_client.h" #include "components/pdf/renderer/pepper_pdf_host.h" #include "components/signin/core/common/profile_management_switches.h" +#include "components/spellcheck/spellcheck_build_features.h" #include "components/startup_metric_utils/common/startup_metric.mojom.h" #include "components/subresource_filter/content/renderer/ruleset_dealer.h" #include "components/subresource_filter/content/renderer/subresource_filter_agent.h" @@ -152,7 +153,7 @@ #include "chrome/renderer/pepper/chrome_pdf_print_client.h" #endif -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) #include "components/spellcheck/renderer/spellcheck.h" #include "components/spellcheck/renderer/spellcheck_provider.h" #endif @@ -242,7 +243,7 @@ } #endif // defined(ENABLE_PLUGINS) -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) class SpellCheckReplacer : public content::RenderViewVisitor { public: explicit SpellCheckReplacer(SpellCheck* spellcheck) @@ -335,7 +336,7 @@ prescient_networking_dispatcher_.reset( new network_hints::PrescientNetworkingDispatcher()); -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) // ChromeRenderViewTest::SetUp() creates a Spellcheck and injects it using // SetSpellcheck(). Don't overwrite it. if (!spellcheck_) { @@ -527,7 +528,7 @@ render_view, std::unique_ptr<printing::PrintWebViewHelper::Delegate>( new ChromePrintWebViewHelperDelegate())); #endif -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) new SpellCheckProvider(render_view, spellcheck_.get()); #endif new prerender::PrerendererClient(render_view); @@ -1177,7 +1178,7 @@ return true; } -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) void ChromeContentRendererClient::SetSpellcheck(SpellCheck* spellcheck) { RenderThread* thread = RenderThread::Get(); if (spellcheck_.get() && thread)
diff --git a/chrome/renderer/chrome_content_renderer_client.h b/chrome/renderer/chrome_content_renderer_client.h index 1cf88d9..4f7bbbbc 100644 --- a/chrome/renderer/chrome_content_renderer_client.h +++ b/chrome/renderer/chrome_content_renderer_client.h
@@ -17,6 +17,7 @@ #include "base/gtest_prod_util.h" #include "base/strings/string16.h" #include "components/rappor/public/interfaces/rappor_recorder.mojom.h" +#include "components/spellcheck/spellcheck_build_features.h" #include "content/public/renderer/content_renderer_client.h" #include "extensions/features/features.h" #include "ipc/ipc_channel_proxy.h" @@ -32,7 +33,7 @@ class ChromePDFPrintClient; #endif class PrescientNetworkingDispatcher; -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) class SpellCheck; class SpellCheckProvider; #endif @@ -186,7 +187,7 @@ bool ShouldEnforceWebRTCRoutingPreferences() override; GURL OverrideFlashEmbedWithHTML(const GURL& url) override; -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) // Sets a new |spellcheck|. Used for testing only. // Takes ownership of |spellcheck|. void SetSpellcheck(SpellCheck* spellcheck); @@ -235,7 +236,7 @@ std::unique_ptr<network_hints::PrescientNetworkingDispatcher> prescient_networking_dispatcher_; -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) std::unique_ptr<SpellCheck> spellcheck_; #endif std::unique_ptr<safe_browsing::PhishingClassifierFilter> phishing_classifier_;
diff --git a/chrome/renderer/plugins/chrome_plugin_placeholder.cc b/chrome/renderer/plugins/chrome_plugin_placeholder.cc index ab5acf6..91222f11 100644 --- a/chrome/renderer/plugins/chrome_plugin_placeholder.cc +++ b/chrome/renderer/plugins/chrome_plugin_placeholder.cc
@@ -30,8 +30,8 @@ #include "content/public/renderer/render_thread.h" #include "gin/object_template_builder.h" #include "third_party/WebKit/public/platform/URLConversion.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/web/WebDocument.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebScriptSource.h" #include "third_party/WebKit/public/web/WebView.h"
diff --git a/chrome/renderer/printing/chrome_print_web_view_helper_delegate.cc b/chrome/renderer/printing/chrome_print_web_view_helper_delegate.cc index 07b03dc..0e8b7c5 100644 --- a/chrome/renderer/printing/chrome_print_web_view_helper_delegate.cc +++ b/chrome/renderer/printing/chrome_print_web_view_helper_delegate.cc
@@ -45,8 +45,9 @@ #if BUILDFLAG(ENABLE_EXTENSIONS) GURL url = frame->document().url(); bool inside_print_preview = url.GetOrigin() == chrome::kChromeUIPrintURL; - bool inside_pdf_extension = url.SchemeIs(extensions::kExtensionScheme) && - url.host() == extension_misc::kPdfExtensionId; + bool inside_pdf_extension = + url.SchemeIs(extensions::kExtensionScheme) && + url.host_piece() == extension_misc::kPdfExtensionId; if (inside_print_preview || inside_pdf_extension) { // <object> with id="plugin" is created in // chrome/browser/resources/pdf/pdf.js.
diff --git a/chrome/service/service_process.cc b/chrome/service/service_process.cc index 0dca832c..a29cc1d 100644 --- a/chrome/service/service_process.cc +++ b/chrome/service/service_process.cc
@@ -237,6 +237,11 @@ mojo_ipc_support_.reset(); ipc_server_.reset(); + + // On POSIX, this must be called before joining |io_thread_| because it posts + // a DeleteSoon() task to that thread. + service_process_state_->SignalStopped(); + // Signal this event before shutting down the service process. That way all // background threads can cleanup. shutdown_event_.Signal(); @@ -257,7 +262,6 @@ // might use it have been shut down. network_change_notifier_.reset(); - service_process_state_->SignalStopped(); return true; }
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index abb52421..f2a022f 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -11,6 +11,7 @@ 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") import("//ppapi/features/features.gni") import("//remoting/remoting_enable.gni") @@ -1228,6 +1229,7 @@ ":repack_pseudo_locales", ":test_support", "//base", + "//components/spellcheck:build_features", "//components/sync:test_support_model", "//extensions/features", "//printing/features", @@ -2924,6 +2926,14 @@ ] } + data = [ + # Needed for isolate script to execute. + "//testing/scripts/common.py", + "//testing/xvfb.py", + "//testing/scripts/run_gtest_perf_test.py", + "//tools/perf/generate_legacy_perf_dashboard_json.py", + ] + # This target should not require the Chrome executable to run. assert_no_deps = [ "//chrome" ] } @@ -2966,6 +2976,23 @@ ] } +group("angle_perftests") { + testonly = true + if (is_win) { + data_deps = [ + "//third_party/angle/src/tests:angle_perftests", + ] + } + + data = [ + # Needed for isolate script to execute. + "//testing/scripts/common.py", + "//testing/xvfb.py", + "//testing/scripts/run_gtest_perf_test.py", + "//tools/perf/generate_legacy_perf_dashboard_json.py", + ] +} + js2gtest("unit_tests_js") { test_type = "unit" sources = [ @@ -3422,6 +3449,7 @@ "//chrome:strings", "//components/component_updater:test_support", "//components/safe_browsing_db:test_database_manager", + "//components/spellcheck:build_features", "//components/subresource_filter/core/browser:test_support", "//components/version_info:generate_version_info", "//courgette:courgette_lib", @@ -4969,6 +4997,7 @@ "//chrome/renderer", "//components/about_handler", "//components/autofill/content/renderer:test_support", + "//components/spellcheck:build_features", "//content/test:test_support", "//extensions/features", "//media/cast:test_support", @@ -4977,6 +5006,14 @@ "//testing/perf", ] + data = [ + # Needed for isolate script to execute. + "//testing/scripts/common.py", + "//testing/xvfb.py", + "//testing/scripts/run_gtest_perf_test.py", + "//tools/perf/generate_legacy_perf_dashboard_json.py", + ] + if (is_win) { configs -= [ "//build/config/win:default_incremental_linking" ] configs +=
diff --git a/chrome/test/base/chrome_render_view_test.cc b/chrome/test/base/chrome_render_view_test.cc index 1e3cb36..26f48914 100644 --- a/chrome/test/base/chrome_render_view_test.cc +++ b/chrome/test/base/chrome_render_view_test.cc
@@ -17,14 +17,15 @@ #include "components/autofill/content/renderer/test_password_autofill_agent.h" #include "components/autofill/content/renderer/test_password_generation_agent.h" #include "components/spellcheck/renderer/spellcheck.h" +#include "components/spellcheck/spellcheck_build_features.h" #include "content/public/browser/native_web_keyboard_event.h" #include "content/public/common/renderer_preferences.h" #include "content/public/renderer/render_view.h" #include "extensions/features/features.h" #include "testing/gmock/include/gmock/gmock.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/platform/WebURLRequest.h" #include "third_party/WebKit/public/web/WebFrame.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" #include "third_party/WebKit/public/web/WebKit.h" #include "third_party/WebKit/public/web/WebScriptController.h" #include "third_party/WebKit/public/web/WebScriptSource.h" @@ -172,7 +173,7 @@ base::MakeUnique<extensions::Dispatcher>( extension_dispatcher_delegate_.get())); #endif -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) client->SetSpellcheck(new SpellCheck()); #endif }
diff --git a/chrome/test/data/chromeos/oobe_webui_browsertest.js b/chrome/test/data/chromeos/oobe_webui_browsertest.js index 34f3f9b5..e36a80c0 100644 --- a/chrome/test/data/chromeos/oobe_webui_browsertest.js +++ b/chrome/test/data/chromeos/oobe_webui_browsertest.js
@@ -137,39 +137,47 @@ }; } -TEST_F('OobeWebUITest', 'EmptyOobe', function() { +// Fails on chromeos, http://crbug.com/665315 +TEST_F('OobeWebUITest', 'DISABLED_EmptyOobe', function() { }); -TEST_F('OobeWebUITest', 'OobeConnect', function() { +// Fails on chromeos, http://crbug.com/665315 +TEST_F('OobeWebUITest', 'DISABLED_OobeConnect', function() { Oobe.getInstance().showScreen({'id':'connect'}); }); -TEST_F('OobeWebUITest', 'OobeEula', function() { +// Fails on chromeos, http://crbug.com/665315 +TEST_F('OobeWebUITest', 'DISABLED_OobeEula', function() { Oobe.getInstance().showScreen({'id':'eula'}); }); -TEST_F('OobeWebUITest', 'OobeUpdate', function() { +// Fails on chromeos, http://crbug.com/665315 +TEST_F('OobeWebUITest', 'DISABLED_OobeUpdate', function() { Oobe.getInstance().showScreen({'id':'update'}); }); -TEST_F('OobeWebUITest', 'OobeGaiaSignIn', function() { +// Fails on chromeos, http://crbug.com/665315 +TEST_F('OobeWebUITest', 'DISABLED_OobeGaiaSignIn', function() { Oobe.getInstance().showScreen({'id':'gaia-signin'}); }); -TEST_F('OobeWebUITest', 'OobeSupervisedUsers', function() { +// Fails on chromeos, http://crbug.com/665315 +TEST_F('OobeWebUITest', 'DISABLED_OobeSupervisedUsers', function() { Oobe.getInstance().showScreen( {'id' : 'supervised-user-creation', 'data' : createOobeWebUITestSupervisedManagerData()}); }); -TEST_F('OobeWebUITest', 'OobeSupervisedUsers2', function() { +// Fails on chromeos, http://crbug.com/665315 +TEST_F('OobeWebUITest', 'DISABLED_OobeSupervisedUsers2', function() { Oobe.getInstance().showScreen( {'id' : 'supervised-user-creation', 'data' : createOobeWebUITestSupervisedManagerData()}); $('supervised-user-creation').setVisiblePage_('manager'); }); -TEST_F('OobeWebUITest', 'OobeSupervisedUsers3', function() { +// Fails on chromeos, http://crbug.com/665315 +TEST_F('OobeWebUITest', 'DISABLED_OobeSupervisedUsers3', function() { Oobe.getInstance().showScreen( {'id' : 'supervised-user-creation', 'data' : createOobeWebUITestSupervisedManagerData()}); @@ -191,8 +199,8 @@ Oobe.getInstance().showScreen({'id':'account-picker'}); }); - -TEST_F('OobeWebUITest', 'HIDDetectionScreenTest', function() { +// Fails on chromeos, http://crbug.com/665315 +TEST_F('OobeWebUITest', 'DISABLED_HIDDetectionScreenTest', function() { function getPincodeSymbol(i) { return $('hid-keyboard-pincode-sym-' + (i + 1)); }
diff --git a/chrome/test/data/extensions/api_test/messaging/on_unload/content_script.js b/chrome/test/data/extensions/api_test/messaging/on_unload/content_script.js new file mode 100644 index 0000000..3e22038 --- /dev/null +++ b/chrome/test/data/extensions/api_test/messaging/on_unload/content_script.js
@@ -0,0 +1,9 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +window.addEventListener('unload', function() { + chrome.runtime.sendMessage('Unloading'); +}); + +chrome.test.sendMessage('listening');
diff --git a/chrome/test/data/extensions/api_test/messaging/on_unload/manifest.json b/chrome/test/data/extensions/api_test/messaging/on_unload/manifest.json new file mode 100644 index 0000000..9b665d5 --- /dev/null +++ b/chrome/test/data/extensions/api_test/messaging/on_unload/manifest.json
@@ -0,0 +1,14 @@ +{ + "name": "send message on unload", + "version": "1.0", + "manifest_version": 2, + "description": "Sends a message on tab unload", + "background": { + "persistent": true, + "scripts": ["test.js"] + }, + "content_scripts": [{ + "matches": ["*://*/*"], + "js": ["content_script.js"] + }] +}
diff --git a/chrome/test/data/extensions/api_test/messaging/on_unload/test.js b/chrome/test/data/extensions/api_test/messaging/on_unload/test.js new file mode 100644 index 0000000..cbef07f1d --- /dev/null +++ b/chrome/test/data/extensions/api_test/messaging/on_unload/test.js
@@ -0,0 +1,10 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +window.messageCount = 0; + +chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { + ++window.messageCount; + window.message = request; +});
diff --git a/chrome/test/data/webui/md_history/history_list_test.js b/chrome/test/data/webui/md_history/history_list_test.js index 075fdfc8..4a82933 100644 --- a/chrome/test/data/webui/md_history/history_list_test.js +++ b/chrome/test/data/webui/md_history/history_list_test.js
@@ -4,7 +4,7 @@ cr.define('md_history.history_list_test', function() { function registerTests() { - suite('history-list', function() { + suite('<history-list>', function() { var app; var element; var toolbar; @@ -12,10 +12,6 @@ var ADDITIONAL_RESULTS; suiteSetup(function() { - app = $('history-app'); - element = app.$['history'].$['infinite-list']; - toolbar = app.$['toolbar']; - TEST_HISTORY_RESULTS = [ createHistoryEntry('2016-03-15', 'https://www.google.com'), createHistoryEntry('2016-03-14 10:00', 'https://www.example.com'), @@ -33,6 +29,9 @@ }); setup(function() { + app = replaceApp(); + element = app.$['history'].$['infinite-list']; + toolbar = app.$['toolbar']; app.queryState_.incremental = true; }); @@ -264,6 +263,7 @@ test('more from this site sends and sets correct data', function(done) { app.queryState_.queryingDisabled = false; + app.historyResult(createHistoryInfo(), TEST_HISTORY_RESULTS); PolymerTest.flushTasks().then(function () { registerMessageCallback('queryHistory', this, function (info) { assertEquals('www.google.com', info[0]); @@ -513,62 +513,65 @@ }); }); - test('focus and keyboard nav', function() { + test('focus and keyboard nav', function(done) { app.historyResult(createHistoryInfo(), TEST_HISTORY_RESULTS); - return PolymerTest.flushTasks().then(function() { + PolymerTest.flushTasks().then(function() { var items = polymerSelectAll(element, 'history-item'); var focused = items[2].$.checkbox; focused.focus(); - MockInteractions.pressAndReleaseKeyOn(focused, 39, [], 'ArrowRight'); - focused = items[2].$.title; - assertEquals(focused, element.lastFocused_); - assertTrue(items[2].row_.isActive()); - assertFalse(items[3].row_.isActive()); + // Wait for next render to ensure that focus handlers have been + // registered (see HistoryItemElement.attached). + Polymer.RenderStatus.afterNextRender(this, function() { + MockInteractions.pressAndReleaseKeyOn( + focused, 39, [], 'ArrowRight'); + focused = items[2].$.title; + assertEquals(focused, element.lastFocused_); + assertTrue(items[2].row_.isActive()); + assertFalse(items[3].row_.isActive()); - MockInteractions.pressAndReleaseKeyOn(focused, 40, [], 'ArrowDown'); - focused = items[3].$.title; - assertEquals(focused, element.lastFocused_); - assertFalse(items[2].row_.isActive()); - assertTrue(items[3].row_.isActive()); + MockInteractions.pressAndReleaseKeyOn(focused, 40, [], 'ArrowDown'); + focused = items[3].$.title; + assertEquals(focused, element.lastFocused_); + assertFalse(items[2].row_.isActive()); + assertTrue(items[3].row_.isActive()); - MockInteractions.pressAndReleaseKeyOn(focused, 39, [], 'ArrowRight'); - focused = items[3].$['menu-button']; - assertEquals(focused, element.lastFocused_); - assertFalse(items[2].row_.isActive()); - assertTrue(items[3].row_.isActive()); + MockInteractions.pressAndReleaseKeyOn( + focused, 39, [], 'ArrowRight'); + focused = items[3].$['menu-button']; + assertEquals(focused, element.lastFocused_); + assertFalse(items[2].row_.isActive()); + assertTrue(items[3].row_.isActive()); - MockInteractions.pressAndReleaseKeyOn(focused, 38, [], 'ArrowUp'); - focused = items[2].$['menu-button']; - assertEquals(focused, element.lastFocused_); - assertTrue(items[2].row_.isActive()); - assertFalse(items[3].row_.isActive()); + MockInteractions.pressAndReleaseKeyOn(focused, 38, [], 'ArrowUp'); + focused = items[2].$['menu-button']; + assertEquals(focused, element.lastFocused_); + assertTrue(items[2].row_.isActive()); + assertFalse(items[3].row_.isActive()); - MockInteractions.pressAndReleaseKeyOn(focused, 37, [], 'ArrowLeft'); - focused = items[2].$$('#bookmark-star'); - assertEquals(focused, element.lastFocused_); - assertTrue(items[2].row_.isActive()); - assertFalse(items[3].row_.isActive()); + MockInteractions.pressAndReleaseKeyOn(focused, 37, [], 'ArrowLeft'); + focused = items[2].$$('#bookmark-star'); + assertEquals(focused, element.lastFocused_); + assertTrue(items[2].row_.isActive()); + assertFalse(items[3].row_.isActive()); - MockInteractions.pressAndReleaseKeyOn(focused, 40, [], 'ArrowDown'); - focused = items[3].$.title; - assertEquals(focused, element.lastFocused_); - assertFalse(items[2].row_.isActive()); - assertTrue(items[3].row_.isActive()); + MockInteractions.pressAndReleaseKeyOn(focused, 40, [], 'ArrowDown'); + focused = items[3].$.title; + assertEquals(focused, element.lastFocused_); + assertFalse(items[2].row_.isActive()); + assertTrue(items[3].row_.isActive()); + + done(); + }); }); }); teardown(function() { - element.historyData_ = []; registerMessageCallback('removeVisits', this, undefined); registerMessageCallback('queryHistory', this, function() {}); registerMessageCallback('navigateToUrl', this, undefined); - app.queryState_.queryingDisabled = true; app.set('queryState_.searchTerm', ''); - // Unselect all items, clear the list. - element.addNewResults([], false); - return PolymerTest.flushTasks(); }); }); }
diff --git a/chrome/test/data/webui/md_history/history_supervised_user_test.js b/chrome/test/data/webui/md_history/history_supervised_user_test.js index 2d5ab81..1e407fb 100644 --- a/chrome/test/data/webui/md_history/history_supervised_user_test.js +++ b/chrome/test/data/webui/md_history/history_supervised_user_test.js
@@ -6,26 +6,26 @@ function registerTests() { suite('history-list supervised-user', function() { var app; - var element; + var historyList; var toolbar; var TEST_HISTORY_RESULTS; suiteSetup(function() { - app = $('history-app'); - element = app.$['history'].$['infinite-list']; - toolbar = app.$['toolbar']; TEST_HISTORY_RESULTS = [createHistoryEntry('2016-03-15', 'https://www.google.com')]; }); setup(function() { + app = replaceApp(); + historyList = app.$['history'].$['infinite-list']; + toolbar = app.$['toolbar']; app.historyResult(createHistoryInfo(), TEST_HISTORY_RESULTS); }); test('checkboxes disabled for supervised user', function() { return PolymerTest.flushTasks().then(function() { var items = - Polymer.dom(element.root).querySelectorAll('history-item'); + Polymer.dom(historyList.root).querySelectorAll('history-item'); MockInteractions.tap(items[0].$['checkbox']); @@ -34,19 +34,19 @@ }); test('deletion disabled for supervised user', function() { - // Make sure that removeVisits is not being called. registerMessageCallback('removeVisits', this, function (toBeRemoved) { - assertTrue(false); + assertNotReached(); }); - element.historyData_[0].selected = true; + historyList.historyData_[0].selected = true; toolbar.onDeleteTap_(); }); - teardown(function() { - element.historyData_ = []; - element.searchedTerm = ''; + test('remove history menu button disabled', function() { + var listContainer = app.$['history']; + listContainer.$.sharedMenu.get(); + assertTrue(listContainer.$$('#menuRemoveButton').disabled); }); }); }
diff --git a/chrome/test/data/webui/md_history/md_history_browsertest.js b/chrome/test/data/webui/md_history/md_history_browsertest.js index 2582e1d..2b9ed5b 100644 --- a/chrome/test/data/webui/md_history/md_history_browsertest.js +++ b/chrome/test/data/webui/md_history/md_history_browsertest.js
@@ -28,17 +28,6 @@ extraLibraries: PolymerTest.getLibraries(ROOT_PATH).concat([ 'test_util.js', - 'browser_service_test.js', - 'history_drawer_test.js', - 'history_grouped_list_test.js', - 'history_item_test.js', - 'history_list_test.js', - 'history_metrics_test.js', - 'history_overflow_menu_test.js', - 'history_routing_test.js', - 'history_supervised_user_test.js', - 'history_synced_tabs_test.js', - 'history_toolbar_test.js', ]), /** @override */ @@ -66,84 +55,130 @@ }, }; -TEST_F('MaterialHistoryBrowserTest', 'BrowserServiceTest', function() { +function MaterialHistoryBrowserServiceTest() {} + +MaterialHistoryBrowserServiceTest.prototype = { + __proto__: MaterialHistoryBrowserTest.prototype, + + extraLibraries: MaterialHistoryBrowserTest.prototype.extraLibraries.concat([ + 'browser_service_test.js', + ]), +}; + +TEST_F('MaterialHistoryBrowserServiceTest', 'All', function() { md_history.browser_service_test.registerTests(); mocha.run(); }); -TEST_F('MaterialHistoryBrowserTest', 'DrawerTest', function() { +function MaterialHistoryDrawerTest() {} + +MaterialHistoryDrawerTest.prototype = { + __proto__: MaterialHistoryBrowserTest.prototype, + + extraLibraries: MaterialHistoryBrowserTest.prototype.extraLibraries.concat([ + 'history_drawer_test.js', + ]), +}; + +TEST_F('MaterialHistoryDrawerTest', 'All', function() { md_history.history_drawer_test.registerTests(); mocha.run(); }); -TEST_F('MaterialHistoryBrowserTest', 'HistoryGroupedListTest', function() { +function MaterialHistoryGroupedListTest() {} + +MaterialHistoryGroupedListTest.prototype = { + __proto__: MaterialHistoryBrowserTest.prototype, + + extraLibraries: MaterialHistoryBrowserTest.prototype.extraLibraries.concat([ + 'history_grouped_list_test.js', + ]), +}; + +TEST_F('MaterialHistoryGroupedListTest', 'All', function() { md_history.history_grouped_list_test.registerTests(); mocha.run(); }); -TEST_F('MaterialHistoryBrowserTest', 'HistoryItemTest', function() { +function MaterialHistoryItemTest() {} + +MaterialHistoryItemTest.prototype = { + __proto__: MaterialHistoryBrowserTest.prototype, + + extraLibraries: MaterialHistoryBrowserTest.prototype.extraLibraries.concat([ + 'history_item_test.js', + ]), +}; + +TEST_F('MaterialHistoryItemTest', 'All', function() { md_history.history_item_test.registerTests(); mocha.run(); }); -TEST_F('MaterialHistoryBrowserTest', 'HistoryListTest', function() { +function MaterialHistoryListTest() {} + +MaterialHistoryListTest.prototype = { + __proto__: MaterialHistoryBrowserTest.prototype, + + extraLibraries: MaterialHistoryBrowserTest.prototype.extraLibraries.concat([ + 'history_list_test.js', + ]), +}; + +TEST_F('MaterialHistoryListTest', 'All', function() { md_history.history_list_test.registerTests(); mocha.run(); }); -TEST_F('MaterialHistoryBrowserTest', 'Metrics', function() { +function MaterialHistoryMetricsTest() {} + +MaterialHistoryMetricsTest.prototype = { + __proto__: MaterialHistoryBrowserTest.prototype, + + extraLibraries: MaterialHistoryBrowserTest.prototype.extraLibraries.concat([ + 'history_metrics_test.js', + ]), +}; + +TEST_F('MaterialHistoryMetricsTest', 'All', function() { md_history.history_metrics_test.registerTests(); mocha.run(); }); -TEST_F('MaterialHistoryBrowserTest', 'HistoryToolbarTest', function() { - md_history.history_toolbar_test.registerTests(); - mocha.run(); -}); +function MaterialHistoryOverflowMenuTest() {} -TEST_F('MaterialHistoryBrowserTest', 'HistoryToolbarFocusTest', function() { - md_history.history_toolbar_focus_test.registerTests(); - mocha.run(); -}); +MaterialHistoryOverflowMenuTest.prototype = { + __proto__: MaterialHistoryBrowserTest.prototype, -TEST_F('MaterialHistoryBrowserTest', 'HistoryOverflowMenuTest', function() { + extraLibraries: MaterialHistoryBrowserTest.prototype.extraLibraries.concat([ + 'history_overflow_menu_test.js', + ]), +}; + +TEST_F('MaterialHistoryOverflowMenuTest', 'All', function() { md_history.history_overflow_menu_test.registerTests(); mocha.run(); }); -TEST_F('MaterialHistoryBrowserTest', 'RoutingTest', function() { +function MaterialHistoryRoutingTest() {} + +MaterialHistoryRoutingTest.prototype = { + __proto__: MaterialHistoryBrowserTest.prototype, + + extraLibraries: MaterialHistoryBrowserTest.prototype.extraLibraries.concat([ + 'history_routing_test.js', + ]), +}; + +TEST_F('MaterialHistoryRoutingTest', 'All', function() { md_history.history_routing_test.registerTests(); mocha.run(); }); -// Fails on Mac, http://crbug.com/640862 -TEST_F('MaterialHistoryBrowserTest', 'DISABLED_SyncedTabsTest', function() { - md_history.history_synced_tabs_test.registerTests(); - mocha.run(); -}); +function MaterialHistoryRoutingWithQueryParamTest() {} -function MaterialHistoryDeletionDisabledTest() {} - -MaterialHistoryDeletionDisabledTest.prototype = { - __proto__: MaterialHistoryBrowserTest.prototype, - - typedefCppFixture: 'HistoryUIBrowserTest', - - testGenPreamble: function() { - GEN(' SetDeleteAllowed(false);'); - } -}; - -TEST_F('MaterialHistoryDeletionDisabledTest', 'HistorySupervisedUserTest', - function() { - md_history.history_supervised_user_test.registerTests(); - mocha.run(); -}); - -function MaterialHistoryWithQueryParamTest() {} - -MaterialHistoryWithQueryParamTest.prototype = { - __proto__: MaterialHistoryBrowserTest.prototype, +MaterialHistoryRoutingWithQueryParamTest.prototype = { + __proto__: MaterialHistoryRoutingTest.prototype, browsePreload: 'chrome://history?q=query', @@ -168,8 +203,64 @@ }, }; -TEST_F('MaterialHistoryWithQueryParamTest', 'RoutingTestWithQueryParam', - function() { +TEST_F('MaterialHistoryRoutingWithQueryParamTest', 'All', function() { md_history.history_routing_test_with_query_param.registerTests(); mocha.run(); }); + +function MaterialHistorySyncedTabsTest() {} + +MaterialHistorySyncedTabsTest.prototype = { + __proto__: MaterialHistoryBrowserTest.prototype, + + extraLibraries: MaterialHistoryBrowserTest.prototype.extraLibraries.concat([ + 'history_synced_tabs_test.js', + ]), +}; + +// Fails on Mac, http://crbug.com/640862 +TEST_F('MaterialHistorySyncedTabsTest', 'DISABLED_All', function() { + md_history.history_synced_tabs_test.registerTests(); + mocha.run(); +}); + +function MaterialHistorySupervisedUserTest() {} + +MaterialHistorySupervisedUserTest.prototype = { + __proto__: MaterialHistoryBrowserTest.prototype, + + typedefCppFixture: 'HistoryUIBrowserTest', + + testGenPreamble: function() { + GEN(' SetDeleteAllowed(false);'); + }, + + extraLibraries: MaterialHistoryBrowserTest.prototype.extraLibraries.concat([ + 'history_supervised_user_test.js', + ]), +}; + +TEST_F('MaterialHistorySupervisedUserTest', 'All', function() { + md_history.history_supervised_user_test.registerTests(); + mocha.run(); +}); + +function MaterialHistoryToolbarTest() {} + +MaterialHistoryToolbarTest.prototype = { + __proto__: MaterialHistoryBrowserTest.prototype, + + extraLibraries: MaterialHistoryBrowserTest.prototype.extraLibraries.concat([ + 'history_toolbar_test.js', + ]), +}; + +TEST_F('MaterialHistoryToolbarTest', 'Basic', function() { + md_history.history_toolbar_test.registerTests(); + mocha.run(); +}); + +TEST_F('MaterialHistoryToolbarTest', 'Focus', function() { + md_history.history_toolbar_focus_test.registerTests(); + mocha.run(); +});
diff --git a/chrome/test/data/webui/settings/cr_settings_browsertest.js b/chrome/test/data/webui/settings/cr_settings_browsertest.js index a53837d..54b5669 100644 --- a/chrome/test/data/webui/settings/cr_settings_browsertest.js +++ b/chrome/test/data/webui/settings/cr_settings_browsertest.js
@@ -632,7 +632,8 @@ 'test_browser_proxy.js', 'test_site_settings_prefs_browser_proxy.js', 'zoom_levels_tests.js', - 'usb_devices_tests.js' + 'usb_devices_tests.js', + 'protocol_handlers_tests.js' ]), }; @@ -643,6 +644,7 @@ site_settings_category.registerTests(); zoom_levels.registerTests(); usb_devices.registerTests(); + protocol_handlers.registerTests(); mocha.run(); });
diff --git a/chrome/test/data/webui/settings/protocol_handlers_tests.js b/chrome/test/data/webui/settings/protocol_handlers_tests.js new file mode 100644 index 0000000..92cde77 --- /dev/null +++ b/chrome/test/data/webui/settings/protocol_handlers_tests.js
@@ -0,0 +1,176 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** @fileoverview Suite of tests for protocol_handlers. */ +cr.define('protocol_handlers', function() { + function registerTests() { + suite('ProtocolHandlers', function() { + /** + * A dummy protocol handler element created before each test. + * @type {ProtocolHandlers} + */ + var testElement; + + /** + * A list of ProtocolEntry fixtures. + * @type {!Array<!ProtocolEntry>} + */ + var protocols = [ + { + default_handler: 0, + handlers: [ + { + host: 'www.google.com', + protocol: 'mailto', + spec: 'http://www.google.com/%s' + } + ], + has_policy_recommendations: false, + is_default_handler_set_by_user: true, + protocol: 'mailto' + }, { + default_handler: 0, + handlers: [ + { + host: 'www.google1.com', + protocol: 'webcal', + spec: 'http://www.google1.com/%s' + }, { + host: 'www.google2.com', + protocol: 'webcal', + spec: 'http://www.google2.com/%s' + } + ], + has_policy_recommendations: false, + is_default_handler_set_by_user: true, + protocol: 'webcal' + } + ]; + + /** + * The mock proxy object to use during test. + * @type {TestSiteSettingsPrefsBrowserProxy} + */ + var browserProxy = null; + + // Import necessary html before running suite. + suiteSetup(function() { + return PolymerTest.importHtml( + 'chrome://md-settings/site_settings/protocol_handlers.html'); + }); + + setup(function() { + browserProxy = new TestSiteSettingsPrefsBrowserProxy(); + settings.SiteSettingsPrefsBrowserProxyImpl.instance_ = browserProxy; + }); + + teardown(function() { + testElement.remove(); + testElement = null; + }); + + /** @return {!Promise} */ + function initPage() { + browserProxy.reset(); + PolymerTest.clearBody(); + testElement = document.createElement('protocol-handlers'); + document.body.appendChild(testElement); + return browserProxy.whenCalled('initializeProtocolHandlerList'). + then(Polymer.dom.flush.bind(Polymer.dom)); + } + + test('empty list', function() { + return initPage().then(function(){ + var listFrames = testElement.root.querySelectorAll('.list-frame'); + assertEquals(0, listFrames.length); + }); + }); + + test('non-empty list', function() { + browserProxy.setProtocolHandlers(protocols); + + return initPage().then(function(){ + var listFrames = testElement.root.querySelectorAll('.list-frame'); + var listItems = testElement.root.querySelectorAll('.list-item'); + // There are two protocols: ["mailto", "webcal"]. + assertEquals(2, listFrames.length); + // There are three total handlers within the two protocols. + assertEquals(3, listItems.length); + + // Check that item hosts are rendered correctly. + var hosts = testElement.root.querySelectorAll('.protocol-host'); + assertEquals('www.google.com', hosts[0].textContent); + assertEquals('www.google1.com', hosts[1].textContent); + assertEquals('www.google2.com', hosts[2].textContent); + + // Check that item default subtexts are rendered correctly. + var defText = testElement.root.querySelectorAll('.protocol-default'); + assertFalse(defText[0].hidden); + assertFalse(defText[1].hidden); + assertTrue(defText[2].hidden); + }); + }); + + /** + * A reusable function to test different action buttons. + * @param {!string} button id of the button to test. + * @param {!string} handler name of browserProxy handler to react. + * @return {!Promise} + */ + function testButtonFlow(button, browserProxyHandler) { + var menuButtons, functionButton, dialog; + + return initPage().then(function(){ + // Initiating the elements + menuButtons = testElement.root. + querySelectorAll('paper-icon-button'); + functionButton = testElement.$[button]; + dialog = testElement.$$('dialog[is=cr-action-menu]'); + assertEquals(3, menuButtons.length); + + // Test the button for the first protocol handler + MockInteractions.tap(menuButtons[0]); + assertTrue(dialog.open); + + MockInteractions.tap(functionButton); + + return browserProxy.whenCalled(browserProxyHandler); + }).then(function(args) { + // BrowserProxy's handler is expected to be called with arguments as + // [protocol, url]. + assertEquals(protocols[0].protocol, args[0]); + assertEquals(protocols[0].handlers[0].spec, args[1]); + + var dialog = testElement.$$('dialog[is=cr-action-menu]'); + assertFalse(dialog.open); + + // Test the button for the second protocol handler + browserProxy.reset(); + MockInteractions.tap(menuButtons[1]); + assertTrue(dialog.open); + MockInteractions.tap(functionButton); + + return browserProxy.whenCalled(browserProxyHandler); + }).then(function(args) { + assertEquals(protocols[1].protocol, args[0]); + assertEquals(protocols[1].handlers[0].spec, args[1]); + }); + } + + test('remove button works', function() { + browserProxy.setProtocolHandlers(protocols); + return testButtonFlow('removeButton', 'removeProtocolHandler'); + }); + + test('default button works', function() { + browserProxy.setProtocolHandlers(protocols); + return testButtonFlow('defaultButton', 'setProtocolDefault'); + }); + }); + } + + return { + registerTests: registerTests, + }; +});
diff --git a/chrome/test/data/webui/settings/quick_unlock_authenticate_browsertest_chromeos.js b/chrome/test/data/webui/settings/quick_unlock_authenticate_browsertest_chromeos.js index 0a2f1f32..a985642 100644 --- a/chrome/test/data/webui/settings/quick_unlock_authenticate_browsertest_chromeos.js +++ b/chrome/test/data/webui/settings/quick_unlock_authenticate_browsertest_chromeos.js
@@ -370,46 +370,50 @@ assertFalse(continueButton.disabled); }); - // Problem messages are hidden if the PIN is cleared. - test('NoProblemShownWithEmptyPin', function() { + // Problem message is always shown. + test('ProblemShownEvenWithEmptyPin', function() { pinKeyboard.value = '11'; assertTrue(isVisible(problemDiv)); pinKeyboard.value = ''; - assertFalse(isVisible(problemDiv)); + assertTrue(isVisible(problemDiv)); }); // If the PIN is too short an error problem is shown. - test('ErrorShownForShortPins', function() { - assertFalse(isVisible(problemDiv)); - + test('WarningShownForShortPins', function() { pinKeyboard.value = '11'; assertTrue(isVisible(problemDiv)); - assertHasClass(problemDiv, 'error'); + assertHasClass(problemDiv, 'warning'); assertTrue(continueButton.disabled); }); // If the PIN is weak a warning problem is shown. test('WarningShownForWeakPins', function() { - assertFalse(isVisible(problemDiv)); - - pinKeyboard.value = '1111'; + pinKeyboard.value = '111111'; assertTrue(isVisible(problemDiv)); assertHasClass(problemDiv, 'warning'); }); - // If the confirm PIN does not match the initial PIN an error is shown and - // the submit button is disabled. - test('ErrorShownForMismatchedPins', function() { + // If the confirm PIN does not match the initial PIN a warning is shown. + // If the user tries to submit the PIN, the warning changes to an error. + test('WarningThenErrorShownForMismatchedPins', function() { pinKeyboard.value = '1118'; MockInteractions.tap(continueButton); - pinKeyboard.value = '1119'; + // Entering a mismatched PIN shows a warning. + pinKeyboard.value = '1119'; assertTrue(isVisible(problemDiv)); + assertHasClass(problemDiv, 'warning'); + + // Submitting a mistmatched PIN shows an error. + MockInteractions.tap(continueButton); assertHasClass(problemDiv, 'error'); - assertTrue(continueButton.disabled); + + // Changing the PIN changes the error to a warning. + pinKeyboard.value = '111'; + assertHasClass(problemDiv, 'warning'); }); // Hitting cancel at the setup step dismisses the dialog.
diff --git a/chrome/test/data/webui/settings/test_site_settings_prefs_browser_proxy.js b/chrome/test/data/webui/settings/test_site_settings_prefs_browser_proxy.js index 4d564d67..cfc08277 100644 --- a/chrome/test/data/webui/settings/test_site_settings_prefs_browser_proxy.js +++ b/chrome/test/data/webui/settings/test_site_settings_prefs_browser_proxy.js
@@ -54,11 +54,14 @@ 'fetchZoomLevels', 'getDefaultValueForContentType', 'getExceptionList', + 'initializeProtocolHandlerList', + 'removeProtocolHandler', 'removeUsbDevice', 'removeZoomLevel', 'resetCategoryPermissionForOrigin', 'setCategoryPermissionForOrigin', 'setDefaultValueForContentType', + 'setProtocolDefault' ]); /** @private {!SiteSettingsPref} */ @@ -67,8 +70,11 @@ /** @private {!Array<ZoomLevelEntry>} */ this.zoomList_ = []; - /** @private {!Array<UsbDeviceEntry>} */ + /** @private {!Array<!UsbDeviceEntry>} */ this.usbDevices_ = []; + + /** @private {!Array<!ProtocolEntry>} */ + this.protocolHandlers_ = []; }; TestSiteSettingsPrefsBrowserProxy.prototype = { @@ -107,6 +113,15 @@ this.usbDevices_ = list.slice(); }, + /** + * Sets the prefs to use when testing. + * @param {!Array<ProtocolEntry>} list The protocol handlers list to set. + */ + setProtocolHandlers: function(list) { + // Shallow copy of the passed-in array so mutation won't impact the source + this.protocolHandlers_ = list.slice(); + }, + /** @override */ setDefaultValueForContentType: function(contentType, defaultValue) { this.methodCalled( @@ -235,5 +250,22 @@ /** @override */ removeUsbDevice: function() { this.methodCalled('removeUsbDevice', arguments); + }, + + /** @override */ + initializeProtocolHandlerList: function() { + cr.webUIListenerCallback('setHandlersEnabled', true); + cr.webUIListenerCallback('setProtocolHandlers', this.protocolHandlers_); + this.methodCalled('initializeProtocolHandlerList'); + }, + + /** @override */ + setProtocolDefault: function() { + this.methodCalled('setProtocolDefault', arguments); + }, + + /** @override */ + removeProtocolHandler: function() { + this.methodCalled('removeProtocolHandler', arguments); } };
diff --git a/chrome/test/data/webui/settings/usb_devices_tests.js b/chrome/test/data/webui/settings/usb_devices_tests.js index bd8c2f9..eb5ebdc5 100644 --- a/chrome/test/data/webui/settings/usb_devices_tests.js +++ b/chrome/test/data/webui/settings/usb_devices_tests.js
@@ -8,7 +8,7 @@ suite('UsbDevices', function() { /** * A dummy usb-devices element created before each test. - * @type {UsbDeviceEntry} + * @type {UsbDevices} */ var testElement;
diff --git a/chrome/test/media_router/resources/common.js b/chrome/test/media_router/resources/common.js index d356a65..35029eaf 100644 --- a/chrome/test/media_router/resources/common.js +++ b/chrome/test/media_router/resources/common.js
@@ -71,14 +71,18 @@ } else { // set the new session startedConnection = session; - if (startedConnection.state != "connecting") { - sendResult(false, - 'Expect connection state to be "connecting", actual "' + - startedConnection.state + '"'); - } - startedConnection.onconnect = () => { + console.log('connection state is "' + startedConnection.state + '"'); + if (startedConnection.state == "connected") { sendResult(true, ''); - }; + } else if (startedConnection.state == "connecting") { + startedConnection.onconnect = () => { + sendResult(true, ''); + }; + } else { + sendResult(false, + 'Expect connection state to be "connecting" or "connected", ' + + 'actual "' + startedConnection.state + '"'); + } } }).catch(function(e) { // terminate old session if exists
diff --git a/chrome/utility/importer/bookmarks_file_importer.cc b/chrome/utility/importer/bookmarks_file_importer.cc index 5e215a1..fc63fc9 100644 --- a/chrome/utility/importer/bookmarks_file_importer.cc +++ b/chrome/utility/importer/bookmarks_file_importer.cc
@@ -50,8 +50,8 @@ // that we support. if (url.SchemeIs(content::kChromeUIScheme) || url.SchemeIs(url::kAboutScheme)) { - if (url.host() == chrome::kChromeUIUberHost || - url.host() == chrome::kChromeUIAboutHost) + if (url.host_piece() == chrome::kChromeUIUberHost || + url.host_piece() == chrome::kChromeUIAboutHost) return true; GURL fixed_url(url_formatter::FixupURL(url.spec(), std::string()));
diff --git a/chromecast/media/audio/cast_audio_output_stream.cc b/chromecast/media/audio/cast_audio_output_stream.cc index 21f3cc9a..654c4b4 100644 --- a/chromecast/media/audio/cast_audio_output_stream.cc +++ b/chromecast/media/audio/cast_audio_output_stream.cc
@@ -122,6 +122,12 @@ decoder_->SetVolume(volume); } + MediaPipelineBackend::AudioDecoder::RenderingDelay GetRenderingDelay() { + DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK(decoder_); + return decoder_->GetRenderingDelay(); + } + private: // MediaPipelineBackend::Decoder::Delegate implementation void OnPushBufferComplete(BufferStatus status) override { @@ -270,12 +276,16 @@ return; } - const base::TimeTicks now = base::TimeTicks::Now(); - base::TimeDelta queue_delay = - std::max(base::TimeDelta(), next_push_time_ - now); + MediaPipelineBackend::AudioDecoder::RenderingDelay rendering_delay = + backend_->GetRenderingDelay(); + base::TimeDelta delay = + base::TimeDelta::FromMicroseconds(rendering_delay.delay_microseconds); + base::TimeTicks delay_timestamp = + base::TimeTicks() + + base::TimeDelta::FromMicroseconds(rendering_delay.timestamp_microseconds); int frame_count = - source_callback_->OnMoreData(queue_delay, now, 0, audio_bus_.get()); - VLOG(3) << "frames_filled=" << frame_count << " with latency=" << queue_delay; + source_callback_->OnMoreData(delay, delay_timestamp, 0, audio_bus_.get()); + VLOG(3) << "frames_filled=" << frame_count << " with latency=" << delay; DCHECK_EQ(frame_count, audio_bus_->frames()); DCHECK_EQ(static_cast<int>(decoder_buffer_->data_size()),
diff --git a/chromecast/media/audio/cast_audio_output_stream_unittest.cc b/chromecast/media/audio/cast_audio_output_stream_unittest.cc index ec23f03..c1f101e 100644 --- a/chromecast/media/audio/cast_audio_output_stream_unittest.cc +++ b/chromecast/media/audio/cast_audio_output_stream_unittest.cc
@@ -4,21 +4,38 @@ #include "chromecast/media/audio/cast_audio_output_stream.h" +#include <stdint.h> + #include <memory> #include <utility> #include "base/memory/ptr_util.h" #include "base/run_loop.h" +#include "base/time/time.h" #include "chromecast/base/metrics/cast_metrics_test_helper.h" #include "chromecast/media/audio/cast_audio_manager.h" #include "chromecast/public/media/cast_decoder_buffer.h" #include "chromecast/public/media/media_pipeline_backend.h" +#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" +using ::testing::Invoke; +using ::testing::_; + namespace chromecast { namespace media { namespace { const char kDefaultDeviceId[] = ""; +const int64_t kDelayUs = 123; +const int64_t kDelayTimestampUs = 123456789; + +int OnMoreData(base::TimeDelta /* delay */, + base::TimeTicks /* delay_timestamp */, + int /* prior_frames_skipped */, + ::media::AudioBus* dest) { + dest->Zero(); + return dest->frames(); +} class FakeAudioDecoder : public MediaPipelineBackend::AudioDecoder { public: @@ -73,7 +90,7 @@ volume_ = volume; return true; } - RenderingDelay GetRenderingDelay() override { return RenderingDelay(); } + RenderingDelay GetRenderingDelay() override { return rendering_delay_; } const AudioConfig& config() const { return config_; } float volume() const { return volume_; } @@ -84,6 +101,9 @@ } pipeline_status_ = status; } + void set_rendering_delay(RenderingDelay rendering_delay) { + rendering_delay_ = rendering_delay; + } unsigned pushed_buffer_count() const { return pushed_buffer_count_; } CastDecoderBuffer* last_buffer() { return last_buffer_; } @@ -96,6 +116,7 @@ int pushed_buffer_count_; CastDecoderBuffer* last_buffer_; Delegate* delegate_; + RenderingDelay rendering_delay_; }; class FakeMediaPipelineBackend : public MediaPipelineBackend { @@ -147,25 +168,13 @@ std::unique_ptr<FakeAudioDecoder> audio_decoder_; }; -class FakeAudioSourceCallback +class MockAudioSourceCallback : public ::media::AudioOutputStream::AudioSourceCallback { public: - FakeAudioSourceCallback() : error_(false) {} - - bool error() const { return error_; } - // ::media::AudioOutputStream::AudioSourceCallback overrides. - int OnMoreData(base::TimeDelta /* delay */, - base::TimeTicks /* delay_timestamp */, - int /* prior_frames_skipped */, - ::media::AudioBus* dest) override { - dest->Zero(); - return dest->frames(); - } - void OnError(::media::AudioOutputStream* stream) override { error_ = true; } - - private: - bool error_; + MOCK_METHOD4(OnMoreData, + int(base::TimeDelta, base::TimeTicks, int, ::media::AudioBus*)); + MOCK_METHOD1(OnError, void(::media::AudioOutputStream*)); }; class FakeAudioManager : public CastAudioManager { @@ -348,8 +357,9 @@ ASSERT_TRUE(backend); EXPECT_EQ(FakeMediaPipelineBackend::kStateStopped, backend->state()); - std::unique_ptr<FakeAudioSourceCallback> source_callback( - new FakeAudioSourceCallback); + auto source_callback(base::MakeUnique<MockAudioSourceCallback>()); + ON_CALL(*source_callback, OnMoreData(_, _, _, _)) + .WillByDefault(Invoke(OnMoreData)); stream->Start(source_callback.get()); EXPECT_EQ(FakeMediaPipelineBackend::kStateRunning, backend->state()); @@ -371,8 +381,11 @@ EXPECT_EQ(0u, audio_decoder->pushed_buffer_count()); EXPECT_FALSE(audio_decoder->last_buffer()); - std::unique_ptr<FakeAudioSourceCallback> source_callback( - new FakeAudioSourceCallback); + auto source_callback(base::MakeUnique<MockAudioSourceCallback>()); + ON_CALL(*source_callback, OnMoreData(_, _, _, _)) + .WillByDefault(Invoke(OnMoreData)); + // No error must be reported to source callback. + EXPECT_CALL(*source_callback, OnError(_)).Times(0); stream->Start(source_callback.get()); RunMessageLoopFor(2); stream->Stop(); @@ -391,9 +404,6 @@ EXPECT_FALSE(buffer->decrypt_config()); // Null because of raw audio. EXPECT_FALSE(buffer->end_of_stream()); - // No error must be reported to source callback. - EXPECT_FALSE(source_callback->error()); - stream->Close(); } @@ -406,14 +416,15 @@ ASSERT_TRUE(audio_decoder); audio_decoder->set_pipeline_status(FakeAudioDecoder::PIPELINE_STATUS_BUSY); - std::unique_ptr<FakeAudioSourceCallback> source_callback( - new FakeAudioSourceCallback); + auto source_callback(base::MakeUnique<MockAudioSourceCallback>()); + ON_CALL(*source_callback, OnMoreData(_, _, _, _)) + .WillByDefault(Invoke(OnMoreData)); + // No error must be reported to source callback. + EXPECT_CALL(*source_callback, OnError(_)).Times(0); stream->Start(source_callback.get()); RunMessageLoopFor(5); // Make sure that one frame was pushed. EXPECT_EQ(1u, audio_decoder->pushed_buffer_count()); - // No error must be reported to source callback. - EXPECT_FALSE(source_callback->error()); // Sleep for a few frames and verify that more frames were not pushed // because the backend device was busy. @@ -424,7 +435,6 @@ audio_decoder->set_pipeline_status(FakeAudioDecoder::PIPELINE_STATUS_OK); RunMessageLoopFor(5); EXPECT_LT(1u, audio_decoder->pushed_buffer_count()); - EXPECT_FALSE(source_callback->error()); stream->Stop(); stream->Close(); @@ -439,14 +449,15 @@ ASSERT_TRUE(audio_decoder); audio_decoder->set_pipeline_status(FakeAudioDecoder::PIPELINE_STATUS_ERROR); - std::unique_ptr<FakeAudioSourceCallback> source_callback( - new FakeAudioSourceCallback); + auto source_callback(base::MakeUnique<MockAudioSourceCallback>()); + ON_CALL(*source_callback, OnMoreData(_, _, _, _)) + .WillByDefault(Invoke(OnMoreData)); + // AudioOutputStream must report error to source callback. + EXPECT_CALL(*source_callback, OnError(_)); stream->Start(source_callback.get()); RunMessageLoopFor(2); // Make sure that AudioOutputStream attempted to push the initial frame. EXPECT_LT(0u, audio_decoder->pushed_buffer_count()); - // AudioOutputStream must report error to source callback. - EXPECT_TRUE(source_callback->error()); stream->Stop(); stream->Close(); @@ -462,15 +473,16 @@ audio_decoder->set_pipeline_status( FakeAudioDecoder::PIPELINE_STATUS_ASYNC_ERROR); - std::unique_ptr<FakeAudioSourceCallback> source_callback( - new FakeAudioSourceCallback); + auto source_callback(base::MakeUnique<MockAudioSourceCallback>()); + ON_CALL(*source_callback, OnMoreData(_, _, _, _)) + .WillByDefault(Invoke(OnMoreData)); + // AudioOutputStream must report error to source callback. + EXPECT_CALL(*source_callback, OnError(_)); stream->Start(source_callback.get()); RunMessageLoopFor(5); // Make sure that one frame was pushed. EXPECT_EQ(1u, audio_decoder->pushed_buffer_count()); - // AudioOutputStream must report error to source callback. - EXPECT_TRUE(source_callback->error()); stream->Stop(); stream->Close(); @@ -501,8 +513,9 @@ ASSERT_TRUE(stream); ASSERT_TRUE(stream->Open()); - std::unique_ptr<FakeAudioSourceCallback> source_callback( - new FakeAudioSourceCallback); + auto source_callback(base::MakeUnique<MockAudioSourceCallback>()); + ON_CALL(*source_callback, OnMoreData(_, _, _, _)) + .WillByDefault(Invoke(OnMoreData)); stream->Start(source_callback.get()); RunMessageLoopFor(2); stream->Stop(); @@ -523,6 +536,30 @@ stream->Close(); } +TEST_F(CastAudioOutputStreamTest, AudioDelay) { + ::media::AudioOutputStream* stream = CreateStream(); + ASSERT_TRUE(stream); + ASSERT_TRUE(stream->Open()); + + FakeAudioDecoder* audio_decoder = GetAudio(); + ASSERT_TRUE(audio_decoder); + audio_decoder->set_rendering_delay( + MediaPipelineBackend::AudioDecoder::RenderingDelay(kDelayUs, + kDelayTimestampUs)); + + auto source_callback(base::MakeUnique<MockAudioSourceCallback>()); + const base::TimeDelta delay(base::TimeDelta::FromMicroseconds(kDelayUs)); + const base::TimeTicks delay_timestamp( + base::TimeTicks() + base::TimeDelta::FromMicroseconds(kDelayTimestampUs)); + EXPECT_CALL(*source_callback, OnMoreData(delay, delay_timestamp, _, _)) + .WillRepeatedly(Invoke(OnMoreData)); + + stream->Start(source_callback.get()); + RunMessageLoopFor(2); + stream->Stop(); + stream->Close(); +} + } // namespace } // namespace media } // namespace chromecast
diff --git a/chromeos/CHROMEOS_LKGM b/chromeos/CHROMEOS_LKGM index 9fa473d..5f07534b 100644 --- a/chromeos/CHROMEOS_LKGM +++ b/chromeos/CHROMEOS_LKGM
@@ -1 +1 @@ -8988.0.0 \ No newline at end of file +8989.0.0 \ No newline at end of file
diff --git a/chromeos/audio/chromeos_sounds.h b/chromeos/audio/chromeos_sounds.h index 81788e6..c289b6e 100644 --- a/chromeos/audio/chromeos_sounds.h +++ b/chromeos/audio/chromeos_sounds.h
@@ -22,6 +22,8 @@ SOUND_PASSTHROUGH, SOUND_EXIT_SCREEN, SOUND_ENTER_SCREEN, + SOUND_SPOKEN_FEEDBACK_TOGGLE_COUNTDOWN_HIGH, + SOUND_SPOKEN_FEEDBACK_TOGGLE_COUNTDOWN_LOW, SOUND_COUNT, };
diff --git a/chromeos/printing/ppd_cache.cc b/chromeos/printing/ppd_cache.cc index 437d626..6671780 100644 --- a/chromeos/printing/ppd_cache.cc +++ b/chromeos/printing/ppd_cache.cc
@@ -13,6 +13,7 @@ #include "base/memory/ptr_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" +#include "base/threading/thread_restrictions.h" #include "base/time/time.h" #include "base/values.h" #include "crypto/sha2.h" @@ -48,6 +49,7 @@ // Public API functions. base::Optional<base::FilePath> Find( const Printer::PpdReference& reference) const override { + base::ThreadRestrictions::AssertIOAllowed(); base::Optional<base::FilePath> ret; // We can't know here if we have a gzipped or un-gzipped version, so just @@ -91,6 +93,7 @@ } const PpdProvider::AvailablePrintersMap* FindAvailablePrinters() override { + base::ThreadRestrictions::AssertIOAllowed(); if (available_printers_ != nullptr && base::Time::Now() - available_printers_timestamp_ < options_.max_available_list_staleness) { @@ -159,7 +162,8 @@ } if (base::WriteFile(available_printers_file_, contents.data(), contents.size()) != static_cast<int>(contents.size())) { - LOG(ERROR) << "Failed to write available printers cache"; + LOG(ERROR) << "Failed to write available printers cache to " + << available_printers_file_.MaybeAsASCII(); } } @@ -229,7 +233,8 @@ if (!base::ReadFileToStringWithMaxSize( available_printers_file_, buf, options_.max_available_list_cached_size)) { - LOG(ERROR) << "Failed to read printer cache"; + LOG(ERROR) << "Failed to read printer cache from " + << available_printers_file_.MaybeAsASCII(); buf->clear(); return false; }
diff --git a/chromeos/printing/ppd_provider.cc b/chromeos/printing/ppd_provider.cc index c35e213..3d1071a 100644 --- a/chromeos/printing/ppd_provider.cc +++ b/chromeos/printing/ppd_provider.cc
@@ -13,6 +13,7 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" +#include "base/task_runner_util.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/time/time.h" #include "base/values.h" @@ -37,21 +38,23 @@ class PpdProviderImpl; -// URLFetcherDelegate that just forwards the complete callback back to -// the PpdProvider that owns the delegate. +// URLFetcherDelegate that just invokes a callback when the fetch is complete. class ForwardingURLFetcherDelegate : public net::URLFetcherDelegate { public: - explicit ForwardingURLFetcherDelegate(PpdProviderImpl* owner) - : owner_(owner) {} + explicit ForwardingURLFetcherDelegate( + const base::Callback<void()>& done_callback) + : done_callback_(done_callback) {} ~ForwardingURLFetcherDelegate() override {} // URLFetcherDelegate API method. Defined below since we need the // PpdProviderImpl definition first. - void OnURLFetchComplete(const net::URLFetcher* source) override; + void OnURLFetchComplete(const net::URLFetcher* source) override { + done_callback_.Run(); + } private: - // owner of this delegate. - PpdProviderImpl* const owner_; + // Callback to be run on fetch complete. + base::Callback<void()> done_callback_; }; class PpdProviderImpl : public PpdProvider { @@ -59,13 +62,15 @@ PpdProviderImpl( const std::string& api_key, scoped_refptr<net::URLRequestContextGetter> url_context_getter, + scoped_refptr<base::SequencedTaskRunner> io_task_runner, std::unique_ptr<PpdCache> cache, const PpdProvider::Options& options) : api_key_(api_key), - forwarding_delegate_(this), url_context_getter_(url_context_getter), + io_task_runner_(io_task_runner), cache_(std::move(cache)), - options_(options) { + options_(options), + weak_factory_(this) { CHECK_GT(options_.max_ppd_contents_size_, 0U); } ~PpdProviderImpl() override {} @@ -76,83 +81,34 @@ CHECK(resolve_sequence_checker_.CalledOnValidSequence()); CHECK(base::SequencedTaskRunnerHandle::IsSet()) << "Resolve must be called from a SequencedTaskRunner context"; - CHECK(resolve_fetcher_ == nullptr) + CHECK(!resolve_inflight_) << "Can't have concurrent PpdProvider Resolve calls"; - - base::Optional<base::FilePath> tmp = cache_->Find(ppd_reference); - if (tmp) { - // Cache hit. Schedule the callback now and return. - base::SequencedTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(cb, PpdProvider::SUCCESS, tmp.value())); - return; - } - - // We don't have a way to automatically resolve user-supplied PPDs yet. So - // if we have one specified, and it's not cached, we fail out rather than - // fall back to quirks-server based resolution. The reasoning here is that - // if the user has specified a PPD when a quirks-server one exists, it - // probably means the quirks server one doesn't work for some reason, so we - // shouldn't silently use it. - if (!ppd_reference.user_supplied_ppd_url.empty()) { - base::SequencedTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(cb, PpdProvider::NOT_FOUND, base::FilePath())); - return; - } - - resolve_reference_ = ppd_reference; - resolve_done_callback_ = cb; - - resolve_fetcher_ = - net::URLFetcher::Create(GetQuirksServerPpdLookupURL(ppd_reference), - net::URLFetcher::GET, &forwarding_delegate_); - resolve_fetcher_->SetRequestContext(url_context_getter_.get()); - resolve_fetcher_->SetLoadFlags( - net::LOAD_BYPASS_CACHE | net::LOAD_DISABLE_CACHE | - net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES | - net::LOAD_DO_NOT_SEND_AUTH_DATA); - resolve_fetcher_->Start(); - }; - - void AbortResolve() override { - // UrlFetcher guarantees that when the object has been destroyed, no further - // callbacks will occur. - resolve_fetcher_.reset(); + resolve_inflight_ = true; + auto cache_result = base::MakeUnique<base::Optional<base::FilePath>>(); + bool post_result = io_task_runner_->PostTaskAndReply( + FROM_HERE, base::Bind(&PpdProviderImpl::ResolveDoCacheLookup, + weak_factory_.GetWeakPtr(), ppd_reference, + cache_result.get()), + base::Bind(&PpdProviderImpl::ResolveCacheLookupDone, + weak_factory_.GetWeakPtr(), ppd_reference, cb, + std::move(cache_result))); + DCHECK(post_result); } void QueryAvailable(const QueryAvailableCallback& cb) override { CHECK(!cb.is_null()); - CHECK(query_sequence_checker_.CalledOnValidSequence()); CHECK(base::SequencedTaskRunnerHandle::IsSet()) << "QueryAvailable() must be called from a SequencedTaskRunner context"; - CHECK(query_fetcher_ == nullptr) - << "Can't have concurrent PpdProvider QueryAvailable() calls"; - - const PpdProvider::AvailablePrintersMap* result = - cache_->FindAvailablePrinters(); - if (result != nullptr) { - // Satisfy from cache. - base::SequencedTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(cb, PpdProvider::SUCCESS, *result)); - return; - } - // Not in the cache, ask QuirksServer. - query_done_callback_ = cb; - - query_fetcher_ = - net::URLFetcher::Create(GetQuirksServerPpdListURL(), - net::URLFetcher::GET, &forwarding_delegate_); - query_fetcher_->SetRequestContext(url_context_getter_.get()); - query_fetcher_->SetLoadFlags( - net::LOAD_BYPASS_CACHE | net::LOAD_DISABLE_CACHE | - net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES | - net::LOAD_DO_NOT_SEND_AUTH_DATA); - query_fetcher_->Start(); - } - - void AbortQueryAvailable() override { - // UrlFetcher guarantees that when the object has been destroyed, no further - // callbacks will occur. - query_fetcher_.reset(); + auto cache_result = base::MakeUnique< + base::Optional<const PpdProvider::AvailablePrintersMap*>>(); + CHECK(!query_inflight_) + << "Can't have concurrent PpdProvider QueryAvailable calls"; + query_inflight_ = true; + CHECK(io_task_runner_->PostTaskAndReply( + FROM_HERE, base::Bind(&PpdProviderImpl::QueryAvailableDoCacheLookup, + weak_factory_.GetWeakPtr(), cache_result.get()), + base::Bind(&PpdProviderImpl::QueryAvailableCacheLookupDone, + weak_factory_.GetWeakPtr(), cb, std::move(cache_result)))); } bool CachePpd(const Printer::PpdReference& ppd_reference, @@ -165,37 +121,96 @@ return static_cast<bool>(cache_->Store(ppd_reference, buf)); } - // Route to the proper fetch complete handler based on which fetcher caused - // it. - void OnURLFetchComplete(const net::URLFetcher* fetcher) { - if (fetcher == resolve_fetcher_.get()) { - OnResolveFetchComplete(); - } else if (fetcher == query_fetcher_.get()) { - OnQueryAvailableFetchComplete(); + private: + // Trivial wrappers around PpdCache::Find() and + // PpdCache::FindAvailablePrinters(). We need these wrappers both because we + // use weak_ptrs to manage lifetime, and so we need to bind callbacks to + // *this*, and because weak_ptr's preclude return values in posted tasks, so + // we have to use a parameter to return state. + void ResolveDoCacheLookup( + const Printer::PpdReference& reference, + base::Optional<base::FilePath>* cache_result) const { + *cache_result = cache_->Find(reference); + } + + void QueryAvailableDoCacheLookup( + base::Optional<const PpdProvider::AvailablePrintersMap*>* cache_result) + const { + auto tmp = cache_->FindAvailablePrinters(); + if (tmp != nullptr) { + *cache_result = tmp; } else { - NOTREACHED() << "Unknown fetcher completed."; + *cache_result = base::nullopt; } } - private: + // Callback that happens when the Resolve() cache lookup completes. If the + // cache satisfied the request, finish the Resolve, otherwise start a URL + // request to satisfy the request. This runs on the same thread as Resolve() + // was invoked on. + void ResolveCacheLookupDone( + const Printer::PpdReference& ppd_reference, + const PpdProvider::ResolveCallback& done_callback, + const std::unique_ptr<base::Optional<base::FilePath>>& cache_result) { + CHECK(resolve_sequence_checker_.CalledOnValidSequence()); + if (*cache_result) { + // Cache hit. Schedule the callback now and return. + resolve_inflight_ = false; + done_callback.Run(PpdProvider::SUCCESS, cache_result->value()); + return; + } + + // We don't have a way to automatically resolve user-supplied PPDs yet. So + // if we have one specified, and it's not cached, we fail out rather than + // fall back to quirks-server based resolution. The reasoning here is that + // if the user has specified a PPD when a quirks-server one exists, it + // probably means the quirks server one doesn't work for some reason, so we + // shouldn't silently use it. + if (!ppd_reference.user_supplied_ppd_url.empty()) { + resolve_inflight_ = false; + done_callback.Run(PpdProvider::NOT_FOUND, base::FilePath()); + return; + } + + // Missed in the cache, so start a URLRequest to resolve the request. + resolve_fetcher_delegate_ = base::MakeUnique<ForwardingURLFetcherDelegate>( + base::Bind(&PpdProviderImpl::OnResolveFetchComplete, + weak_factory_.GetWeakPtr(), ppd_reference, done_callback)); + + resolve_fetcher_ = net::URLFetcher::Create( + GetQuirksServerPpdLookupURL(ppd_reference), net::URLFetcher::GET, + resolve_fetcher_delegate_.get()); + + resolve_fetcher_->SetRequestContext(url_context_getter_.get()); + resolve_fetcher_->SetLoadFlags( + net::LOAD_BYPASS_CACHE | net::LOAD_DISABLE_CACHE | + net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES | + net::LOAD_DO_NOT_SEND_AUTH_DATA); + resolve_fetcher_->Start(); + } + // Called on the same thread as Resolve() when the fetcher completes its // fetch. - void OnResolveFetchComplete() { + void OnResolveFetchComplete( + const Printer::PpdReference& ppd_reference, + const PpdProvider::ResolveCallback& done_callback) { CHECK(resolve_sequence_checker_.CalledOnValidSequence()); - // Scope the allocated |resolve_fetcher_| into this function so we clean it - // up when we're done here instead of leaving it around until the next - // Resolve() call. - auto fetcher = std::move(resolve_fetcher_); + // Scope the allocated |resolve_fetcher_| and |resolve_fetcher_delegate_| + // into this function so we clean it up when we're done here instead of + // leaving it around until the next Resolve() call. + auto fetcher_delegate(std::move(resolve_fetcher_delegate_)); + auto fetcher(std::move(resolve_fetcher_)); + resolve_inflight_ = false; std::string contents; if (!ValidateAndGetResponseAsString(*fetcher, &contents)) { // Something went wrong with the fetch. - resolve_done_callback_.Run(PpdProvider::SERVER_ERROR, base::FilePath()); + done_callback.Run(PpdProvider::SERVER_ERROR, base::FilePath()); return; } auto dict = base::DictionaryValue::From(base::JSONReader::Read(contents)); if (dict == nullptr) { - resolve_done_callback_.Run(PpdProvider::SERVER_ERROR, base::FilePath()); + done_callback.Run(PpdProvider::SERVER_ERROR, base::FilePath()); return; } std::string ppd_contents; @@ -205,7 +220,7 @@ dict->GetString(kJSONLastUpdatedKey, &last_updated_time_string) && base::StringToUint64(last_updated_time_string, &last_updated_time))) { // Malformed response. TODO(justincarlson) - LOG something here? - resolve_done_callback_.Run(PpdProvider::SERVER_ERROR, base::FilePath()); + done_callback.Run(PpdProvider::SERVER_ERROR, base::FilePath()); return; } @@ -217,32 +232,63 @@ // check *uncompressed* size here to head off zip-bombs (e.g. let's // compress 1GBs of zeros into a 900kb file and see what cups does when it // tries to expand that...) - resolve_done_callback_.Run(PpdProvider::SERVER_ERROR, base::FilePath()); + done_callback.Run(PpdProvider::SERVER_ERROR, base::FilePath()); return; } - auto ppd_file = cache_->Store(resolve_reference_, ppd_contents); + auto ppd_file = cache_->Store(ppd_reference, ppd_contents); if (!ppd_file) { // Failed to store. - resolve_done_callback_.Run(PpdProvider::INTERNAL_ERROR, base::FilePath()); + done_callback.Run(PpdProvider::INTERNAL_ERROR, base::FilePath()); return; } - resolve_done_callback_.Run(PpdProvider::SUCCESS, ppd_file.value()); + done_callback.Run(PpdProvider::SUCCESS, ppd_file.value()); } - // Called on the same thread as QueryAvailable() when the fetcher completes - // its fetch. - void OnQueryAvailableFetchComplete() { + // Called on the same thread as QueryAvailable() when the cache lookup is + // done. If the cache satisfied the request, finish the Query, otherwise + // start a URL request to satisfy the Query. This runs on the same thread as + // QueryAvailable() was invoked on. + void QueryAvailableCacheLookupDone( + const PpdProvider::QueryAvailableCallback& done_callback, + const std::unique_ptr< + base::Optional<const PpdProvider::AvailablePrintersMap*>>& + cache_result) { CHECK(query_sequence_checker_.CalledOnValidSequence()); - // Scope the object fetcher into this function so we clean it up when we're - // done here instead of leaving it around until the next QueryAvailable() - // call. - auto fetcher = std::move(query_fetcher_); + if (*cache_result) { + query_inflight_ = false; + done_callback.Run(PpdProvider::SUCCESS, *cache_result->value()); + return; + } + // Missed in the cache, start a query. + query_fetcher_delegate_ = base::MakeUnique<ForwardingURLFetcherDelegate>( + base::Bind(&PpdProviderImpl::OnQueryAvailableFetchComplete, + weak_factory_.GetWeakPtr(), done_callback)); + + query_fetcher_ = net::URLFetcher::Create(GetQuirksServerPpdListURL(), + net::URLFetcher::GET, + query_fetcher_delegate_.get()); + query_fetcher_->SetRequestContext(url_context_getter_.get()); + query_fetcher_->SetLoadFlags( + net::LOAD_BYPASS_CACHE | net::LOAD_DISABLE_CACHE | + net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES | + net::LOAD_DO_NOT_SEND_AUTH_DATA); + query_fetcher_->Start(); + } + + void OnQueryAvailableFetchComplete( + const PpdProvider::QueryAvailableCallback& done_callback) { + CHECK(query_sequence_checker_.CalledOnValidSequence()); + // Scope the object fetcher and task_runner into this function so we clean + // it up when we're done here instead of leaving it around until the next + // QueryAvailable() call. + auto fetcher_delegate(std::move(query_fetcher_delegate_)); + auto fetcher(std::move(query_fetcher_)); + query_inflight_ = false; std::string contents; if (!ValidateAndGetResponseAsString(*fetcher, &contents)) { // Something went wrong with the fetch. - query_done_callback_.Run(PpdProvider::SERVER_ERROR, - AvailablePrintersMap()); + done_callback.Run(PpdProvider::SERVER_ERROR, AvailablePrintersMap()); return; } @@ -253,8 +299,7 @@ const base::ListValue* top_list; if (top_dict == nullptr || !top_dict->GetList(kJSONTopListKey, &top_list)) { LOG(ERROR) << "Malformed response from quirks server"; - query_done_callback_.Run(PpdProvider::SERVER_ERROR, - PpdProvider::AvailablePrintersMap()); + done_callback.Run(PpdProvider::SERVER_ERROR, AvailablePrintersMap()); return; } @@ -282,7 +327,7 @@ } } } - query_done_callback_.Run(PpdProvider::SUCCESS, *result); + done_callback.Run(PpdProvider::SUCCESS, *result); if (!result->empty()) { cache_->StoreAvailablePrinters(std::move(result)); } else { @@ -323,46 +368,45 @@ // State held across a Resolve() call. - // Reference we're currently trying to resolve. - Printer::PpdReference resolve_reference_; - - // Callback to invoke on completion. - PpdProvider::ResolveCallback resolve_done_callback_; - // Check that Resolve() and its callback are sequenced appropriately. base::SequenceChecker resolve_sequence_checker_; - // Fetcher for the current call, if any. + // Fetcher and associated delegate for the current Resolve() call, if a fetch + // is in progress. These are both null if no Resolve() is in flight. std::unique_ptr<net::URLFetcher> resolve_fetcher_; + std::unique_ptr<ForwardingURLFetcherDelegate> resolve_fetcher_delegate_; + // Is there a current Resolve() inflight? Used to help fail-fast in the case + // of inappropriate concurrent usage. + bool resolve_inflight_ = false; // State held across a QueryAvailable() call. - // Callback to invoke on completion. - PpdProvider::QueryAvailableCallback query_done_callback_; - // Check that QueryAvailable() and its callback are sequenced appropriately. base::SequenceChecker query_sequence_checker_; - // Fetcher for the current call, if any. + // Fetcher and associated delegate for the current QueryAvailable() call, if a + // fetch is in progress. These are both null if no QueryAvailable() is in + // flight. std::unique_ptr<net::URLFetcher> query_fetcher_; + std::unique_ptr<ForwardingURLFetcherDelegate> query_fetcher_delegate_; + // Is there a current QueryAvailable() inflight? Used to help fail-fast in + // the case of inappropriate concurrent usage. + bool query_inflight_ = false; // Common state. // API key for accessing quirks server. const std::string api_key_; - ForwardingURLFetcherDelegate forwarding_delegate_; scoped_refptr<net::URLRequestContextGetter> url_context_getter_; + scoped_refptr<base::SequencedTaskRunner> io_task_runner_; std::unique_ptr<PpdCache> cache_; // Construction-time options, immutable. const PpdProvider::Options options_; -}; -void ForwardingURLFetcherDelegate::OnURLFetchComplete( - const net::URLFetcher* source) { - owner_->OnURLFetchComplete(source); -} + base::WeakPtrFactory<PpdProviderImpl> weak_factory_; +}; } // namespace @@ -370,10 +414,11 @@ std::unique_ptr<PpdProvider> PpdProvider::Create( const std::string& api_key, scoped_refptr<net::URLRequestContextGetter> url_context_getter, + scoped_refptr<base::SequencedTaskRunner> io_task_runner, std::unique_ptr<PpdCache> cache, const PpdProvider::Options& options) { - return base::MakeUnique<PpdProviderImpl>(api_key, url_context_getter, - std::move(cache), options); + return base::MakeUnique<PpdProviderImpl>( + api_key, url_context_getter, io_task_runner, std::move(cache), options); } } // namespace printing
diff --git a/chromeos/printing/ppd_provider.h b/chromeos/printing/ppd_provider.h index ff6d6d3d..917e5a1 100644 --- a/chromeos/printing/ppd_provider.h +++ b/chromeos/printing/ppd_provider.h
@@ -12,6 +12,7 @@ #include "base/callback.h" #include "base/files/file_path.h" +#include "base/sequenced_task_runner.h" #include "chromeos/chromeos_export.h" #include "chromeos/printing/printer_configuration.h" @@ -75,9 +76,13 @@ }; // Create and return a new PpdProvider with the given cache and options. + // |io_task_runner| is used to run operations that are long latency and should + // not be on the UI thread. References to |url_context_getter| and + // |io_task_runner| are taken. static std::unique_ptr<PpdProvider> Create( const std::string& api_key, scoped_refptr<net::URLRequestContextGetter> url_context_getter, + scoped_refptr<base::SequencedTaskRunner> io_task_runner, std::unique_ptr<PpdCache> cache, const Options& options = Options()); @@ -90,15 +95,10 @@ // // |cb| will only be called after the task invoking Resolve() is finished. // - // Only one Resolve() call should be outstanding at a time. + // Only one Resolve() call may be outstanding at a time. virtual void Resolve(const Printer::PpdReference& ppd_reference, const ResolveCallback& cb) = 0; - // Abort any outstanding Resolve() call. After this returns, it is guaranteed - // that no ResolveCallback will be called until the next time Resolve is - // called. It is a nop to call this if no Resolve() is outstanding. - virtual void AbortResolve() = 0; - // Get all the printer makes and models we can support. // // Must be called from a Sequenced Task context (i.e. @@ -107,15 +107,9 @@ // |cb| will only be called after the task invoking QueryAvailable() is // finished. // - // Only one QueryAvailable() call should be outstanding at a time. + // Only one QueryAvailable() call may be outstanding at a time. virtual void QueryAvailable(const QueryAvailableCallback& cb) = 0; - // Abort any outstanding QueryAvailable() call. After this returns, it is - // guaranteed that no QueryAvailableCallback will be called until the next - // time QueryAvailable() is called. It is a nop to call this if no - // QueryAvailable() is outstanding. - virtual void AbortQueryAvailable() = 0; - // Most of the time, the cache is just an invisible backend to the Provider, // consulted at Resolve time, but in the case of the user doing "Add Printer" // and "Select PPD" locally, then we get into a state where we want to put
diff --git a/chromeos/printing/ppd_provider_unittest.cc b/chromeos/printing/ppd_provider_unittest.cc index 7061f156..15d9e81 100644 --- a/chromeos/printing/ppd_provider_unittest.cc +++ b/chromeos/printing/ppd_provider_unittest.cc
@@ -74,7 +74,7 @@ auto provider_options = PpdProvider::Options(); provider_options.quirks_server = kTestQuirksServer; ppd_provider_ = PpdProvider::Create( - kTestAPIKey, request_context_getter_, + kTestAPIKey, request_context_getter_.get(), loop_.task_runner().get(), PpdCache::Create(ppd_cache_temp_dir_.GetPath()), provider_options); }
diff --git a/components/autofill/content/renderer/autofill_agent.cc b/components/autofill/content/renderer/autofill_agent.cc index 6de7579d..49cf672 100644 --- a/components/autofill/content/renderer/autofill_agent.cc +++ b/components/autofill/content/renderer/autofill_agent.cc
@@ -43,6 +43,7 @@ #include "net/cert/cert_status_flags.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "services/service_manager/public/cpp/interface_registry.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/platform/WebURLRequest.h" #include "third_party/WebKit/public/web/WebConsoleMessage.h" #include "third_party/WebKit/public/web/WebDataSource.h" @@ -50,7 +51,6 @@ #include "third_party/WebKit/public/web/WebElementCollection.h" #include "third_party/WebKit/public/web/WebFormControlElement.h" #include "third_party/WebKit/public/web/WebFormElement.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebNode.h" #include "third_party/WebKit/public/web/WebOptionElement.h"
diff --git a/components/autofill/content/renderer/page_click_tracker.cc b/components/autofill/content/renderer/page_click_tracker.cc index 84de46b..da70ec2 100644 --- a/components/autofill/content/renderer/page_click_tracker.cc +++ b/components/autofill/content/renderer/page_click_tracker.cc
@@ -10,13 +10,13 @@ #include "components/autofill/core/common/autofill_util.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_view.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/platform/WebPoint.h" #include "third_party/WebKit/public/platform/WebSize.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebFormControlElement.h" #include "third_party/WebKit/public/web/WebHitTestResult.h" #include "third_party/WebKit/public/web/WebInputElement.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebUserGestureIndicator.h" #include "third_party/WebKit/public/web/WebView.h"
diff --git a/components/autofill/content/renderer/password_autofill_agent.cc b/components/autofill/content/renderer/password_autofill_agent.cc index 952033b1..25edf2c8 100644 --- a/components/autofill/content/renderer/password_autofill_agent.cc +++ b/components/autofill/content/renderer/password_autofill_agent.cc
@@ -33,13 +33,13 @@ #include "content/public/renderer/render_view.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "services/service_manager/public/cpp/interface_registry.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/platform/WebSecurityOrigin.h" #include "third_party/WebKit/public/platform/WebVector.h" #include "third_party/WebKit/public/web/WebAutofillClient.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebElement.h" #include "third_party/WebKit/public/web/WebFormElement.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebNode.h" #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
diff --git a/components/autofill/core/browser/form_structure.cc b/components/autofill/core/browser/form_structure.cc index 3b2d93a..cf4ae5c 100644 --- a/components/autofill/core/browser/form_structure.cc +++ b/components/autofill/core/browser/form_structure.cc
@@ -605,7 +605,7 @@ // Rule out http(s)://*/search?... // e.g. http://www.google.com/search?q=... // http://search.yahoo.com/search?p=... - if (target_url_.path() == "/search") + if (target_url_.path_piece() == "/search") return false; bool has_text_field = false;
diff --git a/components/certificate_reporting/error_reporter.cc b/components/certificate_reporting/error_reporter.cc index 3e639ea..02cded5 100644 --- a/components/certificate_reporting/error_reporter.cc +++ b/components/certificate_reporting/error_reporter.cc
@@ -112,14 +112,11 @@ net::URLRequestContext* request_context, const GURL& upload_url, net::ReportSender::CookiesPreference cookies_preference) - : ErrorReporter( - upload_url, - kServerPublicKey, - kServerPublicKeyVersion, - base::MakeUnique<net::ReportSender>(request_context, - cookies_preference, - base::Bind(RecordUMAOnFailure))) { -} + : ErrorReporter(upload_url, + kServerPublicKey, + kServerPublicKeyVersion, + base::MakeUnique<net::ReportSender>(request_context, + cookies_preference)) {} ErrorReporter::ErrorReporter( const GURL& upload_url, @@ -140,7 +137,8 @@ const std::string& serialized_report) { if (upload_url_.SchemeIsCryptographic()) { certificate_report_sender_->Send(upload_url_, "application/octet-stream", - serialized_report); + serialized_report, base::Closure(), + base::Bind(&RecordUMAOnFailure)); } else { EncryptedCertLoggerRequest encrypted_report; if (!EncryptSerializedReport(server_public_key_, server_public_key_version_, @@ -150,8 +148,9 @@ } std::string serialized_encrypted_report; encrypted_report.SerializeToString(&serialized_encrypted_report); - certificate_report_sender_->Send(upload_url_, "application/octet-stream", - serialized_encrypted_report); + certificate_report_sender_->Send( + upload_url_, "application/octet-stream", serialized_encrypted_report, + base::Closure(), base::Bind(&RecordUMAOnFailure)); } }
diff --git a/components/certificate_reporting/error_reporter_unittest.cc b/components/certificate_reporting/error_reporter_unittest.cc index 6e83ca1..2b53409 100644 --- a/components/certificate_reporting/error_reporter_unittest.cc +++ b/components/certificate_reporting/error_reporter_unittest.cc
@@ -42,19 +42,24 @@ : net::ReportSender(nullptr, DO_NOT_SEND_COOKIES) {} ~MockCertificateReportSender() override {} - void Send(const GURL& report_uri, - base::StringPiece content_type, - base::StringPiece report) override { + void Send( + const GURL& report_uri, + base::StringPiece content_type, + base::StringPiece report, + const base::Callback<void()>& success_callback, + const base::Callback<void(const GURL&, int)>& error_callback) override { latest_report_uri_ = report_uri; report.CopyToString(&latest_report_); content_type.CopyToString(&latest_content_type_); } - const GURL& latest_report_uri() { return latest_report_uri_; } + const GURL& latest_report_uri() const { return latest_report_uri_; } - const std::string& latest_report() { return latest_report_; } + const std::string& latest_report() const { return latest_report_; } - const std::string& latest_content_type() { return latest_content_type_; } + const std::string& latest_content_type() const { + return latest_content_type_; + } private: GURL latest_report_uri_;
diff --git a/components/cloud_devices/common/cloud_devices_urls.cc b/components/cloud_devices/common/cloud_devices_urls.cc index 7b4b711..b08cc6f0 100644 --- a/components/cloud_devices/common/cloud_devices_urls.cc +++ b/components/cloud_devices/common/cloud_devices_urls.cc
@@ -77,9 +77,9 @@ } bool IsCloudPrintURL(const GURL& url) { - GURL cloud_print_url = GetCloudPrintURL(); - return url.host() == cloud_print_url.host() && - url.scheme() == cloud_print_url.scheme() && + const GURL& cloud_print_url = GetCloudPrintURL(); + return url.host_piece() == cloud_print_url.host_piece() && + url.scheme_piece() == cloud_print_url.scheme_piece() && base::StartsWith(url.path(), cloud_print_url.path(), base::CompareCase::SENSITIVE); }
diff --git a/components/component_updater/BUILD.gn b/components/component_updater/BUILD.gn index 1b5b142a..210a6be 100644 --- a/components/component_updater/BUILD.gn +++ b/components/component_updater/BUILD.gn
@@ -21,8 +21,6 @@ "pref_names.h", "timer.cc", "timer.h", - "updater_state_win.cc", - "updater_state_win.h", ] deps = [ @@ -55,7 +53,6 @@ "configurator_impl_unittest.cc", "default_component_installer_unittest.cc", "timer_unittest.cc", - "updater_state_unittest_win.cc", ] deps = [
diff --git a/components/component_updater/component_updater_service.cc b/components/component_updater/component_updater_service.cc index d6c4261..b8b27ba 100644 --- a/components/component_updater/component_updater_service.cc +++ b/components/component_updater/component_updater_service.cc
@@ -29,9 +29,6 @@ #include "base/timer/timer.h" #include "components/component_updater/component_updater_service_internal.h" #include "components/component_updater/timer.h" -#if defined(OS_WIN) -#include "components/component_updater/updater_state_win.h" -#endif #include "components/update_client/configurator.h" #include "components/update_client/crx_update_item.h" #include "components/update_client/update_client.h" @@ -50,8 +47,6 @@ UPDATE_TYPE_COUNT, }; -const char kRecoveryComponentId[] = "npdjjkjlcidkjlamlmmdelcjbcpdjocm"; - } // namespace namespace component_updater { @@ -361,17 +356,8 @@ for (const auto& id : ids) { const update_client::CrxComponent* registered_component(GetComponent(id)); - if (registered_component) { + if (registered_component) components->push_back(*registered_component); - if (id == kRecoveryComponentId) { - // Override the installer attributes for the recovery component in the - // components which will be checked for updates. - update_client::CrxComponent& recovery_component(components->back()); - recovery_component.installer_attributes = - GetInstallerAttributesForRecoveryComponentInstaller( - recovery_component); - } - } } } @@ -432,25 +418,6 @@ } } -update_client::InstallerAttributes -CrxUpdateService::GetInstallerAttributesForRecoveryComponentInstaller( - const CrxComponent& crx_component) const { - update_client::InstallerAttributes installer_attributes; -#if defined(OS_WIN) - DCHECK_EQ("recovery", crx_component.name); - - const bool is_machine = - crx_component.installer_attributes.count("ismachine") && - crx_component.installer_attributes.at("ismachine") == "1"; - - auto updater_state(UpdaterState::Create(is_machine)); - if (updater_state) { - installer_attributes = updater_state->MakeInstallerAttributes(); - } -#endif - return installer_attributes; -} - /////////////////////////////////////////////////////////////////////////////// // The component update factory. Using the component updater as a singleton
diff --git a/components/component_updater/component_updater_service_internal.h b/components/component_updater/component_updater_service_internal.h index d8776cb..f25bbc9 100644 --- a/components/component_updater/component_updater_service_internal.h +++ b/components/component_updater/component_updater_service_internal.h
@@ -84,12 +84,6 @@ const base::TimeTicks& start_time, update_client::Error error); - // Returns the map of installer attributes for the recovery component - // installer. This data corresponds to the Omaha updater state and it is - // serialized as part of the update check for the recovery component. - update_client::InstallerAttributes - GetInstallerAttributesForRecoveryComponentInstaller( - const CrxComponent& crx_component) const; base::ThreadChecker thread_checker_; scoped_refptr<Configurator> config_;
diff --git a/components/component_updater/updater_state_unittest_win.cc b/components/component_updater/updater_state_unittest_win.cc deleted file mode 100644 index bda3094..0000000 --- a/components/component_updater/updater_state_unittest_win.cc +++ /dev/null
@@ -1,103 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/macros.h" -#include "base/time/time.h" -#include "base/version.h" -#include "components/component_updater/updater_state_win.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace component_updater { - -class UpdaterStateTest : public testing::Test { - public: - UpdaterStateTest() {} - ~UpdaterStateTest() override {} - - private: - DISALLOW_COPY_AND_ASSIGN(UpdaterStateTest); -}; - -TEST_F(UpdaterStateTest, MakeInstallerAttributes) { - // is_machine argument does not make a difference in this test as, the - // values of the |updater_state| are fake. - auto updater_state = UpdaterState::Create(false); - - // Sanity check all members. - updater_state->google_update_version_ = base::Version("1.0"); - updater_state->last_autoupdate_started_ = base::Time::NowFromSystemTime(); - updater_state->last_checked_ = base::Time::NowFromSystemTime(); - updater_state->is_joined_to_domain_ = false; - updater_state->is_autoupdate_check_enabled_ = true; - updater_state->chrome_update_policy_ = 1; - - auto installer_attributes = updater_state->MakeInstallerAttributes(); - - EXPECT_STREQ("1.0", installer_attributes.at("googleupdatever").c_str()); - EXPECT_STREQ("0", installer_attributes.at("laststarted").c_str()); - EXPECT_STREQ("0", installer_attributes.at("lastchecked").c_str()); - EXPECT_STREQ("0", installer_attributes.at("domainjoined").c_str()); - EXPECT_STREQ("1", installer_attributes.at("autoupdatecheckenabled").c_str()); - EXPECT_STREQ("1", installer_attributes.at("chromeupdatepolicy").c_str()); - - // Tests some of the remaining values. - updater_state = UpdaterState::Create(false); - - // Don't serialize an invalid version if it could not be read. - updater_state->google_update_version_ = base::Version(); - installer_attributes = updater_state->MakeInstallerAttributes(); - EXPECT_EQ(0u, installer_attributes.count("googleupdatever")); - - updater_state->google_update_version_ = base::Version("0.0.0.0"); - installer_attributes = updater_state->MakeInstallerAttributes(); - EXPECT_STREQ("0.0.0.0", installer_attributes.at("googleupdatever").c_str()); - - updater_state->last_autoupdate_started_ = - base::Time::NowFromSystemTime() - base::TimeDelta::FromDays(15); - installer_attributes = updater_state->MakeInstallerAttributes(); - EXPECT_STREQ("408", installer_attributes.at("laststarted").c_str()); - - updater_state->last_autoupdate_started_ = - base::Time::NowFromSystemTime() - base::TimeDelta::FromDays(90); - installer_attributes = updater_state->MakeInstallerAttributes(); - EXPECT_STREQ("1344", installer_attributes.at("laststarted").c_str()); - - // Don't serialize the time if it could not be read. - updater_state->last_autoupdate_started_ = base::Time(); - installer_attributes = updater_state->MakeInstallerAttributes(); - EXPECT_EQ(0u, installer_attributes.count("laststarted")); - - updater_state->last_checked_ = - base::Time::NowFromSystemTime() - base::TimeDelta::FromDays(15); - installer_attributes = updater_state->MakeInstallerAttributes(); - EXPECT_STREQ("408", installer_attributes.at("lastchecked").c_str()); - - updater_state->last_checked_ = - base::Time::NowFromSystemTime() - base::TimeDelta::FromDays(90); - installer_attributes = updater_state->MakeInstallerAttributes(); - EXPECT_STREQ("1344", installer_attributes.at("lastchecked").c_str()); - - // Don't serialize the time if it could not be read. - updater_state->last_checked_ = base::Time(); - installer_attributes = updater_state->MakeInstallerAttributes(); - EXPECT_EQ(0u, installer_attributes.count("lastchecked")); - - updater_state->is_joined_to_domain_ = true; - installer_attributes = updater_state->MakeInstallerAttributes(); - EXPECT_STREQ("1", installer_attributes.at("domainjoined").c_str()); - - updater_state->is_autoupdate_check_enabled_ = false; - installer_attributes = updater_state->MakeInstallerAttributes(); - EXPECT_STREQ("0", installer_attributes.at("autoupdatecheckenabled").c_str()); - - updater_state->chrome_update_policy_ = 0; - installer_attributes = updater_state->MakeInstallerAttributes(); - EXPECT_STREQ("0", installer_attributes.at("chromeupdatepolicy").c_str()); - - updater_state->chrome_update_policy_ = -1; - installer_attributes = updater_state->MakeInstallerAttributes(); - EXPECT_STREQ("-1", installer_attributes.at("chromeupdatepolicy").c_str()); -} - -} // namespace component_updater
diff --git a/components/component_updater/updater_state_win.cc b/components/component_updater/updater_state_win.cc deleted file mode 100644 index b7fd10f7..0000000 --- a/components/component_updater/updater_state_win.cc +++ /dev/null
@@ -1,195 +0,0 @@ - -// Copyright (c) 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/component_updater/updater_state_win.h" - -#include <utility> - -#include "base/memory/ptr_util.h" -#include "base/strings/string16.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/utf_string_conversions.h" - -#include "base/win/registry.h" -#include "base/win/win_util.h" - -namespace component_updater { - -namespace { - -// Google Update group policy settings. -const wchar_t kGoogleUpdatePoliciesKey[] = - L"SOFTWARE\\Policies\\Google\\Update"; -const wchar_t kCheckPeriodOverrideMinutes[] = L"AutoUpdateCheckPeriodMinutes"; -const wchar_t kUpdatePolicyValue[] = L"UpdateDefault"; -const wchar_t kChromeUpdatePolicyOverride[] = - L"Update{8A69D345-D564-463C-AFF1-A69D9E530F96}"; - -// Don't allow update periods longer than six weeks (Chrome release cadence). -const int kCheckPeriodOverrideMinutesMax = 60 * 24 * 7 * 6; - -// Google Update registry settings. -const wchar_t kRegPathGoogleUpdate[] = L"Software\\Google\\Update"; -const wchar_t kRegPathClientsGoogleUpdate[] = - L"Software\\Google\\Update\\Clients\\" - L"{430FD4D0-B729-4F61-AA34-91526481799D}"; -const wchar_t kRegValueGoogleUpdatePv[] = L"pv"; -const wchar_t kRegValueLastStartedAU[] = L"LastStartedAU"; -const wchar_t kRegValueLastChecked[] = L"LastChecked"; - -} // namespace - -UpdaterState::UpdaterState(bool is_machine) : is_machine_(is_machine) {} - -std::unique_ptr<UpdaterState> UpdaterState::Create(bool is_machine) { - std::unique_ptr<UpdaterState> updater_state(new UpdaterState(is_machine)); - updater_state->ReadState(); - return updater_state; -} - -void UpdaterState::ReadState() { - google_update_version_ = GetGoogleUpdateVersion(is_machine_); - last_autoupdate_started_ = GetGoogleUpdateLastStartedAU(is_machine_); - last_checked_ = GetGoogleUpdateLastChecked(is_machine_); - is_joined_to_domain_ = IsJoinedToDomain(); - is_autoupdate_check_enabled_ = IsAutoupdateCheckEnabled(); - chrome_update_policy_ = GetChromeUpdatePolicy(); -} - -update_client::InstallerAttributes UpdaterState::MakeInstallerAttributes() - const { - update_client::InstallerAttributes installer_attributes; - - if (google_update_version_.IsValid()) - installer_attributes["googleupdatever"] = - google_update_version_.GetString(); - - const base::Time now = base::Time::NowFromSystemTime(); - if (!last_autoupdate_started_.is_null()) - installer_attributes["laststarted"] = - NormalizeTimeDelta(now - last_autoupdate_started_); - if (!last_checked_.is_null()) - installer_attributes["lastchecked"] = - NormalizeTimeDelta(now - last_checked_); - - installer_attributes["domainjoined"] = is_joined_to_domain_ ? "1" : "0"; - installer_attributes["autoupdatecheckenabled"] = - is_autoupdate_check_enabled_ ? "1" : "0"; - - DCHECK(chrome_update_policy_ >= 0 && chrome_update_policy_ <= 3 || - chrome_update_policy_ == -1); - installer_attributes["chromeupdatepolicy"] = - base::IntToString(chrome_update_policy_); - - return installer_attributes; -} - -std::string UpdaterState::NormalizeTimeDelta(const base::TimeDelta& delta) { - const base::TimeDelta two_weeks = base::TimeDelta::FromDays(14); - const base::TimeDelta two_months = base::TimeDelta::FromDays(60); - - std::string val; // Contains the value to return in hours. - if (delta <= two_weeks) { - val = "0"; - } else if (two_weeks < delta && delta <= two_months) { - val = "408"; // 2 weeks in hours. - } else { - val = "1344"; // 2*28 days in hours. - } - - DCHECK(!val.empty()); - return val; -} - -base::Version UpdaterState::GetGoogleUpdateVersion(bool is_machine) { - const HKEY root_key = is_machine ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; - base::string16 version; - base::win::RegKey key; - - if (key.Open(root_key, kRegPathClientsGoogleUpdate, - KEY_QUERY_VALUE | KEY_WOW64_32KEY) == ERROR_SUCCESS && - key.ReadValue(kRegValueGoogleUpdatePv, &version) == ERROR_SUCCESS) { - return base::Version(base::UTF16ToUTF8(version)); - } - - return base::Version(); -} - -base::Time UpdaterState::GetGoogleUpdateLastStartedAU(bool is_machine) { - return GetGoogleUpdateTimeValue(is_machine, kRegValueLastStartedAU); -} - -base::Time UpdaterState::GetGoogleUpdateLastChecked(bool is_machine) { - return GetGoogleUpdateTimeValue(is_machine, kRegValueLastChecked); -} - -base::Time UpdaterState::GetGoogleUpdateTimeValue(bool is_machine, - const wchar_t* value_name) { - const HKEY root_key = is_machine ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; - base::win::RegKey update_key; - - if (update_key.Open(root_key, kRegPathGoogleUpdate, - KEY_QUERY_VALUE | KEY_WOW64_32KEY) == ERROR_SUCCESS) { - DWORD value(0); - if (update_key.ReadValueDW(value_name, &value) == ERROR_SUCCESS) { - return base::Time::FromTimeT(value); - } - } - - return base::Time(); -} - -bool UpdaterState::IsAutoupdateCheckEnabled() { - // Check the auto-update check period override. If it is 0 or exceeds the - // maximum timeout, then for all intents and purposes auto updates are - // disabled. - base::win::RegKey policy_key; - DWORD value = 0; - if (policy_key.Open(HKEY_LOCAL_MACHINE, kGoogleUpdatePoliciesKey, - KEY_QUERY_VALUE) == ERROR_SUCCESS && - policy_key.ReadValueDW(kCheckPeriodOverrideMinutes, &value) == - ERROR_SUCCESS && - (value == 0 || value > kCheckPeriodOverrideMinutesMax)) { - return false; - } - - return true; -} - -// Returns -1 if the policy is not found or the value was invalid. Otherwise, -// returns a value in the [0, 3] range, representing the value of the -// Chrome update group policy. -int UpdaterState::GetChromeUpdatePolicy() { - const int kMaxUpdatePolicyValue = 3; - - base::win::RegKey policy_key; - - if (policy_key.Open(HKEY_LOCAL_MACHINE, kGoogleUpdatePoliciesKey, - KEY_QUERY_VALUE) != ERROR_SUCCESS) { - return -1; - } - - DWORD value = 0; - // First try to read the Chrome-specific override. - if (policy_key.ReadValueDW(kChromeUpdatePolicyOverride, &value) == - ERROR_SUCCESS && - value <= kMaxUpdatePolicyValue) { - return value; - } - - // Try to read default override. - if (policy_key.ReadValueDW(kUpdatePolicyValue, &value) == ERROR_SUCCESS && - value <= kMaxUpdatePolicyValue) { - return value; - } - - return -1; -} - -bool UpdaterState::IsJoinedToDomain() { - return base::win::IsEnrolledToDomain(); -} - -} // namespace component_updater
diff --git a/components/component_updater/updater_state_win.h b/components/component_updater/updater_state_win.h deleted file mode 100644 index f09f7d8c..0000000 --- a/components/component_updater/updater_state_win.h +++ /dev/null
@@ -1,57 +0,0 @@ -// Copyright (c) 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_COMPONENT_UPDATER_UPDATER_STATE_WIN_H_ -#define COMPONENTS_COMPONENT_UPDATER_UPDATER_STATE_WIN_H_ - -#include <memory> -#include <string> - -#include "base/gtest_prod_util.h" -#include "base/time/time.h" -#include "base/version.h" -#include "components/update_client/update_client.h" - -namespace component_updater { - -// TODO(sorin): implement this in terms of -// chrome/installer/util/google_update_settings (crbug.com/615187). -class UpdaterState { - public: - static std::unique_ptr<UpdaterState> Create(bool is_machine); - - update_client::InstallerAttributes MakeInstallerAttributes() const; - - private: - FRIEND_TEST_ALL_PREFIXES(UpdaterStateTest, MakeInstallerAttributes); - - explicit UpdaterState(bool is_machine); - - // This function is best-effort. It updates the class members with - // the relevant values that could be retrieved. - void ReadState(); - - static base::Version GetGoogleUpdateVersion(bool is_machine); - static bool IsAutoupdateCheckEnabled(); - static bool IsJoinedToDomain(); - static base::Time GetGoogleUpdateLastStartedAU(bool is_machine); - static base::Time GetGoogleUpdateLastChecked(bool is_machine); - static base::Time GetGoogleUpdateTimeValue(bool is_machine, - const wchar_t* value_name); - static int GetChromeUpdatePolicy(); - - static std::string NormalizeTimeDelta(const base::TimeDelta& delta); - - bool is_machine_; - base::Version google_update_version_; - base::Time last_autoupdate_started_; - base::Time last_checked_; - bool is_joined_to_domain_ = false; - bool is_autoupdate_check_enabled_ = false; - int chrome_update_policy_ = 0; -}; - -} // namespace component_updater - -#endif // COMPONENTS_COMPONENT_UPDATER_UPDATER_STATE_WIN_H_
diff --git a/components/cronet/android/BUILD.gn b/components/cronet/android/BUILD.gn index 5b6b666..c1dc511 100644 --- a/components/cronet/android/BUILD.gn +++ b/components/cronet/android/BUILD.gn
@@ -569,8 +569,8 @@ "//base:base_java", "//base:base_java_test_support", "//net/android:net_java_test_support", - "//third_party/netty-tcnative:netty-tcnative", - "//third_party/netty4:netty_all", + "//third_party/netty-tcnative:netty-tcnative_java", + "//third_party/netty4:netty_all_java", ] run_findbugs_override = true @@ -628,7 +628,7 @@ ":cronet_test_apk_java", ":cronet_test_apk_resources", "//base:base_java", - "//third_party/netty-tcnative:netty-tcnative_all", + "//third_party/netty-tcnative:netty-tcnative-so", ] run_findbugs_override = true
diff --git a/components/exo/wayland/clients/motion_events.cc b/components/exo/wayland/clients/motion_events.cc index 6d913b4..14fa072 100644 --- a/components/exo/wayland/clients/motion_events.cc +++ b/components/exo/wayland/clients/motion_events.cc
@@ -11,6 +11,7 @@ #include <wayland-client-core.h> #include <wayland-client-protocol.h> +#include <cmath> #include <deque> #include <iostream> #include <string> @@ -303,6 +304,7 @@ size_t num_rects, size_t max_frames_pending, bool fullscreen, + bool show_fps_counter, const std::string* use_drm) : width_(width), height_(height), @@ -310,6 +312,7 @@ num_rects_(num_rects), max_frames_pending_(max_frames_pending), fullscreen_(fullscreen), + show_fps_counter_(show_fps_counter), use_drm_(use_drm) {} // Initialize and run client main loop. @@ -324,6 +327,7 @@ const size_t num_rects_; const size_t max_frames_pending_; const bool fullscreen_; + const bool show_fps_counter_; const std::string* use_drm_; Globals globals_; @@ -531,6 +535,12 @@ base::TimeDelta::FromSeconds(kBenchmarkInterval); base::TimeDelta benchmark_wall_time; base::TimeDelta benchmark_cpu_time; + std::string fps_counter_text("??"); + + SkPaint text_paint; + text_paint.setTextSize(32.0f); + text_paint.setColor(SK_ColorWHITE); + text_paint.setStyle(SkPaint::kFill_Style); int dispatch_status = 0; do { @@ -558,6 +568,10 @@ << " cpu=" << benchmark_cpu_time.InMillisecondsF() / frames << ")" << std::endl; + // Set FPS counter text in case it's being shown. + fps_counter_text = base::UintToString( + std::round(frames / benchmark_interval.InSecondsF())); + frames = 0; benchmark_time = wall_time_start; benchmark_wall_time = base::TimeDelta(); @@ -567,8 +581,6 @@ base::ThreadTicks cpu_time_start = base::ThreadTicks::Now(); SkCanvas* canvas = buffer->sk_surface->getCanvas(); - canvas->save(); - if (event_times.empty()) { canvas->clear(SK_ColorBLACK); } else { @@ -584,6 +596,8 @@ (event_times.back() & 0x00ff00) >> 8, (event_times.back() & 0xff0000) >> 16)); canvas->drawIRect(rect, paint); + std::string text = base::UintToString(event_times.back()); + canvas->drawText(text.c_str(), text.length(), 8, y + 32, text_paint); event_times.pop_back(); y += h; } @@ -596,18 +610,25 @@ -SkScalarHalf(half_height), half_width, half_height); SkScalar rotation = SkScalarMulDiv(frame.time, kRotationSpeed, 1000); - SkPaint paint; + canvas->save(); canvas->translate(half_width, half_height); for (size_t i = 0; i < num_rects_; ++i) { const SkColor kColors[] = {SK_ColorBLUE, SK_ColorGREEN, SK_ColorRED, SK_ColorYELLOW, SK_ColorCYAN, SK_ColorMAGENTA}; + SkPaint paint; paint.setColor(SkColorSetA(kColors[i % arraysize(kColors)], 0xA0)); canvas->rotate(rotation / num_rects_); canvas->drawIRect(rect, paint); } - canvas->restore(); + + // Draw FPS counter. + if (show_fps_counter_) { + canvas->drawText(fps_counter_text.c_str(), fps_counter_text.length(), + width_ - 48, 32, text_paint); + } + if (gr_context_) { gr_context_->flush(); glFlush(); @@ -760,6 +781,9 @@ // Specifies if client should be fullscreen. const char kFullscreen[] = "fullscreen"; +// Specifies if FPS counter should be shown. +const char kShowFpsCounter[] = "show-fps-counter"; + // Use drm buffer instead of shared memory. const char kUseDrm[] = "use-drm"; @@ -813,6 +837,7 @@ exo::wayland::clients::MotionEvents client( width, height, scale, num_rects, max_frames_pending, - command_line->HasSwitch(switches::kFullscreen), use_drm.get()); + command_line->HasSwitch(switches::kFullscreen), + command_line->HasSwitch(switches::kShowFpsCounter), use_drm.get()); return client.Run(); }
diff --git a/components/filesystem/directory_impl.cc b/components/filesystem/directory_impl.cc index 7fd998142..745bcf6 100644 --- a/components/filesystem/directory_impl.cc +++ b/components/filesystem/directory_impl.cc
@@ -31,7 +31,7 @@ DirectoryImpl::~DirectoryImpl() {} void DirectoryImpl::Read(const ReadCallback& callback) { - mojo::Array<mojom::DirectoryEntryPtr> entries; + std::vector<mojom::DirectoryEntryPtr> entries; base::FileEnumerator directory_enumerator( directory_path_, false, base::FileEnumerator::DIRECTORIES | base::FileEnumerator::FILES); @@ -45,7 +45,9 @@ entries.push_back(std::move(entry)); } - callback.Run(mojom::FileError::OK, std::move(entries)); + callback.Run(mojom::FileError::OK, + entries.empty() ? base::nullopt + : base::make_optional(std::move(entries))); } // TODO(erg): Consider adding an implementation of Stat()/Touch() to the @@ -53,7 +55,7 @@ // with directories properly, so these are broken for now. // TODO(vtl): Move the implementation to a thread pool. -void DirectoryImpl::OpenFile(const mojo::String& raw_path, +void DirectoryImpl::OpenFile(const std::string& raw_path, mojom::FileRequest file, uint32_t open_flags, const OpenFileCallback& callback) { @@ -87,7 +89,7 @@ callback.Run(mojom::FileError::OK); } -void DirectoryImpl::OpenFileHandle(const mojo::String& raw_path, +void DirectoryImpl::OpenFileHandle(const std::string& raw_path, uint32_t open_flags, const OpenFileHandleCallback& callback) { mojom::FileError error = mojom::FileError::OK; @@ -96,10 +98,9 @@ } void DirectoryImpl::OpenFileHandles( - mojo::Array<mojom::FileOpenDetailsPtr> details, + std::vector<mojom::FileOpenDetailsPtr> details, const OpenFileHandlesCallback& callback) { - mojo::Array<mojom::FileOpenResultPtr> results( - mojo::Array<mojom::FileOpenResultPtr>::New(details.size())); + std::vector<mojom::FileOpenResultPtr> results(details.size()); size_t i = 0; for (const auto& detail : details) { mojom::FileOpenResultPtr result(mojom::FileOpenResult::New()); @@ -111,7 +112,7 @@ callback.Run(std::move(results)); } -void DirectoryImpl::OpenDirectory(const mojo::String& raw_path, +void DirectoryImpl::OpenDirectory(const std::string& raw_path, mojom::DirectoryRequest directory, uint32_t open_flags, const OpenDirectoryCallback& callback) { @@ -152,8 +153,8 @@ callback.Run(mojom::FileError::OK); } -void DirectoryImpl::Rename(const mojo::String& raw_old_path, - const mojo::String& raw_new_path, +void DirectoryImpl::Rename(const std::string& raw_old_path, + const std::string& raw_new_path, const RenameCallback& callback) { base::FilePath old_path; mojom::FileError error = @@ -178,7 +179,7 @@ callback.Run(mojom::FileError::OK); } -void DirectoryImpl::Delete(const mojo::String& raw_path, +void DirectoryImpl::Delete(const std::string& raw_path, uint32_t delete_flags, const DeleteCallback& callback) { base::FilePath path; @@ -197,7 +198,7 @@ callback.Run(mojom::FileError::OK); } -void DirectoryImpl::Exists(const mojo::String& raw_path, +void DirectoryImpl::Exists(const std::string& raw_path, const ExistsCallback& callback) { base::FilePath path; mojom::FileError error = ValidatePath(raw_path, directory_path_, &path); @@ -210,7 +211,7 @@ callback.Run(mojom::FileError::OK, exists); } -void DirectoryImpl::IsWritable(const mojo::String& raw_path, +void DirectoryImpl::IsWritable(const std::string& raw_path, const IsWritableCallback& callback) { base::FilePath path; mojom::FileError error = ValidatePath(raw_path, directory_path_, &path); @@ -237,7 +238,7 @@ callback.Run(mojom::FileError::OK); } -void DirectoryImpl::StatFile(const mojo::String& raw_path, +void DirectoryImpl::StatFile(const std::string& raw_path, const StatFileCallback& callback) { base::FilePath path; mojom::FileError error = ValidatePath(raw_path, directory_path_, &path); @@ -269,23 +270,23 @@ } } -void DirectoryImpl::ReadEntireFile(const mojo::String& raw_path, +void DirectoryImpl::ReadEntireFile(const std::string& raw_path, const ReadEntireFileCallback& callback) { base::FilePath path; mojom::FileError error = ValidatePath(raw_path, directory_path_, &path); if (error != mojom::FileError::OK) { - callback.Run(error, mojo::Array<uint8_t>()); + callback.Run(error, std::vector<uint8_t>()); return; } if (base::DirectoryExists(path)) { - callback.Run(mojom::FileError::NOT_A_FILE, mojo::Array<uint8_t>()); + callback.Run(mojom::FileError::NOT_A_FILE, std::vector<uint8_t>()); return; } base::File base_file(path, base::File::FLAG_OPEN | base::File::FLAG_READ); if (!base_file.IsValid()) { - callback.Run(GetError(base_file), mojo::Array<uint8_t>()); + callback.Run(GetError(base_file), std::vector<uint8_t>()); return; } @@ -299,8 +300,8 @@ callback.Run(mojom::FileError::OK, mojo::Array<uint8_t>::From(contents)); } -void DirectoryImpl::WriteFile(const mojo::String& raw_path, - mojo::Array<uint8_t> data, +void DirectoryImpl::WriteFile(const std::string& raw_path, + const std::vector<uint8_t>& data, const WriteFileCallback& callback) { base::FilePath path; mojom::FileError error = ValidatePath(raw_path, directory_path_, &path); @@ -324,7 +325,7 @@ // If we're given empty data, we don't write and just truncate the file. if (data.size()) { const int data_size = static_cast<int>(data.size()); - if (base_file.Write(0, reinterpret_cast<char*>(&data.front()), + if (base_file.Write(0, reinterpret_cast<const char*>(&data.front()), data_size) == -1) { callback.Run(GetError(base_file)); return; @@ -335,7 +336,7 @@ } mojo::ScopedHandle DirectoryImpl::OpenFileHandleImpl( - const mojo::String& raw_path, + const std::string& raw_path, uint32_t open_flags, mojom::FileError* error) { base::FilePath path;
diff --git a/components/filesystem/directory_impl.h b/components/filesystem/directory_impl.h index 8d874432..9f1a141 100644 --- a/components/filesystem/directory_impl.h +++ b/components/filesystem/directory_impl.h
@@ -31,41 +31,40 @@ // |Directory| implementation: void Read(const ReadCallback& callback) override; - void OpenFile(const mojo::String& path, + void OpenFile(const std::string& path, mojom::FileRequest file, uint32_t open_flags, const OpenFileCallback& callback) override; - void OpenFileHandle(const mojo::String& path, + void OpenFileHandle(const std::string& path, uint32_t open_flags, const OpenFileHandleCallback& callback) override; - void OpenFileHandles(mojo::Array<mojom::FileOpenDetailsPtr> details, + void OpenFileHandles(std::vector<mojom::FileOpenDetailsPtr> details, const OpenFileHandlesCallback& callback) override; - void OpenDirectory(const mojo::String& path, + void OpenDirectory(const std::string& path, mojom::DirectoryRequest directory, uint32_t open_flags, const OpenDirectoryCallback& callback) override; - void Rename(const mojo::String& path, - const mojo::String& new_path, + void Rename(const std::string& path, + const std::string& new_path, const RenameCallback& callback) override; - void Delete(const mojo::String& path, + void Delete(const std::string& path, uint32_t delete_flags, const DeleteCallback& callback) override; - void Exists(const mojo::String& path, - const ExistsCallback& callback) override; - void IsWritable(const mojo::String& path, + void Exists(const std::string& path, const ExistsCallback& callback) override; + void IsWritable(const std::string& path, const IsWritableCallback& callback) override; void Flush(const FlushCallback& callback) override; - void StatFile(const mojo::String& path, + void StatFile(const std::string& path, const StatFileCallback& callback) override; void Clone(mojom::DirectoryRequest directory) override; - void ReadEntireFile(const mojo::String& path, + void ReadEntireFile(const std::string& path, const ReadEntireFileCallback& callback) override; - void WriteFile(const mojo::String& path, - mojo::Array<uint8_t> data, + void WriteFile(const std::string& path, + const std::vector<uint8_t>& data, const WriteFileCallback& callback) override; private: - mojo::ScopedHandle OpenFileHandleImpl(const mojo::String& raw_path, + mojo::ScopedHandle OpenFileHandleImpl(const std::string& raw_path, uint32_t open_flags, mojom::FileError* error);
diff --git a/components/filesystem/directory_impl_unittest.cc b/components/filesystem/directory_impl_unittest.cc index 61ced2e..836d21a 100644 --- a/components/filesystem/directory_impl_unittest.cc +++ b/components/filesystem/directory_impl_unittest.cc
@@ -46,10 +46,11 @@ EXPECT_EQ(mojom::FileError::OK, error); error = mojom::FileError::FAILED; - mojo::Array<mojom::DirectoryEntryPtr> directory_contents; + base::Optional<std::vector<mojom::DirectoryEntryPtr>> directory_contents; handled = directory->Read(&error, &directory_contents); ASSERT_TRUE(handled); EXPECT_EQ(mojom::FileError::OK, error); + ASSERT_TRUE(directory_contents.has_value()); // Expected contents of the directory. std::map<std::string, mojom::FsFileType> expected_contents; @@ -59,13 +60,13 @@ expected_contents["my_dir"] = mojom::FsFileType::DIRECTORY; // Note: We don't expose ".." or ".". - EXPECT_EQ(expected_contents.size(), directory_contents.size()); - for (size_t i = 0; i < directory_contents.size(); i++) { - ASSERT_TRUE(directory_contents[i]); - ASSERT_TRUE(directory_contents[i]->name); - auto it = expected_contents.find(directory_contents[i]->name.get()); + EXPECT_EQ(expected_contents.size(), directory_contents->size()); + for (size_t i = 0; i < directory_contents->size(); i++) { + auto& item = directory_contents.value()[i]; + ASSERT_TRUE(item); + auto it = expected_contents.find(item->name); ASSERT_TRUE(it != expected_contents.end()); - EXPECT_EQ(it->second, directory_contents[i]->type); + EXPECT_EQ(it->second, item->type); expected_contents.erase(it); } } @@ -177,12 +178,13 @@ } { - mojo::Array<uint8_t> file_contents; + std::vector<uint8_t> file_contents; bool handled = clone_two->ReadEntireFile("data", &error, &file_contents); ASSERT_TRUE(handled); EXPECT_EQ(mojom::FileError::OK, error); - EXPECT_EQ(data, file_contents.To<std::string>()); + EXPECT_EQ(data, + mojo::Array<uint8_t>(std::move(file_contents)).To<std::string>()); } } @@ -200,12 +202,13 @@ } { - mojo::Array<uint8_t> file_contents; + std::vector<uint8_t> file_contents; bool handled = directory->ReadEntireFile("data", &error, &file_contents); ASSERT_TRUE(handled); EXPECT_EQ(mojom::FileError::OK, error); - EXPECT_EQ(data, file_contents.To<std::string>()); + EXPECT_EQ(data, + mojo::Array<uint8_t>(std::move(file_contents)).To<std::string>()); } } @@ -215,7 +218,7 @@ mojom::FileError error; { - mojo::Array<uint8_t> file_contents; + std::vector<uint8_t> file_contents; bool handled = directory->ReadEntireFile("doesnt_exist", &error, &file_contents); ASSERT_TRUE(handled); @@ -241,7 +244,7 @@ // Try to read it as a file { - mojo::Array<uint8_t> file_contents; + std::vector<uint8_t> file_contents; bool handled = directory->ReadEntireFile("my_dir", &error, &file_contents); ASSERT_TRUE(handled); EXPECT_EQ(mojom::FileError::NOT_A_FILE, error);
diff --git a/components/filesystem/file_impl.cc b/components/filesystem/file_impl.cc index fce38713..25a76f3d 100644 --- a/components/filesystem/file_impl.cc +++ b/components/filesystem/file_impl.cc
@@ -89,34 +89,34 @@ mojom::Whence whence, const ReadCallback& callback) { if (!file_.IsValid()) { - callback.Run(GetError(file_), mojo::Array<uint8_t>()); + callback.Run(GetError(file_), base::nullopt); return; } if (num_bytes_to_read > kMaxReadSize) { - callback.Run(mojom::FileError::INVALID_OPERATION, mojo::Array<uint8_t>()); + callback.Run(mojom::FileError::INVALID_OPERATION, base::nullopt); return; } mojom::FileError error = IsOffsetValid(offset); if (error != mojom::FileError::OK) { - callback.Run(error, mojo::Array<uint8_t>()); + callback.Run(error, base::nullopt); return; } error = IsWhenceValid(whence); if (error != mojom::FileError::OK) { - callback.Run(error, mojo::Array<uint8_t>()); + callback.Run(error, base::nullopt); return; } if (file_.Seek(static_cast<base::File::Whence>(whence), offset) == -1) { - callback.Run(mojom::FileError::FAILED, mojo::Array<uint8_t>()); + callback.Run(mojom::FileError::FAILED, base::nullopt); return; } - mojo::Array<uint8_t> bytes_read(num_bytes_to_read); + std::vector<uint8_t> bytes_read(num_bytes_to_read); int num_bytes_read = file_.ReadAtCurrentPos( reinterpret_cast<char*>(&bytes_read.front()), num_bytes_to_read); if (num_bytes_read < 0) { - callback.Run(mojom::FileError::FAILED, mojo::Array<uint8_t>()); + callback.Run(mojom::FileError::FAILED, base::nullopt); return; } @@ -126,11 +126,10 @@ } // TODO(vtl): Move the implementation to a thread pool. -void FileImpl::Write(mojo::Array<uint8_t> bytes_to_write, +void FileImpl::Write(const std::vector<uint8_t>& bytes_to_write, int64_t offset, mojom::Whence whence, const WriteCallback& callback) { - DCHECK(!bytes_to_write.is_null()); if (!file_.IsValid()) { callback.Run(GetError(file_), 0); return; @@ -163,7 +162,7 @@ } const char* buf = (bytes_to_write.size() > 0) - ? reinterpret_cast<char*>(&bytes_to_write.front()) + ? reinterpret_cast<const char*>(&bytes_to_write.front()) : nullptr; int num_bytes_written = file_.WriteAtCurrentPos( buf, static_cast<int>(bytes_to_write.size()));
diff --git a/components/filesystem/file_impl.h b/components/filesystem/file_impl.h index 8ad9193..fdcb5c3 100644 --- a/components/filesystem/file_impl.h +++ b/components/filesystem/file_impl.h
@@ -50,7 +50,7 @@ int64_t offset, mojom::Whence whence, const ReadCallback& callback) override; - void Write(mojo::Array<uint8_t> bytes_to_write, + void Write(const std::vector<uint8_t>& bytes_to_write, int64_t offset, mojom::Whence whence, const WriteCallback& callback) override;
diff --git a/components/filesystem/file_impl_unittest.cc b/components/filesystem/file_impl_unittest.cc index 443a4a9..81544b48 100644 --- a/components/filesystem/file_impl_unittest.cc +++ b/components/filesystem/file_impl_unittest.cc
@@ -43,9 +43,8 @@ bytes_to_write.push_back(static_cast<uint8_t>('o')); error = mojom::FileError::FAILED; uint32_t num_bytes_written = 0; - handled = - file->Write(mojo::Array<uint8_t>::From(bytes_to_write), 0, - mojom::Whence::FROM_CURRENT, &error, &num_bytes_written); + handled = file->Write(bytes_to_write, 0, mojom::Whence::FROM_CURRENT, + &error, &num_bytes_written); ASSERT_TRUE(handled); EXPECT_EQ(mojom::FileError::OK, error); EXPECT_EQ(bytes_to_write.size(), num_bytes_written); @@ -74,15 +73,16 @@ EXPECT_EQ(mojom::FileError::OK, error); // Read from it. - mojo::Array<uint8_t> bytes_read; + base::Optional<std::vector<uint8_t>> bytes_read; error = mojom::FileError::FAILED; handled = file->Read(3, 1, mojom::Whence::FROM_BEGIN, &error, &bytes_read); ASSERT_TRUE(handled); EXPECT_EQ(mojom::FileError::OK, error); - ASSERT_EQ(3u, bytes_read.size()); - EXPECT_EQ(static_cast<uint8_t>('e'), bytes_read[0]); - EXPECT_EQ(static_cast<uint8_t>('l'), bytes_read[1]); - EXPECT_EQ(static_cast<uint8_t>('l'), bytes_read[2]); + ASSERT_TRUE(bytes_read.has_value()); + ASSERT_EQ(3u, bytes_read.value().size()); + EXPECT_EQ(static_cast<uint8_t>('e'), bytes_read.value()[0]); + EXPECT_EQ(static_cast<uint8_t>('l'), bytes_read.value()[1]); + EXPECT_EQ(static_cast<uint8_t>('l'), bytes_read.value()[2]); } // TODO(vtl): Test read/write offset options. @@ -113,9 +113,8 @@ // Write to it. error = mojom::FileError::FAILED; uint32_t num_bytes_written = 0; - handled = - file->Write(mojo::Array<uint8_t>::From(bytes_to_write), 0, - mojom::Whence::FROM_CURRENT, &error, &num_bytes_written); + handled = file->Write(bytes_to_write, 0, mojom::Whence::FROM_CURRENT, + &error, &num_bytes_written); ASSERT_TRUE(handled); EXPECT_EQ(mojom::FileError::OK, error); EXPECT_EQ(bytes_to_write.size(), num_bytes_written); @@ -140,9 +139,8 @@ // Try to write in read mode; it should fail. error = mojom::FileError::OK; uint32_t num_bytes_written = 0; - handled = - file->Write(mojo::Array<uint8_t>::From(bytes_to_write), 0, - mojom::Whence::FROM_CURRENT, &error, &num_bytes_written); + handled = file->Write(bytes_to_write, 0, mojom::Whence::FROM_CURRENT, + &error, &num_bytes_written); ASSERT_TRUE(handled); EXPECT_EQ(mojom::FileError::FAILED, error); @@ -180,9 +178,8 @@ bytes_to_write.push_back(static_cast<uint8_t>('o')); error = mojom::FileError::FAILED; uint32_t num_bytes_written = 0; - handled = - file->Write(mojo::Array<uint8_t>::From(bytes_to_write), 0, - mojom::Whence::FROM_CURRENT, &error, &num_bytes_written); + handled = file->Write(bytes_to_write, 0, mojom::Whence::FROM_CURRENT, + &error, &num_bytes_written); ASSERT_TRUE(handled); EXPECT_EQ(mojom::FileError::OK, error); EXPECT_EQ(bytes_to_write.size(), num_bytes_written); @@ -215,9 +212,8 @@ bytes_to_write.push_back(static_cast<uint8_t>('e')); error = mojom::FileError::FAILED; uint32_t num_bytes_written = 0; - handled = - file->Write(mojo::Array<uint8_t>::From(bytes_to_write), 0, - mojom::Whence::FROM_CURRENT, &error, &num_bytes_written); + handled = file->Write(bytes_to_write, 0, mojom::Whence::FROM_CURRENT, + &error, &num_bytes_written); ASSERT_TRUE(handled); EXPECT_EQ(mojom::FileError::OK, error); EXPECT_EQ(bytes_to_write.size(), num_bytes_written); @@ -240,16 +236,17 @@ EXPECT_EQ(mojom::FileError::OK, error); // Read from it. - mojo::Array<uint8_t> bytes_read; + base::Optional<std::vector<uint8_t>> bytes_read; error = mojom::FileError::FAILED; handled = file->Read(12, 0, mojom::Whence::FROM_BEGIN, &error, &bytes_read); ASSERT_TRUE(handled); EXPECT_EQ(mojom::FileError::OK, error); - ASSERT_EQ(12u, bytes_read.size()); - EXPECT_EQ(static_cast<uint8_t>('l'), bytes_read[3]); - EXPECT_EQ(static_cast<uint8_t>('o'), bytes_read[4]); - EXPECT_EQ(static_cast<uint8_t>('g'), bytes_read[5]); - EXPECT_EQ(static_cast<uint8_t>('o'), bytes_read[6]); + ASSERT_TRUE(bytes_read.has_value()); + ASSERT_EQ(12u, bytes_read.value().size()); + EXPECT_EQ(static_cast<uint8_t>('l'), bytes_read.value()[3]); + EXPECT_EQ(static_cast<uint8_t>('o'), bytes_read.value()[4]); + EXPECT_EQ(static_cast<uint8_t>('g'), bytes_read.value()[5]); + EXPECT_EQ(static_cast<uint8_t>('o'), bytes_read.value()[6]); } } @@ -277,9 +274,8 @@ bytes_to_write.push_back(static_cast<uint8_t>('o')); error = mojom::FileError::FAILED; uint32_t num_bytes_written = 0; - handled = - file->Write(mojo::Array<uint8_t>::From(bytes_to_write), 0, - mojom::Whence::FROM_CURRENT, &error, &num_bytes_written); + handled = file->Write(bytes_to_write, 0, mojom::Whence::FROM_CURRENT, + &error, &num_bytes_written); ASSERT_TRUE(handled); EXPECT_EQ(mojom::FileError::OK, error); EXPECT_EQ(bytes_to_write.size(), num_bytes_written); @@ -312,9 +308,8 @@ bytes_to_write.push_back(static_cast<uint8_t>('e')); error = mojom::FileError::FAILED; uint32_t num_bytes_written = 0; - handled = - file->Write(mojo::Array<uint8_t>::From(bytes_to_write), 0, - mojom::Whence::FROM_CURRENT, &error, &num_bytes_written); + handled = file->Write(bytes_to_write, 0, mojom::Whence::FROM_CURRENT, + &error, &num_bytes_written); ASSERT_TRUE(handled); EXPECT_EQ(mojom::FileError::OK, error); EXPECT_EQ(bytes_to_write.size(), num_bytes_written); @@ -337,16 +332,17 @@ EXPECT_EQ(mojom::FileError::OK, error); // Read from it. - mojo::Array<uint8_t> bytes_read; + base::Optional<std::vector<uint8_t>> bytes_read; error = mojom::FileError::FAILED; handled = file->Read(7, 0, mojom::Whence::FROM_BEGIN, &error, &bytes_read); ASSERT_TRUE(handled); EXPECT_EQ(mojom::FileError::OK, error); - ASSERT_EQ(7u, bytes_read.size()); - EXPECT_EQ(static_cast<uint8_t>('g'), bytes_read[0]); - EXPECT_EQ(static_cast<uint8_t>('o'), bytes_read[1]); - EXPECT_EQ(static_cast<uint8_t>('o'), bytes_read[2]); - EXPECT_EQ(static_cast<uint8_t>('d'), bytes_read[3]); + ASSERT_TRUE(bytes_read.has_value()); + ASSERT_EQ(7u, bytes_read.value().size()); + EXPECT_EQ(static_cast<uint8_t>('g'), bytes_read.value()[0]); + EXPECT_EQ(static_cast<uint8_t>('o'), bytes_read.value()[1]); + EXPECT_EQ(static_cast<uint8_t>('o'), bytes_read.value()[2]); + EXPECT_EQ(static_cast<uint8_t>('d'), bytes_read.value()[3]); } } @@ -441,9 +437,8 @@ std::vector<uint8_t> bytes_to_write(1000, '!'); error = mojom::FileError::FAILED; uint32_t num_bytes_written = 0; - handled = - file->Write(mojo::Array<uint8_t>::From(bytes_to_write), 0, - mojom::Whence::FROM_CURRENT, &error, &num_bytes_written); + handled = file->Write(bytes_to_write, 0, mojom::Whence::FROM_CURRENT, &error, + &num_bytes_written); ASSERT_TRUE(handled); EXPECT_EQ(mojom::FileError::OK, error); EXPECT_EQ(bytes_to_write.size(), num_bytes_written); @@ -533,9 +528,8 @@ bytes_to_write.push_back(static_cast<uint8_t>('o')); error = mojom::FileError::FAILED; uint32_t num_bytes_written = 0; - handled = - file1->Write(mojo::Array<uint8_t>::From(bytes_to_write), 0, - mojom::Whence::FROM_CURRENT, &error, &num_bytes_written); + handled = file1->Write(bytes_to_write, 0, mojom::Whence::FROM_CURRENT, &error, + &num_bytes_written); ASSERT_TRUE(handled); EXPECT_EQ(mojom::FileError::OK, error); EXPECT_EQ(bytes_to_write.size(), num_bytes_written); @@ -565,9 +559,8 @@ more_bytes_to_write.push_back(static_cast<uint8_t>('d')); error = mojom::FileError::FAILED; num_bytes_written = 0; - handled = - file2->Write(mojo::Array<uint8_t>::From(more_bytes_to_write), 0, - mojom::Whence::FROM_CURRENT, &error, &num_bytes_written); + handled = file2->Write(more_bytes_to_write, 0, mojom::Whence::FROM_CURRENT, + &error, &num_bytes_written); ASSERT_TRUE(handled); EXPECT_EQ(mojom::FileError::OK, error); EXPECT_EQ(more_bytes_to_write.size(), num_bytes_written); @@ -588,16 +581,17 @@ EXPECT_EQ(mojom::FileError::OK, error); // Read everything using |file2|. - mojo::Array<uint8_t> bytes_read; + base::Optional<std::vector<uint8_t>> bytes_read; error = mojom::FileError::FAILED; handled = file2->Read(1000, 0, mojom::Whence::FROM_BEGIN, &error, &bytes_read); ASSERT_TRUE(handled); EXPECT_EQ(mojom::FileError::OK, error); - ASSERT_EQ(static_cast<size_t>(end_world_pos), bytes_read.size()); + ASSERT_TRUE(bytes_read.has_value()); + ASSERT_EQ(static_cast<size_t>(end_world_pos), bytes_read.value().size()); // Just check the first and last bytes. - EXPECT_EQ(static_cast<uint8_t>('h'), bytes_read[0]); - EXPECT_EQ(static_cast<uint8_t>('d'), bytes_read[end_world_pos - 1]); + EXPECT_EQ(static_cast<uint8_t>('h'), bytes_read.value()[0]); + EXPECT_EQ(static_cast<uint8_t>('d'), bytes_read.value()[end_world_pos - 1]); // TODO(vtl): Test that |file2| has the same open options as |file1|. } @@ -623,9 +617,8 @@ std::vector<uint8_t> bytes_to_write(kInitialSize, '!'); error = mojom::FileError::FAILED; uint32_t num_bytes_written = 0; - handled = - file->Write(mojo::Array<uint8_t>::From(bytes_to_write), 0, - mojom::Whence::FROM_CURRENT, &error, &num_bytes_written); + handled = file->Write(bytes_to_write, 0, mojom::Whence::FROM_CURRENT, &error, + &num_bytes_written); ASSERT_TRUE(handled); EXPECT_EQ(mojom::FileError::OK, error); EXPECT_EQ(kInitialSize, num_bytes_written); @@ -700,17 +693,18 @@ EXPECT_EQ(mojom::FileError::OK, error); // Verify that we wrote data raw on the file descriptor. - mojo::Array<uint8_t> bytes_read; + base::Optional<std::vector<uint8_t>> bytes_read; error = mojom::FileError::FAILED; handled = file2->Read(5, 0, mojom::Whence::FROM_BEGIN, &error, &bytes_read); ASSERT_TRUE(handled); EXPECT_EQ(mojom::FileError::OK, error); - ASSERT_EQ(5u, bytes_read.size()); - EXPECT_EQ(static_cast<uint8_t>('h'), bytes_read[0]); - EXPECT_EQ(static_cast<uint8_t>('e'), bytes_read[1]); - EXPECT_EQ(static_cast<uint8_t>('l'), bytes_read[2]); - EXPECT_EQ(static_cast<uint8_t>('l'), bytes_read[3]); - EXPECT_EQ(static_cast<uint8_t>('o'), bytes_read[4]); + ASSERT_TRUE(bytes_read.has_value()); + ASSERT_EQ(5u, bytes_read.value().size()); + EXPECT_EQ(static_cast<uint8_t>('h'), bytes_read.value()[0]); + EXPECT_EQ(static_cast<uint8_t>('e'), bytes_read.value()[1]); + EXPECT_EQ(static_cast<uint8_t>('l'), bytes_read.value()[2]); + EXPECT_EQ(static_cast<uint8_t>('l'), bytes_read.value()[3]); + EXPECT_EQ(static_cast<uint8_t>('o'), bytes_read.value()[4]); } }
diff --git a/components/filesystem/public/cpp/prefs/filesystem_json_pref_store.cc b/components/filesystem/public/cpp/prefs/filesystem_json_pref_store.cc index 74638b0..0a5d660 100644 --- a/components/filesystem/public/cpp/prefs/filesystem_json_pref_store.cc +++ b/components/filesystem/public/cpp/prefs/filesystem_json_pref_store.cc
@@ -391,7 +391,7 @@ void FilesystemJsonPrefStore::OnPreferencesFileRead( mojom::FileError err, - mojo::Array<uint8_t> contents) { + const std::vector<uint8_t>& contents) { std::unique_ptr<FilesystemJsonPrefStore::ReadResult> read_result( new FilesystemJsonPrefStore::ReadResult); // TODO(erg): Needs even better error handling.
diff --git a/components/filesystem/public/cpp/prefs/filesystem_json_pref_store.h b/components/filesystem/public/cpp/prefs/filesystem_json_pref_store.h index 0ea0d93..d52b0ec 100644 --- a/components/filesystem/public/cpp/prefs/filesystem_json_pref_store.h +++ b/components/filesystem/public/cpp/prefs/filesystem_json_pref_store.h
@@ -148,7 +148,7 @@ // Asynchronous implementation details of ReadPrefsAsync(). void OnPreferencesReadStart(); void OnPreferencesFileRead(mojom::FileError err, - mojo::Array<uint8_t> contents); + const std::vector<uint8_t>& contents); const std::string path_; mojo::Binding<filesystem::mojom::FileSystemClient> binding_;
diff --git a/components/filesystem/public/interfaces/BUILD.gn b/components/filesystem/public/interfaces/BUILD.gn index 32264fb..a1ef7b6 100644 --- a/components/filesystem/public/interfaces/BUILD.gn +++ b/components/filesystem/public/interfaces/BUILD.gn
@@ -11,6 +11,4 @@ "file_system.mojom", "types.mojom", ] - - use_new_wrapper_types = false }
diff --git a/components/filesystem/util.cc b/components/filesystem/util.cc index 059570dd..d9257cc0 100644 --- a/components/filesystem/util.cc +++ b/components/filesystem/util.cc
@@ -146,17 +146,16 @@ return file_info; } -mojom::FileError ValidatePath(const mojo::String& raw_path, +mojom::FileError ValidatePath(const std::string& raw_path, const base::FilePath& filesystem_base, base::FilePath* out) { - DCHECK(!raw_path.is_null()); - if (!base::IsStringUTF8(raw_path.get())) + if (!base::IsStringUTF8(raw_path)) return mojom::FileError::INVALID_OPERATION; #if defined(OS_POSIX) base::FilePath::StringType path = raw_path; #elif defined(OS_WIN) - base::FilePath::StringType path = base::UTF8ToUTF16(raw_path.get()); + base::FilePath::StringType path = base::UTF8ToUTF16(raw_path); #endif // TODO(erg): This isn't really what we want. FilePath::AppendRelativePath()
diff --git a/components/filesystem/util.h b/components/filesystem/util.h index 464565fc..b00fcf5 100644 --- a/components/filesystem/util.h +++ b/components/filesystem/util.h
@@ -20,10 +20,10 @@ // |ERROR_OK| if valid, else the standard/recommended error for the validation // error): -// Checks if |path|, which must be non-null, is (looks like) a valid (relative) -// path. (On failure, returns |ERROR_INVALID_ARGUMENT| if |path| is not UTF-8, -// or |ERROR_PERMISSION_DENIED| if it is not relative.) -mojom::FileError IsPathValid(const mojo::String& path); +// Checks if |path| is (looks like) a valid (relative) path. (On failure, +// returns |ERROR_INVALID_ARGUMENT| if |path| is not UTF-8, or +// |ERROR_PERMISSION_DENIED| if it is not relative.) +mojom::FileError IsPathValid(const std::string& path); // Checks if |whence| is a valid (known) |Whence| value. (On failure, returns // |ERROR_UNIMPLEMENTED|.) @@ -44,7 +44,7 @@ mojom::FileInformationPtr MakeFileInformation(const base::File::Info& info); // Creates an absolute file path and ensures that we don't try to traverse up. -mojom::FileError ValidatePath(const mojo::String& raw_path, +mojom::FileError ValidatePath(const std::string& raw_path, const base::FilePath& filesystem_base, base::FilePath* out);
diff --git a/components/google/core/browser/google_util.cc b/components/google/core/browser/google_util.cc index a6654c9f..f3e8fd4 100644 --- a/components/google/core/browser/google_util.cc +++ b/components/google/core/browser/google_util.cc
@@ -50,6 +50,9 @@ bool IsValidHostName(base::StringPiece host, base::StringPiece domain_in_lower_case, SubdomainPermission subdomain_permission) { + // Fast path to avoid searching the registry set. + if (host.find(domain_in_lower_case) == base::StringPiece::npos) + return false; size_t tld_length = net::registry_controlled_domains::GetCanonicalHostRegistryLength( host, net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES,
diff --git a/components/guest_view/browser/DEPS b/components/guest_view/browser/DEPS index cbd25b5..9ecdca6 100644 --- a/components/guest_view/browser/DEPS +++ b/components/guest_view/browser/DEPS
@@ -4,5 +4,6 @@ "+content/public/common", "+content/public/test", "+ipc", - '+third_party/WebKit/public/web/WebInputEvent.h', + '+third_party/WebKit/public/platform/WebGestureEvent.h', + '+third_party/WebKit/public/platform/WebInputEvent.h', ]
diff --git a/components/guest_view/browser/guest_view_base.cc b/components/guest_view/browser/guest_view_base.cc index e2ffccee..6b56f96 100644 --- a/components/guest_view/browser/guest_view_base.cc +++ b/components/guest_view/browser/guest_view_base.cc
@@ -24,7 +24,7 @@ #include "content/public/browser/web_contents.h" #include "content/public/common/page_zoom.h" #include "content/public/common/url_constants.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" using content::WebContents;
diff --git a/components/history/core/browser/history_match.cc b/components/history/core/browser/history_match.cc index 6e252b9..ae9787b 100644 --- a/components/history/core/browser/history_match.cc +++ b/components/history/core/browser/history_match.cc
@@ -32,8 +32,8 @@ bool HistoryMatch::IsHostOnly() const { const GURL& gurl = url_info.url(); DCHECK(gurl.is_valid()); - return (!gurl.has_path() || (gurl.path() == "/")) && !gurl.has_query() && - !gurl.has_ref(); + return (!gurl.has_path() || (gurl.path_piece() == "/")) && + !gurl.has_query() && !gurl.has_ref(); } } // namespace history
diff --git a/components/history/core/browser/top_sites_impl.cc b/components/history/core/browser/top_sites_impl.cc index a552e81c..57e7249 100644 --- a/components/history/core/browser/top_sites_impl.cc +++ b/components/history/core/browser/top_sites_impl.cc
@@ -311,12 +311,7 @@ void TopSitesImpl::SyncWithHistory() { DCHECK(thread_checker_.CalledOnValidThread()); - if (loaded_ && temp_images_.size()) { - // If we have temporary thumbnails it means there isn't much data, and most - // likely the user is first running Chrome. During this time we throttle - // updating from history by 30 seconds. If the user creates a new tab page - // during this window of time we force updating from history so that the new - // tab page isn't so far out of date. + if (loaded_) { timer_.Stop(); StartQueryForMostVisited(); }
diff --git a/components/history/core/browser/url_utils.cc b/components/history/core/browser/url_utils.cc index 522af9b..307c894 100644 --- a/components/history/core/browser/url_utils.cc +++ b/components/history/core/browser/url_utils.cc
@@ -46,8 +46,8 @@ } bool HaveSameSchemeHostAndPort(const GURL&url1, const GURL& url2) { - return url1.scheme() == url2.scheme() && url1.host() == url2.host() && - url1.port() == url2.port(); + return url1.scheme_piece() == url2.scheme_piece() && + url1.host_piece() == url2.host_piece() && url1.port() == url2.port(); } bool IsPathPrefix(const std::string& p1, const std::string& p2) {
diff --git a/components/leveldb/env_mojo.cc b/components/leveldb/env_mojo.cc index b226ce4..3a2f839 100644 --- a/components/leveldb/env_mojo.cc +++ b/components/leveldb/env_mojo.cc
@@ -229,8 +229,7 @@ SequentialFile** result) { TRACE_EVENT1("leveldb", "MojoEnv::NewSequentialFile", "fname", fname); base::File f = thread_->OpenFileHandle( - dir_, mojo::String::From(fname), - filesystem::mojom::kFlagOpen | filesystem::mojom::kFlagRead); + dir_, fname, filesystem::mojom::kFlagOpen | filesystem::mojom::kFlagRead); if (!f.IsValid()) { *result = nullptr; return MakeIOError(fname, "Unable to create sequential file", @@ -245,8 +244,7 @@ RandomAccessFile** result) { TRACE_EVENT1("leveldb", "MojoEnv::NewRandomAccessFile", "fname", fname); base::File f = thread_->OpenFileHandle( - dir_, mojo::String::From(fname), - filesystem::mojom::kFlagRead | filesystem::mojom::kFlagOpen); + dir_, fname, filesystem::mojom::kFlagRead | filesystem::mojom::kFlagOpen); if (!f.IsValid()) { *result = nullptr; base::File::Error error_code = f.error_details(); @@ -261,9 +259,9 @@ Status MojoEnv::NewWritableFile(const std::string& fname, WritableFile** result) { TRACE_EVENT1("leveldb", "MojoEnv::NewWritableFile", "fname", fname); - base::File f = thread_->OpenFileHandle( - dir_, mojo::String::From(fname), - filesystem::mojom::kCreateAlways | filesystem::mojom::kFlagWrite); + base::File f = + thread_->OpenFileHandle(dir_, fname, filesystem::mojom::kCreateAlways | + filesystem::mojom::kFlagWrite); if (!f.IsValid()) { *result = nullptr; return MakeIOError(fname, "Unable to create writable file", @@ -277,9 +275,9 @@ Status MojoEnv::NewAppendableFile(const std::string& fname, WritableFile** result) { TRACE_EVENT1("leveldb", "MojoEnv::NewAppendableFile", "fname", fname); - base::File f = thread_->OpenFileHandle( - dir_, mojo::String::From(fname), - filesystem::mojom::kFlagOpenAlways | filesystem::mojom::kFlagAppend); + base::File f = + thread_->OpenFileHandle(dir_, fname, filesystem::mojom::kFlagOpenAlways | + filesystem::mojom::kFlagAppend); if (!f.IsValid()) { *result = nullptr; return MakeIOError(fname, "Unable to create appendable file", @@ -338,7 +336,7 @@ TRACE_EVENT1("leveldb", "MojoEnv::LockFile", "fname", fname); std::pair<filesystem::mojom::FileError, LevelDBMojoProxy::OpaqueLock*> p = - thread_->LockFile(dir_, mojo::String::From(fname)); + thread_->LockFile(dir_, fname); if (p.second) *lock = new MojoFileLock(p.second, fname); @@ -370,7 +368,7 @@ Status MojoEnv::NewLogger(const std::string& fname, Logger** result) { TRACE_EVENT1("leveldb", "MojoEnv::NewLogger", "fname", fname); base::File f(thread_->OpenFileHandle( - dir_, mojo::String::From(fname), + dir_, fname, filesystem::mojom::kCreateAlways | filesystem::mojom::kFlagWrite)); if (!f.IsValid()) { *result = NULL;
diff --git a/components/leveldb/leveldb_mojo_proxy.cc b/components/leveldb/leveldb_mojo_proxy.cc index b25fb60..67c0521 100644 --- a/components/leveldb/leveldb_mojo_proxy.cc +++ b/components/leveldb/leveldb_mojo_proxy.cc
@@ -185,8 +185,8 @@ base::File* output_file) { mojo::ScopedHandle handle; filesystem::mojom::FileError error = filesystem::mojom::FileError::FAILED; - bool completed = dir->directory->OpenFileHandle(mojo::String::From(name), - open_flags, &error, &handle); + bool completed = + dir->directory->OpenFileHandle(name, open_flags, &error, &handle); DCHECK(completed); if (error != filesystem::mojom::FileError::OK) { @@ -225,8 +225,7 @@ std::string name, bool* exists) { filesystem::mojom::FileError error = filesystem::mojom::FileError::FAILED; - bool completed = - dir->directory->Exists(mojo::String::From(name), &error, exists); + bool completed = dir->directory->Exists(name, &error, exists); DCHECK(completed); } @@ -245,13 +244,14 @@ if (*out_error != filesystem::mojom::FileError::OK) return; - mojo::Array<filesystem::mojom::DirectoryEntryPtr> directory_contents; + base::Optional<std::vector<filesystem::mojom::DirectoryEntryPtr>> + directory_contents; completed = target->Read(out_error, &directory_contents); DCHECK(completed); - if (!directory_contents.is_null()) { - for (size_t i = 0; i < directory_contents.size(); ++i) - out_contents->push_back(directory_contents[i]->name.To<std::string>()); + if (directory_contents.has_value()) { + for (size_t i = 0; i < directory_contents->size(); ++i) + out_contents->push_back(directory_contents.value()[i]->name); } } @@ -259,8 +259,7 @@ std::string name, uint32_t delete_flags, filesystem::mojom::FileError* out_error) { - bool completed = - dir->directory->Delete(mojo::String::From(name), delete_flags, out_error); + bool completed = dir->directory->Delete(name, delete_flags, out_error); DCHECK(completed); } @@ -291,8 +290,7 @@ const std::string& old_path, const std::string& new_path, filesystem::mojom::FileError* out_error) { - bool completed = dir->directory->Rename( - mojo::String::From(old_path), mojo::String::From(new_path), out_error); + bool completed = dir->directory->Rename(old_path, new_path, out_error); DCHECK(completed); } @@ -304,11 +302,11 @@ // have a persistent file on the other side of the connection. filesystem::mojom::FilePtr target; filesystem::mojom::FileRequest proxy = GetProxy(&target); - bool completed = dir->directory->OpenFile( - mojo::String::From(path), std::move(proxy), - filesystem::mojom::kFlagOpenAlways | filesystem::mojom::kFlagRead | - filesystem::mojom::kFlagWrite, - out_error); + bool completed = dir->directory->OpenFile(path, std::move(proxy), + filesystem::mojom::kFlagOpenAlways | + filesystem::mojom::kFlagRead | + filesystem::mojom::kFlagWrite, + out_error); DCHECK(completed); if (*out_error != filesystem::mojom::FileError::OK)
diff --git a/components/nacl/loader/nacl_ipc_adapter.cc b/components/nacl/loader/nacl_ipc_adapter.cc index 33f74f8..7418696 100644 --- a/components/nacl/loader/nacl_ipc_adapter.cc +++ b/components/nacl/loader/nacl_ipc_adapter.cc
@@ -626,7 +626,6 @@ ppapi::proxy::SerializedHandle::WriteHeader(sh.header(), new_msg.get()); new_msg->WriteBool(true); // valid == true - new_msg->WriteBool(false); // brokerable == false // The file descriptor is at index 0. There's only ever one file // descriptor provided for this message type, so this will be correct. new_msg->WriteInt(0);
diff --git a/components/ntp_snippets/content_suggestion.cc b/components/ntp_snippets/content_suggestion.cc index 59c3bd4..efe1aad 100644 --- a/components/ntp_snippets/content_suggestion.cc +++ b/components/ntp_snippets/content_suggestion.cc
@@ -38,8 +38,14 @@ void ContentSuggestion::set_download_suggestion_extra( std::unique_ptr<DownloadSuggestionExtra> download_suggestion_extra) { - DCHECK_EQ(id_.category().id(), static_cast<int>(KnownCategories::DOWNLOADS)); + DCHECK(id_.category().IsKnownCategory(KnownCategories::DOWNLOADS)); download_suggestion_extra_ = std::move(download_suggestion_extra); } +void ContentSuggestion::set_recent_tab_suggestion_extra( + std::unique_ptr<RecentTabSuggestionExtra> recent_tab_suggestion_extra) { + DCHECK(id_.category().IsKnownCategory(KnownCategories::RECENT_TABS)); + recent_tab_suggestion_extra_ = std::move(recent_tab_suggestion_extra); +} + } // namespace ntp_snippets
diff --git a/components/ntp_snippets/content_suggestion.h b/components/ntp_snippets/content_suggestion.h index 16d8d7d..630b7e5 100644 --- a/components/ntp_snippets/content_suggestion.h +++ b/components/ntp_snippets/content_suggestion.h
@@ -28,6 +28,14 @@ bool is_download_asset = false; }; +// Contains additional data which is only available for recent tab suggestions. +struct RecentTabSuggestionExtra { + // Corresponding tab identifier. + std::string tab_id; + // Underlying offline page identifier. + std::string offline_page_id; +}; + // A content suggestion for the new tab page, which can be an article or an // offline page, for example. class ContentSuggestion { @@ -115,6 +123,14 @@ void set_download_suggestion_extra( std::unique_ptr<DownloadSuggestionExtra> download_suggestion_extra); + // Extra information for recent tab suggestions. Only available for + // KnownCategories::RECENT_TABS suggestions. + RecentTabSuggestionExtra* recent_tab_suggestion_extra() const { + return recent_tab_suggestion_extra_.get(); + } + void set_recent_tab_suggestion_extra( + std::unique_ptr<RecentTabSuggestionExtra> recent_tab_suggestion_extra); + private: ID id_; GURL url_; @@ -125,6 +141,7 @@ base::string16 publisher_name_; float score_; std::unique_ptr<DownloadSuggestionExtra> download_suggestion_extra_; + std::unique_ptr<RecentTabSuggestionExtra> recent_tab_suggestion_extra_; DISALLOW_COPY_AND_ASSIGN(ContentSuggestion); };
diff --git a/components/ntp_snippets/offline_pages/recent_tab_suggestions_provider.cc b/components/ntp_snippets/offline_pages/recent_tab_suggestions_provider.cc index a6312607..2a135b1 100644 --- a/components/ntp_snippets/offline_pages/recent_tab_suggestions_provider.cc +++ b/components/ntp_snippets/offline_pages/recent_tab_suggestions_provider.cc
@@ -8,6 +8,7 @@ #include <utility> #include "base/bind.h" +#include "base/memory/ptr_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_task_runner_handle.h" @@ -254,6 +255,10 @@ } suggestion.set_publish_date(offline_page.creation_time); suggestion.set_publisher_name(base::UTF8ToUTF16(offline_page.url.host())); + auto extra = base::MakeUnique<RecentTabSuggestionExtra>(); + extra->tab_id = offline_page.client_id.id; + extra->offline_page_id = base::Int64ToString(offline_page.offline_id); + suggestion.set_recent_tab_suggestion_extra(std::move(extra)); return suggestion; }
diff --git a/components/ntp_snippets/remote/remote_suggestions_provider.cc b/components/ntp_snippets/remote/remote_suggestions_provider.cc index 96ad674..99c41e8 100644 --- a/components/ntp_snippets/remote/remote_suggestions_provider.cc +++ b/components/ntp_snippets/remote/remote_suggestions_provider.cc
@@ -1091,6 +1091,10 @@ if (state == state_) return; + UMA_HISTOGRAM_ENUMERATION("NewTabPage.Snippets.EnteredState", + static_cast<int>(state), + static_cast<int>(State::COUNT)); + switch (state) { case State::NOT_INITED: // Initial state, it should not be possible to get back there. @@ -1118,6 +1122,10 @@ state_ = State::ERROR_OCCURRED; EnterStateError(); break; + + case State::COUNT: + NOTREACHED(); + break; } // Schedule or un-schedule background fetching after each state change.
diff --git a/components/ntp_snippets/remote/remote_suggestions_provider.h b/components/ntp_snippets/remote/remote_suggestions_provider.h index bd5aad80..3cfa532 100644 --- a/components/ntp_snippets/remote/remote_suggestions_provider.h +++ b/components/ntp_snippets/remote/remote_suggestions_provider.h
@@ -191,7 +191,9 @@ // The service or one of its dependencies encountered an unrecoverable error // and the service can't be used anymore. - ERROR_OCCURRED + ERROR_OCCURRED, + + COUNT }; struct CategoryContent {
diff --git a/components/ntp_snippets_strings.grdp b/components/ntp_snippets_strings.grdp index 8c5215c..57a4076 100644 --- a/components/ntp_snippets_strings.grdp +++ b/components/ntp_snippets_strings.grdp
@@ -25,7 +25,7 @@ Recent tabs </message> - <message name="IDS_NTP_BOOKMARK_SUGGESTIONS_SECTION_HEADER" desc="Header of the bookmarks section, which is a list of the user's most recently used bookmarks displayed as cards on the New Tab Page."> + <message name="IDS_NTP_BOOKMARK_SUGGESTIONS_SECTION_HEADER" desc="Header of the bookmarks section. The bookmarks section shows a list of recently *visited* bookmarks, irrespective of their creation date. It is *not* a list of recently *created* bookmarks"> Recent bookmarks </message>
diff --git a/components/ntp_tiles/most_visited_sites.cc b/components/ntp_tiles/most_visited_sites.cc index fab0384..e78b0e0 100644 --- a/components/ntp_tiles/most_visited_sites.cc +++ b/components/ntp_tiles/most_visited_sites.cc
@@ -76,7 +76,8 @@ } bool AreURLsEquivalent(const GURL& url1, const GURL& url2) { - return url1.host() == url2.host() && url1.path() == url2.path(); + return url1.host_piece() == url2.host_piece() && + url1.path_piece() == url2.path_piece(); } } // namespace
diff --git a/components/omnibox/browser/history_url_provider.cc b/components/omnibox/browser/history_url_provider.cc index 433c8d1..08cd7a9 100644 --- a/components/omnibox/browser/history_url_provider.cc +++ b/components/omnibox/browser/history_url_provider.cc
@@ -945,8 +945,8 @@ // which will have empty reference fragments.) if ((type == UNVISITED_INTRANET) && (params->input.type() != metrics::OmniboxInputType::URL) && - url.username().empty() && url.password().empty() && - url.port().empty() && (url.path() == "/") && url.query().empty() && + url.username().empty() && url.password().empty() && url.port().empty() && + (url.path_piece() == "/") && url.query().empty() && (parsed.CountCharactersBefore(url::Parsed::REF, true) != parsed.CountCharactersBefore(url::Parsed::REF, false))) { return false;
diff --git a/components/omnibox/browser/omnibox_edit_model.cc b/components/omnibox/browser/omnibox_edit_model.cc index 2cf5692b..aad6574c 100644 --- a/components/omnibox/browser/omnibox_edit_model.cc +++ b/components/omnibox/browser/omnibox_edit_model.cc
@@ -358,8 +358,8 @@ // entire host, and the user hasn't edited the host or manually removed the // scheme. GURL perm_url(PermanentURL()); - if (perm_url.SchemeIs(url::kHttpScheme) && - url->SchemeIs(url::kHttpScheme) && perm_url.host() == url->host()) { + if (perm_url.SchemeIs(url::kHttpScheme) && url->SchemeIs(url::kHttpScheme) && + perm_url.host_piece() == url->host_piece()) { *write_url = true; base::string16 http = base::ASCIIToUTF16(url::kHttpScheme) + base::ASCIIToUTF16(url::kStandardSchemeSeparator);
diff --git a/components/password_manager/core/browser/password_form_manager.cc b/components/password_manager/core/browser/password_form_manager.cc index 78f3ba0..7ae0096 100644 --- a/components/password_manager/core/browser/password_form_manager.cc +++ b/components/password_manager/core/browser/password_form_manager.cc
@@ -236,10 +236,10 @@ // redirects to HTTPS (as in http://example.org -> https://example.org/auth). if (!origins_match && !observed_form_.origin.SchemeIsCryptographic() && form.origin.SchemeIsCryptographic()) { - const std::string& old_path = observed_form_.origin.path(); - const std::string& new_path = form.origin.path(); + const base::StringPiece& old_path = observed_form_.origin.path_piece(); + const base::StringPiece& new_path = form.origin.path_piece(); origins_match = - observed_form_.origin.host() == form.origin.host() && + observed_form_.origin.host_piece() == form.origin.host_piece() && observed_form_.origin.port() == form.origin.port() && base::StartsWith(new_path, old_path, base::CompareCase::SENSITIVE); } @@ -1162,7 +1162,8 @@ } if (observed_form_.scheme == PasswordForm::SCHEME_HTML) { - return (blacklisted_form.origin.path() == observed_form_.origin.path()) || + return (blacklisted_form.origin.path_piece() == + observed_form_.origin.path_piece()) || (AreStringsEqualOrEmpty(blacklisted_form.submit_element, observed_form_.submit_element) && AreStringsEqualOrEmpty(blacklisted_form.password_element,
diff --git a/components/password_manager/core/browser/password_store.cc b/components/password_manager/core/browser/password_store.cc index 314c1eb..93ddc39 100644 --- a/components/password_manager/core/browser/password_store.cc +++ b/components/password_manager/core/browser/password_store.cc
@@ -26,18 +26,6 @@ namespace password_manager { -namespace { - -// http://crbug.com/404012. Let's see where the empty fields come from. -void CheckForEmptyUsernameAndPassword(const PasswordForm& form) { - if (form.username_value.empty() && - form.password_value.empty() && - !form.blacklisted_by_user) - base::debug::DumpWithoutCrashing(); -} - -} // namespace - PasswordStore::GetLoginsRequest::GetLoginsRequest( PasswordStoreConsumer* consumer) : consumer_weak_(consumer->GetWeakPtr()) { @@ -107,19 +95,16 @@ } void PasswordStore::AddLogin(const PasswordForm& form) { - CheckForEmptyUsernameAndPassword(form); ScheduleTask(base::Bind(&PasswordStore::AddLoginInternal, this, form)); } void PasswordStore::UpdateLogin(const PasswordForm& form) { - CheckForEmptyUsernameAndPassword(form); ScheduleTask(base::Bind(&PasswordStore::UpdateLoginInternal, this, form)); } void PasswordStore::UpdateLoginWithPrimaryKey( const autofill::PasswordForm& new_form, const autofill::PasswordForm& old_primary_key) { - CheckForEmptyUsernameAndPassword(new_form); ScheduleTask(base::Bind(&PasswordStore::UpdateLoginWithPrimaryKeyInternal, this, new_form, old_primary_key)); }
diff --git a/components/plugins/renderer/loadable_plugin_placeholder.cc b/components/plugins/renderer/loadable_plugin_placeholder.cc index 9bc0478..5c804c9 100644 --- a/components/plugins/renderer/loadable_plugin_placeholder.cc +++ b/components/plugins/renderer/loadable_plugin_placeholder.cc
@@ -17,10 +17,10 @@ #include "content/public/child/v8_value_converter.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_thread.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/web/WebDOMMessageEvent.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebElement.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" #include "third_party/WebKit/public/web/WebKit.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebPluginContainer.h"
diff --git a/components/plugins/renderer/webview_plugin.cc b/components/plugins/renderer/webview_plugin.cc index 4cba2c15..8d45c42 100644 --- a/components/plugins/renderer/webview_plugin.cc +++ b/components/plugins/renderer/webview_plugin.cc
@@ -17,12 +17,12 @@ #include "content/public/renderer/render_view.h" #include "gin/converter.h" #include "skia/ext/platform_canvas.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/platform/WebURL.h" #include "third_party/WebKit/public/platform/WebURLResponse.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebElement.h" #include "third_party/WebKit/public/web/WebFrameWidget.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebPluginContainer.h" #include "third_party/WebKit/public/web/WebView.h" @@ -245,7 +245,9 @@ const WebImage&, const WebPoint&) { // Immediately stop dragging. - web_view_->dragSourceSystemDragEnded(); + DCHECK(web_view_->mainFrame()->isWebLocalFrame()); + web_view_->mainFrame()->toWebLocalFrame()->frameWidget()-> + dragSourceSystemDragEnded(); } bool WebViewPlugin::allowsBrokenNullLayerTreeView() const {
diff --git a/components/policy/resources/policy_templates.json b/components/policy/resources/policy_templates.json index 18682b8..2f889747a 100644 --- a/components/policy/resources/policy_templates.json +++ b/components/policy/resources/policy_templates.json
@@ -5812,9 +5812,17 @@ 'tags': [], 'supported_on': ['chrome_os:54-'], 'caption': '''Treat external storage devices as read-only.''', - 'desc': '''When this policy is set to true, users cannot write anything to external storage devices.''', + 'desc': '''Treat external storage devices as read-only. + + This policy is effective only when ExternalStorageDisabled is set to false or not configured. + + When this policy is set to true, users cannot write anything to external storage devices. + + If this setting is disabled or not configured then users can create and modify files of external storage devices which are physically writable. + + Dynamic refresh of this policy is supported in M56 and later.''', 'features': { - 'dynamic_refresh': False, + 'dynamic_refresh': True, 'per_profile': True, }, 'example_value': True
diff --git a/components/safe_browsing_db/safe_browsing_prefs.cc b/components/safe_browsing_db/safe_browsing_prefs.cc index bb17314e..82e4a1d 100644 --- a/components/safe_browsing_db/safe_browsing_prefs.cc +++ b/components/safe_browsing_db/safe_browsing_prefs.cc
@@ -2,10 +2,25 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "base/command_line.h" #include "base/metrics/histogram_macros.h" #include "components/prefs/pref_service.h" #include "components/safe_browsing_db/safe_browsing_prefs.h" +namespace { + +// Switch value which force the ScoutGroupSelected pref to true. +const char kForceScoutGroupValueTrue[] = "true"; +// Switch value which force the ScoutGroupSelected pref to false. +const char kForceScoutGroupValueFalse[] = "false"; + +// Returns if Scout is the currently-active pref. +bool IsScout(const std::string& pref) { + return pref == prefs::kSafeBrowsingScoutReportingEnabled; +} + +} // namespace + namespace prefs { const char kSafeBrowsingExtendedReportingEnabled[] = "safebrowsing.extended_reporting_enabled"; @@ -17,12 +32,22 @@ namespace safe_browsing { +const char kSwitchForceScoutGroup[] = "force-scout-group"; + const base::Feature kCanShowScoutOptIn{"CanShowScoutOptIn", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kOnlyShowScoutOptIn{"OnlyShowScoutOptIn", base::FEATURE_DISABLED_BY_DEFAULT}; +int ChooseOptInTextResource(const PrefService& prefs, + int extended_reporting_resource, + int scout_resource) { + return IsScout(GetExtendedReportingPrefName(prefs)) + ? scout_resource + : extended_reporting_resource; +} + bool ExtendedReportingPrefExists(const PrefService& prefs) { return prefs.HasPrefPath(GetExtendedReportingPrefName(prefs)); } @@ -41,6 +66,20 @@ return prefs::kSafeBrowsingExtendedReportingEnabled; } +void InitializeSafeBrowsingPrefs(PrefService* prefs) { + if (base::CommandLine::ForCurrentProcess()->HasSwitch( + kSwitchForceScoutGroup)) { + std::string switch_value = + base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( + kSwitchForceScoutGroup); + if (switch_value == kForceScoutGroupValueTrue) { + prefs->SetBoolean(prefs::kSafeBrowsingScoutGroupSelected, true); + } else if (switch_value == kForceScoutGroupValueFalse) { + prefs->SetBoolean(prefs::kSafeBrowsingScoutGroupSelected, false); + } + } +} + bool IsExtendedReportingEnabled(const PrefService& prefs) { return prefs.GetBoolean(GetExtendedReportingPrefName(prefs)); }
diff --git a/components/safe_browsing_db/safe_browsing_prefs.h b/components/safe_browsing_db/safe_browsing_prefs.h index 6acc08b..76249256 100644 --- a/components/safe_browsing_db/safe_browsing_prefs.h +++ b/components/safe_browsing_db/safe_browsing_prefs.h
@@ -27,14 +27,29 @@ namespace safe_browsing { +// Command-line switch for changing the scout_group_selected preference. Should +// be set to either 'true' or 'false'. Primarily for testing purposes. +// TODO: this is temporary (crbug.com/662944) +extern const char kSwitchForceScoutGroup[]; + // When this feature is enabled, the Scout opt-in text will be displayed as of // the next security incident. Until then, the legacy SBER text will appear. +// TODO: this is temporary (crbug.com/662944) extern const base::Feature kCanShowScoutOptIn; // When this feature is enabled, the Scout opt-in text will immediately be // displayed everywhere. +// TODO: this is temporary (crbug.com/662944) extern const base::Feature kOnlyShowScoutOptIn; +// Determines which opt-in text should be used based on the currently active +// preference. Will return either |extended_reporting_resource| if the legacy +// Extended Reporting pref is active, or |scout_resource| if the Scout pref is +// active. +int ChooseOptInTextResource(const PrefService& prefs, + int extended_reporting_resource, + int scout_resource); + // Returns whether the currently active Safe Browsing Extended Reporting // preference exists (eg: has been set before). bool ExtendedReportingPrefExists(const PrefService& prefs); @@ -43,6 +58,11 @@ // currently in effect. The specific pref in-use may change through experiments. const char* GetExtendedReportingPrefName(const PrefService& prefs); +// Initializes Safe Browsing preferences based on data such as experiment state, +// command line flags, etc. +// TODO: this is temporary (crbug.com/662944) +void InitializeSafeBrowsingPrefs(PrefService* prefs); + // Returns whether Safe Browsing Extended Reporting is currently enabled. // This should be used to decide if any of the reporting preferences are set, // regardless of which specific one is set.
diff --git a/components/safe_browsing_db/safe_browsing_prefs_unittest.cc b/components/safe_browsing_db/safe_browsing_prefs_unittest.cc index 821675c..a06708f3 100644 --- a/components/safe_browsing_db/safe_browsing_prefs_unittest.cc +++ b/components/safe_browsing_db/safe_browsing_prefs_unittest.cc
@@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <string> +#include <vector> + +#include "base/command_line.h" #include "base/strings/string_util.h" #include "base/test/scoped_feature_list.h" #include "components/prefs/pref_registry_simple.h" @@ -68,8 +72,15 @@ << " only_show_scout=" << only_show_scout; } - private: + void InitPrefs() { InitializeSafeBrowsingPrefs(&prefs_); } + + bool IsScoutGroupSelected() { + return prefs_.GetBoolean(prefs::kSafeBrowsingScoutGroupSelected); + } + TestingPrefServiceSimple prefs_; + + private: std::unique_ptr<base::test::ScopedFeatureList> feature_list_; }; @@ -140,4 +151,50 @@ TestGetPrefName(true, true, true, true, true, scout); } +// Basic test that command-line flags can force the ScoutGroupSelected pref on +// or off. +TEST_F(SafeBrowsingPrefsTest, InitPrefs_ForceScoutGroupOnOff) { + // By default ScoutGroupSelected is off. + EXPECT_FALSE(IsScoutGroupSelected()); + + // Command-line flag can force it on during initialization. + base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( + kSwitchForceScoutGroup, "true"); + InitPrefs(); + EXPECT_TRUE(IsScoutGroupSelected()); + + // ScoutGroup remains on if switches are cleared. + base::CommandLine::StringVector empty; + base::CommandLine::ForCurrentProcess()->InitFromArgv(empty); + InitPrefs(); + EXPECT_TRUE(IsScoutGroupSelected()); + + // Nonsense values are ignored and ScoutGroup is unchanged. + base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( + kSwitchForceScoutGroup, "foo"); + InitPrefs(); + EXPECT_TRUE(IsScoutGroupSelected()); + + // ScoutGroup can also be forced off during initialization. + base::CommandLine::ForCurrentProcess()->InitFromArgv(empty); + base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( + kSwitchForceScoutGroup, "false"); + InitPrefs(); + EXPECT_FALSE(IsScoutGroupSelected()); +} + +TEST_F(SafeBrowsingPrefsTest, ChooseOptInText) { + const int kSberResource = 100; + const int kScoutResource = 500; + // By default, SBER opt-in is used + EXPECT_EQ(kSberResource, + ChooseOptInTextResource(prefs_, kSberResource, kScoutResource)); + + // Enabling Scout switches to the Scout opt-in text. + ResetExperiments(/*can_show_scout=*/false, /*only_show_scout=*/true); + ResetPrefs(/*sber=*/false, /*scout=*/false, /*scout_group=*/true); + EXPECT_EQ(kScoutResource, + ChooseOptInTextResource(prefs_, kSberResource, kScoutResource)); +} + } // namespace safe_browsing
diff --git a/components/safe_browsing_db/v4_local_database_manager.cc b/components/safe_browsing_db/v4_local_database_manager.cc index 07aa34b..3abee493 100644 --- a/components/safe_browsing_db/v4_local_database_manager.cc +++ b/components/safe_browsing_db/v4_local_database_manager.cc
@@ -15,6 +15,7 @@ #include "base/memory/ref_counted.h" #include "base/metrics/histogram_macros.h" #include "components/safe_browsing_db/v4_feature_list.h" +#include "components/safe_browsing_db/v4_protocol_manager_util.h" #include "content/public/browser/browser_thread.h" using content::BrowserThread; @@ -236,9 +237,23 @@ } bool V4LocalDatabaseManager::MatchMalwareIP(const std::string& ip_address) { - // TODO(vakh): Implement this skeleton. DCHECK_CURRENTLY_ON(BrowserThread::IO); - return false; + if (!enabled_) { + return false; + } + FullHash hashed_encoded_ip; + if (!V4ProtocolManagerUtil::IPAddressToEncodedIPV6Hash(ip_address, + &hashed_encoded_ip)) { + return false; + } + + std::set<FullHash> hashed_encoded_ips{hashed_encoded_ip}; + std::unique_ptr<PendingCheck> check = base::MakeUnique<PendingCheck>( + nullptr, ClientCallbackType::CHECK_MALWARE_IP, + StoresToCheck({GetAnyIpMalwareId()}), hashed_encoded_ips); + + // HandleCheckSynchronously() tells us whether the resource is safe. + return !HandleCheckSynchronously(std::move(check)); } bool V4LocalDatabaseManager::MatchModuleWhitelistString( @@ -371,7 +386,8 @@ const base::TimeTicks before = TimeTicks::Now(); if (check->client_callback_type == ClientCallbackType::CHECK_BROWSE_URL || check->client_callback_type == ClientCallbackType::CHECK_DOWNLOAD_URLS || - check->client_callback_type == ClientCallbackType::CHECK_EXTENSION_IDS) { + check->client_callback_type == ClientCallbackType::CHECK_EXTENSION_IDS || + check->client_callback_type == ClientCallbackType::CHECK_MALWARE_IP) { DCHECK(!check->full_hashes.empty()); full_hash_to_store_and_hash_prefixes->clear(); @@ -455,9 +471,20 @@ base::Bind(&V4LocalDatabaseManager::PerformFullHashCheck, this, base::Passed(std::move(check)), full_hash_to_store_and_hash_prefixes)); + return false; } +bool V4LocalDatabaseManager::HandleCheckSynchronously( + std::unique_ptr<PendingCheck> check) { + if (!v4_database_) { + return true; + } + + FullHashToStoreAndHashPrefixesMap full_hash_to_store_and_hash_prefixes; + return !GetPrefixMatches(check, &full_hash_to_store_and_hash_prefixes); +} + void V4LocalDatabaseManager::OnFullHashResponse( std::unique_ptr<PendingCheck> pending_check, const std::vector<FullHashInfo>& full_hash_infos) {
diff --git a/components/safe_browsing_db/v4_local_database_manager.h b/components/safe_browsing_db/v4_local_database_manager.h index 297fdf05..e525f66 100644 --- a/components/safe_browsing_db/v4_local_database_manager.h +++ b/components/safe_browsing_db/v4_local_database_manager.h
@@ -95,9 +95,13 @@ // unsafe resource. CHECK_RESOURCE_URL = 2, - // This represents the case where we're trying to determine if a Chrome + // This represents the case when we're trying to determine if a Chrome // extension is a unsafe. - CHECK_EXTENSION_IDS = 3 + CHECK_EXTENSION_IDS = 3, + + // This represents the case when we're trying to determing if an IP address + // is unsafe due to hosting Malware. + CHECK_MALWARE_IP = 4, }; // The information we need to process a URL safety reputation request and @@ -197,6 +201,11 @@ // schedules a task to perform full hash check and returns false. bool HandleCheck(std::unique_ptr<PendingCheck> check); + // Checks the database for prefix matches. Returns true if the database isn't + // ready or if there's no match; false otherwise. This is used for lists that + // have full hash information in the database. + bool HandleCheckSynchronously(std::unique_ptr<PendingCheck> check); + // Called when the |v4_get_hash_protocol_manager_| has the full hash response // available for the URL that we requested. It determines the severest // threat type and responds to the |client| with that information.
diff --git a/components/safe_browsing_db/v4_local_database_manager_unittest.cc b/components/safe_browsing_db/v4_local_database_manager_unittest.cc index 5d0f850c..2deb3e0 100644 --- a/components/safe_browsing_db/v4_local_database_manager_unittest.cc +++ b/components/safe_browsing_db/v4_local_database_manager_unittest.cc
@@ -37,7 +37,13 @@ const FullHash& full_hash, const StoresToCheck& stores_to_check, StoreAndHashPrefixes* store_and_hash_prefixes) override { - *store_and_hash_prefixes = store_and_hash_prefixes_; + store_and_hash_prefixes->clear(); + for (const StoreAndHashPrefix& stored_sahp : store_and_hash_prefixes_) { + const PrefixSize& prefix_size = stored_sahp.hash_prefix.size(); + if (!full_hash.compare(0, prefix_size, stored_sahp.hash_prefix)) { + store_and_hash_prefixes->push_back(stored_sahp); + } + } } private: @@ -231,7 +237,8 @@ net::TestURLFetcherFactory factory; StoreAndHashPrefixes store_and_hash_prefixes; - store_and_hash_prefixes.emplace_back(GetUrlMalwareId(), HashPrefix("aaaa")); + store_and_hash_prefixes.emplace_back(GetUrlMalwareId(), + HashPrefix("eW\x1A\xF\xA9")); ReplaceV4Database(store_and_hash_prefixes); // The fake database returns a matched hash prefix. @@ -318,7 +325,8 @@ net::TestURLFetcherFactory factory; StoreAndHashPrefixes store_and_hash_prefixes; - store_and_hash_prefixes.emplace_back(GetUrlMalwareId(), HashPrefix("aaaa")); + store_and_hash_prefixes.emplace_back(GetUrlMalwareId(), + HashPrefix("eW\x1A\xF\xA9")); ReplaceV4Database(store_and_hash_prefixes); // The fake database returns a matched hash prefix. @@ -347,7 +355,8 @@ net::TestURLFetcherFactory factory; StoreAndHashPrefixes store_and_hash_prefixes; - store_and_hash_prefixes.emplace_back(GetUrlMalwareId(), HashPrefix("aaaa")); + store_and_hash_prefixes.emplace_back(GetUrlMalwareId(), + HashPrefix("eW\x1A\xF\xA9")); ReplaceV4Database(store_and_hash_prefixes); // The fake database returns a matched hash prefix. @@ -365,4 +374,37 @@ WaitForTasksOnTaskRunner(); } +TEST_F(V4LocalDatabaseManagerTest, TestMatchMalwareIP) { + StopLocalDatabaseManager(); + v4_local_database_manager_ = + make_scoped_refptr(new FakeV4LocalDatabaseManager(base_dir_.GetPath())); + SetTaskRunnerForTest(); + StartLocalDatabaseManager(); + WaitForTasksOnTaskRunner(); + + // >>> hashlib.sha1(socket.inet_pton(socket.AF_INET6, + // '::ffff:192.168.1.2')).digest() + chr(128) + // '\xb3\xe0z\xafAv#h\x9a\xcf<\xf3ee\x94\xda\xf6y\xb1\xad\x80' + StoreAndHashPrefixes store_and_hash_prefixes; + store_and_hash_prefixes.emplace_back(GetAnyIpMalwareId(), + FullHash("\xB3\xE0z\xAF" + "Av#h\x9A\xCF<\xF3" + "ee\x94\xDA\xF6y\xB1\xAD\x80")); + ReplaceV4Database(store_and_hash_prefixes); + + EXPECT_FALSE(v4_local_database_manager_->MatchMalwareIP("")); + EXPECT_FALSE(FakeV4LocalDatabaseManager::PerformFullHashCheckCalled( + v4_local_database_manager_)); + + // The fake database returns no match. + EXPECT_FALSE(v4_local_database_manager_->MatchMalwareIP("192.168.1.1")); + EXPECT_FALSE(FakeV4LocalDatabaseManager::PerformFullHashCheckCalled( + v4_local_database_manager_)); + + // The fake database returns a matched hash prefix. + EXPECT_TRUE(v4_local_database_manager_->MatchMalwareIP("192.168.1.2")); + EXPECT_FALSE(FakeV4LocalDatabaseManager::PerformFullHashCheckCalled( + v4_local_database_manager_)); +} + } // namespace safe_browsing
diff --git a/components/safe_browsing_db/v4_protocol_manager_util.cc b/components/safe_browsing_db/v4_protocol_manager_util.cc index 5d251155..072f8d1 100644 --- a/components/safe_browsing_db/v4_protocol_manager_util.cc +++ b/components/safe_browsing_db/v4_protocol_manager_util.cc
@@ -7,10 +7,12 @@ #include "base/base64.h" #include "base/metrics/histogram_macros.h" #include "base/rand_util.h" +#include "base/sha1.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "crypto/sha2.h" #include "net/base/escape.h" +#include "net/base/ip_address.h" #include "net/http/http_request_headers.h" #include "url/url_util.h" @@ -85,6 +87,10 @@ #endif } +const ListIdentifier GetAnyIpMalwareId() { + return ListIdentifier(ANY_PLATFORM, IP_RANGE, MALWARE_THREAT); +} + const ListIdentifier GetChromeUrlApiId() { return ListIdentifier(CHROME_PLATFORM, URL, API_ABUSE); } @@ -528,4 +534,37 @@ client_info->set_client_version(config.version); } +// static +bool V4ProtocolManagerUtil::GetIPV6AddressFromString( + const std::string& ip_address, + net::IPAddress* address) { + DCHECK(address); + if (!address->AssignFromIPLiteral(ip_address)) + return false; + if (address->IsIPv4()) + *address = net::ConvertIPv4ToIPv4MappedIPv6(*address); + return address->IsIPv6(); +} + +// static +bool V4ProtocolManagerUtil::IPAddressToEncodedIPV6Hash( + const std::string& ip_address, + FullHash* hashed_encoded_ip) { + net::IPAddress address; + if (!GetIPV6AddressFromString(ip_address, &address)) { + return false; + } + std::string packed_ip = net::IPAddressToPackedString(address); + if (packed_ip.empty()) { + return false; + } + + const std::string hash = base::SHA1HashString(packed_ip); + DCHECK_EQ(20u, hash.size()); + hashed_encoded_ip->resize(hash.size() + 1); + hashed_encoded_ip->replace(0, hash.size(), hash); + (*hashed_encoded_ip)[hash.size()] = static_cast<unsigned char>(128); + return true; +} + } // namespace safe_browsing
diff --git a/components/safe_browsing_db/v4_protocol_manager_util.h b/components/safe_browsing_db/v4_protocol_manager_util.h index 4970f07..3cadb0b 100644 --- a/components/safe_browsing_db/v4_protocol_manager_util.h +++ b/components/safe_browsing_db/v4_protocol_manager_util.h
@@ -20,6 +20,7 @@ namespace net { class HttpRequestHeaders; +class IPAddress; } // namespace net namespace safe_browsing { @@ -136,6 +137,7 @@ std::ostream& operator<<(std::ostream& os, const ListIdentifier& id); PlatformType GetCurrentPlatformType(); +const ListIdentifier GetAnyIpMalwareId(); const ListIdentifier GetChromeUrlApiId(); const ListIdentifier GetChromeUrlClientIncidentId(); const ListIdentifier GetChromeUrlMalwareId(); @@ -272,6 +274,16 @@ static void SetClientInfoFromConfig(ClientInfo* client_info, const V4ProtocolConfig& config); + static bool GetIPV6AddressFromString(const std::string& ip_address, + net::IPAddress* address); + + // Converts a IPV4 or IPV6 address in |ip_address| to the SHA1 hash of the + // corresponding packed IPV6 address in |hashed_encoded_ip|, and adds an + // extra byte containing the value 128 at the end. This is done to match the + // server implementation for calculating the hash prefix of an IP address. + static bool IPAddressToEncodedIPV6Hash(const std::string& ip_address, + FullHash* hashed_encoded_ip); + private: V4ProtocolManagerUtil(){}; FRIEND_TEST_ALL_PREFIXES(V4ProtocolManagerUtilTest, TestBackOffLogic);
diff --git a/components/safe_browsing_db/v4_protocol_manager_util_unittest.cc b/components/safe_browsing_db/v4_protocol_manager_util_unittest.cc index f3effab..0680d3c 100644 --- a/components/safe_browsing_db/v4_protocol_manager_util_unittest.cc +++ b/components/safe_browsing_db/v4_protocol_manager_util_unittest.cc
@@ -238,4 +238,35 @@ } } +TEST_F(V4ProtocolManagerUtilTest, TestIPAddressToEncodedIPV6) { + // To verify the test values, here's the python code: + // >> import socket, hashlib, binascii + // >> hashlib.sha1(socket.inet_pton(socket.AF_INET6, input)).digest() + + // chr(128) + // For example: + // >>> hashlib.sha1(socket.inet_pton(socket.AF_INET6, + // '::ffff:192.168.1.1')).digest() + chr(128) + // 'X\xf8\xa1\x17I\xe6Pl\xfd\xdb\xbb\xa0\x0c\x02\x9d#\n|\xe7\xcd\x80' + std::vector<std::tuple<bool, std::string, std::string>> test_cases = { + std::make_tuple(false, "", ""), + std::make_tuple( + true, "192.168.1.1", + "X\xF8\xA1\x17I\xE6Pl\xFD\xDB\xBB\xA0\f\x2\x9D#\n|\xE7\xCD\x80"), + std::make_tuple( + true, "::", + "\xE1)\xF2|Q\x3\xBC\\\xC4K\xCD\xF0\xA1^\x16\rDPf\xFF\x80")}; + for (size_t i = 0; i < test_cases.size(); i++) { + DVLOG(1) << "Running case: " << i; + bool success = std::get<0>(test_cases[i]); + const auto& input = std::get<1>(test_cases[i]); + const auto& expected_output = std::get<2>(test_cases[i]); + std::string encoded_ip; + ASSERT_EQ(success, V4ProtocolManagerUtil::IPAddressToEncodedIPV6Hash( + input, &encoded_ip)); + if (success) { + ASSERT_EQ(expected_output, encoded_ip); + } + } +} + } // namespace safe_browsing
diff --git a/components/search_engines/template_url_service.cc b/components/search_engines/template_url_service.cc index 22e2db0b..a858e96 100644 --- a/components/search_engines/template_url_service.cc +++ b/components/search_engines/template_url_service.cc
@@ -441,7 +441,8 @@ return provider_map_->GetTemplateURLForHost(host); TemplateURL* initial_dsp = initial_default_search_provider_.get(); return (initial_dsp && - (initial_dsp->GenerateSearchURL(search_terms_data()).host() == host)) + (initial_dsp->GenerateSearchURL(search_terms_data()).host_piece() == + host)) ? initial_dsp : nullptr; }
diff --git a/components/sessions/content/content_serialized_navigation_driver.cc b/components/sessions/content/content_serialized_navigation_driver.cc index 8f4d47bd..7aa7de8 100644 --- a/components/sessions/content/content_serialized_navigation_driver.cc +++ b/components/sessions/content/content_serialized_navigation_driver.cc
@@ -21,8 +21,8 @@ bool IsUberOrUberReplacementURL(const GURL& url) { return url.SchemeIs(content::kChromeUIScheme) && - (url.host() == content::kChromeUIHistoryHost || - url.host() == content::kChromeUIUberHost); + (url.host_piece() == content::kChromeUIHistoryHost || + url.host_piece() == content::kChromeUIUberHost); } } // namespace @@ -131,8 +131,8 @@ #if defined(OS_ANDROID) // Rewrite the old new tab and welcome page URLs to the new NTP URL. if (navigation->virtual_url_.SchemeIs(content::kChromeUIScheme) && - (navigation->virtual_url_.host() == "welcome" || - navigation->virtual_url_.host() == "newtab")) { + (navigation->virtual_url_.host_piece() == "welcome" || + navigation->virtual_url_.host_piece() == "newtab")) { navigation->virtual_url_ = GURL("chrome-native://newtab/"); navigation->original_request_url_ = navigation->virtual_url_; navigation->encoded_page_state_ = content::PageState::CreateFromURL(
diff --git a/components/spellcheck/BUILD.gn b/components/spellcheck/BUILD.gn new file mode 100644 index 0000000..d8d629a --- /dev/null +++ b/components/spellcheck/BUILD.gn
@@ -0,0 +1,17 @@ +# Copyright 2016 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//build/buildflag_header.gni") +import("//components/spellcheck/spellcheck_build_features.gni") + +buildflag_header("build_features") { + # Name this "build" features to avoid confusion with + # components/spellcheck/common/spellcheck_features.h which are runtime + # features. + header = "spellcheck_build_features.h" + flags = [ + "ENABLE_SPELLCHECK=$enable_spellcheck", + "USE_BROWSER_SPELLCHECKER=$use_browser_spellchecker", + ] +}
diff --git a/components/spellcheck/browser/BUILD.gn b/components/spellcheck/browser/BUILD.gn index e7315b8..5a571da 100644 --- a/components/spellcheck/browser/BUILD.gn +++ b/components/spellcheck/browser/BUILD.gn
@@ -36,6 +36,7 @@ public_deps = [ "//base", + "//components/spellcheck:build_features", "//components/spellcheck/common", ] deps = [
diff --git a/components/spellcheck/common/BUILD.gn b/components/spellcheck/common/BUILD.gn index 465a327..9062ff8 100644 --- a/components/spellcheck/common/BUILD.gn +++ b/components/spellcheck/common/BUILD.gn
@@ -18,6 +18,9 @@ "spellcheck_switches.h", ] + public_deps = [ + "//components/spellcheck:build_features", + ] deps = [ "//base:i18n", "//ipc",
diff --git a/components/spellcheck/common/spellcheck_features.cc b/components/spellcheck/common/spellcheck_features.cc index 33b2271..f6e8bb3 100644 --- a/components/spellcheck/common/spellcheck_features.cc +++ b/components/spellcheck/common/spellcheck_features.cc
@@ -5,10 +5,11 @@ #include "components/spellcheck/common/spellcheck_features.h" #include "base/sys_info.h" +#include "components/spellcheck/spellcheck_build_features.h" namespace spellcheck { -#if defined(ENABLE_SPELLCHECK) && defined(OS_ANDROID) +#if BUILDFLAG(ENABLE_SPELLCHECK) && defined(OS_ANDROID) // Enables/disables Android spellchecker. const base::Feature kAndroidSpellChecker{ @@ -32,6 +33,6 @@ return false; } -#endif // defined(ENABLE_SPELLCHECK) && defined(OS_ANDROID) +#endif // BUILDFLAG(ENABLE_SPELLCHECK) && defined(OS_ANDROID) } // namespace spellcheck
diff --git a/components/spellcheck/common/spellcheck_features.h b/components/spellcheck/common/spellcheck_features.h index ba0e2f2..311ac738 100644 --- a/components/spellcheck/common/spellcheck_features.h +++ b/components/spellcheck/common/spellcheck_features.h
@@ -6,15 +6,16 @@ #define COMPONENTS_SPELLCHECK_COMMON_SPELLCHECK_FEATURES_H_ #include "base/feature_list.h" +#include "components/spellcheck/spellcheck_build_features.h" namespace spellcheck { -#if defined(ENABLE_SPELLCHECK) && defined(OS_ANDROID) +#if BUILDFLAG(ENABLE_SPELLCHECK) && defined(OS_ANDROID) extern const base::Feature kAndroidSpellChecker; extern const base::Feature kAndroidSpellCheckerNonLowEnd; bool IsAndroidSpellCheckFeatureEnabled(); -#endif // defined(ENABLE_SPELLCHECK) && defined(OS_ANDROID) +#endif // BUILDFLAG(ENABLE_SPELLCHECK) && defined(OS_ANDROID) } // namespace spellcheck
diff --git a/components/spellcheck/common/spellcheck_message_generator.h b/components/spellcheck/common/spellcheck_message_generator.h index 0876034c..ccd76dd 100644 --- a/components/spellcheck/common/spellcheck_message_generator.h +++ b/components/spellcheck/common/spellcheck_message_generator.h
@@ -4,6 +4,8 @@ // Multiply-included file, hence no include guard. -#if defined(ENABLE_SPELLCHECK) +#include "components/spellcheck/spellcheck_build_features.h" + +#if BUILDFLAG(ENABLE_SPELLCHECK) #include "components/spellcheck/common/spellcheck_messages.h" #endif
diff --git a/components/spellcheck/common/spellcheck_messages.h b/components/spellcheck/common/spellcheck_messages.h index 49ef8020..60caa60 100644 --- a/components/spellcheck/common/spellcheck_messages.h +++ b/components/spellcheck/common/spellcheck_messages.h
@@ -10,10 +10,11 @@ #include "components/spellcheck/common/spellcheck_bdict_language.h" #include "components/spellcheck/common/spellcheck_marker.h" #include "components/spellcheck/common/spellcheck_result.h" +#include "components/spellcheck/spellcheck_build_features.h" #include "ipc/ipc_message_macros.h" #include "ipc/ipc_platform_file.h" -#if !defined(ENABLE_SPELLCHECK) +#if !BUILDFLAG(ENABLE_SPELLCHECK) #error "Spellcheck should be enabled" #endif @@ -65,7 +66,7 @@ IPC_MESSAGE_CONTROL1(SpellCheckHostMsg_RespondDocumentMarkers, std::vector<uint32_t> /* document marker identifiers */) -#if !defined(USE_BROWSER_SPELLCHECKER) +#if !BUILDFLAG(USE_BROWSER_SPELLCHECKER) // Sends text-check results from the Spelling service when the service finishes // checking text received by a SpellCheckHostMsg_CallSpellingService message. // If the service is not available, the 4th parameter should be false and the @@ -77,7 +78,7 @@ std::vector<SpellCheckResult>) #endif -#if defined(USE_BROWSER_SPELLCHECKER) +#if BUILDFLAG(USE_BROWSER_SPELLCHECKER) // This message tells the renderer to advance to the next misspelling. It is // sent when the user clicks the "Find Next" button on the spelling panel. IPC_MESSAGE_ROUTED0(SpellCheckMsg_AdvanceToNextMisspelling) @@ -104,7 +105,7 @@ base::string16 /* word */, bool /* true if checked word is misspelled */) -#if !defined(USE_BROWSER_SPELLCHECKER) +#if !BUILDFLAG(USE_BROWSER_SPELLCHECKER) // Asks the Spelling service to check text. When the service finishes checking // the input text, it sends a SpellingCheckMsg_RespondSpellingService with // text-check results. @@ -115,7 +116,7 @@ std::vector<SpellCheckMarker> /* markers */) #endif -#if defined(USE_BROWSER_SPELLCHECKER) +#if BUILDFLAG(USE_BROWSER_SPELLCHECKER) // Tells the browser to display or not display the SpellingPanel IPC_MESSAGE_ROUTED1(SpellCheckHostMsg_ShowSpellingPanel, bool /* if true, then show it, otherwise hide it*/)
diff --git a/components/spellcheck/common/spellcheck_switches.cc b/components/spellcheck/common/spellcheck_switches.cc index 0e79463..614b96a 100644 --- a/components/spellcheck/common/spellcheck_switches.cc +++ b/components/spellcheck/common/spellcheck_switches.cc
@@ -4,11 +4,12 @@ #include "build/build_config.h" #include "components/spellcheck/common/spellcheck_switches.h" +#include "components/spellcheck/spellcheck_build_features.h" namespace spellcheck { namespace switches { -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) // Enables participation in the field trial for user feedback to spelling // service. const char kEnableSpellingFeedbackFieldTrial[] = @@ -27,7 +28,7 @@ // TODO(rouslan): Remove this flag when feedback testing is complete. Revisit by // August 2013. const char kSpellingServiceFeedbackUrl[] = "spelling-service-feedback-url"; -#endif // defined(ENABLE_SPELLCHECK) +#endif // BUILDFLAG(ENABLE_SPELLCHECK) } // namespace switches } // namespace spellcheck
diff --git a/components/spellcheck/common/spellcheck_switches.h b/components/spellcheck/common/spellcheck_switches.h index abe4d6e2..30977908 100644 --- a/components/spellcheck/common/spellcheck_switches.h +++ b/components/spellcheck/common/spellcheck_switches.h
@@ -6,15 +6,16 @@ #define COMPONENTS_SPELLCHECK_COMMON_SPELLCHECK_SWITCHES_H_ #include "build/build_config.h" +#include "components/spellcheck/spellcheck_build_features.h" namespace spellcheck { namespace switches { -#if defined(ENABLE_SPELLCHECK) +#if BUILDFLAG(ENABLE_SPELLCHECK) extern const char kEnableSpellingFeedbackFieldTrial[]; extern const char kSpellingServiceFeedbackIntervalSeconds[]; extern const char kSpellingServiceFeedbackUrl[]; -#endif // defined(ENABLE_SPELLCHECK) +#endif // BUILDFLAG(ENABLE_SPELLCHECK) } // namespace switches } // namespace spellcheck
diff --git a/components/spellcheck/renderer/BUILD.gn b/components/spellcheck/renderer/BUILD.gn index 96663628..5160fb6 100644 --- a/components/spellcheck/renderer/BUILD.gn +++ b/components/spellcheck/renderer/BUILD.gn
@@ -2,7 +2,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -import("//build/config/features.gni") +import("//components/spellcheck/spellcheck_build_features.gni") source_set("renderer") { sources = [ @@ -37,6 +37,9 @@ ] } + public_deps = [ + "//components/spellcheck:build_features", + ] deps = [ "//base:i18n", "//components/spellcheck/common",
diff --git a/components/spellcheck/renderer/hunspell_engine.cc b/components/spellcheck/renderer/hunspell_engine.cc index 1918565..8617aaa 100644 --- a/components/spellcheck/renderer/hunspell_engine.cc +++ b/components/spellcheck/renderer/hunspell_engine.cc
@@ -13,6 +13,7 @@ #include "base/time/time.h" #include "components/spellcheck/common/spellcheck_common.h" #include "components/spellcheck/common/spellcheck_messages.h" +#include "components/spellcheck/spellcheck_build_features.h" #include "content/public/renderer/render_thread.h" #include "third_party/hunspell/src/hunspell/hunspell.hxx" @@ -33,7 +34,7 @@ "MaxSuggestLen too long"); } // namespace -#if !defined(USE_BROWSER_SPELLCHECKER) +#if !BUILDFLAG(USE_BROWSER_SPELLCHECKER) SpellingEngine* CreateNativeSpellingEngine() { return new HunspellEngine(); }
diff --git a/components/spellcheck/renderer/spellcheck.cc b/components/spellcheck/renderer/spellcheck.cc index 4757dc65..11fdc67 100644 --- a/components/spellcheck/renderer/spellcheck.cc +++ b/components/spellcheck/renderer/spellcheck.cc
@@ -25,6 +25,7 @@ #include "components/spellcheck/common/spellcheck_switches.h" #include "components/spellcheck/renderer/spellcheck_language.h" #include "components/spellcheck/renderer/spellcheck_provider.h" +#include "components/spellcheck/spellcheck_build_features.h" #include "content/public/renderer/render_thread.h" #include "content/public/renderer/render_view.h" #include "content/public/renderer/render_view_visitor.h" @@ -230,7 +231,7 @@ } custom_dictionary_.Init(custom_words); -#if !defined(USE_BROWSER_SPELLCHECKER) +#if !BUILDFLAG(USE_BROWSER_SPELLCHECKER) PostDelayedSpellCheckTask(pending_request_param_.release()); #endif } @@ -370,7 +371,7 @@ bool SpellCheck::SpellCheckParagraph( const base::string16& text, WebVector<WebTextCheckingResult>* results) { -#if !defined(USE_BROWSER_SPELLCHECKER) +#if !BUILDFLAG(USE_BROWSER_SPELLCHECKER) // Mac and Android have their own spell checkers,so this method won't be used DCHECK(results); std::vector<WebTextCheckingResult> textcheck_results; @@ -418,7 +419,7 @@ } // OSX and Android use their own spell checkers -#if !defined(USE_BROWSER_SPELLCHECKER) +#if !BUILDFLAG(USE_BROWSER_SPELLCHECKER) void SpellCheck::RequestTextChecking( const base::string16& text, blink::WebTextCheckingCompletion* completion) { @@ -448,7 +449,7 @@ } // OSX and Android don't have |pending_request_param_| -#if !defined(USE_BROWSER_SPELLCHECKER) +#if !BUILDFLAG(USE_BROWSER_SPELLCHECKER) void SpellCheck::PostDelayedSpellCheckTask(SpellcheckRequest* request) { if (!request) return; @@ -460,7 +461,7 @@ #endif // Mac and Android use their platform engines instead. -#if !defined(USE_BROWSER_SPELLCHECKER) +#if !BUILDFLAG(USE_BROWSER_SPELLCHECKER) void SpellCheck::PerformSpellCheck(SpellcheckRequest* param) { DCHECK(param);
diff --git a/components/spellcheck/renderer/spellcheck.h b/components/spellcheck/renderer/spellcheck.h index 9bcd1ce..fb9e9b9 100644 --- a/components/spellcheck/renderer/spellcheck.h +++ b/components/spellcheck/renderer/spellcheck.h
@@ -17,6 +17,7 @@ #include "base/memory/weak_ptr.h" #include "base/strings/string16.h" #include "components/spellcheck/renderer/custom_dictionary_engine.h" +#include "components/spellcheck/spellcheck_build_features.h" #include "content/public/renderer/render_thread_observer.h" struct SpellCheckBDictLanguage; @@ -89,7 +90,7 @@ // Requests to spellcheck the specified text in the background. This function // posts a background task and calls SpellCheckParagraph() in the task. -#if !defined (USE_BROWSER_SPELLCHECKER) +#if !BUILDFLAG(USE_BROWSER_SPELLCHECKER) void RequestTextChecking(const base::string16& text, blink::WebTextCheckingCompletion* completion); #endif @@ -132,7 +133,7 @@ void OnEnableSpellCheck(bool enable); void OnRequestDocumentMarkers(); -#if !defined (USE_BROWSER_SPELLCHECKER) +#if !BUILDFLAG(USE_BROWSER_SPELLCHECKER) // Posts delayed spellcheck task and clear it if any. // Takes ownership of |request|. void PostDelayedSpellCheckTask(SpellcheckRequest* request);
diff --git a/components/spellcheck/renderer/spellcheck_provider.cc b/components/spellcheck/renderer/spellcheck_provider.cc index f52fe59..bd91fc5 100644 --- a/components/spellcheck/renderer/spellcheck_provider.cc +++ b/components/spellcheck/renderer/spellcheck_provider.cc
@@ -11,6 +11,7 @@ #include "components/spellcheck/common/spellcheck_result.h" #include "components/spellcheck/renderer/spellcheck.h" #include "components/spellcheck/renderer/spellcheck_language.h" +#include "components/spellcheck/spellcheck_build_features.h" #include "content/public/renderer/render_view.h" #include "third_party/WebKit/public/platform/WebVector.h" #include "third_party/WebKit/public/web/WebDocument.h" @@ -72,7 +73,7 @@ last_request_.clear(); last_results_.assign(blink::WebVector<blink::WebTextCheckingResult>()); -#if defined(USE_BROWSER_SPELLCHECKER) +#if BUILDFLAG(USE_BROWSER_SPELLCHECKER) // Text check (unified request for grammar and spell check) is only // available for browser process, so we ask the system spellchecker // over IPC or return an empty result if the checker is not @@ -94,11 +95,11 @@ bool SpellCheckProvider::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(SpellCheckProvider, message) -#if !defined(USE_BROWSER_SPELLCHECKER) +#if !BUILDFLAG(USE_BROWSER_SPELLCHECKER) IPC_MESSAGE_HANDLER(SpellCheckMsg_RespondSpellingService, OnRespondSpellingService) #endif -#if defined(USE_BROWSER_SPELLCHECKER) +#if BUILDFLAG(USE_BROWSER_SPELLCHECKER) IPC_MESSAGE_HANDLER(SpellCheckMsg_AdvanceToNextMisspelling, OnAdvanceToNextMisspelling) IPC_MESSAGE_HANDLER(SpellCheckMsg_RespondTextCheck, OnRespondTextCheck) @@ -110,7 +111,7 @@ } void SpellCheckProvider::FocusedNodeChanged(const blink::WebNode& unused) { -#if defined(USE_BROWSER_SPELLCHECKER) +#if BUILDFLAG(USE_BROWSER_SPELLCHECKER) WebLocalFrame* frame = render_view()->GetWebView()->focusedFrame(); WebElement element = frame->document().isNull() ? WebElement() : frame->document().focusedElement(); @@ -166,7 +167,7 @@ } void SpellCheckProvider::showSpellingUI(bool show) { -#if defined(USE_BROWSER_SPELLCHECKER) +#if BUILDFLAG(USE_BROWSER_SPELLCHECKER) UMA_HISTOGRAM_BOOLEAN("SpellCheck.api.showUI", show); Send(new SpellCheckHostMsg_ShowSpellingPanel(routing_id(), show)); #endif @@ -178,13 +179,13 @@ void SpellCheckProvider::updateSpellingUIWithMisspelledWord( const WebString& word) { -#if defined(USE_BROWSER_SPELLCHECKER) +#if BUILDFLAG(USE_BROWSER_SPELLCHECKER) Send(new SpellCheckHostMsg_UpdateSpellingPanelWithMisspelledWord(routing_id(), word)); #endif } -#if !defined(USE_BROWSER_SPELLCHECKER) +#if !BUILDFLAG(USE_BROWSER_SPELLCHECKER) void SpellCheckProvider::OnRespondSpellingService( int identifier, bool succeeded, @@ -233,7 +234,7 @@ return false; } -#if defined(USE_BROWSER_SPELLCHECKER) +#if BUILDFLAG(USE_BROWSER_SPELLCHECKER) void SpellCheckProvider::OnAdvanceToNextMisspelling() { if (!render_view()->GetWebView()) return;
diff --git a/components/spellcheck/renderer/spellcheck_provider.h b/components/spellcheck/renderer/spellcheck_provider.h index 46e1606..82f8fa4 100644 --- a/components/spellcheck/renderer/spellcheck_provider.h +++ b/components/spellcheck/renderer/spellcheck_provider.h
@@ -12,6 +12,7 @@ #include "base/id_map.h" #include "base/macros.h" +#include "components/spellcheck/spellcheck_build_features.h" #include "content/public/renderer/render_view_observer.h" #include "content/public/renderer/render_view_observer_tracker.h" #include "third_party/WebKit/public/web/WebSpellCheckClient.h" @@ -93,7 +94,7 @@ void updateSpellingUIWithMisspelledWord( const blink::WebString& word) override; -#if !defined(USE_BROWSER_SPELLCHECKER) +#if !BUILDFLAG(USE_BROWSER_SPELLCHECKER) void OnRespondSpellingService( int identifier, bool succeeded, @@ -105,7 +106,7 @@ // needs to check this text. bool HasWordCharacters(const base::string16& text, int index) const; -#if defined(USE_BROWSER_SPELLCHECKER) +#if BUILDFLAG(USE_BROWSER_SPELLCHECKER) void OnAdvanceToNextMisspelling(); void OnRespondTextCheck( int identifier,
diff --git a/components/spellcheck/renderer/spellcheck_provider_test.cc b/components/spellcheck/renderer/spellcheck_provider_test.cc index 71a6c6d..de8c016 100644 --- a/components/spellcheck/renderer/spellcheck_provider_test.cc +++ b/components/spellcheck/renderer/spellcheck_provider_test.cc
@@ -8,6 +8,7 @@ #include "components/spellcheck/common/spellcheck_marker.h" #include "components/spellcheck/common/spellcheck_messages.h" #include "components/spellcheck/renderer/spellcheck.h" +#include "components/spellcheck/spellcheck_build_features.h" #include "ipc/ipc_message_macros.h" class MockSpellcheck: public SpellCheck { @@ -46,7 +47,7 @@ } bool TestingSpellCheckProvider::Send(IPC::Message* message) { -#if !defined(USE_BROWSER_SPELLCHECKER) +#if !BUILDFLAG(USE_BROWSER_SPELLCHECKER) // Call our mock message handlers. bool handled = true; IPC_BEGIN_MESSAGE_MAP(TestingSpellCheckProvider, *message) @@ -69,7 +70,7 @@ int identifier, const base::string16& text, const std::vector<SpellCheckMarker>& markers) { -#if defined (USE_BROWSER_SPELLCHECKER) +#if BUILDFLAG(USE_BROWSER_SPELLCHECKER) NOTREACHED(); #else ++spelling_service_call_count_;
diff --git a/components/spellcheck/spellcheck_build_features.gni b/components/spellcheck/spellcheck_build_features.gni new file mode 100644 index 0000000..ef26aea4a --- /dev/null +++ b/components/spellcheck/spellcheck_build_features.gni
@@ -0,0 +1,11 @@ +# Copyright 2016 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# Enable the spell checker. +enable_spellcheck = !is_ios + +# Use the operating system's spellchecker rather than hunspell. This does +# not affect the "red underline" spellchecker which can consult Google's +# server-based spellcheck service. +use_browser_spellchecker = is_android || is_mac
diff --git a/components/subresource_filter/content/browser/BUILD.gn b/components/subresource_filter/content/browser/BUILD.gn index 985dc83..5fe23a1 100644 --- a/components/subresource_filter/content/browser/BUILD.gn +++ b/components/subresource_filter/content/browser/BUILD.gn
@@ -4,8 +4,8 @@ static_library("browser") { sources = [ - "content_ruleset_distributor.cc", - "content_ruleset_distributor.h", + "content_ruleset_service_delegate.cc", + "content_ruleset_service_delegate.h", "content_subresource_filter_driver.cc", "content_subresource_filter_driver.h", "content_subresource_filter_driver_factory.cc", @@ -27,7 +27,7 @@ source_set("unit_tests") { testonly = true sources = [ - "content_ruleset_distributor_unittest.cc", + "content_ruleset_service_delegate_unittest.cc", "content_subresource_filter_driver_factory_unittest.cc", ] deps = [
diff --git a/components/subresource_filter/content/browser/content_ruleset_distributor_unittest.cc b/components/subresource_filter/content/browser/content_ruleset_distributor_unittest.cc deleted file mode 100644 index b067302..0000000 --- a/components/subresource_filter/content/browser/content_ruleset_distributor_unittest.cc +++ /dev/null
@@ -1,130 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/subresource_filter/content/browser/content_ruleset_distributor.h" - -#include <stddef.h> - -#include <string> -#include <tuple> -#include <utility> - -#include "base/files/file.h" -#include "base/files/file_util.h" -#include "base/files/scoped_temp_dir.h" -#include "base/numerics/safe_conversions.h" -#include "base/run_loop.h" -#include "components/subresource_filter/content/common/subresource_filter_messages.h" -#include "content/public/browser/notification_service.h" -#include "content/public/browser/notification_source.h" -#include "content/public/browser/notification_types.h" -#include "content/public/test/mock_render_process_host.h" -#include "content/public/test/test_browser_context.h" -#include "content/public/test/test_browser_thread_bundle.h" -#include "ipc/ipc_platform_file.h" -#include "ipc/ipc_test_sink.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace subresource_filter { - -namespace { - -class NotifyingMockRenderProcessHost : public content::MockRenderProcessHost { - public: - explicit NotifyingMockRenderProcessHost( - content::BrowserContext* browser_context) - : content::MockRenderProcessHost(browser_context) { - content::NotificationService::current()->Notify( - content::NOTIFICATION_RENDERER_PROCESS_CREATED, - content::Source<content::RenderProcessHost>(this), - content::NotificationService::NoDetails()); - } -}; - -std::string ReadFileContents(base::File* file) { - size_t length = base::checked_cast<size_t>(file->GetLength()); - std::string contents(length, 0); - file->Read(0, &contents[0], base::checked_cast<int>(length)); - return contents; -} - -// Extracts and takes ownership of the ruleset file handle in the IPC message. -base::File ExtractRulesetFromMessage(const IPC::Message* message) { - std::tuple<IPC::PlatformFileForTransit> arg; - SubresourceFilterMsg_SetRulesetForProcess::Read(message, &arg); - return IPC::PlatformFileForTransitToFile(std::get<0>(arg)); -} - -} // namespace - -class SubresourceFilterContentRulesetDistributorTest : public ::testing::Test { - public: - SubresourceFilterContentRulesetDistributorTest() - : existing_renderer_(&browser_context_) {} - - protected: - void SetUp() override { ASSERT_TRUE(scoped_temp_dir_.CreateUniqueTempDir()); } - - content::TestBrowserContext* browser_context() { return &browser_context_; } - - base::FilePath scoped_temp_file() const { - return scoped_temp_dir_.GetPath().AppendASCII("data"); - } - - void AssertSetRulesetForProcessMessageWithContent( - const IPC::Message* message, - const std::string& expected_contents) { - ASSERT_EQ(SubresourceFilterMsg_SetRulesetForProcess::ID, message->type()); - base::File ruleset_file = ExtractRulesetFromMessage(message); - ASSERT_TRUE(ruleset_file.IsValid()); - ASSERT_EQ(expected_contents, ReadFileContents(&ruleset_file)); - } - - private: - content::TestBrowserThreadBundle thread_bundle_; - content::TestBrowserContext browser_context_; - base::ScopedTempDir scoped_temp_dir_; - NotifyingMockRenderProcessHost existing_renderer_; - - DISALLOW_COPY_AND_ASSIGN(SubresourceFilterContentRulesetDistributorTest); -}; - -TEST_F(SubresourceFilterContentRulesetDistributorTest, - NoRuleset_NoIPCMessages) { - NotifyingMockRenderProcessHost existing_renderer(browser_context()); - ContentRulesetDistributor distributor; - NotifyingMockRenderProcessHost new_renderer(browser_context()); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(0u, existing_renderer.sink().message_count()); - EXPECT_EQ(0u, new_renderer.sink().message_count()); -} - -TEST_F(SubresourceFilterContentRulesetDistributorTest, - PublishedRuleset_IsDistributedToExistingAndNewRenderers) { - const char kTestFileContents[] = "foobar"; - base::WriteFile(scoped_temp_file(), kTestFileContents, - strlen(kTestFileContents)); - - base::File file; - file.Initialize(scoped_temp_file(), - base::File::FLAG_OPEN | base::File::FLAG_READ); - - NotifyingMockRenderProcessHost existing_renderer(browser_context()); - ContentRulesetDistributor distributor; - distributor.PublishNewVersion(std::move(file)); - base::RunLoop().RunUntilIdle(); - - ASSERT_EQ(1u, existing_renderer.sink().message_count()); - ASSERT_NO_FATAL_FAILURE(AssertSetRulesetForProcessMessageWithContent( - existing_renderer.sink().GetMessageAt(0), kTestFileContents)); - - NotifyingMockRenderProcessHost second_renderer(browser_context()); - base::RunLoop().RunUntilIdle(); - - ASSERT_EQ(1u, second_renderer.sink().message_count()); - ASSERT_NO_FATAL_FAILURE(AssertSetRulesetForProcessMessageWithContent( - second_renderer.sink().GetMessageAt(0), kTestFileContents)); -} - -} // namespace subresource_filter
diff --git a/components/subresource_filter/content/browser/content_ruleset_distributor.cc b/components/subresource_filter/content/browser/content_ruleset_service_delegate.cc similarity index 76% rename from components/subresource_filter/content/browser/content_ruleset_distributor.cc rename to components/subresource_filter/content/browser/content_ruleset_service_delegate.cc index 63b8193..079798aa 100644 --- a/components/subresource_filter/content/browser/content_ruleset_distributor.cc +++ b/components/subresource_filter/content/browser/content_ruleset_service_delegate.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/subresource_filter/content/browser/content_ruleset_distributor.h" +#include "components/subresource_filter/content/browser/content_ruleset_service_delegate.h" #include <utility> @@ -42,7 +42,7 @@ } // namespace -ContentRulesetDistributor::ContentRulesetDistributor() { +ContentRulesetServiceDelegate::ContentRulesetServiceDelegate() { // Must rely on notifications as RenderProcessHostObserver::RenderProcessReady // would only be called after queued IPC messages (potentially triggering a // navigation) had already been sent to the new renderer. @@ -51,11 +51,24 @@ content::NotificationService::AllBrowserContextsAndSources()); } -ContentRulesetDistributor::~ContentRulesetDistributor() { +ContentRulesetServiceDelegate::~ContentRulesetServiceDelegate() { CloseFileOnFileThread(&ruleset_data_); } -void ContentRulesetDistributor::PublishNewVersion(base::File ruleset_data) { +void ContentRulesetServiceDelegate::SetRulesetPublishedCallbackForTesting( + base::Closure callback) { + ruleset_published_callback_ = callback; +} + +void ContentRulesetServiceDelegate::PostAfterStartupTask(base::Closure task) { + content::BrowserThread::PostAfterStartupTask( + FROM_HERE, content::BrowserThread::GetTaskRunnerForThread( + content::BrowserThread::UI), + task); +} + +void ContentRulesetServiceDelegate::PublishNewRulesetVersion( + base::File ruleset_data) { DCHECK(ruleset_data.IsValid()); CloseFileOnFileThread(&ruleset_data_); ruleset_data_ = std::move(ruleset_data); @@ -63,9 +76,12 @@ it.Advance()) { SendRulesetToRenderProcess(&ruleset_data_, it.GetCurrentValue()); } + + if (!ruleset_published_callback_.is_null()) + ruleset_published_callback_.Run(); } -void ContentRulesetDistributor::Observe( +void ContentRulesetServiceDelegate::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) {
diff --git a/components/subresource_filter/content/browser/content_ruleset_distributor.h b/components/subresource_filter/content/browser/content_ruleset_service_delegate.h similarity index 61% rename from components/subresource_filter/content/browser/content_ruleset_distributor.h rename to components/subresource_filter/content/browser/content_ruleset_service_delegate.h index 70afa362..2238e9c 100644 --- a/components/subresource_filter/content/browser/content_ruleset_distributor.h +++ b/components/subresource_filter/content/browser/content_ruleset_service_delegate.h
@@ -2,27 +2,30 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef COMPONENTS_SUBRESOURCE_FILTER_CONTENT_BROWSER_CONTENT_RULESET_DISTRIBUTOR_H_ -#define COMPONENTS_SUBRESOURCE_FILTER_CONTENT_BROWSER_CONTENT_RULESET_DISTRIBUTOR_H_ +#ifndef COMPONENTS_SUBRESOURCE_FILTER_CONTENT_BROWSER_CONTENT_RULESET_SERVICE_DELEGATE_H_ +#define COMPONENTS_SUBRESOURCE_FILTER_CONTENT_BROWSER_CONTENT_RULESET_SERVICE_DELEGATE_H_ +#include "base/callback.h" #include "base/files/file.h" #include "base/macros.h" -#include "components/subresource_filter/core/browser/ruleset_distributor.h" +#include "components/subresource_filter/core/browser/ruleset_service_delegate.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" namespace subresource_filter { -// The content-layer specific implementation that receives the new versions of -// subresource filtering rules from the RulesetService, and distributes them to -// renderer processes, each with its own RulesetDealer. +// The content-layer specific implementation of RulesetServiceDelegate. +// +// Its main responsibility is receiving new versions of subresource filtering +// rules from the RulesetService, and distributing them to renderer processes, +// where they will be memory-mapped as-needed by the RulesetDealer. // // The distribution pipeline looks like this: // // RulesetService // | // v Browser -// RulesetDistributor +// RulesetServiceDelegate // | | // - - - - - - -|- - - - - - - |- - - - - - - - - - // | | | @@ -37,14 +40,17 @@ // // Renderer #1 | Renderer #n // -class ContentRulesetDistributor : public RulesetDistributor, - content::NotificationObserver { +class ContentRulesetServiceDelegate : public RulesetServiceDelegate, + content::NotificationObserver { public: - ContentRulesetDistributor(); - ~ContentRulesetDistributor() override; + ContentRulesetServiceDelegate(); + ~ContentRulesetServiceDelegate() override; + + void SetRulesetPublishedCallbackForTesting(base::Closure callback); // RulesetDistributor: - void PublishNewVersion(base::File ruleset_data) override; + void PostAfterStartupTask(base::Closure task) override; + void PublishNewRulesetVersion(base::File ruleset_data) override; private: // content::NotificationObserver: @@ -54,10 +60,11 @@ content::NotificationRegistrar notification_registrar_; base::File ruleset_data_; + base::Closure ruleset_published_callback_; - DISALLOW_COPY_AND_ASSIGN(ContentRulesetDistributor); + DISALLOW_COPY_AND_ASSIGN(ContentRulesetServiceDelegate); }; } // namespace subresource_filter -#endif // COMPONENTS_SUBRESOURCE_FILTER_CONTENT_BROWSER_CONTENT_RULESET_DISTRIBUTOR_H_ +#endif // COMPONENTS_SUBRESOURCE_FILTER_CONTENT_BROWSER_CONTENT_RULESET_SERVICE_DELEGATE_H_
diff --git a/components/subresource_filter/content/browser/content_ruleset_service_delegate_unittest.cc b/components/subresource_filter/content/browser/content_ruleset_service_delegate_unittest.cc new file mode 100644 index 0000000..8f3de27 --- /dev/null +++ b/components/subresource_filter/content/browser/content_ruleset_service_delegate_unittest.cc
@@ -0,0 +1,194 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/subresource_filter/content/browser/content_ruleset_service_delegate.h" + +#include <stddef.h> + +#include <string> +#include <tuple> +#include <utility> + +#include "base/bind.h" +#include "base/bind_helpers.h" +#include "base/callback.h" +#include "base/files/file.h" +#include "base/files/file_util.h" +#include "base/files/scoped_temp_dir.h" +#include "base/numerics/safe_conversions.h" +#include "base/run_loop.h" +#include "base/task_runner.h" +#include "components/subresource_filter/content/common/subresource_filter_messages.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/content_browser_client.h" +#include "content/public/browser/notification_service.h" +#include "content/public/browser/notification_source.h" +#include "content/public/browser/notification_types.h" +#include "content/public/test/mock_render_process_host.h" +#include "content/public/test/test_browser_context.h" +#include "content/public/test/test_browser_thread_bundle.h" +#include "ipc/ipc_platform_file.h" +#include "ipc/ipc_test_sink.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace subresource_filter { + +namespace { + +using MockClosureTarget = + ::testing::StrictMock<::testing::MockFunction<void()>>; + +class TestContentBrowserClient : public ::content::ContentBrowserClient { + public: + TestContentBrowserClient() {} + + // ::content::ContentBrowserClient: + void PostAfterStartupTask(const tracked_objects::Location&, + const scoped_refptr<base::TaskRunner>& task_runner, + const base::Closure& task) override { + scoped_refptr<base::TaskRunner> ui_task_runner = + content::BrowserThread::GetTaskRunnerForThread( + content::BrowserThread::UI); + EXPECT_EQ(ui_task_runner, task_runner); + last_task_ = task; + } + + void RunAfterStartupTask() { + if (!last_task_.is_null()) + last_task_.Run(); + } + + private: + base::Closure last_task_; + + DISALLOW_COPY_AND_ASSIGN(TestContentBrowserClient); +}; + +class NotifyingMockRenderProcessHost : public content::MockRenderProcessHost { + public: + explicit NotifyingMockRenderProcessHost( + content::BrowserContext* browser_context) + : content::MockRenderProcessHost(browser_context) { + content::NotificationService::current()->Notify( + content::NOTIFICATION_RENDERER_PROCESS_CREATED, + content::Source<content::RenderProcessHost>(this), + content::NotificationService::NoDetails()); + } +}; + +std::string ReadFileContents(base::File* file) { + size_t length = base::checked_cast<size_t>(file->GetLength()); + std::string contents(length, 0); + file->Read(0, &contents[0], base::checked_cast<int>(length)); + return contents; +} + +// Extracts and takes ownership of the ruleset file handle in the IPC message. +base::File ExtractRulesetFromMessage(const IPC::Message* message) { + std::tuple<IPC::PlatformFileForTransit> arg; + SubresourceFilterMsg_SetRulesetForProcess::Read(message, &arg); + return IPC::PlatformFileForTransitToFile(std::get<0>(arg)); +} + +} // namespace + +class SubresourceFilterContentRulesetServiceDelegateTest + : public ::testing::Test { + public: + SubresourceFilterContentRulesetServiceDelegateTest() + : old_browser_client_(nullptr), existing_renderer_(&browser_context_) {} + + protected: + void SetUp() override { + ASSERT_TRUE(scoped_temp_dir_.CreateUniqueTempDir()); + old_browser_client_ = content::SetBrowserClientForTesting(&browser_client_); + } + + void TearDown() override { + content::SetBrowserClientForTesting(old_browser_client_); + } + + content::TestBrowserContext* browser_context() { return &browser_context_; } + TestContentBrowserClient* browser_client() { return &browser_client_; } + + base::FilePath scoped_temp_file() const { + return scoped_temp_dir_.GetPath().AppendASCII("data"); + } + + void AssertSetRulesetForProcessMessageWithContent( + const IPC::Message* message, + const std::string& expected_contents) { + ASSERT_EQ(SubresourceFilterMsg_SetRulesetForProcess::ID, message->type()); + base::File ruleset_file = ExtractRulesetFromMessage(message); + ASSERT_TRUE(ruleset_file.IsValid()); + ASSERT_EQ(expected_contents, ReadFileContents(&ruleset_file)); + } + + private: + TestContentBrowserClient browser_client_; + content::ContentBrowserClient* old_browser_client_; + content::TestBrowserThreadBundle thread_bundle_; + content::TestBrowserContext browser_context_; + base::ScopedTempDir scoped_temp_dir_; + NotifyingMockRenderProcessHost existing_renderer_; + + DISALLOW_COPY_AND_ASSIGN(SubresourceFilterContentRulesetServiceDelegateTest); +}; + +TEST_F(SubresourceFilterContentRulesetServiceDelegateTest, + NoRuleset_NoIPCMessages) { + NotifyingMockRenderProcessHost existing_renderer(browser_context()); + ContentRulesetServiceDelegate delegate; + NotifyingMockRenderProcessHost new_renderer(browser_context()); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(0u, existing_renderer.sink().message_count()); + EXPECT_EQ(0u, new_renderer.sink().message_count()); +} + +TEST_F(SubresourceFilterContentRulesetServiceDelegateTest, + PublishedRuleset_IsDistributedToExistingAndNewRenderers) { + const char kTestFileContents[] = "foobar"; + base::WriteFile(scoped_temp_file(), kTestFileContents, + strlen(kTestFileContents)); + + base::File file; + file.Initialize(scoped_temp_file(), + base::File::FLAG_OPEN | base::File::FLAG_READ); + + NotifyingMockRenderProcessHost existing_renderer(browser_context()); + ContentRulesetServiceDelegate delegate; + MockClosureTarget publish_callback_target; + delegate.SetRulesetPublishedCallbackForTesting(base::Bind( + &MockClosureTarget::Call, base::Unretained(&publish_callback_target))); + EXPECT_CALL(publish_callback_target, Call()).Times(1); + delegate.PublishNewRulesetVersion(std::move(file)); + base::RunLoop().RunUntilIdle(); + ::testing::Mock::VerifyAndClearExpectations(&publish_callback_target); + + ASSERT_EQ(1u, existing_renderer.sink().message_count()); + ASSERT_NO_FATAL_FAILURE(AssertSetRulesetForProcessMessageWithContent( + existing_renderer.sink().GetMessageAt(0), kTestFileContents)); + + NotifyingMockRenderProcessHost second_renderer(browser_context()); + base::RunLoop().RunUntilIdle(); + + ASSERT_EQ(1u, second_renderer.sink().message_count()); + ASSERT_NO_FATAL_FAILURE(AssertSetRulesetForProcessMessageWithContent( + second_renderer.sink().GetMessageAt(0), kTestFileContents)); +} + +TEST_F(SubresourceFilterContentRulesetServiceDelegateTest, + PostAfterStartupTask) { + ContentRulesetServiceDelegate delegate; + + MockClosureTarget mock_closure_target; + delegate.PostAfterStartupTask(base::Bind( + &MockClosureTarget::Call, base::Unretained(&mock_closure_target))); + + EXPECT_CALL(mock_closure_target, Call()).Times(1); + browser_client()->RunAfterStartupTask(); +} + +} // namespace subresource_filter
diff --git a/components/subresource_filter/core/browser/BUILD.gn b/components/subresource_filter/core/browser/BUILD.gn index 9e3ba6f..39518b48 100644 --- a/components/subresource_filter/core/browser/BUILD.gn +++ b/components/subresource_filter/core/browser/BUILD.gn
@@ -4,9 +4,9 @@ static_library("browser") { sources = [ - "ruleset_distributor.h", "ruleset_service.cc", "ruleset_service.h", + "ruleset_service_delegate.h", "subresource_filter_client.h", "subresource_filter_constants.cc", "subresource_filter_constants.h",
diff --git a/components/subresource_filter/core/browser/ruleset_distributor.h b/components/subresource_filter/core/browser/ruleset_distributor.h deleted file mode 100644 index fe9e62e..0000000 --- a/components/subresource_filter/core/browser/ruleset_distributor.h +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_SUBRESOURCE_FILTER_CORE_BROWSER_RULESET_DISTRIBUTOR_H_ -#define COMPONENTS_SUBRESOURCE_FILTER_CORE_BROWSER_RULESET_DISTRIBUTOR_H_ - -#include "base/files/file.h" - -namespace subresource_filter { - -// Defines the interface for the implementation responsible for distributing -// updated versions of subresource filtering rules to consumers. It is not -// intended as a general-purpose `subscriber` to the RulesetService. The extra -// level of indirection exists to allow the service to not depend on content/. -class RulesetDistributor { - public: - virtual ~RulesetDistributor() = default; - - // Instructs the distributor to redistribute the new version of the |ruleset| - // to all existing consumers, and to distribute it to future consumers. - virtual void PublishNewVersion(base::File ruleset_data) = 0; -}; - -} // namespace subresource_filter - -#endif // COMPONENTS_SUBRESOURCE_FILTER_CORE_BROWSER_RULESET_DISTRIBUTOR_H_
diff --git a/components/subresource_filter/core/browser/ruleset_service.cc b/components/subresource_filter/core/browser/ruleset_service.cc index c35c51f..8908987 100644 --- a/components/subresource_filter/core/browser/ruleset_service.cc +++ b/components/subresource_filter/core/browser/ruleset_service.cc
@@ -22,7 +22,7 @@ #include "base/threading/thread_restrictions.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" -#include "components/subresource_filter/core/browser/ruleset_distributor.h" +#include "components/subresource_filter/core/browser/ruleset_service_delegate.h" #include "components/subresource_filter/core/browser/subresource_filter_constants.h" #include "components/subresource_filter/core/common/copying_file_stream.h" #include "components/subresource_filter/core/common/indexed_ruleset.h" @@ -51,7 +51,7 @@ } // Implements operations on a `sentinel file`, which is used as a safeguard to -// prevent crash-looping if ruleset indexing crashes on start-up. +// prevent crash-looping if ruleset indexing crashes right after start-up. // // The sentinel file is placed in the ruleset version directory just before // indexing commences, and removed afterwards. Therefore, if a sentinel file is @@ -146,23 +146,34 @@ RulesetService::RulesetService( PrefService* local_state, scoped_refptr<base::SequencedTaskRunner> blocking_task_runner, + std::unique_ptr<RulesetServiceDelegate> delegate, const base::FilePath& indexed_ruleset_base_dir) : local_state_(local_state), blocking_task_runner_(blocking_task_runner), + delegate_(std::move(delegate)), + is_after_startup_(false), indexed_ruleset_base_dir_(indexed_ruleset_base_dir) { + DCHECK(delegate_); DCHECK_NE(local_state_->GetInitializationStatus(), PrefService::INITIALIZATION_STATUS_WAITING); + delegate_->PostAfterStartupTask( + base::Bind(&RulesetService::InitializeAfterStartup, AsWeakPtr())); + IndexedRulesetVersion most_recently_indexed_version; most_recently_indexed_version.ReadFromPrefs(local_state_); if (most_recently_indexed_version.IsValid() && - most_recently_indexed_version.IsCurrentFormatVersion()) + most_recently_indexed_version.IsCurrentFormatVersion()) { OpenAndPublishRuleset(most_recently_indexed_version); + } } RulesetService::~RulesetService() {} void RulesetService::IndexAndStoreAndPublishRulesetIfNeeded( const UnindexedRulesetInfo& unindexed_ruleset_info) { + if (unindexed_ruleset_info.content_version.empty()) + return; + // Trying to store a ruleset with the same version for a second time would not // only be futile, but would fail on Windows due to "File System Tunneling" as // long as the previously stored copy of the rules is still in use. @@ -170,21 +181,22 @@ most_recently_indexed_version.ReadFromPrefs(local_state_); if (most_recently_indexed_version.IsCurrentFormatVersion() && most_recently_indexed_version.content_version == - unindexed_ruleset_info.content_version) + unindexed_ruleset_info.content_version) { return; + } + + // During start-up, retain information about the most recently supplied + // unindexed ruleset, to be processed after start-up is complete. + if (!is_after_startup_) { + queued_unindexed_ruleset_info_ = unindexed_ruleset_info; + return; + } IndexAndStoreRuleset( unindexed_ruleset_info, base::Bind(&RulesetService::OpenAndPublishRuleset, AsWeakPtr())); } -void RulesetService::RegisterDistributor( - std::unique_ptr<RulesetDistributor> distributor) { - if (ruleset_data_ && ruleset_data_->IsValid()) - distributor->PublishNewVersion(ruleset_data_->DuplicateFile()); - distributors_.push_back(std::move(distributor)); -} - // static base::FilePath RulesetService::GetRulesetDataFilePath( const base::FilePath& version_directory) { @@ -356,11 +368,20 @@ return IndexAndWriteRulesetResult::SUCCESS; } +void RulesetService::InitializeAfterStartup() { + is_after_startup_ = true; + if (!queued_unindexed_ruleset_info_.content_version.empty()) { + IndexAndStoreRuleset( + queued_unindexed_ruleset_info_, + base::Bind(&RulesetService::OpenAndPublishRuleset, AsWeakPtr())); + queued_unindexed_ruleset_info_ = UnindexedRulesetInfo(); + } +} + void RulesetService::IndexAndStoreRuleset( const UnindexedRulesetInfo& unindexed_ruleset_info, const WriteRulesetCallback& success_callback) { - if (unindexed_ruleset_info.content_version.empty()) - return; + DCHECK(!unindexed_ruleset_info.content_version.empty()); base::PostTaskAndReplyWithResult( blocking_task_runner_.get(), FROM_HERE, base::Bind(&RulesetService::IndexAndWriteRuleset, @@ -411,8 +432,7 @@ return; DCHECK_EQ(error, base::File::Error::FILE_OK); - for (auto& distributor : distributors_) - distributor->PublishNewVersion(ruleset_data_->DuplicateFile()); + delegate_->PublishNewRulesetVersion(ruleset_data_->DuplicateFile()); } } // namespace subresource_filter
diff --git a/components/subresource_filter/core/browser/ruleset_service.h b/components/subresource_filter/core/browser/ruleset_service.h index d01579a..e133c1b3 100644 --- a/components/subresource_filter/core/browser/ruleset_service.h +++ b/components/subresource_filter/core/browser/ruleset_service.h
@@ -32,7 +32,7 @@ namespace subresource_filter { class RulesetIndexer; -class RulesetDistributor; +class RulesetServiceDelegate; // Encapsulates information about a version of unindexed subresource // filtering rules on disk. @@ -90,7 +90,8 @@ // Responsible for indexing subresource filtering rules that are downloaded // through the component updater; for versioned storage of the indexed ruleset; // and for supplying the most up-to-date version of the indexed ruleset to the -// RulesetDistributors for distribution. +// RulesetServiceDelegate, provided in the constructor, that abstracts away +// distribution of the ruleset to renderers. // // Files corresponding to each version of the indexed ruleset are stored in a // separate subdirectory inside |indexed_ruleset_base_dir| named after the @@ -126,6 +127,7 @@ // See class comments for details of arguments. RulesetService(PrefService* local_state, scoped_refptr<base::SequencedTaskRunner> blocking_task_runner, + std::unique_ptr<RulesetServiceDelegate> delegate, const base::FilePath& indexed_ruleset_base_dir); virtual ~RulesetService(); @@ -135,17 +137,15 @@ // need to remain accessible even after the method returns. // // Computation-heavy steps and I/O are performed on a background thread. - // Still, to prevent start-up congestion, this method should be called at the - // earliest shortly after start-up. + // Furthermore, to prevent start-up congestion, new rulesets provided via this + // method will not be processed until after start-up. // // Virtual so that it can be mocked out in tests. virtual void IndexAndStoreAndPublishRulesetIfNeeded( const UnindexedRulesetInfo& unindexed_ruleset_info); - // Registers a |distributor| that will be notified each time a new version of - // the ruleset becomes avalable. The |distributor| will be destroyed along - // with |this|. - void RegisterDistributor(std::unique_ptr<RulesetDistributor> distributor); + // Exposed for browser tests. + RulesetServiceDelegate* delegate() { return delegate_.get(); } private: friend class SubresourceFilteringRulesetServiceTest; @@ -198,6 +198,9 @@ static decltype(&IndexRuleset) g_index_ruleset_func; static decltype(&base::ReplaceFile) g_replace_file_func; + // Performs indexing of the queued unindexed ruleset (if any) after start-up. + void InitializeAfterStartup(); + // Posts a task to the |blocking_task_runner_| to index and persist the given // unindexed ruleset. Then, on success, updates the most recently indexed // version in preferences and invokes |success_callback| on the calling @@ -213,10 +216,13 @@ PrefService* const local_state_; scoped_refptr<base::SequencedTaskRunner> blocking_task_runner_; + std::unique_ptr<RulesetServiceDelegate> delegate_; + + UnindexedRulesetInfo queued_unindexed_ruleset_info_; + bool is_after_startup_; const base::FilePath indexed_ruleset_base_dir_; std::unique_ptr<base::FileProxy> ruleset_data_; - std::vector<std::unique_ptr<RulesetDistributor>> distributors_; DISALLOW_COPY_AND_ASSIGN(RulesetService); };
diff --git a/components/subresource_filter/core/browser/ruleset_service_delegate.h b/components/subresource_filter/core/browser/ruleset_service_delegate.h new file mode 100644 index 0000000..e6aa823 --- /dev/null +++ b/components/subresource_filter/core/browser/ruleset_service_delegate.h
@@ -0,0 +1,29 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_SUBRESOURCE_FILTER_CORE_BROWSER_RULESET_SERVICE_DELEGATE_H_ +#define COMPONENTS_SUBRESOURCE_FILTER_CORE_BROWSER_RULESET_SERVICE_DELEGATE_H_ + +#include "base/callback_forward.h" +#include "base/files/file.h" + +namespace subresource_filter { + +// Interface for a delegate that implements RulesetService operations that +// depend on content/, thus allowing the service to not directly depend on it. +class RulesetServiceDelegate { + public: + virtual ~RulesetServiceDelegate() = default; + + // Posts |task| to be executed on the UI thread after browser start-up. + virtual void PostAfterStartupTask(base::Closure task) = 0; + + // Redistributes the new version of the |ruleset| to all existing consumers, + // and sets up |ruleset| to be distributed to all future consumers. + virtual void PublishNewRulesetVersion(base::File ruleset_data) = 0; +}; + +} // namespace subresource_filter + +#endif // COMPONENTS_SUBRESOURCE_FILTER_CORE_BROWSER_RULESET_SERVICE_DELEGATE_H_
diff --git a/components/subresource_filter/core/browser/ruleset_service_unittest.cc b/components/subresource_filter/core/browser/ruleset_service_unittest.cc index bdc571f88..ad45dd8 100644 --- a/components/subresource_filter/core/browser/ruleset_service_unittest.cc +++ b/components/subresource_filter/core/browser/ruleset_service_unittest.cc
@@ -26,7 +26,7 @@ #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "components/prefs/testing_pref_service.h" -#include "components/subresource_filter/core/browser/ruleset_distributor.h" +#include "components/subresource_filter/core/browser/ruleset_service_delegate.h" #include "components/subresource_filter/core/common/test_ruleset_creator.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -39,9 +39,11 @@ const char kTestContentVersion1[] = "1.2.3.4"; const char kTestContentVersion2[] = "1.2.3.5"; +const char kTestContentVersion3[] = "1.2.3.6"; const char kTestDisallowedSuffix1[] = "foo"; const char kTestDisallowedSuffix2[] = "bar"; +const char kTestDisallowedSuffix3[] = "baz"; const char kTestLicenseContents[] = "Lorem ipsum"; // Helpers -------------------------------------------------------------------- @@ -81,21 +83,37 @@ // Mocks ---------------------------------------------------------------------- -class MockRulesetDistributor : public RulesetDistributor { +class MockRulesetServiceDelegate : public RulesetServiceDelegate { public: - MockRulesetDistributor() = default; - ~MockRulesetDistributor() override = default; + MockRulesetServiceDelegate() = default; + ~MockRulesetServiceDelegate() override = default; - void PublishNewVersion(base::File ruleset_data) override { + void SimulateStartupCompleted() { + is_after_startup_ = true; + for (const auto& task : after_startup_tasks_) + task.Run(); + after_startup_tasks_.clear(); + } + + void PostAfterStartupTask(base::Closure task) override { + if (is_after_startup_) + task.Run(); + else + after_startup_tasks_.push_back(task); + } + + void PublishNewRulesetVersion(base::File ruleset_data) override { published_rulesets_.push_back(std::move(ruleset_data)); } std::vector<base::File>& published_rulesets() { return published_rulesets_; } private: + bool is_after_startup_ = false; + std::vector<base::Closure> after_startup_tasks_; std::vector<base::File> published_rulesets_; - DISALLOW_COPY_AND_ASSIGN(MockRulesetDistributor); + DISALLOW_COPY_AND_ASSIGN(MockRulesetServiceDelegate); }; bool MockFailingReplaceFile(const base::FilePath&, @@ -128,14 +146,14 @@ SubresourceFilteringRulesetServiceTest() : task_runner_(new base::TestSimpleTaskRunner), task_runner_handle_(task_runner_), - mock_distributor_(nullptr) {} + mock_delegate_(nullptr) {} protected: void SetUp() override { IndexedRulesetVersion::RegisterPrefs(pref_service_.registry()); SetUpTempDir(); - ResetService(CreateRulesetService()); + ResetRulesetService(); RunUntilIdle(); ASSERT_NO_FATAL_FAILURE( @@ -144,25 +162,25 @@ ASSERT_NO_FATAL_FAILURE( ruleset_creator_.CreateRulesetToDisallowURLsWithPathSuffix( kTestDisallowedSuffix2, &test_ruleset_2_)); + ASSERT_NO_FATAL_FAILURE( + ruleset_creator_.CreateRulesetToDisallowURLsWithPathSuffix( + kTestDisallowedSuffix3, &test_ruleset_3_)); } virtual void SetUpTempDir() { ASSERT_TRUE(scoped_temp_dir_.CreateUniqueTempDir()); } - std::unique_ptr<RulesetService> CreateRulesetService() { - return base::MakeUnique<RulesetService>(&pref_service_, task_runner_, - base_dir()); + void ResetRulesetService() { + service_ = base::MakeUnique<RulesetService>( + &pref_service_, task_runner_, + base::WrapUnique(mock_delegate_ = new MockRulesetServiceDelegate), + base_dir()); } - void ResetService(std::unique_ptr<RulesetService> new_service = nullptr) { - service_ = std::move(new_service); - if (service_) { - service_->RegisterDistributor( - base::WrapUnique(mock_distributor_ = new MockRulesetDistributor())); - } else { - mock_distributor_ = nullptr; - } + void ClearRulesetService() { + mock_delegate_ = nullptr; + service_.reset(); } // Creates a new file with the given license |contents| at a unique temporary @@ -239,7 +257,7 @@ PrefService* prefs() { return &pref_service_; } RulesetService* service() { return service_.get(); } - MockRulesetDistributor* mock_distributor() { return mock_distributor_; } + MockRulesetServiceDelegate* mock_delegate() { return mock_delegate_; } virtual base::FilePath effective_temp_dir() const { return scoped_temp_dir_.GetPath(); @@ -248,6 +266,7 @@ TestRulesetCreator* test_ruleset_creator() { return &ruleset_creator_; } const TestRulesetPair& test_ruleset_1() const { return test_ruleset_1_; } const TestRulesetPair& test_ruleset_2() const { return test_ruleset_2_; } + const TestRulesetPair& test_ruleset_3() const { return test_ruleset_3_; } base::FilePath base_dir() const { return effective_temp_dir().AppendASCII("Rules").AppendASCII("Indexed"); } @@ -260,10 +279,11 @@ TestRulesetCreator ruleset_creator_; TestRulesetPair test_ruleset_1_; TestRulesetPair test_ruleset_2_; + TestRulesetPair test_ruleset_3_; base::ScopedTempDir scoped_temp_dir_; std::unique_ptr<RulesetService> service_; - MockRulesetDistributor* mock_distributor_; // Weak, owned by |service_|. + MockRulesetServiceDelegate* mock_delegate_; // Weak, owned by |service_|. DISALLOW_COPY_AND_ASSIGN(SubresourceFilteringRulesetServiceTest); }; @@ -392,7 +412,8 @@ } TEST_F(SubresourceFilteringRulesetServiceTest, Startup_NoRulesetNotPublished) { - EXPECT_EQ(0u, mock_distributor()->published_rulesets().size()); + RunUntilIdle(); + EXPECT_EQ(0u, mock_delegate()->published_rulesets().size()); } // It should not normally happen that Local State indicates that a usable @@ -405,9 +426,9 @@ // "Forget" to write ruleset data. current_version.SaveToPrefs(prefs()); - ResetService(CreateRulesetService()); + ResetRulesetService(); RunUntilIdle(); - EXPECT_EQ(0u, mock_distributor()->published_rulesets().size()); + EXPECT_EQ(0u, mock_delegate()->published_rulesets().size()); } TEST_F(SubresourceFilteringRulesetServiceTest, @@ -419,9 +440,9 @@ legacy_version.SaveToPrefs(prefs()); WriteRuleset(test_ruleset_1(), legacy_version); - ResetService(CreateRulesetService()); + ResetRulesetService(); RunUntilIdle(); - EXPECT_EQ(0u, mock_distributor()->published_rulesets().size()); + EXPECT_EQ(0u, mock_delegate()->published_rulesets().size()); } TEST_F(SubresourceFilteringRulesetServiceTest, @@ -431,45 +452,58 @@ current_version.SaveToPrefs(prefs()); WriteRuleset(test_ruleset_1(), current_version); - ResetService(CreateRulesetService()); + ResetRulesetService(); RunUntilIdle(); - ASSERT_EQ(1u, mock_distributor()->published_rulesets().size()); + ASSERT_EQ(1u, mock_delegate()->published_rulesets().size()); ASSERT_NO_FATAL_FAILURE(AssertValidRulesetFileWithContents( - &mock_distributor()->published_rulesets()[0], + &mock_delegate()->published_rulesets()[0], test_ruleset_1().indexed.contents)); + + mock_delegate()->SimulateStartupCompleted(); + RunUntilIdle(); + EXPECT_EQ(1u, mock_delegate()->published_rulesets().size()); } TEST_F(SubresourceFilteringRulesetServiceTest, NewRuleset_Published) { + mock_delegate()->SimulateStartupCompleted(); IndexAndStoreAndPublishUpdatedRuleset(test_ruleset_1(), kTestContentVersion1); RunUntilIdle(); - ASSERT_EQ(1u, mock_distributor()->published_rulesets().size()); + ASSERT_EQ(1u, mock_delegate()->published_rulesets().size()); ASSERT_NO_FATAL_FAILURE(AssertValidRulesetFileWithContents( - &mock_distributor()->published_rulesets()[0], - test_ruleset_1().indexed.contents)); - - MockRulesetDistributor* new_distributor = new MockRulesetDistributor; - service()->RegisterDistributor(base::WrapUnique(new_distributor)); - ASSERT_EQ(1u, new_distributor->published_rulesets().size()); - ASSERT_NO_FATAL_FAILURE(AssertValidRulesetFileWithContents( - &new_distributor->published_rulesets()[0], + &mock_delegate()->published_rulesets()[0], test_ruleset_1().indexed.contents)); } TEST_F(SubresourceFilteringRulesetServiceTest, NewRulesetWithEmptyVersion_NotPublished) { + mock_delegate()->SimulateStartupCompleted(); IndexAndStoreAndPublishUpdatedRuleset(test_ruleset_1(), std::string()); RunUntilIdle(); - ASSERT_EQ(0u, mock_distributor()->published_rulesets().size()); - MockRulesetDistributor* new_distributor = new MockRulesetDistributor; - service()->RegisterDistributor(base::WrapUnique(new_distributor)); - ASSERT_EQ(0u, new_distributor->published_rulesets().size()); + ASSERT_EQ(0u, mock_delegate()->published_rulesets().size()); +} + +TEST_F(SubresourceFilteringRulesetServiceTest, + NewRulesetEarly_PublishedAfterStartupCompleted) { + IndexAndStoreAndPublishUpdatedRuleset(test_ruleset_1(), kTestContentVersion1); + RunUntilIdle(); + + ASSERT_EQ(0u, mock_delegate()->published_rulesets().size()); + + mock_delegate()->SimulateStartupCompleted(); + RunUntilIdle(); + + ASSERT_EQ(1u, mock_delegate()->published_rulesets().size()); + ASSERT_NO_FATAL_FAILURE(AssertValidRulesetFileWithContents( + &mock_delegate()->published_rulesets()[0], + test_ruleset_1().indexed.contents)); } TEST_F(SubresourceFilteringRulesetServiceTest, NewRuleset_Persisted) { base::HistogramTester histogram_tester; + mock_delegate()->SimulateStartupCompleted(); base::FilePath original_license_path; CreateTestLicenseFile(kTestLicenseContents, &original_license_path); @@ -492,12 +526,12 @@ &actual_license_contents)); EXPECT_EQ(kTestLicenseContents, actual_license_contents); - ResetService(CreateRulesetService()); + ResetRulesetService(); RunUntilIdle(); - ASSERT_EQ(1u, mock_distributor()->published_rulesets().size()); + ASSERT_EQ(1u, mock_delegate()->published_rulesets().size()); ASSERT_NO_FATAL_FAILURE(AssertValidRulesetFileWithContents( - &mock_distributor()->published_rulesets()[0], + &mock_delegate()->published_rulesets()[0], test_ruleset_1().indexed.contents)); histogram_tester.ExpectTotalCount( @@ -518,6 +552,7 @@ // contents when the same version of the ruleset is fed to the service again. TEST_F(SubresourceFilteringRulesetServiceTest, NewRuleset_OverwritesBadCopyOfSameVersionOnDisk) { + mock_delegate()->SimulateStartupCompleted(); // Emulate a bad ruleset by writing |test_ruleset_2| into the directory // corresponding to |test_ruleset_1| and not updating prefs. IndexedRulesetVersion same_version_but_incomplete( @@ -534,15 +569,16 @@ stored_version.format_version); EXPECT_FALSE(base::PathExists(GetExpectedSentinelFilePath(stored_version))); - ASSERT_EQ(1u, mock_distributor()->published_rulesets().size()); + ASSERT_EQ(1u, mock_delegate()->published_rulesets().size()); ASSERT_NO_FATAL_FAILURE(AssertValidRulesetFileWithContents( - &mock_distributor()->published_rulesets()[0], + &mock_delegate()->published_rulesets()[0], test_ruleset_1().indexed.contents)); } TEST_F(SubresourceFilteringRulesetServiceTest, NewRuleset_SuccessWithUnsupportedRules) { base::HistogramTester histogram_tester; + mock_delegate()->SimulateStartupCompleted(); // URL patterns longer than 255 characters are not supported. const std::string kTooLongSuffix(1000, 'a'); @@ -562,7 +598,7 @@ stored_version.format_version); EXPECT_FALSE(base::PathExists(GetExpectedSentinelFilePath(stored_version))); - ASSERT_EQ(1u, mock_distributor()->published_rulesets().size()); + ASSERT_EQ(1u, mock_delegate()->published_rulesets().size()); histogram_tester.ExpectTotalCount( "SubresourceFilter.IndexRuleset.WallDuration", 1); @@ -576,6 +612,8 @@ TEST_F(SubresourceFilteringRulesetServiceTest, NewRuleset_CannotOpenUnindexedRulesetFile) { base::HistogramTester histogram_tester; + mock_delegate()->SimulateStartupCompleted(); + UnindexedRulesetInfo ruleset_info; ruleset_info.ruleset_path = base::FilePath(); // Non-existent. ruleset_info.content_version = kTestContentVersion1; @@ -592,7 +630,7 @@ kTestContentVersion1, IndexedRulesetVersion::CurrentFormatVersion()); EXPECT_FALSE(base::PathExists(GetExpectedSentinelFilePath(failed_version))); - ASSERT_EQ(0u, mock_distributor()->published_rulesets().size()); + ASSERT_EQ(0u, mock_delegate()->published_rulesets().size()); histogram_tester.ExpectUniqueSample( "SubresourceFilter.WriteRuleset.Result", @@ -603,6 +641,8 @@ TEST_F(SubresourceFilteringRulesetServiceTest, NewRuleset_ParseFailure) { base::HistogramTester histogram_tester; + mock_delegate()->SimulateStartupCompleted(); + const std::string kGarbage(10000, '\xff'); ASSERT_TRUE(base::AppendToFile(test_ruleset_1().unindexed.path, kGarbage.data(), @@ -620,7 +660,7 @@ kTestContentVersion1, IndexedRulesetVersion::CurrentFormatVersion()); EXPECT_TRUE(base::PathExists(GetExpectedSentinelFilePath(failed_version))); - ASSERT_EQ(0u, mock_distributor()->published_rulesets().size()); + ASSERT_EQ(0u, mock_delegate()->published_rulesets().size()); histogram_tester.ExpectUniqueSample( "SubresourceFilter.WriteRuleset.Result", @@ -630,6 +670,7 @@ } TEST_F(SubresourceFilteringRulesetServiceDeathTest, NewRuleset_IndexingCrash) { + mock_delegate()->SimulateStartupCompleted(); #if GTEST_HAS_DEATH_TEST auto scoped_override(OverrideFunctionForScope( &RulesetService::g_index_ruleset_func, &MockCrashingIndexRuleset)); @@ -654,10 +695,11 @@ EXPECT_TRUE(base::PathExists(GetExpectedSentinelFilePath(crashed_version))); base::HistogramTester histogram_tester; - ResetService(CreateRulesetService()); + ResetRulesetService(); + mock_delegate()->SimulateStartupCompleted(); RunUntilIdle(); - ASSERT_EQ(0u, mock_distributor()->published_rulesets().size()); + ASSERT_EQ(0u, mock_delegate()->published_rulesets().size()); // The subsequent indexing attempt should be aborted. IndexAndStoreAndPublishUpdatedRuleset(test_ruleset_1(), kTestContentVersion1); @@ -667,7 +709,7 @@ stored_version.ReadFromPrefs(prefs()); EXPECT_FALSE(stored_version.IsValid()); - ASSERT_EQ(0u, mock_distributor()->published_rulesets().size()); + ASSERT_EQ(0u, mock_delegate()->published_rulesets().size()); histogram_tester.ExpectUniqueSample( "SubresourceFilter.WriteRuleset.Result", @@ -678,8 +720,10 @@ TEST_F(SubresourceFilteringRulesetServiceTest, NewRuleset_WriteFailure) { base::HistogramTester histogram_tester; + mock_delegate()->SimulateStartupCompleted(); auto scoped_override(OverrideFunctionForScope( &RulesetService::g_replace_file_func, &MockFailingReplaceFile)); + IndexAndStoreAndPublishUpdatedRuleset(test_ruleset_1(), kTestContentVersion1); RunUntilIdle(); @@ -687,7 +731,7 @@ stored_version.ReadFromPrefs(prefs()); EXPECT_FALSE(stored_version.IsValid()); - ASSERT_EQ(0u, mock_distributor()->published_rulesets().size()); + ASSERT_EQ(0u, mock_delegate()->published_rulesets().size()); // Expect that the sentinel file is already gone. Write failures are quite // frequent and are often transient, so it is worth attempting indexing again. @@ -710,6 +754,7 @@ TEST_F(SubresourceFilteringRulesetServiceTest, NewRulesetTwice_SecondRulesetPrevails) { + mock_delegate()->SimulateStartupCompleted(); IndexAndStoreAndPublishUpdatedRuleset(test_ruleset_1(), kTestContentVersion1); RunUntilIdle(); @@ -718,19 +763,12 @@ // This verifies that the contents from the first version of the ruleset file // can still be read after it has been deprecated. - ASSERT_EQ(2u, mock_distributor()->published_rulesets().size()); + ASSERT_EQ(2u, mock_delegate()->published_rulesets().size()); ASSERT_NO_FATAL_FAILURE(AssertValidRulesetFileWithContents( - &mock_distributor()->published_rulesets()[0], + &mock_delegate()->published_rulesets()[0], test_ruleset_1().indexed.contents)); ASSERT_NO_FATAL_FAILURE(AssertValidRulesetFileWithContents( - &mock_distributor()->published_rulesets()[1], - test_ruleset_2().indexed.contents)); - - MockRulesetDistributor* new_distributor = new MockRulesetDistributor; - service()->RegisterDistributor(base::WrapUnique(new_distributor)); - ASSERT_EQ(1u, new_distributor->published_rulesets().size()); - ASSERT_NO_FATAL_FAILURE(AssertValidRulesetFileWithContents( - &new_distributor->published_rulesets()[0], + &mock_delegate()->published_rulesets()[1], test_ruleset_2().indexed.contents)); IndexedRulesetVersion stored_version; @@ -740,6 +778,7 @@ TEST_F(SubresourceFilteringRulesetServiceTest, NewRulesetTwiceWithTheSameVersion_SecondIsIgnored) { + mock_delegate()->SimulateStartupCompleted(); IndexAndStoreAndPublishUpdatedRuleset(test_ruleset_1(), kTestContentVersion1); RunUntilIdle(); @@ -748,16 +787,9 @@ IndexAndStoreAndPublishUpdatedRuleset(test_ruleset_2(), kTestContentVersion1); ASSERT_NO_FATAL_FAILURE(AssertNoPendingTasks()); - ASSERT_EQ(1u, mock_distributor()->published_rulesets().size()); + ASSERT_EQ(1u, mock_delegate()->published_rulesets().size()); ASSERT_NO_FATAL_FAILURE(AssertValidRulesetFileWithContents( - &mock_distributor()->published_rulesets()[0], - test_ruleset_1().indexed.contents)); - - MockRulesetDistributor* new_distributor = new MockRulesetDistributor; - service()->RegisterDistributor(base::WrapUnique(new_distributor)); - ASSERT_EQ(1u, new_distributor->published_rulesets().size()); - ASSERT_NO_FATAL_FAILURE(AssertValidRulesetFileWithContents( - &new_distributor->published_rulesets()[0], + &mock_delegate()->published_rulesets()[0], test_ruleset_1().indexed.contents)); IndexedRulesetVersion stored_version; @@ -766,19 +798,54 @@ } TEST_F(SubresourceFilteringRulesetServiceTest, + MultipleNewRulesetsEarly_MostRecentIsPublishedAfterStartupIsComplete) { + IndexedRulesetVersion current_version( + kTestContentVersion1, IndexedRulesetVersion::CurrentFormatVersion()); + current_version.SaveToPrefs(prefs()); + WriteRuleset(test_ruleset_1(), current_version); + + ResetRulesetService(); + + IndexAndStoreAndPublishUpdatedRuleset(test_ruleset_1(), kTestContentVersion1); + IndexAndStoreAndPublishUpdatedRuleset(test_ruleset_2(), kTestContentVersion2); + IndexAndStoreAndPublishUpdatedRuleset(test_ruleset_3(), kTestContentVersion3); + IndexAndStoreAndPublishUpdatedRuleset(test_ruleset_1(), kTestContentVersion1); + + mock_delegate()->SimulateStartupCompleted(); + RunUntilIdle(); + + // Optionally permit the publication of the pre-existing ruleset, but the last + // published ruleset must be the one that was set the latest (and with a + // different version number than the pre-existing ruleset). + ASSERT_LE(1u, mock_delegate()->published_rulesets().size()); + ASSERT_GE(2u, mock_delegate()->published_rulesets().size()); + if (mock_delegate()->published_rulesets().size() == 2) { + ASSERT_NO_FATAL_FAILURE(AssertValidRulesetFileWithContents( + &mock_delegate()->published_rulesets().front(), + test_ruleset_1().indexed.contents)); + } + ASSERT_NO_FATAL_FAILURE(AssertValidRulesetFileWithContents( + &mock_delegate()->published_rulesets().back(), + test_ruleset_3().indexed.contents)); +} + +TEST_F(SubresourceFilteringRulesetServiceTest, NewRulesetSetShortlyBeforeDestruction_NoCrashes) { for (size_t num_tasks_inbetween = 0; num_tasks_inbetween < 5u; ++num_tasks_inbetween) { SCOPED_TRACE(::testing::Message() << "#Tasks: " << num_tasks_inbetween); + mock_delegate()->SimulateStartupCompleted(); + RunUntilIdle(); + IndexAndStoreAndPublishUpdatedRuleset(test_ruleset_1(), kTestContentVersion1); RunPendingTasksNTimes(num_tasks_inbetween); - ResetService(); + ClearRulesetService(); RunUntilIdle(); EXPECT_TRUE(base::DeleteFile(base_dir(), true)); - ResetService(CreateRulesetService()); + ResetRulesetService(); } // Must pump out PostTaskWithReply tasks that are referencing the very same @@ -792,20 +859,22 @@ ++num_tasks_inbetween) { SCOPED_TRACE(::testing::Message() << "#Tasks: " << num_tasks_inbetween); + mock_delegate()->SimulateStartupCompleted(); + RunUntilIdle(); + IndexAndStoreAndPublishUpdatedRuleset(test_ruleset_1(), kTestContentVersion1); RunPendingTasksNTimes(num_tasks_inbetween); - IndexAndStoreAndPublishUpdatedRuleset(test_ruleset_2(), kTestContentVersion2); RunUntilIdle(); // Optionally permit a "hazardous" publication of either the old or new // version of the ruleset, but the last ruleset message must be the new one. - ASSERT_LE(1u, mock_distributor()->published_rulesets().size()); - ASSERT_GE(2u, mock_distributor()->published_rulesets().size()); - if (mock_distributor()->published_rulesets().size() == 2) { - base::File* file = &mock_distributor()->published_rulesets()[0]; + ASSERT_LE(1u, mock_delegate()->published_rulesets().size()); + ASSERT_GE(2u, mock_delegate()->published_rulesets().size()); + if (mock_delegate()->published_rulesets().size() == 2) { + base::File* file = &mock_delegate()->published_rulesets()[0]; ASSERT_TRUE(file->IsValid()); EXPECT_THAT( ReadFileContents(file), @@ -813,42 +882,30 @@ ::testing::Eq(test_ruleset_2().indexed.contents))); } ASSERT_NO_FATAL_FAILURE(AssertValidRulesetFileWithContents( - &mock_distributor()->published_rulesets().back(), - test_ruleset_2().indexed.contents)); - - MockRulesetDistributor* new_distributor = new MockRulesetDistributor; - service()->RegisterDistributor(base::WrapUnique(new_distributor)); - ASSERT_EQ(1u, new_distributor->published_rulesets().size()); - ASSERT_NO_FATAL_FAILURE(AssertValidRulesetFileWithContents( - &new_distributor->published_rulesets()[0], + &mock_delegate()->published_rulesets().back(), test_ruleset_2().indexed.contents)); IndexedRulesetVersion stored_version; stored_version.ReadFromPrefs(prefs()); EXPECT_EQ(kTestContentVersion2, stored_version.content_version); - ResetService(); + ClearRulesetService(); RunUntilIdle(); EXPECT_TRUE(base::DeleteFile(base_dir(), true)); IndexedRulesetVersion().SaveToPrefs(prefs()); - ResetService(CreateRulesetService()); + ResetRulesetService(); } } TEST_F(SubresourceFilteringRulesetServiceTest, RulesetIsReadonly) { + mock_delegate()->SimulateStartupCompleted(); IndexAndStoreAndPublishUpdatedRuleset(test_ruleset_1(), kTestContentVersion1); RunUntilIdle(); - ASSERT_EQ(1u, mock_distributor()->published_rulesets().size()); + ASSERT_EQ(1u, mock_delegate()->published_rulesets().size()); ASSERT_NO_FATAL_FAILURE( - AssertReadonlyRulesetFile(&mock_distributor()->published_rulesets()[0])); - - MockRulesetDistributor* new_distributor = new MockRulesetDistributor; - service()->RegisterDistributor(base::WrapUnique(new_distributor)); - ASSERT_EQ(1u, new_distributor->published_rulesets().size()); - ASSERT_NO_FATAL_FAILURE( - AssertReadonlyRulesetFile(&new_distributor->published_rulesets()[0])); + AssertReadonlyRulesetFile(&mock_delegate()->published_rulesets()[0])); } } // namespace subresource_filter
diff --git a/components/sync/driver/glue/sync_backend_host_impl.cc b/components/sync/driver/glue/sync_backend_host_impl.cc index 06d6c1e..bc181a6 100644 --- a/components/sync/driver/glue/sync_backend_host_impl.cc +++ b/components/sync/driver/glue/sync_backend_host_impl.cc
@@ -109,6 +109,10 @@ factory_switches.pre_commit_updates_policy = EngineComponentsFactory::FORCE_ENABLE_PRE_COMMIT_UPDATE_AVOIDANCE; } + if (cl->HasSwitch(switches::kSyncShortNudgeDelayForTest)) { + factory_switches.nudge_delay = + EngineComponentsFactory::NudgeDelay::SHORT_NUDGE_DELAY; + } std::map<ModelType, int64_t> invalidation_versions; sync_prefs_->GetInvalidationVersions(&invalidation_versions);
diff --git a/components/sync/driver/sync_driver_switches.cc b/components/sync/driver/sync_driver_switches.cc index 77c95d72..6f446ec 100644 --- a/components/sync/driver/sync_driver_switches.cc +++ b/components/sync/driver/sync_driver_switches.cc
@@ -25,12 +25,19 @@ const char kSyncShortInitialRetryOverride[] = "sync-short-initial-retry-override"; +// This flag significantly shortens the delay between nudge cycles. Its primary +// purpose is to speed up integration tests. The normal delay allows coalescing +// and prevention of server overload, so don't use this unless you're really +// sure +// that it's what you want. +const char kSyncShortNudgeDelayForTest[] = "sync-short-nudge-delay-for-test"; + // Enables clearing of sync data when a user enables passphrase encryption. const base::Feature kSyncClearDataOnPassphraseEncryption{ "ClearSyncDataOnPassphraseEncryption", base::FEATURE_DISABLED_BY_DEFAULT}; // Enables USS implementation of DeviceInfo datatype. This flag controls whether -// SyncableService based or ModelTypeSyncBridge based implementation is used for +// SyncableService based or ModelTypeService based implementation is used for // DeviceInfo type. const base::Feature kSyncUSSDeviceInfo{"EnableSyncUSSDeviceInfo", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/components/sync/driver/sync_driver_switches.h b/components/sync/driver/sync_driver_switches.h index 525504c..9e37127 100644 --- a/components/sync/driver/sync_driver_switches.h +++ b/components/sync/driver/sync_driver_switches.h
@@ -17,6 +17,7 @@ extern const char kSyncEnableGetUpdateAvoidance[]; extern const char kSyncServiceURL[]; extern const char kSyncShortInitialRetryOverride[]; +extern const char kSyncShortNudgeDelayForTest[]; extern const base::Feature kSyncClearDataOnPassphraseEncryption; extern const base::Feature kSyncUSSDeviceInfo;
diff --git a/components/sync/engine/engine_components_factory.h b/components/sync/engine/engine_components_factory.h index 175af5c..fb80d03 100644 --- a/components/sync/engine/engine_components_factory.h +++ b/components/sync/engine/engine_components_factory.h
@@ -56,6 +56,11 @@ FORCE_ENABLE_PRE_COMMIT_UPDATE_AVOIDANCE, }; + enum class NudgeDelay { + DEFAULT_NUDGE_DELAY, + SHORT_NUDGE_DELAY, + }; + // Configuration options for internal components. This struct is expected // to grow and shrink over time with transient features / experiments, // roughly following command line flags in chrome. Implementations of @@ -64,6 +69,7 @@ struct Switches { EncryptionMethod encryption_method; BackoffOverride backoff_override; + NudgeDelay nudge_delay; PreCommitUpdatesPolicy pre_commit_updates_policy; };
diff --git a/components/sync/engine/engine_components_factory_impl.cc b/components/sync/engine/engine_components_factory_impl.cc index 73c7a551f..d3d3a88 100644 --- a/components/sync/engine/engine_components_factory_impl.cc +++ b/components/sync/engine/engine_components_factory_impl.cc
@@ -4,6 +4,7 @@ #include "components/sync/engine/engine_components_factory_impl.h" +#include "base/memory/ptr_util.h" #include "components/sync/engine_impl/backoff_delay_provider.h" #include "components/sync/engine_impl/cycle/sync_cycle_context.h" #include "components/sync/engine_impl/sync_scheduler_impl.h" @@ -12,6 +13,10 @@ using base::TimeDelta; +namespace { +const int kShortNudgeDelayDurationMS = 1; +} + namespace syncer { EngineComponentsFactoryImpl::EngineComponentsFactoryImpl( @@ -27,11 +32,28 @@ std::unique_ptr<BackoffDelayProvider> delay( BackoffDelayProvider::FromDefaults()); - if (switches_.backoff_override == BACKOFF_SHORT_INITIAL_RETRY_OVERRIDE) + if (switches_.backoff_override == BACKOFF_SHORT_INITIAL_RETRY_OVERRIDE) { delay.reset(BackoffDelayProvider::WithShortInitialRetryOverride()); + } - return std::unique_ptr<SyncScheduler>(new SyncSchedulerImpl( - name, delay.release(), context, new Syncer(cancelation_signal))); + std::unique_ptr<SyncSchedulerImpl> scheduler = + base::MakeUnique<SyncSchedulerImpl>(name, delay.release(), context, + new Syncer(cancelation_signal)); + if (switches_.nudge_delay == NudgeDelay::SHORT_NUDGE_DELAY) { + // Set the default nudge delay to 0 because the default is used as a floor + // for override values, and we don't want the below override to be ignored. + scheduler->SetDefaultNudgeDelay(TimeDelta::FromMilliseconds(0)); + // Only protocol types can have their delay customized. + ModelTypeSet protocol_types = syncer::ProtocolTypes(); + std::map<ModelType, base::TimeDelta> nudge_delays; + for (ModelTypeSet::Iterator it = protocol_types.First(); it.Good(); + it.Inc()) { + nudge_delays[it.Get()] = + TimeDelta::FromMilliseconds(kShortNudgeDelayDurationMS); + } + scheduler->OnReceivedCustomNudgeDelays(nudge_delays); + } + return std::move(scheduler); } std::unique_ptr<SyncCycleContext> EngineComponentsFactoryImpl::BuildContext(
diff --git a/components/sync/engine_impl/sync_scheduler_impl.h b/components/sync/engine_impl/sync_scheduler_impl.h index 7c5e06f..ae6fe10 100644 --- a/components/sync/engine_impl/sync_scheduler_impl.h +++ b/components/sync/engine_impl/sync_scheduler_impl.h
@@ -86,6 +86,11 @@ // Returns true if the client is currently in exponential backoff. bool IsBackingOff() const; + // Changes the default delay between nudge cycles. Model-type specific + // overrides will still apply. This is made public so that nudge cycles can be + // shortened in integration tests. + void SetDefaultNudgeDelay(base::TimeDelta delay_ms); + private: enum JobPriority { // Non-canary jobs respect exponential backoff. @@ -139,8 +144,6 @@ static const char* GetModeString(Mode mode); - void SetDefaultNudgeDelay(base::TimeDelta delay_ms); - // Invoke the syncer to perform a nudge job. void DoNudgeSyncCycleJob(JobPriority priority);
diff --git a/components/sync_sessions/sessions_sync_manager.cc b/components/sync_sessions/sessions_sync_manager.cc index b2c62df0..4fa6f7ec 100644 --- a/components/sync_sessions/sessions_sync_manager.cc +++ b/components/sync_sessions/sessions_sync_manager.cc
@@ -156,8 +156,7 @@ syncer::SyncChangeList new_changes; // First, we iterate over sync data to update our session_tracker_. - syncer::SyncDataList restored_tabs; - if (!InitFromSyncModel(initial_sync_data, &restored_tabs, &new_changes)) { + if (!InitFromSyncModel(initial_sync_data, &new_changes)) { // The sync db didn't have a header node for us. Create one. sync_pb::EntitySpecifics specifics; sync_pb::SessionSpecifics* base_specifics = specifics.mutable_session(); @@ -179,7 +178,7 @@ #endif // Check if anything has changed on the local client side. - AssociateWindows(RELOAD_TABS, restored_tabs, &new_changes); + AssociateWindows(RELOAD_TABS, &new_changes); local_tab_pool_out_of_sync_ = false; merge_result.set_error( @@ -191,7 +190,6 @@ void SessionsSyncManager::AssociateWindows( ReloadTabsOption option, - const syncer::SyncDataList& restored_tabs, syncer::SyncChangeList* change_output) { const std::string local_tag = current_machine_tag(); sync_pb::SessionSpecifics specifics; @@ -273,7 +271,7 @@ if (synced_tab->GetSyncId() > TabNodePool::kInvalidTabNodeID && tab_id > TabNodePool::kInvalidTabID) { AssociateRestoredPlaceholderTab(*synced_tab, tab_id, window_id, - restored_tabs, change_output); + change_output); found_tabs = true; window_s.add_tab(tab_id); } @@ -352,14 +350,10 @@ tab->SetSyncId(tab_node_id); } local_tab_pool_.AssociateTabNode(tab_node_id, tab_id); - tab_link = new TabLink(tab_node_id, tab); + tab_link = new TabLink(tab_node_id); local_tab_map_[tab_id] = make_linked_ptr<TabLink>(tab_link); } else { - // This tab is already associated with a sync node, reuse it. - // Note: on some platforms the tab object may have changed, so we ensure - // the tab link is up to date. tab_link = local_tab_map_iter->second.get(); - local_tab_map_iter->second->set_tab(tab); } DCHECK(tab_link); DCHECK_NE(tab_link->tab_node_id(), TabNodePool::kInvalidTabNodeID); @@ -445,7 +439,7 @@ // "interesting" by going to a valid URL, in which case it needs to be added // to the window's tab information. Similarly, if a tab became // "uninteresting", we remove it from the window's tab information. - AssociateWindows(DONT_RELOAD_TABS, syncer::SyncDataList(), &changes); + AssociateWindows(DONT_RELOAD_TABS, &changes); sync_processor_->ProcessSyncChanges(FROM_HERE, changes); } @@ -580,7 +574,7 @@ LOG(WARNING) << "Dropping modification to local session."; return syncer::SyncError(); } - UpdateTrackerWithForeignSession( + UpdateTrackerWithSpecifics( session, syncer::SyncDataRemote(it->sync_data()).GetModifiedTime()); break; default: @@ -618,7 +612,6 @@ bool SessionsSyncManager::InitFromSyncModel( const syncer::SyncDataList& sync_data, - syncer::SyncDataList* restored_tabs, syncer::SyncChangeList* new_changes) { bool found_current_header = false; int bad_foreign_hash_count = 0; @@ -636,7 +629,7 @@ new_changes->push_back(tombstone); } else if (specifics.session_tag() != current_machine_tag()) { if (TagHashFromSpecifics(specifics) == remote.GetClientTagHash()) { - UpdateTrackerWithForeignSession(specifics, remote.GetModifiedTime()); + UpdateTrackerWithSpecifics(specifics, remote.GetModifiedTime()); } else { // In the past, like years ago, we believe that some session data was // created with bad tag hashes. This causes any change this client makes @@ -655,6 +648,10 @@ found_current_header = true; if (specifics.header().has_client_name()) current_session_name_ = specifics.header().client_name(); + + // TODO(zea): crbug.com/639009 update the tracker with the specifics + // from the header node as well. This will be necessary to preserve + // the set of open tabs when a custom tab is opened. } else { if (specifics.has_header() || !specifics.has_tab()) { LOG(WARNING) << "Found more than one session header node with local " @@ -663,10 +660,14 @@ if (tombstone.IsValid()) new_changes->push_back(tombstone); } else { - // This is a valid old tab node, add it to the pool so it can be - // reused for reassociation. + // This is a valid old tab node, reassociate it and add it to the + // tracker. + local_tab_map_[specifics.tab().tab_id()] = + make_linked_ptr<TabLink>(new TabLink(specifics.tab_node_id())); local_tab_pool_.AddTabNode(specifics.tab_node_id()); - restored_tabs->push_back(*it); + local_tab_pool_.AssociateTabNode(specifics.tab_node_id(), + specifics.tab().tab_id()); + UpdateTrackerWithSpecifics(specifics, remote.GetModifiedTime()); } } } @@ -687,69 +688,64 @@ return found_current_header; } -void SessionsSyncManager::UpdateTrackerWithForeignSession( +void SessionsSyncManager::UpdateTrackerWithSpecifics( const sync_pb::SessionSpecifics& specifics, const base::Time& modification_time) { - std::string foreign_session_tag = specifics.session_tag(); - DCHECK_NE(foreign_session_tag, current_machine_tag()); - - SyncedSession* foreign_session = - session_tracker_.GetSession(foreign_session_tag); + std::string session_tag = specifics.session_tag(); + SyncedSession* session = session_tracker_.GetSession(session_tag); if (specifics.has_header()) { - // Read in the header data for this foreign session. Header data is + // Read in the header data for this session. Header data is // essentially a collection of windows, each of which has an ordered id list // for their tabs. if (!IsValidSessionHeader(specifics.header())) { - LOG(WARNING) << "Ignoring foreign session node with invalid header " - << "and tag " << foreign_session_tag << "."; + LOG(WARNING) << "Ignoring session node with invalid header " + << "and tag " << session_tag << "."; return; } // Load (or create) the SyncedSession object for this client. const sync_pb::SessionHeader& header = specifics.header(); - PopulateSessionHeaderFromSpecifics(header, modification_time, - foreign_session); + PopulateSessionHeaderFromSpecifics(header, modification_time, session); // Reset the tab/window tracking for this session (must do this before // we start calling PutWindowInSession and PutTabInWindow so that all // unused tabs/windows get cleared by the CleanupSession(...) call). - session_tracker_.ResetSessionTracking(foreign_session_tag); + session_tracker_.ResetSessionTracking(session_tag); // Process all the windows and their tab information. int num_windows = header.window_size(); - DVLOG(1) << "Associating " << foreign_session_tag << " with " << num_windows + DVLOG(1) << "Associating " << session_tag << " with " << num_windows << " windows."; for (int i = 0; i < num_windows; ++i) { const sync_pb::SessionWindow& window_s = header.window(i); SessionID::id_type window_id = window_s.window_id(); - session_tracker_.PutWindowInSession(foreign_session_tag, window_id); - BuildSyncedSessionFromSpecifics( - foreign_session_tag, window_s, modification_time, - foreign_session->windows[window_id].get()); + session_tracker_.PutWindowInSession(session_tag, window_id); + BuildSyncedSessionFromSpecifics(session_tag, window_s, modification_time, + session->windows[window_id].get()); } // Delete any closed windows and unused tabs as necessary. - session_tracker_.CleanupSession(foreign_session_tag); + session_tracker_.CleanupSession(session_tag); } else if (specifics.has_tab()) { const sync_pb::SessionTab& tab_s = specifics.tab(); SessionID::id_type tab_id = tab_s.tab_id(); const sessions::SessionTab* existing_tab; - if (session_tracker_.LookupSessionTab(foreign_session_tag, tab_id, - &existing_tab) && + if (session_tracker_.LookupSessionTab(session_tag, tab_id, &existing_tab) && existing_tab->timestamp > modification_time) { // Force the tracker to remember this tab node id, even if it isn't // currently being used. - session_tracker_.GetTab(foreign_session_tag, tab_id, - specifics.tab_node_id()); - DVLOG(1) << "Ignoring " << foreign_session_tag << "'s session tab " - << tab_id << " with earlier modification time"; + session_tracker_.GetTab(session_tag, tab_id, specifics.tab_node_id()); + DVLOG(1) << "Ignoring " << session_tag << "'s session tab " << tab_id + << " with earlier modification time"; return; } - sessions::SessionTab* tab = session_tracker_.GetTab( - foreign_session_tag, tab_id, specifics.tab_node_id()); + DVLOG(1) << "Associating tab " << tab_id << " with node " + << specifics.tab_node_id(); + sessions::SessionTab* tab = + session_tracker_.GetTab(session_tag, tab_id, specifics.tab_node_id()); // Update SessionTab based on protobuf. tab->SetFromSyncData(tab_s, modification_time); @@ -759,11 +755,11 @@ RefreshFaviconVisitTimesFromForeignTab(tab_s, modification_time); // Update the last modified time. - if (foreign_session->modified_time < modification_time) - foreign_session->modified_time = modification_time; + if (session->modified_time < modification_time) + session->modified_time = modification_time; } else { - LOG(WARNING) << "Ignoring foreign session node with missing header/tab " - << "fields and tag " << foreign_session_tag << "."; + LOG(WARNING) << "Ignoring session node with missing header/tab " + << "fields and tag " << session_tag << "."; } } @@ -965,8 +961,8 @@ const SyncedTabDelegate& tab_delegate, sync_pb::SessionSpecifics* specifics) { sessions::SessionTab* session_tab = nullptr; - session_tab = session_tracker_.GetTab(current_machine_tag(), - tab_delegate.GetSessionId(), + SessionID::id_type tab_id = tab_delegate.GetSessionId(); + session_tab = session_tracker_.GetTab(current_machine_tag(), tab_id, tab_delegate.GetSyncId()); SetSessionTabFromDelegate(tab_delegate, base::Time::Now(), session_tab); SetVariationIds(session_tab); @@ -980,47 +976,52 @@ const SyncedTabDelegate& tab_delegate, SessionID::id_type new_tab_id, SessionID::id_type new_window_id, - const syncer::SyncDataList& restored_tabs, syncer::SyncChangeList* change_output) { DCHECK_NE(tab_delegate.GetSyncId(), TabNodePool::kInvalidTabNodeID); - // Rewrite the tab using |restored_tabs| to retrieve the specifics. - if (restored_tabs.empty()) { - DLOG(WARNING) << "Can't Update tab ID."; + + SessionID::id_type old_tab_id = + local_tab_pool_.GetTabIdFromTabNodeId(tab_delegate.GetSyncId()); + DVLOG(1) << "Restoring tab id " << new_tab_id << " from sync node " + << tab_delegate.GetSyncId() << " (old tab id was " << old_tab_id + << ")."; + + // Update tab node pool and tracker with the new association (note that + // reassociating the tracker depends on the old tab pool data, so it must be + // reassociated first). + if (!session_tracker_.ReassociateTab(current_machine_tag(), old_tab_id, + new_tab_id)) { + LOG(ERROR) << "Failed to reassociate tab " << new_tab_id; return; } + local_tab_pool_.ReassociateTabNode(tab_delegate.GetSyncId(), new_tab_id); - for (syncer::SyncDataList::const_iterator it = restored_tabs.begin(); - it != restored_tabs.end(); ++it) { - if (it->GetSpecifics().session().tab_node_id() != - tab_delegate.GetSyncId()) { - continue; - } - - sync_pb::EntitySpecifics entity; - sync_pb::SessionSpecifics* specifics = entity.mutable_session(); - specifics->CopyFrom(it->GetSpecifics().session()); - DCHECK(specifics->has_tab()); - - // Update tab node pool with the new association. - local_tab_pool_.ReassociateTabNode(tab_delegate.GetSyncId(), new_tab_id); - TabLink* tab_link = new TabLink(tab_delegate.GetSyncId(), &tab_delegate); - local_tab_map_[new_tab_id] = make_linked_ptr<TabLink>(tab_link); - - if (specifics->tab().tab_id() == new_tab_id && - specifics->tab().window_id() == new_window_id) + // If the tab id hasn't changed, the tab map doesn't need to be updated. But + // the window id may have changed, so the specifics still need to be + // rewritten. + if (old_tab_id != new_tab_id) { + auto iter = local_tab_map_.find(old_tab_id); + if (iter == local_tab_map_.end()) { + LOG(ERROR) << "Failed to update local tab map for " << new_tab_id; return; - - // Either the tab_id or window_id changed (e.g due to session restore), so - // update the sync node. - specifics->mutable_tab()->set_tab_id(new_tab_id); - specifics->mutable_tab()->set_window_id(new_window_id); - syncer::SyncData data = syncer::SyncData::CreateLocalData( - TabNodePool::TabIdToTag(current_machine_tag_, specifics->tab_node_id()), - current_session_name_, entity); - change_output->push_back( - syncer::SyncChange(FROM_HERE, syncer::SyncChange::ACTION_UPDATE, data)); - return; + } + local_tab_map_[new_tab_id] = iter->second; + local_tab_map_.erase(iter); } + + sync_pb::EntitySpecifics entity; + sync_pb::SessionSpecifics* specifics = entity.mutable_session(); + + // This will rewrite the tab id and window id based on the delegate. Note + // that it won't update the SessionWindow that holds the tab (which happens + // separately when the header node is associated). + LocalTabDelegateToSpecifics(tab_delegate, specifics); + DCHECK(specifics->has_tab()); + + syncer::SyncData data = syncer::SyncData::CreateLocalData( + TabNodePool::TabIdToTag(current_machine_tag_, specifics->tab_node_id()), + current_session_name_, entity); + change_output->push_back( + syncer::SyncChange(FROM_HERE, syncer::SyncChange::ACTION_UPDATE, data)); } // static
diff --git a/components/sync_sessions/sessions_sync_manager.h b/components/sync_sessions/sessions_sync_manager.h index b81eac5..584db75 100644 --- a/components/sync_sessions/sessions_sync_manager.h +++ b/components/sync_sessions/sessions_sync_manager.h
@@ -119,28 +119,22 @@ void DoGarbageCollection(); private: - // Keep all the links to local tab data in one place. A tab_node_id and tab - // must be passed at creation. The tab_node_id is not mutable, although - // all other fields are. + // Track links between a tab id and it's sync tab node id and url. The tab + // node id is not mutable, as the entity backing a tab should never change + // during runtime. The url can be updated as navigations are performed. class TabLink { public: - TabLink(int tab_node_id, const SyncedTabDelegate* tab) - : tab_node_id_(tab_node_id), tab_(tab) {} + explicit TabLink(int tab_node_id) : tab_node_id_(tab_node_id) {} - void set_tab(const SyncedTabDelegate* tab) { tab_ = tab; } void set_url(const GURL& url) { url_ = url; } int tab_node_id() const { return tab_node_id_; } - const SyncedTabDelegate* tab() const { return tab_; } const GURL& url() const { return url_; } private: // The id for the sync node this tab is stored in. const int tab_node_id_; - // The tab object itself. - const SyncedTabDelegate* tab_; - // The currently visible url of the tab (used for syncing favicons). GURL url_; @@ -183,20 +177,16 @@ void InitializeCurrentMachineTag(); - // Load and add window or tab data for a foreign session to our internal + // Load and add window or tab data from synced specifics to our internal // tracking. - void UpdateTrackerWithForeignSession( - const sync_pb::SessionSpecifics& specifics, - const base::Time& modification_time); + void UpdateTrackerWithSpecifics(const sync_pb::SessionSpecifics& specifics, + const base::Time& modification_time); // Returns true if |sync_data| contained a header node for the current - // machine, false otherwise. |restored_tabs| is a filtered tab-only - // subset of |sync_data| returned by this function for convenience. - // |new_changes| is a link to the SyncChange pipeline that exists in the - // caller's context. This function will append necessary changes for - // processing later. + // machine, false otherwise. |new_changes| is a link to the SyncChange + // pipeline that exists in the caller's context. This function will append + // necessary changes for processing later. bool InitFromSyncModel(const syncer::SyncDataList& sync_data, - syncer::SyncDataList* restored_tabs, syncer::SyncChangeList* new_changes); // Helper to construct a deletion SyncChange for a *tab node*. @@ -245,11 +235,6 @@ // RELOAD_TABS will additionally cause a resync of all tabs (same as calling // AssociateTabs with a vector of all tabs). // - // |restored_tabs| is a filtered tab-only subset of initial sync data, if - // available (during MergeDataAndStartSyncing). It can be used to obtain - // baseline SessionSpecifics for tabs we can't fully associate any other - // way because they don't yet have a WebContents. - // // Returns: false if the local session's sync nodes were deleted and // reassociation is necessary, true otherwise. // @@ -258,7 +243,6 @@ // changes for processing later. enum ReloadTabsOption { RELOAD_TABS, DONT_RELOAD_TABS }; void AssociateWindows(ReloadTabsOption option, - const syncer::SyncDataList& restored_tabs, syncer::SyncChangeList* change_output); // Loads and reassociates the local tabs referenced in |tabs|. @@ -287,17 +271,10 @@ // as they may have changed after a session was restored. This method // compares new_tab_id and new_window_id against the previously persisted tab // ID and window ID (from our TabNodePool) and updates them if either differs. - // |restored_tabs| is a filtered tab-only subset of initial sync data, if - // available (during MergeDataAndStartSyncing). It can be used to obtain - // baseline SessionSpecifics for tabs we can't fully associate any other - // way because they don't yet have a WebContents. - // TODO(tim): Bug 98892. We should be able to test this for this on android - // even though we didn't have tests for old API-based sessions sync. void AssociateRestoredPlaceholderTab( const SyncedTabDelegate& tab_delegate, SessionID::id_type new_tab_id, SessionID::id_type new_window_id, - const syncer::SyncDataList& restored_tabs, syncer::SyncChangeList* change_output); // Stops and re-starts syncing to rebuild association mappings.
diff --git a/components/sync_sessions/synced_session_tracker.cc b/components/sync_sessions/synced_session_tracker.cc index a74b877c..52385d7 100644 --- a/components/sync_sessions/synced_session_tracker.cc +++ b/components/sync_sessions/synced_session_tracker.cc
@@ -339,6 +339,48 @@ return tab_ptr; } +bool SyncedSessionTracker::ReassociateTab(const std::string& session_tag, + SessionID::id_type old_tab_id, + SessionID::id_type new_tab_id) { + DCHECK_NE(TabNodePool::kInvalidTabID, old_tab_id); + DCHECK_NE(TabNodePool::kInvalidTabID, new_tab_id); + + sessions::SessionTab* tab_ptr = nullptr; + auto old_tab_iter = synced_tab_map_[session_tag].find(old_tab_id); + if (old_tab_iter == synced_tab_map_[session_tag].end()) + return false; + + // It's possible a placeholder is already in place for the new tab. If that's + // the case, reuse the placeholder SessionTab. Otherwise, reuse the old + // SessionTab. + auto new_tab_iter = synced_tab_map_[session_tag].find(new_tab_id); + if (new_tab_iter != synced_tab_map_[session_tag].end()) { + tab_ptr = new_tab_iter->second; + } else { + tab_ptr = old_tab_iter->second; + } + + // If the old tab is unmapped, update the tab id under which it is indexed. + auto unmapped_tabs_iter = unmapped_tabs_[session_tag].find(old_tab_id); + if (unmapped_tabs_iter != unmapped_tabs_[session_tag].end()) { + std::unique_ptr<sessions::SessionTab> tab = + std::move(unmapped_tabs_iter->second); + unmapped_tabs_[session_tag].erase(unmapped_tabs_iter); + unmapped_tabs_[session_tag][new_tab_id] = std::move(tab); + } + + // Update the tab id. + DVLOG(1) << "Remapped tab " << old_tab_id << " to tab " << new_tab_id; + tab_ptr->tab_id.set_id(new_tab_id); + + // Remove the tab from the synced tab map under the old id. + synced_tab_map_[session_tag].erase(old_tab_iter); + + // Add the tab back into the tab map with the new id. + synced_tab_map_[session_tag][new_tab_id] = tab_ptr; + return true; +} + void SyncedSessionTracker::Clear() { // Cleanup unmapped tabs and windows. unmapped_windows_.clear();
diff --git a/components/sync_sessions/synced_session_tracker.h b/components/sync_sessions/synced_session_tracker.h index 35123d7..b9a00c8 100644 --- a/components/sync_sessions/synced_session_tracker.h +++ b/components/sync_sessions/synced_session_tracker.h
@@ -133,6 +133,15 @@ SessionID::id_type tab_id, int tab_node_id); + // Reassociated the tab denoted by |old_tab_id| with a new tab id. + // This is useful on restart when sync needs to reassociate tabs from a + // previous session with newly restored tabs (and can be used in conjunction + // with PutTabInWindow). + // Returns whether the reassociation succeeded. + bool ReassociateTab(const std::string& session_tag, + SessionID::id_type old_tab_id, + SessionID::id_type new_tab_id); + // Fills |tab_node_ids| with the tab node ids (see GetTab) for all the tabs* // associated with the session having tag |session_tag|. void LookupTabNodeIds(const std::string& session_tag, @@ -168,12 +177,12 @@ // The client of the sync sessions datatype. SyncSessionsClient* const sessions_client_; - // The mapping of tab/window ids to their SessionTab/SessionWindow objects. + // The mapping of tab/window to their SessionTab/SessionWindow objects. // The SessionTab/SessionWindow objects referred to may be owned either by the // session in the |synced_session_map_| or be temporarily unmapped and live in // the |unmapped_tabs_|/|unmapped_windows_| collections. // - // Map: session tag -> (tab/window id -> SessionTab*/SessionWindow*) + // Map: session tag -> (tab/window -> SessionTab*/SessionWindow*) std::map<std::string, std::map<SessionID::id_type, sessions::SessionTab*>> synced_tab_map_; std::map<std::string, std::map<SessionID::id_type, sessions::SessionWindow*>>
diff --git a/components/sync_sessions/synced_session_tracker_unittest.cc b/components/sync_sessions/synced_session_tracker_unittest.cc index 68c1f471..b6f81ed4d 100644 --- a/components/sync_sessions/synced_session_tracker_unittest.cc +++ b/components/sync_sessions/synced_session_tracker_unittest.cc
@@ -17,6 +17,10 @@ const char kValidUrl[] = "http://www.example.com"; const char kInvalidUrl[] = "invalid.url"; +const char kTag[] = "tag"; +const char kTag2[] = "tag2"; +const char kTag3[] = "tag3"; +const char kTitle[] = "title"; } // namespace @@ -33,34 +37,34 @@ }; TEST_F(SyncedSessionTrackerTest, GetSession) { - SyncedSession* session1 = GetTracker()->GetSession("tag"); - SyncedSession* session2 = GetTracker()->GetSession("tag2"); - ASSERT_EQ(session1, GetTracker()->GetSession("tag")); + SyncedSession* session1 = GetTracker()->GetSession(kTag); + SyncedSession* session2 = GetTracker()->GetSession(kTag2); + ASSERT_EQ(session1, GetTracker()->GetSession(kTag)); ASSERT_NE(session1, session2); // Should clean up memory on its own. } TEST_F(SyncedSessionTrackerTest, GetTabUnmapped) { - sessions::SessionTab* tab = GetTracker()->GetTab("tag", 0, 0); - ASSERT_EQ(tab, GetTracker()->GetTab("tag", 0, 0)); + sessions::SessionTab* tab = GetTracker()->GetTab(kTag, 0, 0); + ASSERT_EQ(tab, GetTracker()->GetTab(kTag, 0, 0)); // Should clean up memory on its own. } TEST_F(SyncedSessionTrackerTest, PutWindowInSession) { - GetTracker()->PutWindowInSession("tag", 0); - SyncedSession* session = GetTracker()->GetSession("tag"); + GetTracker()->PutWindowInSession(kTag, 0); + SyncedSession* session = GetTracker()->GetSession(kTag); ASSERT_EQ(1U, session->windows.size()); // Should clean up memory on its own. } TEST_F(SyncedSessionTrackerTest, PutTabInWindow) { - GetTracker()->PutWindowInSession("tag", 10); - GetTracker()->PutTabInWindow("tag", 10, 15, + GetTracker()->PutWindowInSession(kTag, 10); + GetTracker()->PutTabInWindow(kTag, 10, 15, 0); // win id 10, tab id 15, tab ind 0. - SyncedSession* session = GetTracker()->GetSession("tag"); + SyncedSession* session = GetTracker()->GetSession(kTag); ASSERT_EQ(1U, session->windows.size()); ASSERT_EQ(1U, session->windows[10]->tabs.size()); - ASSERT_EQ(GetTracker()->GetTab("tag", 15, 1), + ASSERT_EQ(GetTracker()->GetTab(kTag, 15, 1), session->windows[10]->tabs[0].get()); // Should clean up memory on its own. } @@ -69,28 +73,28 @@ std::vector<const SyncedSession*> sessions; ASSERT_FALSE(GetTracker()->LookupAllForeignSessions( &sessions, SyncedSessionTracker::PRESENTABLE)); - GetTracker()->GetSession("tag1"); - GetTracker()->PutWindowInSession("tag1", 0); - GetTracker()->PutTabInWindow("tag1", 0, 15, 0); - sessions::SessionTab* tab = GetTracker()->GetTab("tag1", 15, 1); + GetTracker()->GetSession(kTag); + GetTracker()->PutWindowInSession(kTag, 0); + GetTracker()->PutTabInWindow(kTag, 0, 15, 0); + sessions::SessionTab* tab = GetTracker()->GetTab(kTag, 15, 1); ASSERT_TRUE(tab); tab->navigations.push_back( sessions::SerializedNavigationEntryTestHelper::CreateNavigation(kValidUrl, - "title")); - GetTracker()->GetSession("tag2"); - GetTracker()->GetSession("tag3"); - GetTracker()->PutWindowInSession("tag3", 0); - GetTracker()->PutTabInWindow("tag3", 0, 15, 0); - tab = GetTracker()->GetTab("tag3", 15, 1); + kTitle)); + GetTracker()->GetSession(kTag2); + GetTracker()->GetSession(kTag3); + GetTracker()->PutWindowInSession(kTag3, 0); + GetTracker()->PutTabInWindow(kTag3, 0, 15, 0); + tab = GetTracker()->GetTab(kTag3, 15, 1); ASSERT_TRUE(tab); tab->navigations.push_back( sessions::SerializedNavigationEntryTestHelper::CreateNavigation( - kInvalidUrl, "title")); + kInvalidUrl, kTitle)); ASSERT_TRUE(GetTracker()->LookupAllForeignSessions( &sessions, SyncedSessionTracker::PRESENTABLE)); // Only the session with a valid window and tab gets returned. ASSERT_EQ(1U, sessions.size()); - ASSERT_EQ("tag1", sessions[0]->session_tag); + ASSERT_EQ(kTag, sessions[0]->session_tag); ASSERT_TRUE(GetTracker()->LookupAllForeignSessions( &sessions, SyncedSessionTracker::RAW)); @@ -99,15 +103,15 @@ TEST_F(SyncedSessionTrackerTest, LookupSessionWindows) { std::vector<const sessions::SessionWindow*> windows; - ASSERT_FALSE(GetTracker()->LookupSessionWindows("tag1", &windows)); - GetTracker()->GetSession("tag1"); - GetTracker()->PutWindowInSession("tag1", 0); - GetTracker()->PutWindowInSession("tag1", 2); - GetTracker()->GetSession("tag2"); - GetTracker()->PutWindowInSession("tag2", 0); - GetTracker()->PutWindowInSession("tag2", 2); - ASSERT_TRUE(GetTracker()->LookupSessionWindows("tag1", &windows)); - ASSERT_EQ(2U, windows.size()); // Only windows from tag1 session. + ASSERT_FALSE(GetTracker()->LookupSessionWindows(kTag, &windows)); + GetTracker()->GetSession(kTag); + GetTracker()->PutWindowInSession(kTag, 0); + GetTracker()->PutWindowInSession(kTag, 2); + GetTracker()->GetSession(kTag2); + GetTracker()->PutWindowInSession(kTag2, 0); + GetTracker()->PutWindowInSession(kTag2, 2); + ASSERT_TRUE(GetTracker()->LookupSessionWindows(kTag, &windows)); + ASSERT_EQ(2U, windows.size()); // Only windows from kTag session. ASSERT_NE((sessions::SessionWindow*)nullptr, windows[0]); ASSERT_NE((sessions::SessionWindow*)nullptr, windows[1]); ASSERT_NE(windows[1], windows[0]); @@ -115,40 +119,37 @@ TEST_F(SyncedSessionTrackerTest, LookupSessionTab) { const sessions::SessionTab* tab; - ASSERT_FALSE(GetTracker()->LookupSessionTab("tag1", 5, &tab)); - GetTracker()->GetSession("tag1"); - GetTracker()->PutWindowInSession("tag1", 0); - GetTracker()->PutTabInWindow("tag1", 0, 5, 0); - ASSERT_TRUE(GetTracker()->LookupSessionTab("tag1", 5, &tab)); + ASSERT_FALSE(GetTracker()->LookupSessionTab(kTag, 5, &tab)); + GetTracker()->GetSession(kTag); + GetTracker()->PutWindowInSession(kTag, 0); + GetTracker()->PutTabInWindow(kTag, 0, 5, 0); + ASSERT_TRUE(GetTracker()->LookupSessionTab(kTag, 5, &tab)); ASSERT_NE((sessions::SessionTab*)nullptr, tab); } TEST_F(SyncedSessionTrackerTest, Complex) { - const std::string tag1 = "tag"; - const std::string tag2 = "tag2"; - const std::string tag3 = "tag3"; std::vector<sessions::SessionTab *> tabs1, tabs2; sessions::SessionTab* temp_tab; ASSERT_TRUE(GetTracker()->Empty()); ASSERT_EQ(0U, GetTracker()->num_synced_sessions()); - ASSERT_EQ(0U, GetTracker()->num_synced_tabs(tag1)); - tabs1.push_back(GetTracker()->GetTab(tag1, 0, 0)); - tabs1.push_back(GetTracker()->GetTab(tag1, 1, 1)); - tabs1.push_back(GetTracker()->GetTab(tag1, 2, 2)); - ASSERT_EQ(3U, GetTracker()->num_synced_tabs(tag1)); + ASSERT_EQ(0U, GetTracker()->num_synced_tabs(kTag)); + tabs1.push_back(GetTracker()->GetTab(kTag, 0, 0)); + tabs1.push_back(GetTracker()->GetTab(kTag, 1, 1)); + tabs1.push_back(GetTracker()->GetTab(kTag, 2, 2)); + ASSERT_EQ(3U, GetTracker()->num_synced_tabs(kTag)); ASSERT_EQ(1U, GetTracker()->num_synced_sessions()); - temp_tab = GetTracker()->GetTab(tag1, 0, 0); // Already created. - ASSERT_EQ(3U, GetTracker()->num_synced_tabs(tag1)); + temp_tab = GetTracker()->GetTab(kTag, 0, 0); // Already created. + ASSERT_EQ(3U, GetTracker()->num_synced_tabs(kTag)); ASSERT_EQ(1U, GetTracker()->num_synced_sessions()); ASSERT_EQ(tabs1[0], temp_tab); - tabs2.push_back(GetTracker()->GetTab(tag2, 0, 0)); - ASSERT_EQ(1U, GetTracker()->num_synced_tabs(tag2)); + tabs2.push_back(GetTracker()->GetTab(kTag2, 0, 0)); + ASSERT_EQ(1U, GetTracker()->num_synced_tabs(kTag2)); ASSERT_EQ(2U, GetTracker()->num_synced_sessions()); - ASSERT_FALSE(GetTracker()->DeleteSession(tag3)); + ASSERT_FALSE(GetTracker()->DeleteSession(kTag3)); - SyncedSession* session = GetTracker()->GetSession(tag1); - SyncedSession* session2 = GetTracker()->GetSession(tag2); - SyncedSession* session3 = GetTracker()->GetSession(tag3); + SyncedSession* session = GetTracker()->GetSession(kTag); + SyncedSession* session2 = GetTracker()->GetSession(kTag2); + SyncedSession* session3 = GetTracker()->GetSession(kTag3); session3->device_type = SyncedSession::TYPE_OTHER; ASSERT_EQ(3U, GetTracker()->num_synced_sessions()); @@ -157,25 +158,25 @@ ASSERT_TRUE(session3); ASSERT_NE(session, session2); ASSERT_NE(session2, session3); - ASSERT_TRUE(GetTracker()->DeleteSession(tag3)); + ASSERT_TRUE(GetTracker()->DeleteSession(kTag3)); ASSERT_EQ(2U, GetTracker()->num_synced_sessions()); - GetTracker()->PutWindowInSession(tag1, 0); // Create a window. - GetTracker()->PutTabInWindow(tag1, 0, 2, 0); // No longer unmapped. - ASSERT_EQ(3U, GetTracker()->num_synced_tabs(tag1)); // Has not changed. + GetTracker()->PutWindowInSession(kTag, 0); // Create a window. + GetTracker()->PutTabInWindow(kTag, 0, 2, 0); // No longer unmapped. + ASSERT_EQ(3U, GetTracker()->num_synced_tabs(kTag)); // Has not changed. const sessions::SessionTab* tab_ptr; - ASSERT_TRUE(GetTracker()->LookupSessionTab(tag1, 0, &tab_ptr)); + ASSERT_TRUE(GetTracker()->LookupSessionTab(kTag, 0, &tab_ptr)); ASSERT_EQ(tab_ptr, tabs1[0]); - ASSERT_TRUE(GetTracker()->LookupSessionTab(tag1, 2, &tab_ptr)); + ASSERT_TRUE(GetTracker()->LookupSessionTab(kTag, 2, &tab_ptr)); ASSERT_EQ(tab_ptr, tabs1[2]); - ASSERT_FALSE(GetTracker()->LookupSessionTab(tag1, 3, &tab_ptr)); + ASSERT_FALSE(GetTracker()->LookupSessionTab(kTag, 3, &tab_ptr)); ASSERT_FALSE(tab_ptr); std::vector<const sessions::SessionWindow*> windows; - ASSERT_TRUE(GetTracker()->LookupSessionWindows(tag1, &windows)); + ASSERT_TRUE(GetTracker()->LookupSessionWindows(kTag, &windows)); ASSERT_EQ(1U, windows.size()); - ASSERT_TRUE(GetTracker()->LookupSessionWindows(tag2, &windows)); + ASSERT_TRUE(GetTracker()->LookupSessionWindows(kTag2, &windows)); ASSERT_EQ(0U, windows.size()); // The sessions don't have valid tabs, lookup should not succeed. @@ -187,8 +188,8 @@ ASSERT_EQ(2U, sessions.size()); GetTracker()->Clear(); - ASSERT_EQ(0U, GetTracker()->num_synced_tabs(tag1)); - ASSERT_EQ(0U, GetTracker()->num_synced_tabs(tag2)); + ASSERT_EQ(0U, GetTracker()->num_synced_tabs(kTag)); + ASSERT_EQ(0U, GetTracker()->num_synced_tabs(kTag2)); ASSERT_EQ(0U, GetTracker()->num_synced_sessions()); } @@ -212,98 +213,93 @@ TEST_F(SyncedSessionTrackerTest, LookupTabNodeIds) { std::set<int> result; - std::string tag1 = "session1"; - std::string tag2 = "session2"; - std::string tag3 = "session3"; - GetTracker()->GetTab(tag1, 1, 1); - GetTracker()->GetTab(tag1, 2, 2); - GetTracker()->LookupTabNodeIds(tag1, &result); + GetTracker()->GetTab(kTag, 1, 1); + GetTracker()->GetTab(kTag, 2, 2); + GetTracker()->LookupTabNodeIds(kTag, &result); EXPECT_EQ(2U, result.size()); EXPECT_FALSE(result.end() == result.find(1)); EXPECT_FALSE(result.end() == result.find(2)); - GetTracker()->LookupTabNodeIds(tag2, &result); + GetTracker()->LookupTabNodeIds(kTag2, &result); EXPECT_TRUE(result.empty()); - GetTracker()->PutWindowInSession(tag1, 0); - GetTracker()->PutTabInWindow(tag1, 0, 3, 0); - GetTracker()->LookupTabNodeIds(tag1, &result); + GetTracker()->PutWindowInSession(kTag, 0); + GetTracker()->PutTabInWindow(kTag, 0, 3, 0); + GetTracker()->LookupTabNodeIds(kTag, &result); EXPECT_EQ(2U, result.size()); - GetTracker()->GetTab(tag1, 3, 3); - GetTracker()->LookupTabNodeIds(tag1, &result); + GetTracker()->GetTab(kTag, 3, 3); + GetTracker()->LookupTabNodeIds(kTag, &result); EXPECT_EQ(3U, result.size()); EXPECT_FALSE(result.end() == result.find(3)); - GetTracker()->GetTab(tag2, 1, 21); - GetTracker()->GetTab(tag2, 2, 22); - GetTracker()->LookupTabNodeIds(tag2, &result); + GetTracker()->GetTab(kTag2, 1, 21); + GetTracker()->GetTab(kTag2, 2, 22); + GetTracker()->LookupTabNodeIds(kTag2, &result); EXPECT_EQ(2U, result.size()); EXPECT_FALSE(result.end() == result.find(21)); EXPECT_FALSE(result.end() == result.find(22)); - GetTracker()->LookupTabNodeIds(tag1, &result); + GetTracker()->LookupTabNodeIds(kTag, &result); EXPECT_EQ(3U, result.size()); EXPECT_FALSE(result.end() == result.find(1)); EXPECT_FALSE(result.end() == result.find(2)); - GetTracker()->LookupTabNodeIds(tag3, &result); + GetTracker()->LookupTabNodeIds(kTag3, &result); EXPECT_TRUE(result.empty()); - GetTracker()->PutWindowInSession(tag3, 1); - GetTracker()->PutTabInWindow(tag3, 1, 5, 0); - GetTracker()->LookupTabNodeIds(tag3, &result); + GetTracker()->PutWindowInSession(kTag3, 1); + GetTracker()->PutTabInWindow(kTag3, 1, 5, 0); + GetTracker()->LookupTabNodeIds(kTag3, &result); EXPECT_TRUE(result.empty()); - EXPECT_FALSE(GetTracker()->DeleteSession(tag3)); - GetTracker()->LookupTabNodeIds(tag3, &result); + EXPECT_FALSE(GetTracker()->DeleteSession(kTag3)); + GetTracker()->LookupTabNodeIds(kTag3, &result); EXPECT_TRUE(result.empty()); - EXPECT_FALSE(GetTracker()->DeleteSession(tag1)); - GetTracker()->LookupTabNodeIds(tag1, &result); + EXPECT_FALSE(GetTracker()->DeleteSession(kTag)); + GetTracker()->LookupTabNodeIds(kTag, &result); EXPECT_TRUE(result.empty()); - GetTracker()->LookupTabNodeIds(tag2, &result); + GetTracker()->LookupTabNodeIds(kTag2, &result); EXPECT_EQ(2U, result.size()); EXPECT_FALSE(result.end() == result.find(21)); EXPECT_FALSE(result.end() == result.find(22)); - GetTracker()->GetTab(tag2, 1, 21); - GetTracker()->GetTab(tag2, 2, 23); - GetTracker()->LookupTabNodeIds(tag2, &result); + GetTracker()->GetTab(kTag2, 1, 21); + GetTracker()->GetTab(kTag2, 2, 23); + GetTracker()->LookupTabNodeIds(kTag2, &result); EXPECT_EQ(3U, result.size()); EXPECT_FALSE(result.end() == result.find(21)); EXPECT_FALSE(result.end() == result.find(22)); EXPECT_FALSE(result.end() == result.find(23)); - EXPECT_FALSE(GetTracker()->DeleteSession(tag2)); - GetTracker()->LookupTabNodeIds(tag2, &result); + EXPECT_FALSE(GetTracker()->DeleteSession(kTag2)); + GetTracker()->LookupTabNodeIds(kTag2, &result); EXPECT_TRUE(result.empty()); } TEST_F(SyncedSessionTrackerTest, SessionTracking) { ASSERT_TRUE(GetTracker()->Empty()); - std::string tag1 = "tag1"; - std::string tag2 = "tag2"; // Create some session information that is stale. - SyncedSession* session1 = GetTracker()->GetSession(tag1); - GetTracker()->PutWindowInSession(tag1, 0); - GetTracker()->PutTabInWindow(tag1, 0, 0, 0); - GetTracker()->PutTabInWindow(tag1, 0, 1, 1); - GetTracker()->GetTab(tag1, 2, 3U)->window_id.set_id(0); // Will be unmapped. - GetTracker()->GetTab(tag1, 3, 4U)->window_id.set_id(0); // Will be unmapped. - GetTracker()->PutWindowInSession(tag1, 1); - GetTracker()->PutTabInWindow(tag1, 1, 4, 0); - GetTracker()->PutTabInWindow(tag1, 1, 5, 1); + SyncedSession* session1 = GetTracker()->GetSession(kTag); + GetTracker()->PutWindowInSession(kTag, 0); + GetTracker()->PutTabInWindow(kTag, 0, 0, 0); + GetTracker()->PutTabInWindow(kTag, 0, 1, 1); + GetTracker()->GetTab(kTag, 2, 3U)->window_id.set_id(0); // Will be unmapped. + GetTracker()->GetTab(kTag, 3, 4U)->window_id.set_id(0); // Will be unmapped. + GetTracker()->PutWindowInSession(kTag, 1); + GetTracker()->PutTabInWindow(kTag, 1, 4, 0); + GetTracker()->PutTabInWindow(kTag, 1, 5, 1); ASSERT_EQ(2U, session1->windows.size()); ASSERT_EQ(2U, session1->windows[0]->tabs.size()); ASSERT_EQ(2U, session1->windows[1]->tabs.size()); - ASSERT_EQ(6U, GetTracker()->num_synced_tabs(tag1)); + ASSERT_EQ(6U, GetTracker()->num_synced_tabs(kTag)); // Create a session that should not be affected. - SyncedSession* session2 = GetTracker()->GetSession(tag2); - GetTracker()->PutWindowInSession(tag2, 2); - GetTracker()->PutTabInWindow(tag2, 2, 1, 0); + SyncedSession* session2 = GetTracker()->GetSession(kTag2); + GetTracker()->PutWindowInSession(kTag2, 2); + GetTracker()->PutTabInWindow(kTag2, 2, 1, 0); ASSERT_EQ(1U, session2->windows.size()); ASSERT_EQ(1U, session2->windows[2]->tabs.size()); - ASSERT_EQ(1U, GetTracker()->num_synced_tabs(tag2)); + ASSERT_EQ(1U, GetTracker()->num_synced_tabs(kTag2)); // Reset tracking and get the current windows/tabs. // We simulate moving a tab from one window to another, then closing the @@ -311,18 +307,18 @@ // on the remaining window. // New tab, arrived before meta node so unmapped. - GetTracker()->GetTab(tag1, 6, 7U); - GetTracker()->ResetSessionTracking(tag1); - GetTracker()->PutWindowInSession(tag1, 0); - GetTracker()->PutTabInWindow(tag1, 0, 0, 0); + GetTracker()->GetTab(kTag, 6, 7U); + GetTracker()->ResetSessionTracking(kTag); + GetTracker()->PutWindowInSession(kTag, 0); + GetTracker()->PutTabInWindow(kTag, 0, 0, 0); // Tab 1 is closed. - GetTracker()->PutTabInWindow(tag1, 0, 2, 1); // No longer unmapped. + GetTracker()->PutTabInWindow(kTag, 0, 2, 1); // No longer unmapped. // Tab 3 was unmapped and does not get used. - GetTracker()->PutTabInWindow(tag1, 0, 4, 2); // Moved from window 1. + GetTracker()->PutTabInWindow(kTag, 0, 4, 2); // Moved from window 1. // Window 1 was closed, along with tab 5. - GetTracker()->PutTabInWindow(tag1, 0, 6, 3); // No longer unmapped. + GetTracker()->PutTabInWindow(kTag, 0, 6, 3); // No longer unmapped. // Session 2 should not be affected. - GetTracker()->CleanupSession(tag1); + GetTracker()->CleanupSession(kTag); // Verify that only those parts of the session not owned have been removed. ASSERT_EQ(1U, session1->windows.size()); @@ -330,39 +326,90 @@ ASSERT_EQ(1U, session2->windows.size()); ASSERT_EQ(1U, session2->windows[2]->tabs.size()); ASSERT_EQ(2U, GetTracker()->num_synced_sessions()); - ASSERT_EQ(4U, GetTracker()->num_synced_tabs(tag1)); - ASSERT_EQ(1U, GetTracker()->num_synced_tabs(tag2)); + ASSERT_EQ(4U, GetTracker()->num_synced_tabs(kTag)); + ASSERT_EQ(1U, GetTracker()->num_synced_tabs(kTag2)); // All memory should be properly deallocated by destructor for the // SyncedSessionTracker. } TEST_F(SyncedSessionTrackerTest, DeleteForeignTab) { - std::string session_tag = "session_tag"; int tab_id_1 = 1; int tab_id_2 = 2; int tab_node_id_3 = 3; int tab_node_id_4 = 4; std::set<int> result; - GetTracker()->GetTab(session_tag, tab_id_1, tab_node_id_3); - GetTracker()->GetTab(session_tag, tab_id_1, tab_node_id_4); - GetTracker()->GetTab(session_tag, tab_id_2, tab_node_id_3); - GetTracker()->GetTab(session_tag, tab_id_2, tab_node_id_4); + GetTracker()->GetTab(kTag, tab_id_1, tab_node_id_3); + GetTracker()->GetTab(kTag, tab_id_1, tab_node_id_4); + GetTracker()->GetTab(kTag, tab_id_2, tab_node_id_3); + GetTracker()->GetTab(kTag, tab_id_2, tab_node_id_4); - GetTracker()->LookupTabNodeIds(session_tag, &result); + GetTracker()->LookupTabNodeIds(kTag, &result); EXPECT_EQ(2U, result.size()); EXPECT_TRUE(result.find(tab_node_id_3) != result.end()); EXPECT_TRUE(result.find(tab_node_id_4) != result.end()); - GetTracker()->DeleteForeignTab(session_tag, tab_node_id_3); - GetTracker()->LookupTabNodeIds(session_tag, &result); + GetTracker()->DeleteForeignTab(kTag, tab_node_id_3); + GetTracker()->LookupTabNodeIds(kTag, &result); EXPECT_EQ(1U, result.size()); EXPECT_TRUE(result.find(tab_node_id_4) != result.end()); - GetTracker()->DeleteForeignTab(session_tag, tab_node_id_4); - GetTracker()->LookupTabNodeIds(session_tag, &result); + GetTracker()->DeleteForeignTab(kTag, tab_node_id_4); + GetTracker()->LookupTabNodeIds(kTag, &result); EXPECT_TRUE(result.empty()); } +TEST_F(SyncedSessionTrackerTest, ReassociateTabMapped) { + const int kWindow1 = 1; + const int kTab1 = 15; + const int kTab2 = 25; + const int kTabNodeId = 1; + + // First create the tab normally. + GetTracker()->PutWindowInSession(kTag, kWindow1); + GetTracker()->PutTabInWindow(kTag, kWindow1, kTab1, 0); + SyncedSession* session = GetTracker()->GetSession(kTag); + sessions::SessionTab* tab = session->windows[kWindow1]->tabs[0].get(); + ASSERT_EQ(1U, session->windows.size()); + ASSERT_EQ(1U, session->windows[kWindow1]->tabs.size()); + ASSERT_EQ(GetTracker()->GetTab(kTag, kTab1, 1), + session->windows[kWindow1]->tabs[0].get()); + + // Then reassociate with a new tab id. + ASSERT_TRUE(GetTracker()->ReassociateTab(kTag, kTab1, kTab2)); + ASSERT_EQ(tab, GetTracker()->GetTab(kTag, kTab2, kTabNodeId)); + + // Reset tracking, and put the new tab id into the window. + GetTracker()->ResetSessionTracking(kTag); + GetTracker()->PutWindowInSession(kTag, kWindow1); + GetTracker()->PutTabInWindow(kTag, kWindow1, kTab2, 0); + GetTracker()->CleanupSession(kTag); + ASSERT_EQ(GetTracker()->GetTab(kTag, kTab2, kTabNodeId), + session->windows[kWindow1]->tabs[0].get()); +} + +TEST_F(SyncedSessionTrackerTest, ReassociateTabUnmapped) { + const int kWindow1 = 1; + const int kTab1 = 15; + const int kTab2 = 25; + const int kTabNodeId = 1; + + // First create the old tab in an unmapped state. + ASSERT_TRUE(GetTracker()->GetTab(kTag, kTab1, kTabNodeId)); + + // Then handle loading the window and reassociating the tab. + GetTracker()->ResetSessionTracking(kTag); + ASSERT_TRUE(GetTracker()->ReassociateTab(kTag, kTab1, kTab2)); + GetTracker()->PutWindowInSession(kTag, kWindow1); + GetTracker()->PutTabInWindow(kTag, kWindow1, kTab2, 0); + GetTracker()->CleanupSession(kTag); + + // Then reassociate with a new tab id. It should be accessible both via the + // GetSession as well as GetTab. + SyncedSession* session = GetTracker()->GetSession(kTag); + ASSERT_EQ(GetTracker()->GetTab(kTag, kTab2, 1), + session->windows[kWindow1]->tabs[0].get()); +} + } // namespace sync_sessions
diff --git a/components/test_runner/event_sender.cc b/components/test_runner/event_sender.cc index a45154a..8b2ccef 100644 --- a/components/test_runner/event_sender.cc +++ b/components/test_runner/event_sender.cc
@@ -26,6 +26,7 @@ #include "gin/handle.h" #include "gin/object_template_builder.h" #include "gin/wrappable.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" #include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/platform/WebPointerProperties.h" #include "third_party/WebKit/public/platform/WebString.h" @@ -2698,8 +2699,9 @@ mainFrameWidget()->dragTargetDragLeave(); } current_drag_data_.reset(); - view()->dragSourceEndedAt(client_point, screen_point, current_drag_effect_); - view()->dragSourceSystemDragEnded(); + mainFrameWidget()->dragSourceEndedAt(client_point, screen_point, + current_drag_effect_); + mainFrameWidget()->dragSourceSystemDragEnded(); } void EventSender::DoDragAfterMouseUp(const WebMouseEvent& raw_event) {
diff --git a/components/test_runner/test_plugin.cc b/components/test_runner/test_plugin.cc index c8a0ca4..6818384 100644 --- a/components/test_runner/test_plugin.cc +++ b/components/test_runner/test_plugin.cc
@@ -21,6 +21,7 @@ #include "gpu/command_buffer/client/gles2_interface.h" #include "third_party/WebKit/public/platform/Platform.h" #include "third_party/WebKit/public/platform/WebCompositorSupport.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" #include "third_party/WebKit/public/platform/WebGraphicsContext3DProvider.h" #include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/platform/WebThread.h"
diff --git a/components/test_runner/text_input_controller.cc b/components/test_runner/text_input_controller.cc index 7148946..d1d6c03a 100644 --- a/components/test_runner/text_input_controller.cc +++ b/components/test_runner/text_input_controller.cc
@@ -11,9 +11,9 @@ #include "gin/handle.h" #include "gin/object_template_builder.h" #include "gin/wrappable.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/web/WebCompositionUnderline.h" #include "third_party/WebKit/public/web/WebFrameWidget.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" #include "third_party/WebKit/public/web/WebInputMethodController.h" #include "third_party/WebKit/public/web/WebKit.h" #include "third_party/WebKit/public/web/WebLocalFrame.h"
diff --git a/components/tracing/BUILD.gn b/components/tracing/BUILD.gn index 1dabb29..b73c3d6 100644 --- a/components/tracing/BUILD.gn +++ b/components/tracing/BUILD.gn
@@ -132,6 +132,14 @@ "//testing/perf", ] + data = [ + # Needed for isolate script to execute. + "//testing/scripts/common.py", + "//testing/xvfb.py", + "//testing/scripts/run_gtest_perf_test.py", + "//tools/perf/generate_legacy_perf_dashboard_json.py", + ] + if (is_android) { deps += [ "//testing/android/native_test:native_test_native_code" ] }
diff --git a/components/tracing/docs/adding_memory_infra_tracing.md b/components/tracing/docs/adding_memory_infra_tracing.md index 7960e153..ea01fa7e 100644 --- a/components/tracing/docs/adding_memory_infra_tracing.md +++ b/components/tracing/docs/adding_memory_infra_tracing.md
@@ -1,178 +1,2 @@ -# Adding MemoryInfra Tracing to a Component +This document has moved to [//docs/memory-infra/adding_memory_infra_tracing.md](/docs/memory-infra/adding_memory_infra_tracing.md). -If you have a component that manages memory allocations, you should be -registering and tracking those allocations with Chrome's MemoryInfra system. -This lets you: - - * See an overview of your allocations, giving insight into total size and - breakdown. - * Understand how your allocations change over time and how they are impacted by - other parts of Chrome. - * Catch regressions in your component's allocations size by setting up - telemetry tests which monitor your allocation sizes under certain - circumstances. - -Some existing components that use MemoryInfra: - - * **Discardable Memory**: Tracks usage of discardable memory throughout Chrome. - * **GPU**: Tracks OpenGL and other GPU object allocations. - * **V8**: Tracks the heap size for JS. - -[TOC] - -## Overview - -In order to hook into Chrome's MemoryInfra system, your component needs to do -two things: - - 1. Create a [`MemoryDumpProvider`][mdp] for your component. - 2. Register and unregister you dump provider with the - [`MemoryDumpManager`][mdm]. - -[mdp]: https://chromium.googlesource.com/chromium/src/+/master/base/trace_event/memory_dump_provider.h -[mdm]: https://chromium.googlesource.com/chromium/src/+/master/base/trace_event/memory_dump_manager.h - -## Creating a Memory Dump Provider - -You can implement a [`MemoryDumpProvider`][mdp] as a stand-alone class, or as an -additional interface on an existing class. For example, this interface is -frequently implemented on classes which manage a pool of allocations (see -[`cc::ResourcePool`][resource-pool] for an example). - -A `MemoryDumpProvider` has one basic job, to implement `OnMemoryDump`. This -function is responsible for iterating over the resources allocated or tracked by -your component, and creating a [`MemoryAllocatorDump`][mem-alloc-dump] for each -using [`ProcessMemoryDump::CreateAllocatorDump`][pmd]. A simple example: - -```cpp -bool MyComponent::OnMemoryDump(const MemoryDumpArgs& args, - ProcessMemoryDump* process_memory_dump) { - for (const auto& allocation : my_allocations_) { - auto* dump = process_memory_dump->CreateAllocatorDump( - "path/to/my/component/allocation_" + allocation.id().ToString()); - dump->AddScalar(base::trace_event::MemoryAllocatorDump::kNameSize, - base::trace_event::MemoryAllocatorDump::kUnitsBytes, - allocation.size_bytes()); - - // While you will typically have a kNameSize entry, you can add additional - // entries to your dump with free-form names. In this example we also dump - // an object's "free_size", assuming the object may not be entirely in use. - dump->AddScalar("free_size", - base::trace_event::MemoryAllocatorDump::kUnitsBytes, - allocation.free_size_bytes()); - } -} -``` - -For many components, this may be all that is needed. See -[Handling Shared Memory Allocations](#Handling-Shared-Memory-Allocations) and -[Suballocations](#Suballocations) for information on more complex use cases. - -[resource-pool]: https://chromium.googlesource.com/chromium/src/+/master/cc/resources/resource_pool.h -[mem-alloc-dump]: https://chromium.googlesource.com/chromium/src/+/master/base/trace_event/memory_allocator_dump.h -[pmd]: https://chromium.googlesource.com/chromium/src/+/master/base/trace_event/process_memory_dump.h - -## Registering a Memory Dump Provider - -Once you have created a [`MemoryDumpProvider`][mdp], you need to register it -with the [`MemoryDumpManager`][mdm] before the system can start polling it for -memory information. Registration is generally straightforward, and involves -calling `MemoryDumpManager::RegisterDumpProvider`: - -```cpp -// Each process uses a singleton |MemoryDumpManager|. -base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider( - my_memory_dump_provider_, my_single_thread_task_runner_); -``` - -In the above code, `my_memory_dump_provider_` is the `MemoryDumpProvider` -outlined in the previous section. `my_single_thread_task_runner_` is more -complex and may be a number of things: - - * Most commonly, if your component is always used from the main message loop, - `my_single_thread_task_runner_` may just be - [`base::ThreadTaskRunnerHandle::Get()`][task-runner-handle]. - * If your component already uses a custom `base::SingleThreadTaskRunner` for - executing tasks on a specific thread, you should likely use this runner. - -[task-runner-handle]: https://chromium.googlesource.com/chromium/src/+/master/base/thread_task_runner_handle.h - -## Unregistration - -Unregistration must happen on the thread belonging to the -`SingleThreadTaskRunner` provided at registration time. Unregistering on another -thread can lead to race conditions if tracing is active when the provider is -unregistered. - -```cpp -base::trace_event::MemoryDumpManager::GetInstance()->UnregisterDumpProvider( - my_memory_dump_provider_); -``` - -## Handling Shared Memory Allocations - -When an allocation is shared between two components, it may be useful to dump -the allocation in both components, but you also want to avoid double-counting -the allocation. This can be achieved using the concept of _ownership edges_. -An ownership edge represents that the _source_ memory allocator dump owns a -_target_ memory allocator dump. If multiple source dumps own a single target, -then the cost of that target allocation will be split between the sources. -Additionally, importance can be added to a specific ownership edge, allowing -the highest importance source of that edge to claim the entire cost of the -target. - -In the typical case, you will use [`ProcessMemoryDump`][pmd] to create a shared -global allocator dump. This dump will act as the target of all -component-specific dumps of a specific resource: - -```cpp -// Component 1 is going to create a dump, source_mad, for an allocation, -// alloc_, which may be shared with other components / processes. -MyAllocationType* alloc_; -base::trace_event::MemoryAllocatorDump* source_mad; - -// Component 1 creates and populates source_mad; -... - -// In addition to creating a source dump, we must create a global shared -// target dump. This dump should be created with a unique global ID which can be -// generated any place the allocation is used. I recommend adding a global ID -// generation function to the allocation type. -base::trace_event::MemoryAllocatorDumpGUID guid(alloc_->GetGUIDString()); - -// From this global ID we can generate the parent allocator dump. -base::trace_event::MemoryAllocatorDump* target_mad = - process_memory_dump->CreateSharedGlobalAllocatorDump(guid); - -// We now create an ownership edge from the source dump to the target dump. -// When creating an edge, you can assign an importance to this edge. If all -// edges have the same importance, the size of the allocation will be split -// between all sources which create a dump for the allocation. If one -// edge has higher importance than the others, its source will be assigned the -// full size of the allocation. -const int kImportance = 1; -process_memory_dump->AddOwnershipEdge( - source_mad->guid(), target_mad->guid(), kImportance); -``` - -If an allocation is being shared across process boundaries, it may be useful to -generate a global ID which incorporates the ID of the local process, preventing -two processes from generating colliding IDs. As it is not recommended to pass a -process ID between processes for security reasons, a function -`MemoryDumpManager::GetTracingProcessId` is provided which generates a unique ID -per process that can be passed with the resource without security concerns. -Frequently this ID is used to generate a global ID that is based on the -allocated resource's ID combined with the allocating process' tracing ID. - -## Suballocations - -Another advanced use case involves tracking sub-allocations of a larger -allocation. For instance, this is used in -[`gpu::gles2::TextureManager`][texture-manager] to dump both the suballocations -which make up a texture. To create a suballocation, instead of calling -[`ProcessMemoryDump::CreateAllocatorDump`][pmd] to create a -[`MemoryAllocatorDump`][mem-alloc-dump], you call -[`ProcessMemoryDump::AddSubAllocation`][pmd], providing the ID of the parent -allocation as the first parameter. - -[texture-manager]: https://chromium.googlesource.com/chromium/src/+/master/gpu/command_buffer/service/texture_manager.cc
diff --git a/components/tracing/docs/heap_profiler.md b/components/tracing/docs/heap_profiler.md index 18d1b44..e432b276 100644 --- a/components/tracing/docs/heap_profiler.md +++ b/components/tracing/docs/heap_profiler.md
@@ -1,168 +1,2 @@ -# Heap Profiling with MemoryInfra +This document has moved to [//docs/memory-infra/heap_profiler.md](/docs/memory-infra/heap_profiler.md). -As of Chrome 48, MemoryInfra supports heap profiling. The core principle is -a solution that JustWorks™ on all platforms without patching or rebuilding, -intergrated with the chrome://tracing ecosystem. - -[TOC] - -## How to Use - - 1. Start Chrome with the `--enable-heap-profiling` switch. This will make - Chrome keep track of all allocations. - - 2. Grab a [MemoryInfra][memory-infra] trace. For best results, start tracing - first, and _then_ open a new tab that you want to trace. Furthermore, - enabling more categories (besides memory-infra) will yield more detailed - information in the heap profiler backtraces. - - 3. When the trace has been collected, select a heavy memory dump indicated by - a purple ![M][m-purple] dot. Heap dumps are only included in heavy memory - dumps. - - 4. In the analysis view, cells marked with a triple bar icon (☰) contain heap - dumps. Select such a cell. - - ![Cells containing a heap dump][cells-heap-dump] - - 5. Scroll down all the way to _Heap Details_. - - 6. Pinpoint the memory bug and live happily ever after. - -[memory-infra]: memory_infra.md -[m-purple]: https://storage.googleapis.com/chromium-docs.appspot.com/d7bdf4d16204c293688be2e5a0bcb2bf463dbbc3 -[cells-heap-dump]: https://storage.googleapis.com/chromium-docs.appspot.com/a24d80d6a08da088e2e9c8b2b64daa215be4dacb - -### Native stack traces - -By default heap profiling collects pseudo allocation traces, which are based -on trace events. I.e. frames in allocation traces correspond to trace events -that were active at the time of allocations, and are not real function names. -However, you can build a special Linux / Android build that will collect -real C/C++ stack traces. - - 1. Build with the following GN flags: - - Linux - - enable_profiling = true - - - Android - - arm_use_thumb = false - enable_profiling = true - - 2. Start Chrome with `--enable-heap-profiling=native` switch (notice - `=native` part). - - On Android use the command line tool before starting the app: - - build/android/adb_chrome_public_command_line --enable-heap-profiling=native - - (run the tool with an empty argument `''` to clear the command line) - - 3. Grab a [MemoryInfra][memory-infra] trace. You don't need any other - categories besides `memory-infra`. - - 4. Save the grabbed trace file. This step is needed because freshly - taken trace file contains raw addresses (which look like `pc:dcf5dbf8`) - instead of function names, and needs to be symbolized. - - 4. Symbolize the trace file. During symbolization addresses are resolved to - the corresponding function names and trace file is rewritten (but a backup - is saved with `.BACKUP` extension). - - Linux - - third_party/catapult/tracing/bin/symbolize_trace <trace file> - - Android - - third_party/catapult/tracing/bin/symbolize_trace --output-directory out/Release <trace file> - - (note `--output-directory` and make sure it's right for your setup) - - 5. Load the trace file in `chrome://tracing`. Locate a purple ![M][m-purple] - dot, and continue from step *3* from the instructions above. Native stack - traces will be shown in the _Heap Details_ pane. - -## Heap Details - -The heap details view contains a tree that represents the heap. The size of the -root node corresponds to the selected allocator cell. - -*** aside -The size value in the heap details view will not match the value in the selected -analysis view cell exactly. There are three reasons for this. First, the heap -profiler reports the memory that _the program requested_, whereas the allocator -reports the memory that it _actually allocated_ plus its own bookkeeping -overhead. Second, allocations that happen early --- before Chrome knows that -heap profiling is enabled --- are not captured by the heap profiler, but they -are reported by the allocator. Third, tracing overhead is not discounted by the -heap profiler. -*** - -The heap can be broken down in two ways: by _backtrace_ (marked with an ƒ), and -by _type_ (marked with a Ⓣ). When tracing is enabled, Chrome records trace -events, most of which appear in the flame chart in timeline view. At every -point in time these trace events form a pseudo stack, and a vertical slice -through the flame chart is like a backtrace. This corresponds to the ƒ nodes in -the heap details view. Hence enabling more tracing categories will give a more -detailed breakdown of the heap. - -The other way to break down the heap is by object type. At the moment this is -only supported for PartitionAlloc. - -*** aside -In official builds, only the most common type names are included due to binary -size concerns. Development builds have full type information. -*** - -To keep the trace log small, uninteresting information is omitted from heap -dumps. The long tail of small nodes is not dumped, but grouped in an `<other>` -node instead. Note that altough these small nodes are insignificant on their -own, together they can be responsible for a significant portion of the heap. The -`<other>` node is large in that case. - -## Example - -In the trace below, `ParseAuthorStyleSheet` is called at some point. - -![ParseAuthorStyleSheet pseudo stack][pseudo-stack] - -The pseudo stack of trace events corresponds to the tree of ƒ nodes below. Of -the 23.5 MiB of memory allocated with PartitionAlloc, 1.9 MiB was allocated -inside `ParseAuthorStyleSheet`, either directly, or at a deeper level (like -`CSSParserImpl::parseStyleSheet`). - -![Memory Allocated in ParseAuthorStyleSheet][break-down-by-backtrace] - -By expanding `ParseAuthorStyleSheet`, we can see which types were allocated -there. Of the 1.9 MiB, 371 KiB was spent on `ImmutableStylePropertySet`s, and -238 KiB was spent on `StringImpl`s. - -![ParseAuthorStyleSheet broken down by type][break-down-by-type] - -It is also possible to break down by type first, and then by backtrace. Below -we see that of the 23.5 MiB allocated with PartitionAlloc, 1 MiB is spent on -`Node`s, and about half of the memory spent on nodes was allocated in -`HTMLDocumentParser`. - -![The PartitionAlloc heap broken down by type first and then by backtrace][type-then-backtrace] - -Heap dump diffs are fully supported by trace viewer. Select a heavy memory dump -(a purple dot), then with the control key select a heavy memory dump earlier in -time. Below is a diff of theverge.com before and in the middle of loading ads. -We can see that 4 MiB were allocated when parsing the documents in all those -iframes, almost a megabyte of which was due to JavaScript. (Note that this is -memory allocated by PartitionAlloc alone, the total renderer memory increase was -around 72 MiB.) - -![Diff of The Verge before and after loading ads][diff] - -[pseudo-stack]: https://storage.googleapis.com/chromium-docs.appspot.com/058e50350836f55724e100d4dbbddf4b9803f550 -[break-down-by-backtrace]: https://storage.googleapis.com/chromium-docs.appspot.com/ec61c5f15705f5bcf3ca83a155ed647a0538bbe1 -[break-down-by-type]: https://storage.googleapis.com/chromium-docs.appspot.com/2236e61021922c0813908c6745136953fa20a37b -[type-then-backtrace]: https://storage.googleapis.com/chromium-docs.appspot.com/c5367dde11476bdbf2d5a1c51674148915573d11 -[diff]: https://storage.googleapis.com/chromium-docs.appspot.com/802141906869cd533bb613da5f91bd0b071ceb24
diff --git a/components/tracing/docs/heap_profiler_internals.md b/components/tracing/docs/heap_profiler_internals.md index d1019c8..a54e7f3 100644 --- a/components/tracing/docs/heap_profiler_internals.md +++ b/components/tracing/docs/heap_profiler_internals.md
@@ -1,184 +1,2 @@ -# Heap Profiler Internals +This document has moved to [//docs/memory-infra/heap_profiler_internals.md](/docs/memory-infra/heap_profiler_internals.md). -This document describes how the heap profiler works and how to add heap -profiling support to your allocator. If you just want to know how to use it, -see [Heap Profiling with MemoryInfra](heap_profiler.md) - -[TOC] - -## Overview - -The heap profiler consists of tree main components: - - * **The Context Tracker**: Responsible for providing context (pseudo stack - backtrace) when an allocation occurs. - * **The Allocation Register**: A specialized hash table that stores allocation - details by address. - * **The Heap Dump Writer**: Extracts the most important information from a set - of recorded allocations and converts it into a format that can be dumped into - the trace log. - -These components are designed to work well together, but to be usable -independently as well. - -When there is a way to get notified of all allocations and frees, this is the -normal flow: - - 1. When an allocation occurs, call - [`AllocationContextTracker::GetInstanceForCurrentThread()->GetContextSnapshot()`][context-tracker] - to get an [`AllocationContext`][alloc-context]. - 2. Insert that context together with the address and size into an - [`AllocationRegister`][alloc-register] by calling `Insert()`. - 3. When memory is freed, remove it from the register with `Remove()`. - 4. On memory dump, collect the allocations from the register, call - [`ExportHeapDump()`][export-heap-dump], and add the generated heap dump to - the memory dump. - -[context-tracker]: https://chromium.googlesource.com/chromium/src/+/master/base/trace_event/heap_profiler_allocation_context_tracker.h -[alloc-context]: https://chromium.googlesource.com/chromium/src/+/master/base/trace_event/heap_profiler_allocation_context.h -[alloc-register]: https://chromium.googlesource.com/chromium/src/+/master/base/trace_event/heap_profiler_allocation_register.h -[export-heap-dump]: https://chromium.googlesource.com/chromium/src/+/master/base/trace_event/heap_profiler_heap_dump_writer.h - -*** aside -An allocator can skip step 2 and 3 if it is able to store the context itself, -and if it is able to enumerate all allocations for step 4. -*** - -When heap profiling is enabled (the `--enable-heap-profiling` flag is passed), -the memory dump manager calls `OnHeapProfilingEnabled()` on every -`MemoryDumpProvider` as early as possible, so allocators can start recording -allocations. This should be done even when tracing has not been started, -because these allocations might still be around when a heap dump happens during -tracing. - -## Context Tracker - -The [`AllocationContextTracker`][context-tracker] is a thread-local object. Its -main purpose is to keep track of a pseudo stack of trace events. Chrome has -been instrumented with lots of `TRACE_EVENT` macros. These trace events push -their name to a thread-local stack when they go into scope, and pop when they -go out of scope, if all of the following conditions have been met: - - * A trace is being recorded. - * The category of the event is enabled in the trace config. - * Heap profiling is enabled (with the `--enable-heap-profiling` flag). - -This means that allocations that occur before tracing is started will not have -backtrace information in their context. - -A thread-local instance of the context tracker is initialized lazily when it is -first accessed. This might be because a trace event pushed or popped, or because -`GetContextSnapshot()` was called when an allocation occurred. - -[`AllocationContext`][alloc-context] is what is used to group and break down -allocations. Currently `AllocationContext` has the following fields: - - * Backtrace: filled by the context tracker, obtained from the thread-local - pseudo stack. - * Type name: to be filled in at a point where the type of a pointer is known, - set to _[unknown]_ by default. - -It is possible to modify this context after insertion into the register, for -instance to set the type name if it was not known at the time of allocation. - -## Allocation Register - -The [`AllocationRegister`][alloc-register] is a hash table specialized for -storing `(size, AllocationContext)` pairs by address. It has been optimized for -Chrome's typical number of unfreed allocations, and it is backed by `mmap` -memory directly so there are no reentrancy issues when using it to record -`malloc` allocations. - -The allocation register is threading-agnostic. Access must be synchronised -properly. - -## Heap Dump Writer - -Dumping every single allocation in the allocation register straight into the -trace log is not an option due to the sheer volume (~300k unfreed allocations). -The role of the [`ExportHeapDump()`][export-heap-dump] function is to group -allocations, striking a balance between trace log size and detail. - -See the [Heap Dump Format][heap-dump-format] document for more details about the -structure of the heap dump in the trace log. - -[heap-dump-format]: https://docs.google.com/document/d/1NqBg1MzVnuMsnvV1AKLdKaPSPGpd81NaMPVk5stYanQ - -## Instrumenting an Allocator - -Below is an example of adding heap profiling support to an allocator that has -an existing memory dump provider. - -```cpp -class FooDumpProvider : public MemoryDumpProvider { - - // Kept as pointer because |AllocationRegister| allocates a lot of virtual - // address space when constructed, so only construct it when heap profiling is - // enabled. - scoped_ptr<AllocationRegister> allocation_register_; - Lock allocation_register_lock_; - - static FooDumpProvider* GetInstance(); - - void InsertAllocation(void* address, size_t size) { - AllocationContext context = AllocationContextTracker::GetInstanceForCurrentThread()->GetContextSnapshot(); - AutoLock lock(allocation_register_lock_); - allocation_register_->Insert(address, size, context); - } - - void RemoveAllocation(void* address) { - AutoLock lock(allocation_register_lock_); - allocation_register_->Remove(address); - } - - // Will be called as early as possible by the memory dump manager. - void OnHeapProfilingEnabled(bool enabled) override { - AutoLock lock(allocation_register_lock_); - allocation_register_.reset(new AllocationRegister()); - - // At this point, make sure that from now on, for every allocation and - // free, |FooDumpProvider::GetInstance()->InsertAllocation()| and - // |RemoveAllocation| are called. - } - - bool OnMemoryDump(const MemoryDumpArgs& args, - ProcessMemoryDump& pmd) override { - // Do regular dumping here. - - // Dump the heap only for detailed dumps. - if (args.level_of_detail == MemoryDumpLevelOfDetail::DETAILED) { - TraceEventMemoryOverhead overhead; - hash_map<AllocationContext, size_t> bytes_by_context; - - { - AutoLock lock(allocation_register_lock_); - if (allocation_register_) { - // Group allocations in the register into |bytes_by_context|, but do - // no additional processing inside the lock. - for (const auto& alloc_size : *allocation_register_) - bytes_by_context[alloc_size.context] += alloc_size.size; - - allocation_register_->EstimateTraceMemoryOverhead(&overhead); - } - } - - if (!bytes_by_context.empty()) { - scoped_refptr<TracedValue> heap_dump = ExportHeapDump( - bytes_by_context, - pmd->session_state()->stack_frame_deduplicator(), - pmb->session_state()->type_name_deduplicator()); - pmd->AddHeapDump("foo_allocator", heap_dump); - overhead.DumpInto("tracing/heap_profiler", pmd); - } - } - - return true; - } -}; - -``` - -*** aside -The implementation for `malloc` is more complicated because it needs to deal -with reentrancy. -***
diff --git a/components/tracing/docs/memory_infra.md b/components/tracing/docs/memory_infra.md index 3fbb545..48e242b 100644 --- a/components/tracing/docs/memory_infra.md +++ b/components/tracing/docs/memory_infra.md
@@ -1,171 +1,2 @@ -# MemoryInfra +This document has moved to [//docs/memory-infra/README.md](/docs/memory-infra/README.md). -MemoryInfra is a timeline-based profiling system integrated in chrome://tracing. -It aims at creating Chrome-scale memory measurement tooling so that on any -Chrome in the world --- desktop, mobile, Chrome OS or any other --- with the -click of a button you can understand where memory is being used in your system. - -[TOC] - -## Getting Started - - 1. Get a bleeding-edge or tip-of-tree build of Chrome. - - 2. [Record a trace as usual][record-trace]: open [chrome://tracing][tracing] - on Desktop Chrome or [chrome://inspect?tracing][inspect-tracing] to trace - Chrome for Android. - - 3. Make sure to enable the **memory-infra** category on the right. - - ![Tick the memory-infra checkbox when recording a trace.][memory-infra-box] - - 4. For now, some subsystems only work if Chrome is started with the - `--no-sandbox` flag. - <!-- TODO(primiano) TODO(ssid): https://crbug.com/461788 --> - -[record-trace]: https://sites.google.com/a/chromium.org/dev/developers/how-tos/trace-event-profiling-tool/recording-tracing-runs -[tracing]: chrome://tracing -[inspect-tracing]: chrome://inspect?tracing -[memory-infra-box]: https://storage.googleapis.com/chromium-docs.appspot.com/1c6d1886584e7cc6ffed0d377f32023f8da53e02 - -![Timeline View and Analysis View][tracing-views] - -After recording a trace, you will see the **timeline view**. Timeline view -shows: - - * Total resident memory grouped by process (at the top). - * Total resident memory grouped by subsystem (at the top). - * Allocated memory per subsystem for every process. - -Click one of the ![M][m-blue] dots to bring up the **analysis view**. Click -on a cell in analysis view to reveal more information about its subsystem. -PartitionAlloc for instance, has more details about its partitions. - -![Component details for PartitionAlloc][partalloc-details] - -The purple ![M][m-purple] dots represent heavy dumps. In these dumps, components -can provide more details than in the regular dumps. The full details of the -MemoryInfra UI are explained in its [design doc][mi-ui-doc]. - -[tracing-views]: https://storage.googleapis.com/chromium-docs.appspot.com/db12015bd262385f0f8bd69133330978a99da1ca -[m-blue]: https://storage.googleapis.com/chromium-docs.appspot.com/b60f342e38ff3a3767bbe4c8640d96a2d8bc864b -[partalloc-details]: https://storage.googleapis.com/chromium-docs.appspot.com/02eade61d57c83f8ef8227965513456555fc3324 -[m-purple]: https://storage.googleapis.com/chromium-docs.appspot.com/d7bdf4d16204c293688be2e5a0bcb2bf463dbbc3 -[mi-ui-doc]: https://docs.google.com/document/d/1b5BSBEd1oB-3zj_CBAQWiQZ0cmI0HmjmXG-5iNveLqw/edit - -## Columns - -**Columns in blue** reflect the amount of actual physical memory used by the -process. This is what exerts memory pressure on the system. - - * **Total Resident**: (TODO: document this). - * **Peak Total Resident**: (TODO: document this). - * **PSS**: (TODO: document this). - * **Private Dirty**: (TODO: document this). - * **Swapped**: (TODO: document this). - -**Columns in black** reflect a best estimation of the the amount of physical -memory used by various subsystems of Chrome. - - * **Blink GC**: Memory used by [Oilpan][oilpan]. - * **CC**: Memory used by the compositor. - See [cc/memory][cc-memory] for the full details. - * **Discardable**: (TODO: document this). - * **Font Caches**: (TODO: document this). - * **GPU** and **GPU Memory Buffer**: GPU memory and RAM used for GPU purposes. - See [GPU Memory Tracing][gpu-memory]. - * **LevelDB**: (TODO: document this). - * **Malloc**: Memory allocated by calls to `malloc`, or `new` for most - non-Blink objects. - * **PartitionAlloc**: Memory allocated via [PartitionAlloc][partalloc]. - Blink objects that are not managed by Oilpan are allocated with - PartitionAlloc. - * **Skia**: (TODO: document this). - * **SQLite**: (TODO: document this). - * **V8**: (TODO: document this). - * **Web Cache**: (TODO: document this). - -The **tracing column in gray** reports memory that is used to collect all of the -above information. This memory would not be used if tracing were not enabled, -and it is discounted from malloc and the blue columns. - -<!-- TODO(primiano): Improve this. https://crbug.com/??? --> - -[oilpan]: /third_party/WebKit/Source/platform/heap/BlinkGCDesign.md -[cc-memory]: /cc/memory.md -[gpu-memory]: memory_infra_gpu.md -[partalloc]: /third_party/WebKit/Source/wtf/allocator/PartitionAlloc.md - -## Related Pages - - * [Adding MemoryInfra Tracing to a Component](adding_memory_infra_tracing.md) - * [GPU Memory Tracing](memory_infra_gpu.md) - * [Heap Profiler Internals](heap_profiler_internals.md) - * [Heap Profiling with MemoryInfra](heap_profiler.md) - * [Startup Tracing with MemoryInfra](memory_infra_startup_tracing.md) - -## Rationale - -Another memory profiler? What is wrong with tool X? -Most of the existing tools: - - * Are hard to get working with Chrome. (Massive symbols, require OS-specific - tricks.) - * Lack Chrome-related context. - * Don't deal with multi-process scenarios. - -MemoryInfra leverages the existing tracing infrastructure in Chrome and provides -contextual data: - - * **It speaks Chrome slang.** - The Chromium codebase is instrumented. Its memory subsystems (allocators, - caches, etc.) uniformly report their stats into the trace in a way that can - be understood by Chrome developers. No more - `__gnu_cxx::new_allocator< std::_Rb_tree_node< std::pair< std::string const, base::Value*>>> ::allocate`. - * **Timeline data that can be correlated with other events.** - Did memory suddenly increase during a specific Blink / V8 / HTML parsing - event? Which subsystem increased? Did memory not go down as expected after - closing a tab? Which other threads were active during a bloat? - * **Works out of the box on desktop and mobile.** - No recompilations with unmaintained `GYP_DEFINES`, no time-consuming - symbolizations stages. All the logic is already into Chrome, ready to dump at - any time. - * **The same technology is used for telemetry and the ChromePerf dashboard.** - See [the slides][chromeperf-slides] and take a look at - [some ChromePerf dashboards][chromeperf] and - [telemetry documentation][telemetry]. - -[chromeperf-slides]: https://docs.google.com/presentation/d/1OyxyT1sfg50lA36A7ibZ7-bBRXI1kVlvCW0W9qAmM_0/present?slide=id.gde150139b_0_137 -[chromeperf]: https://chromeperf.appspot.com/report?sid=3b54e60c9951656574e19252fadeca846813afe04453c98a49136af4c8820b8d -[telemetry]: https://catapult.gsrc.io/telemetry - -## Development - -MemoryInfra is based on a simple and extensible architecture. See -[the slides][dp-slides] on how to get your subsystem reported in MemoryInfra, -or take a look at one of the existing examples such as -[malloc_dump_provider.cc][malloc-dp]. The crbug label is -[Hotlist-MemoryInfra][hotlist]. Don't hesitate to contact -[tracing@chromium.org][mailtracing] for questions and support. - -[dp-slides]: https://docs.google.com/presentation/d/1GI3HY3Mm5-Mvp6eZyVB0JiaJ-u3L1MMJeKHJg4lxjEI/present?slide=id.g995514d5c_1_45 -[malloc-dp]: https://chromium.googlesource.com/chromium/src.git/+/master/base/trace_event/malloc_dump_provider.cc -[hotlist]: https://code.google.com/p/chromium/issues/list?q=label:Hotlist-MemoryInfra -[mailtracing]: mailto:tracing@chromium.org - -## Design documents - -Architectural: - -<iframe width="100%" height="300px" src="https://docs.google.com/a/google.com/embeddedfolderview?id=0B3KuDeqD-lVJfmp0cW1VcE5XVWNxZndxelV5T19kT2NFSndYZlNFbkFpc3pSa2VDN0hlMm8"> -</iframe> - -Chrome-side design docs: - -<iframe width="100%" height="300px" src="https://docs.google.com/a/google.com/embeddedfolderview?id=0B3KuDeqD-lVJfndSa2dleUQtMnZDeWpPZk1JV0QtbVM5STkwWms4YThzQ0pGTmU1QU9kNVk"> -</iframe> - -Catapult-side design docs: - -<iframe width="100%" height="300px" src="https://docs.google.com/a/google.com/embeddedfolderview?id=0B3KuDeqD-lVJfm10bXd5YmRNWUpKOElOWS0xdU1tMmV1S3F4aHo0ZDJLTmtGRy1qVnQtVWM"> -</iframe>
diff --git a/components/tracing/docs/memory_infra_gpu.md b/components/tracing/docs/memory_infra_gpu.md index 57f49a4..799ba7c 100644 --- a/components/tracing/docs/memory_infra_gpu.md +++ b/components/tracing/docs/memory_infra_gpu.md
@@ -1,93 +1,2 @@ -# GPU Memory Tracing +This document has moved to [//docs/memory-infra/probe-gpu.md](/docs/memory-infra/probe-gpu.md). -This is an overview of the GPU column in [MemoryInfra][memory-infra]. - -[TOC] - -## Quick Start - -If you want an overview of total GPU memory usage, select the GPU process' GPU -category and look at the _size_ column. (Not _effective size_.) - -![Look at the size column for total GPU memory][gpu-size-column] - -[memory-infra]: memory_infra.md -[gpu-size-column]: https://storage.googleapis.com/chromium-docs.appspot.com/c7d632c18d90d99e393ad0ade929f96e7d8243fe - -## In Depth - -GPU Memory in Chrome involves several different types of allocations. These -include, but are not limited to: - - * **Raw OpenGL Objects**: These objects are allocated by Chrome using the - OpenGL API. Chrome itself has handles to these objects, but the actual - backing memory may live in a variety of places (CPU side in the GPU process, - CPU side in the kernel, GPU side). Because most OpenGL operations occur over - IPC, communicating with Chrome's GPU process, these allocations are almost - always shared between a renderer or browser process and the GPU process. - * **GPU Memory Buffers**: These objects provide a chunk of writable memory - which can be handed off cross-process. While GPUMemoryBuffers represent a - platform-independent way to access this memory, they have a number of - possible platform-specific implementations (EGL surfaces on Linux, - IOSurfaces on Mac, or CPU side shared memory). Because of their cross - process use case, these objects will almost always be shared between a - renderer or browser process and the GPU process. - * **GLImages**: GLImages are a platform-independent abstraction around GPU - memory, similar to GPU Memory Buffers. In many cases, GLImages are created - from GPUMemoryBuffers. The primary difference is that GLImages are designed - to be bound to an OpenGL texture using the image extension. - -GPU Memory can be found across a number of different processes, in a few -different categories. - -Renderer or browser process: - - * **CC Category**: The CC category contains all resource allocations used in - the Chrome Compositor. When GPU rasterization is enabled, these resource - allocations will be GPU allocations as well. See also - [cc/memory][cc-memory]. - * **Skia/gpu_resources Category**: All GPU resources used by Skia. - * **GPUMemoryBuffer Category**: All GPUMemoryBuffers in use in the current - process. - -GPU process: - - * **GPU Category**: All GPU allocations, many shared with other processes. - * **GPUMemoryBuffer Category**: All GPUMemoryBuffers. - -## Example - -Many of the objects listed above are shared between multiple processes. -Consider a GL texture used by CC --- this texture is shared between a renderer -and the GPU process. Additionally, the texture may be backed by a GLImage which -was created from a GPUMemoryBuffer, which is also shared between the renderer -and GPU process. This means that the single texture may show up in the memory -logs of two different processes multiple times. - -To make things easier to understand, each GPU allocation is only ever "owned" -by a single process and category. For instance, in the above example, the -texture would be owned by the CC category of the renderer process. Each -allocation has (at least) two sizes recorded --- _size_ and _effective size_. -In the owning allocation, these two numbers will match: - -![Matching size and effective size][owner-size] - -Note that the allocation also gives information on what other processes it is -shared with (seen by hovering over the green arrow). If we navigate to the -other allocation (in this case, gpu/gl/textures/client_25/texture_216) we will -see a non-owning allocation. In this allocation the size is the same, but the -_effective size_ is 0: - -![Effective size of zero][non-owner-size] - -Other types, such as GPUMemoryBuffers and GLImages have similar sharing -patterns. - -When trying to get an overview of the absolute memory usage tied to the GPU, -you can look at the size column (not effective size) of just the GPU process' -GPU category. This will show all GPU allocations, whether or not they are owned -by another process. - -[cc-memory]: /cc/memory.md -[owner-size]: https://storage.googleapis.com/chromium-docs.appspot.com/a325c4426422e53394a322d31b652cfa34231189 -[non-owner-size]: https://storage.googleapis.com/chromium-docs.appspot.com/b8cf464636940d0925f29a102e99aabb9af40b13
diff --git a/components/tracing/docs/memory_infra_startup_tracing.md b/components/tracing/docs/memory_infra_startup_tracing.md index 138be30..738810f 100644 --- a/components/tracing/docs/memory_infra_startup_tracing.md +++ b/components/tracing/docs/memory_infra_startup_tracing.md
@@ -1,74 +1,2 @@ -# Startup Tracing with MemoryInfra +This document has moved to [//docs/memory-infra/memory_infra_startup_tracing.md](/docs/memory-infra/memory_infra_startup_tracing.md). -[MemoryInfra](memory_infra.md) supports startup tracing. - -## The Simple Way - -Start Chrome as follows: - - $ chrome --no-sandbox \ - --trace-startup=-*,disabled-by-default-memory-infra \ - --trace-startup-file=/tmp/trace.json \ - --trace-startup-duration=7 - -On Android, enable startup tracing and start Chrome as follows: - - $ build/android/adb_chrome_public_command_line \ - --trace-startup=-*,disabled-by-default-memory-infra \ - --trace-startup-file=/sdcard/Download/trace.json \ - --trace-startup-duration=7 - - $ build/android/adb_run_chrome_public - - $ adb pull /sdcard/Download/trace.json # After tracing. - -Note that startup tracing will be enabled upon every Chrome launch until you -delete the command-line flags: - - $ build/android/adb_chrome_public_command_line "" - -This will use the default configuration: one memory dump every 250 ms with a -detailed dump ever two seconds. - -## The Advanced Way - -If you need more control over the granularity of the memory dumps, you can -specify a custom trace config file as follows: - - $ cat > /tmp/trace.config - { - "startup_duration": 4, - "result_file": "/tmp/trace.json", - "trace_config": { - "included_categories": ["disabled-by-default-memory-infra"], - "excluded_categories": ["*"], - "memory_dump_config": { - "triggers": [ - { "mode": "light", "periodic_interval_ms": 50 }, - { "mode": "detailed", "periodic_interval_ms": 1000 } - ] - } - } - } - - $ chrome --no-sandbox --trace-config-file=/tmp/trace.config - -On Android, the config file has to be pushed to a fixed file location: - - $ adb root - $ adb push /tmp/trace.config /data/local/chrome-trace-config.json - - $ build/android/adb_run_chrome_public - - $ adb pull /sdcard/Download/trace.json # After tracing. - -Make sure that the "result_file" location is writable by the Chrome process on -Android (e.g. "/sdcard/Download/trace.json"). Note that startup tracing will be -enabled upon every Chrome launch until you delete the config file: - - $ adb shell rm /data/local/chrome-trace-config.json - -## Related Pages - - * [General information about startup tracing](https://sites.google.com/a/chromium.org/dev/developers/how-tos/trace-event-profiling-tool/recording-tracing-runs) - * [Memory tracing with MemoryInfra](memory_infra.md)
diff --git a/components/tracing/test/trace_event_perftest.cc b/components/tracing/test/trace_event_perftest.cc index 4c93e2f..f893cce 100644 --- a/components/tracing/test/trace_event_perftest.cc +++ b/components/tracing/test/trace_event_perftest.cc
@@ -3,20 +3,28 @@ // found in the LICENSE file. #include "base/bind.h" +#include "base/memory/ptr_util.h" #include "base/memory/ref_counted_memory.h" #include "base/run_loop.h" +#include "base/threading/thread.h" #include "base/trace_event/trace_event.h" +#include "base/trace_event/trace_event_argument.h" #include "perf_test_helpers.h" #include "testing/gtest/include/gtest/gtest.h" namespace tracing { namespace { +using base::Bind; +using base::Thread; +using base::Unretained; +using base::WaitableEvent; using base::trace_event::TraceConfig; using base::trace_event::TraceLog; using base::trace_event::TraceRecordMode; +using base::trace_event::TracedValue; -const int kNumRuns = 100; +const int kNumRuns = 10; class TraceEventPerfTest : public ::testing::Test { public: @@ -43,6 +51,34 @@ if (!has_more_events) quit_closure.Run(); } + + std::unique_ptr<TracedValue> MakeTracedValue(int counter) { + auto value = base::MakeUnique<TracedValue>(); + value->SetInteger("counter", counter); + value->BeginDictionary("test_dict"); + value->BeginArray("nodes"); + for (int i = 0; i < 10; i++) { + value->BeginDictionary(); + value->SetInteger("id", i); + value->SetBoolean("valid", true); + value->SetString("value", "foo"); + value->EndDictionary(); + } + value->EndArray(); + value->SetInteger("count", 10); + value->EndDictionary(); + return value; + } + + static void SubmitTraceEventsAndSignal(WaitableEvent* complete_event) { + for (int i = 0; i < 10000; i++) { + TRACE_EVENT0("test_category", "some call"); + } + complete_event->Signal(); + } + + private: + base::MessageLoop _message_loop; }; TEST_F(TraceEventPerfTest, Submit_10000_TRACE_EVENT0) { @@ -57,5 +93,77 @@ EndTraceAndFlush(); } +TEST_F(TraceEventPerfTest, Long_TRACE_EVENT0) { + BeginTrace(); + IterableStopwatch stopwatch("long_event"); + for (int lap = 0; lap < kNumRuns; lap++) { + TRACE_EVENT0("test_category", "Outer event"); + for (int i = 0; i < 10000; i++) { + TRACE_EVENT0("test_category", "TRACE_EVENT0 call"); + } + stopwatch.NextLap(); + } + EndTraceAndFlush(); +} + +TEST_F(TraceEventPerfTest, Create_10000_TracedValue) { + std::unique_ptr<TracedValue> value; + { + ScopedStopwatch value_sw("create_traced_values"); + for (int i = 0; i < 10000; i++) { + value = MakeTracedValue(i); + } + } +} + +TEST_F(TraceEventPerfTest, Submit_10000_TRACE_EVENT_with_TracedValue) { + BeginTrace(); + // Time reported by this timer includes TracedValue creation as well. + IterableStopwatch trace_sw("events_with_value"); + for (int lap = 0; lap < kNumRuns; lap++) { + for (int i = 0; i < 10000; i++) { + TRACE_EVENT_INSTANT1("test_category", "event_with_value", + TRACE_EVENT_SCOPE_THREAD, "value", MakeTracedValue(i)); + } + trace_sw.NextLap(); + } + EndTraceAndFlush(); +} + +TEST_F(TraceEventPerfTest, Submit_10000_TRACE_EVENT0_multithreaded) { + BeginTrace(); + const int kNumThreads = 4; + + std::vector<std::unique_ptr<Thread>> threads; + std::vector<std::unique_ptr<WaitableEvent>> complete_events; + + for (int i = 0; i < kNumThreads; i++) { + Thread* thread = new Thread(std::string("thread_%d") + std::to_string(i)); + WaitableEvent* complete_event = + new WaitableEvent(WaitableEvent::ResetPolicy::AUTOMATIC, + WaitableEvent::InitialState::NOT_SIGNALED); + threads.push_back(base::WrapUnique(thread)); + complete_events.push_back(base::WrapUnique(complete_event)); + thread->Start(); + } + + { + ScopedStopwatch stopwatch("events_over_multiple_threads"); + for (int i = 0; i < kNumThreads; i++) { + threads[i]->task_runner()->PostTask( + FROM_HERE, + base::Bind(&SubmitTraceEventsAndSignal, complete_events[i].get())); + } + for (int i = 0; i < kNumThreads; i++) { + complete_events[i]->Wait(); + } + } + + EndTraceAndFlush(); + for (int i = 0; i < kNumThreads; i++) { + threads[i]->Stop(); + } +} + } // namespace } // namespace tracing
diff --git a/components/update_client/BUILD.gn b/components/update_client/BUILD.gn index 4b8548f..7e0164f 100644 --- a/components/update_client/BUILD.gn +++ b/components/update_client/BUILD.gn
@@ -49,6 +49,9 @@ "update_query_params_delegate.h", "update_response.cc", "update_response.h", + "updater_state.cc", + "updater_state.h", + "updater_state_win.cc", "url_fetcher_downloader.cc", "url_fetcher_downloader.h", "utils.cc", @@ -126,6 +129,7 @@ "update_client_unittest.cc", "update_query_params_unittest.cc", "update_response_unittest.cc", + "updater_state_unittest.cc", "utils_unittest.cc", ]
diff --git a/components/update_client/configurator.h b/components/update_client/configurator.h index 384b23de6..c021710 100644 --- a/components/update_client/configurator.h +++ b/components/update_client/configurator.h
@@ -132,7 +132,8 @@ virtual PrefService* GetPrefService() const = 0; // Returns true if the Chrome is installed for the current user only, or false - // if Chrome is installed for all users on the machine. + // if Chrome is installed for all users on the machine. This function must be + // called only from a blocking pool thread, as it may access the file system. virtual bool IsPerUserInstall() const = 0; protected:
diff --git a/components/update_client/ping_manager.cc b/components/update_client/ping_manager.cc index 47ae77c3..838e98b 100644 --- a/components/update_client/ping_manager.cc +++ b/components/update_client/ping_manager.cc
@@ -24,6 +24,7 @@ #include "components/update_client/configurator.h" #include "components/update_client/crx_update_item.h" #include "components/update_client/request_sender.h" +#include "components/update_client/updater_state.h" #include "components/update_client/utils.h" #include "net/url_request/url_fetcher.h" #include "url/gurl.h" @@ -162,10 +163,11 @@ ping_event.c_str(), // ping event BuildDownloadCompleteEventElements(item).c_str())); // download events + // The ping request does not include any updater state. return BuildProtocolRequest( config.GetProdId(), config.GetBrowserVersion().GetString(), config.GetChannel(), config.GetLang(), config.GetOSLongName(), - config.GetDownloadPreference(), app_element, ""); + config.GetDownloadPreference(), app_element, "", nullptr); } // Sends a fire and forget ping. The instances of this class have no
diff --git a/components/update_client/update_checker.cc b/components/update_client/update_checker.cc index a421fcb..1459d561 100644 --- a/components/update_client/update_checker.cc +++ b/components/update_client/update_checker.cc
@@ -23,6 +23,7 @@ #include "components/update_client/persisted_data.h" #include "components/update_client/request_sender.h" #include "components/update_client/update_client.h" +#include "components/update_client/updater_state.h" #include "components/update_client/utils.h" #include "url/gurl.h" @@ -69,11 +70,13 @@ // <package fp="abcd"/> // </packages> // </app> -std::string BuildUpdateCheckRequest(const Configurator& config, - const IdToCrxUpdateItemMap& items, - PersistedData* metadata, - const std::string& additional_attributes, - bool enabled_component_updates) { +std::string BuildUpdateCheckRequest( + const Configurator& config, + const IdToCrxUpdateItemMap& items, + PersistedData* metadata, + const std::string& additional_attributes, + bool enabled_component_updates, + const std::unique_ptr<UpdaterState::Attributes>& updater_state_attributes) { const std::string brand(SanitizeBrand(config.GetBrand())); std::string app_elements; for (const auto& item_pair : items) { @@ -124,10 +127,12 @@ VLOG(1) << "Appending to update request: " << app; } + // Include the updater state in the update check request. return BuildProtocolRequest( config.GetProdId(), config.GetBrowserVersion().GetString(), config.GetChannel(), config.GetLang(), config.GetOSLongName(), - config.GetDownloadPreference(), app_elements, additional_attributes); + config.GetDownloadPreference(), app_elements, additional_attributes, + updater_state_attributes); } class UpdateCheckerImpl : public UpdateChecker { @@ -144,6 +149,11 @@ const UpdateCheckCallback& update_check_callback) override; private: + void ReadUpdaterStateAttributes(); + void CheckForUpdatesHelper(const IdToCrxUpdateItemMap& items_to_check, + const std::string& additional_attributes, + bool enabled_component_updates); + void OnRequestSenderComplete( std::unique_ptr<std::vector<std::string>> ids_checked, int error, @@ -154,6 +164,7 @@ const scoped_refptr<Configurator> config_; PersistedData* metadata_; UpdateCheckCallback update_check_callback_; + std::unique_ptr<UpdaterState::Attributes> updater_state_attributes_; std::unique_ptr<RequestSender> request_sender_; DISALLOW_COPY_AND_ASSIGN(UpdateCheckerImpl); @@ -174,13 +185,28 @@ const UpdateCheckCallback& update_check_callback) { DCHECK(thread_checker_.CalledOnValidThread()); - if (request_sender_.get()) { - NOTREACHED(); - return false; // Another update check is in progress. - } - update_check_callback_ = update_check_callback; + return config_->GetSequencedTaskRunner()->PostTaskAndReply( + FROM_HERE, base::Bind(&UpdateCheckerImpl::ReadUpdaterStateAttributes, + base::Unretained(this)), + base::Bind(&UpdateCheckerImpl::CheckForUpdatesHelper, + base::Unretained(this), base::ConstRef(items_to_check), + additional_attributes, enabled_component_updates)); +} + +// This function runs on the blocking pool task runner. +void UpdateCheckerImpl::ReadUpdaterStateAttributes() { + const bool is_machine_install = !config_->IsPerUserInstall(); + updater_state_attributes_ = UpdaterState::GetState(is_machine_install); +} + +void UpdateCheckerImpl::CheckForUpdatesHelper( + const IdToCrxUpdateItemMap& items_to_check, + const std::string& additional_attributes, + bool enabled_component_updates) { + DCHECK(thread_checker_.CalledOnValidThread()); + auto urls(config_->UpdateUrl()); if (IsEncryptionRequired(items_to_check)) RemoveUnsecureUrls(&urls); @@ -193,10 +219,10 @@ request_sender_->Send( config_->EnabledCupSigning(), BuildUpdateCheckRequest(*config_, items_to_check, metadata_, - additional_attributes, enabled_component_updates), + additional_attributes, enabled_component_updates, + updater_state_attributes_), urls, base::Bind(&UpdateCheckerImpl::OnRequestSenderComplete, base::Unretained(this), base::Passed(&ids_checked))); - return true; } void UpdateCheckerImpl::OnRequestSenderComplete(
diff --git a/components/update_client/update_checker_unittest.cc b/components/update_client/update_checker_unittest.cc index 498e3f81..681f1fa 100644 --- a/components/update_client/update_checker_unittest.cc +++ b/components/update_client/update_checker_unittest.cc
@@ -192,34 +192,41 @@ << post_interceptor_->GetRequestsAsString(); // Sanity check the request. + const auto request = post_interceptor_->GetRequests()[0]; EXPECT_NE(string::npos, post_interceptor_->GetRequests()[0].find( "request protocol=\"3.0\" extra=\"params\"")); // The request must not contain any "dlpref" in the default case. - EXPECT_EQ(string::npos, - post_interceptor_->GetRequests()[0].find(" dlpref=\"")); + EXPECT_EQ(string::npos, request.find(" dlpref=\"")); EXPECT_NE( string::npos, - post_interceptor_->GetRequests()[0].find( + request.find( std::string("<app appid=\"") + kUpdateItemId + "\" version=\"0.9\" " "brand=\"TEST\" ap=\"some_ap\"><updatecheck/><ping rd=\"-2\" ")); EXPECT_NE(string::npos, - post_interceptor_->GetRequests()[0].find( - "<packages><package fp=\"fp1\"/></packages></app>")); + request.find("<packages><package fp=\"fp1\"/></packages></app>")); - EXPECT_NE(string::npos, - post_interceptor_->GetRequests()[0].find("<hw physmemory=")); + EXPECT_NE(string::npos, request.find("<hw physmemory=")); // Tests that the progid is injected correctly from the configurator. - EXPECT_NE(string::npos, - post_interceptor_->GetRequests()[0].find( - " version=\"fake_prodid-30.0\" prodversion=\"30.0\" ")); + EXPECT_NE( + string::npos, + request.find(" version=\"fake_prodid-30.0\" prodversion=\"30.0\" ")); // Sanity check the arguments of the callback after parsing. EXPECT_EQ(0, error_); EXPECT_EQ(1ul, results_.list.size()); EXPECT_STREQ(kUpdateItemId, results_.list[0].extension_id.c_str()); EXPECT_STREQ("1.0", results_.list[0].manifest.version.c_str()); + +#if (OS_WIN) + EXPECT_NE(string::npos, request.find(" domainjoined=")); +#if defined(GOOGLE_CHROME_BUILD) + // Check the Omaha updater state data in the request. + EXPECT_NE(string::npos, request.find("<updater ")); + EXPECT_NE(string::npos, request.find(" name=\"Omaha\" ")); +#endif // GOOGLE_CHROME_BUILD +#endif // OS_WINDOWS } // Tests that an invalid "ap" is not serialized.
diff --git a/components/update_client/updater_state.cc b/components/update_client/updater_state.cc new file mode 100644 index 0000000..0e588bf --- /dev/null +++ b/components/update_client/updater_state.cc
@@ -0,0 +1,92 @@ + +// Copyright (c) 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/update_client/updater_state.h" + +#include <utility> + +#include "base/memory/ptr_util.h" +#include "base/strings/string16.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/utf_string_conversions.h" + +namespace update_client { + +const char UpdaterState::kDomainJoined[] = "domainjoined"; + +UpdaterState::UpdaterState(bool is_machine) : is_machine_(is_machine) {} + +UpdaterState::~UpdaterState() {} + +std::unique_ptr<UpdaterState::Attributes> UpdaterState::GetState( + bool is_machine) { +#if defined(OS_WIN) + UpdaterState updater_state(is_machine); + updater_state.ReadState(); + return base::MakeUnique<Attributes>(updater_state.BuildAttributes()); +#else + return nullptr; +#endif // OS_WIN +} + +#if defined(OS_WIN) +void UpdaterState::ReadState() { + is_joined_to_domain_ = IsJoinedToDomain(); + +#if defined(GOOGLE_CHROME_BUILD) + updater_name_ = GetUpdaterName(); + updater_version_ = GetUpdaterVersion(is_machine_); + last_autoupdate_started_ = GetUpdaterLastStartedAU(is_machine_); + last_checked_ = GetUpdaterLastChecked(is_machine_); + is_autoupdate_check_enabled_ = IsAutoupdateCheckEnabled(); + update_policy_ = GetUpdatePolicy(); +#endif // GOOGLE_CHROME_BUILD +} +#endif // OS_WIN + +UpdaterState::Attributes UpdaterState::BuildAttributes() const { + Attributes attributes; + + attributes[kDomainJoined] = is_joined_to_domain_ ? "1" : "0"; + + attributes["name"] = updater_name_; + + if (updater_version_.IsValid()) + attributes["version"] = updater_version_.GetString(); + + const base::Time now = base::Time::NowFromSystemTime(); + if (!last_autoupdate_started_.is_null()) + attributes["laststarted"] = + NormalizeTimeDelta(now - last_autoupdate_started_); + if (!last_checked_.is_null()) + attributes["lastchecked"] = NormalizeTimeDelta(now - last_checked_); + + attributes["autoupdatecheckenabled"] = + is_autoupdate_check_enabled_ ? "1" : "0"; + + DCHECK((update_policy_ >= 0 && update_policy_ <= 3) || update_policy_ == -1); + attributes["updatepolicy"] = base::IntToString(update_policy_); + + return attributes; +} + +std::string UpdaterState::NormalizeTimeDelta(const base::TimeDelta& delta) { + const base::TimeDelta two_weeks = base::TimeDelta::FromDays(14); + const base::TimeDelta two_months = base::TimeDelta::FromDays(60); + + std::string val; // Contains the value to return in hours. + if (delta <= two_weeks) { + val = "0"; + } else if (two_weeks < delta && delta <= two_months) { + val = "408"; // 2 weeks in hours. + } else { + val = "1344"; // 2*28 days in hours. + } + + DCHECK(!val.empty()); + return val; +} + +} // namespace update_client
diff --git a/components/update_client/updater_state.h b/components/update_client/updater_state.h new file mode 100644 index 0000000..cd537ec --- /dev/null +++ b/components/update_client/updater_state.h
@@ -0,0 +1,68 @@ +// Copyright (c) 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_UPDATE_CLIENT_UPDATER_STATE_H_ +#define COMPONENTS_UPDATE_CLIENT_UPDATER_STATE_H_ + +#include <map> +#include <memory> +#include <string> + +#include "base/gtest_prod_util.h" +#include "base/time/time.h" +#include "base/version.h" + +namespace update_client { + +class UpdaterState { + public: + using Attributes = std::map<std::string, std::string>; + + static const char kDomainJoined[]; + + // Returns a map of items representing the state of an updater. These items + // can be serialized as XML attributes in the request building. + // |is_machine| is true for per-system installs of Chrome. Returns nullptr on + // the platforms and builds where this feature is not supported. + static std::unique_ptr<Attributes> GetState(bool is_machine); + + ~UpdaterState(); + + private: + FRIEND_TEST_ALL_PREFIXES(UpdaterStateTest, Serialize); + + explicit UpdaterState(bool is_machine); + + // This function is best-effort. It updates the class members with + // the relevant values that could be retrieved. + void ReadState(); + + // Builds the map of state attributes by serializing this object state. + Attributes BuildAttributes() const; + + static std::string GetUpdaterName(); + static base::Version GetUpdaterVersion(bool is_machine); + static bool IsAutoupdateCheckEnabled(); + static bool IsJoinedToDomain(); + static base::Time GetUpdaterLastStartedAU(bool is_machine); + static base::Time GetUpdaterLastChecked(bool is_machine); + static base::Time GetUpdaterTimeValue(bool is_machine, + const wchar_t* value_name); + static int GetUpdatePolicy(); + + static std::string NormalizeTimeDelta(const base::TimeDelta& delta); + + bool is_machine_ = false; + std::string updater_name_; + base::Version updater_version_; + base::Time last_autoupdate_started_; + base::Time last_checked_; + bool is_joined_to_domain_ = false; + bool is_autoupdate_check_enabled_ = false; + int update_policy_ = 0; +}; + +} // namespace update_client + +#endif // COMPONENTS_UPDATE_CLIENT_UPDATER_STATE_H_
diff --git a/components/update_client/updater_state_unittest.cc b/components/update_client/updater_state_unittest.cc new file mode 100644 index 0000000..74828596c --- /dev/null +++ b/components/update_client/updater_state_unittest.cc
@@ -0,0 +1,108 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/macros.h" +#include "base/time/time.h" +#include "base/version.h" +#include "components/update_client/updater_state.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace update_client { + +class UpdaterStateTest : public testing::Test { + public: + UpdaterStateTest() {} + ~UpdaterStateTest() override {} + + private: + DISALLOW_COPY_AND_ASSIGN(UpdaterStateTest); +}; + +TEST_F(UpdaterStateTest, Serialize) { + UpdaterState updater_state(false); + + updater_state.updater_name_ = "the updater"; + updater_state.updater_version_ = base::Version("1.0"); + updater_state.last_autoupdate_started_ = base::Time::NowFromSystemTime(); + updater_state.last_checked_ = base::Time::NowFromSystemTime(); + updater_state.is_joined_to_domain_ = false; + updater_state.is_autoupdate_check_enabled_ = true; + updater_state.update_policy_ = 1; + + auto attributes = updater_state.BuildAttributes(); + + // Sanity check all members. + EXPECT_STREQ("the updater", attributes.at("name").c_str()); + EXPECT_STREQ("1.0", attributes.at("version").c_str()); + EXPECT_STREQ("0", attributes.at("laststarted").c_str()); + EXPECT_STREQ("0", attributes.at("lastchecked").c_str()); + EXPECT_STREQ("0", attributes.at("domainjoined").c_str()); + EXPECT_STREQ("1", attributes.at("autoupdatecheckenabled").c_str()); + EXPECT_STREQ("1", attributes.at("updatepolicy").c_str()); + + // Tests some of the remaining values. + updater_state = UpdaterState(false); + +#if defined(GOOGLE_CHROME_BUILD) + // The name of the Windows updater for Chrome. + EXPECT_STREQ("Omaha", attributes.at("name").c_str()); +#endif // GOOGLE_CHROME_BUILD + + // Don't serialize an invalid version if it could not be read. + updater_state.updater_version_ = base::Version(); + attributes = updater_state.BuildAttributes(); + EXPECT_EQ(0u, attributes.count("version")); + + updater_state.updater_version_ = base::Version("0.0.0.0"); + attributes = updater_state.BuildAttributes(); + EXPECT_STREQ("0.0.0.0", attributes.at("version").c_str()); + + updater_state.last_autoupdate_started_ = + base::Time::NowFromSystemTime() - base::TimeDelta::FromDays(15); + attributes = updater_state.BuildAttributes(); + EXPECT_STREQ("408", attributes.at("laststarted").c_str()); + + updater_state.last_autoupdate_started_ = + base::Time::NowFromSystemTime() - base::TimeDelta::FromDays(90); + attributes = updater_state.BuildAttributes(); + EXPECT_STREQ("1344", attributes.at("laststarted").c_str()); + + // Don't serialize the time if it could not be read. + updater_state.last_autoupdate_started_ = base::Time(); + attributes = updater_state.BuildAttributes(); + EXPECT_EQ(0u, attributes.count("laststarted")); + + updater_state.last_checked_ = + base::Time::NowFromSystemTime() - base::TimeDelta::FromDays(15); + attributes = updater_state.BuildAttributes(); + EXPECT_STREQ("408", attributes.at("lastchecked").c_str()); + + updater_state.last_checked_ = + base::Time::NowFromSystemTime() - base::TimeDelta::FromDays(90); + attributes = updater_state.BuildAttributes(); + EXPECT_STREQ("1344", attributes.at("lastchecked").c_str()); + + // Don't serialize the time if it could not be read (the value is invalid). + updater_state.last_checked_ = base::Time(); + attributes = updater_state.BuildAttributes(); + EXPECT_EQ(0u, attributes.count("lastchecked")); + + updater_state.is_joined_to_domain_ = true; + attributes = updater_state.BuildAttributes(); + EXPECT_STREQ("1", attributes.at("domainjoined").c_str()); + + updater_state.is_autoupdate_check_enabled_ = false; + attributes = updater_state.BuildAttributes(); + EXPECT_STREQ("0", attributes.at("autoupdatecheckenabled").c_str()); + + updater_state.update_policy_ = 0; + attributes = updater_state.BuildAttributes(); + EXPECT_STREQ("0", attributes.at("updatepolicy").c_str()); + + updater_state.update_policy_ = -1; + attributes = updater_state.BuildAttributes(); + EXPECT_STREQ("-1", attributes.at("updatepolicy").c_str()); +} + +} // namespace update_client
diff --git a/components/update_client/updater_state_win.cc b/components/update_client/updater_state_win.cc new file mode 100644 index 0000000..396395a --- /dev/null +++ b/components/update_client/updater_state_win.cc
@@ -0,0 +1,140 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/update_client/updater_state.h" + +#include <string> +#include <utility> + +#include "base/memory/ptr_util.h" +#include "base/strings/string16.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/utf_string_conversions.h" + +#include "base/win/registry.h" +#include "base/win/win_util.h" + +// TODO(sorin): implement this in terms of +// chrome/installer/util/google_update_settings (crbug.com/615187). + +namespace update_client { + +namespace { + +// Google Update group policy settings. +const wchar_t kGoogleUpdatePoliciesKey[] = + L"SOFTWARE\\Policies\\Google\\Update"; +const wchar_t kCheckPeriodOverrideMinutes[] = L"AutoUpdateCheckPeriodMinutes"; +const wchar_t kUpdatePolicyValue[] = L"UpdateDefault"; +const wchar_t kChromeUpdatePolicyOverride[] = + L"Update{8A69D345-D564-463C-AFF1-A69D9E530F96}"; + +// Don't allow update periods longer than six weeks (Chrome release cadence). +const int kCheckPeriodOverrideMinutesMax = 60 * 24 * 7 * 6; + +// Google Update registry settings. +const wchar_t kRegPathGoogleUpdate[] = L"Software\\Google\\Update"; +const wchar_t kRegPathClientsGoogleUpdate[] = + L"Software\\Google\\Update\\Clients\\" + L"{430FD4D0-B729-4F61-AA34-91526481799D}"; +const wchar_t kRegValueGoogleUpdatePv[] = L"pv"; +const wchar_t kRegValueLastStartedAU[] = L"LastStartedAU"; +const wchar_t kRegValueLastChecked[] = L"LastChecked"; + +} // namespace + +std::string UpdaterState::GetUpdaterName() { + return std::string("Omaha"); +} + +base::Version UpdaterState::GetUpdaterVersion(bool is_machine) { + const HKEY root_key = is_machine ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; + base::string16 version; + base::win::RegKey key; + + if (key.Open(root_key, kRegPathClientsGoogleUpdate, + KEY_QUERY_VALUE | KEY_WOW64_32KEY) == ERROR_SUCCESS && + key.ReadValue(kRegValueGoogleUpdatePv, &version) == ERROR_SUCCESS) { + return base::Version(base::UTF16ToUTF8(version)); + } + + return base::Version(); +} + +base::Time UpdaterState::GetUpdaterLastStartedAU(bool is_machine) { + return GetUpdaterTimeValue(is_machine, kRegValueLastStartedAU); +} + +base::Time UpdaterState::GetUpdaterLastChecked(bool is_machine) { + return GetUpdaterTimeValue(is_machine, kRegValueLastChecked); +} + +base::Time UpdaterState::GetUpdaterTimeValue(bool is_machine, + const wchar_t* value_name) { + const HKEY root_key = is_machine ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; + base::win::RegKey update_key; + + if (update_key.Open(root_key, kRegPathGoogleUpdate, + KEY_QUERY_VALUE | KEY_WOW64_32KEY) == ERROR_SUCCESS) { + DWORD value(0); + if (update_key.ReadValueDW(value_name, &value) == ERROR_SUCCESS) { + return base::Time::FromTimeT(value); + } + } + + return base::Time(); +} + +bool UpdaterState::IsAutoupdateCheckEnabled() { + // Check the auto-update check period override. If it is 0 or exceeds the + // maximum timeout, then for all intents and purposes auto updates are + // disabled. + base::win::RegKey policy_key; + DWORD value = 0; + if (policy_key.Open(HKEY_LOCAL_MACHINE, kGoogleUpdatePoliciesKey, + KEY_QUERY_VALUE) == ERROR_SUCCESS && + policy_key.ReadValueDW(kCheckPeriodOverrideMinutes, &value) == + ERROR_SUCCESS && + (value == 0 || value > kCheckPeriodOverrideMinutesMax)) { + return false; + } + + return true; +} + +// Returns -1 if the policy is not found or the value was invalid. Otherwise, +// returns a value in the [0, 3] range, representing the value of the +// Chrome update group policy. +int UpdaterState::GetUpdatePolicy() { + const int kMaxUpdatePolicyValue = 3; + + base::win::RegKey policy_key; + + if (policy_key.Open(HKEY_LOCAL_MACHINE, kGoogleUpdatePoliciesKey, + KEY_QUERY_VALUE) != ERROR_SUCCESS) { + return -1; + } + + DWORD value = 0; + // First try to read the Chrome-specific override. + if (policy_key.ReadValueDW(kChromeUpdatePolicyOverride, &value) == + ERROR_SUCCESS && + value <= kMaxUpdatePolicyValue) { + return value; + } + + // Try to read default override. + if (policy_key.ReadValueDW(kUpdatePolicyValue, &value) == ERROR_SUCCESS && + value <= kMaxUpdatePolicyValue) { + return value; + } + + return -1; +} + +bool UpdaterState::IsJoinedToDomain() { + return base::win::IsEnrolledToDomain(); +} + +} // namespace update_client
diff --git a/components/update_client/utils.cc b/components/update_client/utils.cc index 967b7ba..ea5a39d3 100644 --- a/components/update_client/utils.cc +++ b/components/update_client/utils.cc
@@ -10,6 +10,7 @@ #include <algorithm> #include <cmath> #include <cstring> +#include <map> #include <vector> #include "base/callback.h" @@ -30,6 +31,7 @@ #include "components/update_client/update_client.h" #include "components/update_client/update_client_errors.h" #include "components/update_client/update_query_params.h" +#include "components/update_client/updater_state.h" #include "crypto/secure_hash.h" #include "crypto/sha2.h" #include "net/base/load_flags.h" @@ -90,14 +92,16 @@ } // namespace -std::string BuildProtocolRequest(const std::string& prod_id, - const std::string& browser_version, - const std::string& channel, - const std::string& lang, - const std::string& os_long_name, - const std::string& download_preference, - const std::string& request_body, - const std::string& additional_attributes) { +std::string BuildProtocolRequest( + const std::string& prod_id, + const std::string& browser_version, + const std::string& channel, + const std::string& lang, + const std::string& os_long_name, + const std::string& download_preference, + const std::string& request_body, + const std::string& additional_attributes, + const std::unique_ptr<UpdaterState::Attributes>& updater_state_attributes) { std::string request( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" "<request protocol=\"3.0\" "); @@ -115,7 +119,7 @@ browser_version.c_str(), browser_version.c_str(), // "prodversion" base::GenerateGUID().c_str(), // "requestid" - lang.c_str(), // "lang", + lang.c_str(), // "lang" channel.c_str(), // "updaterchannel" channel.c_str(), // "prodchannel" UpdateQueryParams::GetOS(), // "os" @@ -130,6 +134,13 @@ if (!download_preference.empty()) base::StringAppendF(&request, " dlpref=\"%s\"", download_preference.c_str()); + if (updater_state_attributes && + updater_state_attributes->count(UpdaterState::kDomainJoined)) { + base::StringAppendF( + &request, " %s=\"%s\"", // domainjoined + UpdaterState::kDomainJoined, + (*updater_state_attributes)[UpdaterState::kDomainJoined].c_str()); + } base::StringAppendF(&request, ">"); // HW platform information. @@ -139,7 +150,6 @@ // OS version and platform information. const std::string os_version = GetOSVersion(); const std::string os_sp = GetServicePack(); - base::StringAppendF( &request, "<os platform=\"%s\" arch=\"%s\"", os_long_name.c_str(), // "platform" @@ -150,6 +160,20 @@ base::StringAppendF(&request, " sp=\"%s\"", os_sp.c_str()); base::StringAppendF(&request, "/>"); +#if defined(GOOGLE_CHROME_BUILD) + // Updater state. + if (updater_state_attributes) { + base::StringAppendF(&request, "<updater"); + for (const auto& attr : *updater_state_attributes) { + if (attr.first != UpdaterState::kDomainJoined) { + base::StringAppendF(&request, " %s=\"%s\"", attr.first.c_str(), + attr.second.c_str()); + } + } + base::StringAppendF(&request, "/>"); + } +#endif // GOOGLE_CHROME_BUILD + // The actual payload of the request. base::StringAppendF(&request, "%s</request>", request_body.c_str());
diff --git a/components/update_client/utils.h b/components/update_client/utils.h index 9f761c42..f82fb92 100644 --- a/components/update_client/utils.h +++ b/components/update_client/utils.h
@@ -12,6 +12,7 @@ #include "base/callback_forward.h" #include "components/update_client/update_client.h" +#include "components/update_client/updater_state.h" class GURL; @@ -58,15 +59,19 @@ // affects the list of download URLs returned in the update response. // If specified, |additional_attributes| are appended as attributes of the // request element. The additional attributes have to be well-formed for -// insertion in the request element. -std::string BuildProtocolRequest(const std::string& prod_id, - const std::string& browser_version, - const std::string& channel, - const std::string& lang, - const std::string& os_long_name, - const std::string& download_preference, - const std::string& request_body, - const std::string& additional_attributes); +// insertion in the request element. |updater_state_attributes| is an optional +// parameter specifying that an <updater> element is serialized as part of +// the request. +std::string BuildProtocolRequest( + const std::string& prod_id, + const std::string& browser_version, + const std::string& channel, + const std::string& lang, + const std::string& os_long_name, + const std::string& download_preference, + const std::string& request_body, + const std::string& additional_attributes, + const std::unique_ptr<UpdaterState::Attributes>& updater_state_attributes); // Sends a protocol request to the the service endpoint specified by |url|. // The body of the request is provided by |protocol_request| and it is
diff --git a/components/update_client/utils_unittest.cc b/components/update_client/utils_unittest.cc index 9370a879..8cadf138 100644 --- a/components/update_client/utils_unittest.cc +++ b/components/update_client/utils_unittest.cc
@@ -3,7 +3,9 @@ // found in the LICENSE file. #include "base/files/file_path.h" +#include "base/memory/ptr_util.h" #include "base/path_service.h" +#include "components/update_client/updater_state.h" #include "components/update_client/utils.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" @@ -25,23 +27,25 @@ TEST(UpdateClientUtils, BuildProtocolRequest_ProdIdVersion) { // Verifies that |prod_id| and |version| are serialized. - const string request = - BuildProtocolRequest("some_prod_id", "1.0", "", "", "", "", "", ""); + const string request = BuildProtocolRequest("some_prod_id", "1.0", "", "", "", + "", "", "", nullptr); EXPECT_NE(string::npos, request.find(" version=\"some_prod_id-1.0\" ")); } TEST(UpdateClientUtils, BuildProtocolRequest_DownloadPreference) { // Verifies that an empty |download_preference| is not serialized. const string request_no_dlpref = - BuildProtocolRequest("", "", "", "", "", "", "", ""); + BuildProtocolRequest("", "", "", "", "", "", "", "", nullptr); EXPECT_EQ(string::npos, request_no_dlpref.find(" dlpref=")); // Verifies that |download_preference| is serialized. const string request_with_dlpref = - BuildProtocolRequest("", "", "", "", "", "some pref", "", ""); + BuildProtocolRequest("", "", "", "", "", "some pref", "", "", nullptr); EXPECT_NE(string::npos, request_with_dlpref.find(" dlpref=\"some pref\"")); } +TEST(UpdateClientUtils, BuildProtocolRequest_UpdaterState) {} + TEST(UpdateClientUtils, VerifyFileHash256) { EXPECT_TRUE(VerifyFileHash256( MakeTestFilePath("jebgalgnebhfojomionfpkfelancnnkf.crx"), @@ -166,4 +170,35 @@ EXPECT_EQ(0u, urls.size()); } +TEST(UpdateClientUtils, BuildProtocolRequestUpdaterStateAttributes) { + // When no updater state is provided, then check that the elements and + // attributes related to the updater state are not serialized. + std::string request = + BuildProtocolRequest("", "", "", "", "", "", "", "", nullptr).c_str(); + EXPECT_EQ(std::string::npos, request.find(" domainjoined")); + EXPECT_EQ(std::string::npos, request.find("<updater")); + + UpdaterState::Attributes attributes; + attributes["domainjoined"] = "1"; + attributes["name"] = "Omaha"; + attributes["version"] = "1.2.3.4"; + attributes["laststarted"] = "1"; + attributes["lastchecked"] = "2"; + attributes["autoupdatecheckenabled"] = "0"; + attributes["updatepolicy"] = "-1"; + request = BuildProtocolRequest( + "", "", "", "", "", "", "", "", + base::MakeUnique<UpdaterState::Attributes>(attributes)); + EXPECT_NE(std::string::npos, request.find(" domainjoined=\"1\"")); + const std::string updater_element = + "<updater autoupdatecheckenabled=\"0\" " + "lastchecked=\"2\" laststarted=\"1\" name=\"Omaha\" " + "updatepolicy=\"-1\" version=\"1.2.3.4\"/>"; +#if defined(GOOGLE_CHROME_BUILD) + EXPECT_NE(std::string::npos, request.find(updater_element)); +#else + EXPECT_EQ(std::string::npos, request.find(updater_element)); +#endif // GOOGLE_CHROME_BUILD +} + } // namespace update_client
diff --git a/components/url_formatter/url_formatter.cc b/components/url_formatter/url_formatter.cc index 59b072033..43b5341 100644 --- a/components/url_formatter/url_formatter.cc +++ b/components/url_formatter/url_formatter.cc
@@ -778,7 +778,7 @@ // Omit the path only for standard, non-file URLs with nothing but "/" after // the hostname. return url.IsStandard() && !url.SchemeIsFile() && !url.SchemeIsFileSystem() && - !url.has_query() && !url.has_ref() && url.path() == "/"; + !url.has_query() && !url.has_ref() && url.path_piece() == "/"; } void AppendFormattedHost(const GURL& url, base::string16* output) {
diff --git a/content/DEPS b/content/DEPS index f8681796..e891ebc7 100644 --- a/content/DEPS +++ b/content/DEPS
@@ -78,8 +78,7 @@ "+third_party/webrtc", "+third_party/webrtc_overrides", "+third_party/zlib/google", - "+third_party/WebKit/public/platform", - "+third_party/WebKit/public/web", + "+third_party/WebKit/public", "+ui/accelerated_widget_mac", "+ui/accessibility",
diff --git a/content/browser/DEPS b/content/browser/DEPS index dd5d7b9e..67c21058 100644 --- a/content/browser/DEPS +++ b/content/browser/DEPS
@@ -63,6 +63,7 @@ "+third_party/WebKit/public/platform/WebFocusType.h", "+third_party/WebKit/public/platform/WebGamepad.h", "+third_party/WebKit/public/platform/WebGamepads.h", + "+third_party/WebKit/public/platform/WebGestureEvent.h", "+third_party/WebKit/public/platform/WebInputEvent.h", "+third_party/WebKit/public/platform/WebInsecureRequestPolicy.h", "+third_party/WebKit/public/platform/WebNavigationHintType.h", @@ -106,7 +107,6 @@ "+third_party/WebKit/public/web/WebDragStatus.h", "+third_party/WebKit/public/web/WebFindOptions.h", "+third_party/WebKit/public/web/WebFrameSerializerCacheControlPolicy.h", - "+third_party/WebKit/public/web/WebInputEvent.h", "+third_party/WebKit/public/web/WebMediaPlayerAction.h", "+third_party/WebKit/public/web/WebPluginAction.h", "+third_party/WebKit/public/web/WebPopupType.h",
diff --git a/content/browser/android/content_view_core_impl.cc b/content/browser/android/content_view_core_impl.cc index e55405f9..c124bc2 100644 --- a/content/browser/android/content_view_core_impl.cc +++ b/content/browser/android/content_view_core_impl.cc
@@ -52,7 +52,7 @@ #include "device/geolocation/geolocation_service_context.h" #include "jni/ContentViewCore_jni.h" #include "jni/DragEvent_jni.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/android/view_android.h" #include "ui/android/window_android.h" #include "ui/base/clipboard/clipboard.h"
diff --git a/content/browser/android/content_view_core_impl.h b/content/browser/android/content_view_core_impl.h index 454a698..79bb545 100644 --- a/content/browser/android/content_view_core_impl.h +++ b/content/browser/android/content_view_core_impl.h
@@ -22,7 +22,7 @@ #include "content/browser/web_contents/web_contents_impl.h" #include "content/public/browser/android/content_view_core.h" #include "content/public/browser/web_contents_observer.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/android/overscroll_refresh.h" #include "ui/android/view_android.h" #include "ui/gfx/geometry/rect.h"
diff --git a/content/browser/android/overscroll_controller_android.cc b/content/browser/android/overscroll_controller_android.cc index b60f302c..6e92d182 100644 --- a/content/browser/android/overscroll_controller_android.cc +++ b/content/browser/android/overscroll_controller_android.cc
@@ -13,7 +13,7 @@ #include "content/public/browser/navigation_controller.h" #include "content/public/browser/user_metrics.h" #include "content/public/common/content_switches.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/android/edge_effect.h" #include "ui/android/edge_effect_l.h" #include "ui/android/resources/resource_manager.h"
diff --git a/content/browser/appcache/appcache_quota_client.cc b/content/browser/appcache/appcache_quota_client.cc index cff864026..6edfd88 100644 --- a/content/browser/appcache/appcache_quota_client.cc +++ b/content/browser/appcache/appcache_quota_client.cc
@@ -184,7 +184,7 @@ std::set<GURL> origins; for (AppCacheStorage::UsageMap::const_iterator iter = map->begin(); iter != map->end(); ++iter) { - if (opt_host.empty() || iter->first.host() == opt_host) + if (opt_host.empty() || iter->first.host_piece() == opt_host) origins.insert(iter->first); } callback.Run(origins);
diff --git a/content/browser/bluetooth/bluetooth_device_chooser_controller.cc b/content/browser/bluetooth/bluetooth_device_chooser_controller.cc index 809f3a15..082d1e8 100644 --- a/content/browser/bluetooth/bluetooth_device_chooser_controller.cc +++ b/content/browser/bluetooth/bluetooth_device_chooser_controller.cc
@@ -25,6 +25,7 @@ #include "device/bluetooth/bluetooth_discovery_session.h" using device::BluetoothUUID; +using UUIDSet = device::BluetoothDevice::UUIDSet; namespace { @@ -106,25 +107,25 @@ IsEmptyOrInvalidFilter); } -bool MatchesFilter(const device::BluetoothDevice& device, +bool MatchesFilter(const std::string* device_name, + const UUIDSet& device_uuids, const blink::mojom::WebBluetoothScanFilterPtr& filter) { if (!filter->name.is_null()) { - if (!device.GetName()) + if (device_name == nullptr) return false; - if (filter->name != device.GetName().value()) + if (filter->name != *device_name) return false; } if (!filter->name_prefix.is_null() && filter->name_prefix.size()) { - if (!device.GetName()) + if (device_name == nullptr) return false; - if (!base::StartsWith(device.GetName().value(), filter->name_prefix.get(), + if (!base::StartsWith(*device_name, filter->name_prefix.get(), base::CompareCase::SENSITIVE)) return false; } if (!filter->services.is_null()) { - const device::BluetoothDevice::UUIDSet& device_uuids = device.GetUUIDs(); for (const base::Optional<BluetoothUUID>& service : filter->services) { if (!base::ContainsKey(device_uuids, service.value())) { return false; @@ -136,11 +137,12 @@ } bool MatchesFilters( - const device::BluetoothDevice& device, + const std::string* device_name, + const UUIDSet& device_uuids, const mojo::Array<blink::mojom::WebBluetoothScanFilterPtr>& filters) { DCHECK(!HasEmptyOrInvalidFilter(filters)); for (const auto& filter : filters) { - if (MatchesFilter(device, filter)) { + if (MatchesFilter(device_name, device_uuids, filter)) { return true; } } @@ -359,7 +361,10 @@ void BluetoothDeviceChooserController::AddFilteredDevice( const device::BluetoothDevice& device) { - if (chooser_.get() && MatchesFilters(device, options_->filters)) { + base::Optional<std::string> device_name = device.GetName(); + if (chooser_.get() && + MatchesFilters(device_name ? &device_name.value() : nullptr, + device.GetUUIDs(), options_->filters)) { base::Optional<int8_t> rssi = device.GetInquiryRSSI(); chooser_->AddOrUpdateDevice( device.GetAddress(), !!device.GetName() /* should_update_name */,
diff --git a/content/browser/browser_plugin/browser_plugin_embedder.cc b/content/browser/browser_plugin/browser_plugin_embedder.cc index 16a75a19..76e2446 100644 --- a/content/browser/browser_plugin/browser_plugin_embedder.cc +++ b/content/browser/browser_plugin/browser_plugin_embedder.cc
@@ -116,10 +116,6 @@ base::Bind(&BrowserPluginEmbedder::DidSendScreenRectsCallback)); } -bool BrowserPluginEmbedder::OnMessageReceived(const IPC::Message& message) { - return OnMessageReceived(message, nullptr); -} - bool BrowserPluginEmbedder::OnMessageReceived( const IPC::Message& message, RenderFrameHost* render_frame_host) { @@ -127,8 +123,6 @@ IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(BrowserPluginEmbedder, message, render_frame_host) IPC_MESSAGE_HANDLER(BrowserPluginHostMsg_Attach, OnAttach) - IPC_MESSAGE_HANDLER_GENERIC(DragHostMsg_UpdateDragCursor, - OnUpdateDragCursor(&handled)); IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; @@ -156,8 +150,8 @@ ClearGuestDragStateIfApplicable(); } -void BrowserPluginEmbedder::OnUpdateDragCursor(bool* handled) { - *handled = !!guest_dragging_over_; +bool BrowserPluginEmbedder::OnUpdateDragCursor() { + return !!guest_dragging_over_; } void BrowserPluginEmbedder::OnAttach(
diff --git a/content/browser/browser_plugin/browser_plugin_embedder.h b/content/browser/browser_plugin/browser_plugin_embedder.h index 63f60d85..5e4026c 100644 --- a/content/browser/browser_plugin/browser_plugin_embedder.h +++ b/content/browser/browser_plugin/browser_plugin_embedder.h
@@ -38,7 +38,6 @@ void DidSendScreenRects(); // WebContentsObserver implementation. - bool OnMessageReceived(const IPC::Message& message) override; bool OnMessageReceived(const IPC::Message& message, RenderFrameHost* render_frame_host) override; @@ -67,6 +66,11 @@ // operation, if there's any. void SystemDragEnded(); + // The page wants to update the mouse cursor during a drag & drop + // operation. This update will be suppressed if the cursor is dragging over a + // guest. + bool OnUpdateDragCursor(); + // Used to handle special keyboard events. bool HandleKeyboardEvent(const NativeWebKeyboardEvent& event); @@ -117,7 +121,6 @@ void OnAttach(RenderFrameHost* render_frame_host, int instance_id, const BrowserPluginHostMsg_Attach_Params& params); - void OnUpdateDragCursor(bool* handled); // Used to correctly update the cursor when dragging over a guest, and to // handle a race condition when dropping onto the guest that started the drag
diff --git a/content/browser/browser_plugin/browser_plugin_guest.cc b/content/browser/browser_plugin/browser_plugin_guest.cc index 1d6931d0..14e4e99 100644 --- a/content/browser/browser_plugin/browser_plugin_guest.cc +++ b/content/browser/browser_plugin/browser_plugin_guest.cc
@@ -509,10 +509,15 @@ owner_web_contents_->Send(msg.release()); } -void BrowserPluginGuest::DragSourceEndedAt(int client_x, int client_y, - int screen_x, int screen_y, blink::WebDragOperation operation) { - web_contents()->GetRenderViewHost()->DragSourceEndedAt(client_x, client_y, - screen_x, screen_y, operation); +void BrowserPluginGuest::DragSourceEndedAt(int client_x, + int client_y, + int screen_x, + int screen_y, + blink::WebDragOperation operation) { + // TODO(paulmeyer): This will need to target the correct specific + // RenderWidgetHost to work with OOPIFs. See crbug.com/647249. + web_contents()->GetRenderViewHost()->GetWidget()->DragSourceEndedAt( + client_x, client_y, screen_x, screen_y, operation); seen_embedder_drag_source_ended_at_ = true; EndSystemDragIfApplicable(); } @@ -541,7 +546,7 @@ seen_embedder_drag_source_ended_at_ && seen_embedder_system_drag_ended_) { RenderViewHostImpl* guest_rvh = static_cast<RenderViewHostImpl*>( GetWebContents()->GetRenderViewHost()); - guest_rvh->DragSourceSystemDragEnded(); + guest_rvh->GetWidget()->DragSourceSystemDragEnded(); last_drag_status_ = blink::WebDragStatusUnknown; seen_embedder_system_drag_ended_ = false; seen_embedder_drag_source_ended_at_ = false;
diff --git a/content/browser/browser_plugin/browser_plugin_guest.h b/content/browser/browser_plugin/browser_plugin_guest.h index fa184a6..1705d009e 100644 --- a/content/browser/browser_plugin/browser_plugin_guest.h +++ b/content/browser/browser_plugin/browser_plugin_guest.h
@@ -37,9 +37,9 @@ #include "content/public/browser/web_contents_observer.h" #include "third_party/WebKit/public/platform/WebDragOperation.h" #include "third_party/WebKit/public/platform/WebFocusType.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/web/WebCompositionUnderline.h" #include "third_party/WebKit/public/web/WebDragStatus.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" #include "ui/base/ime/text_input_mode.h" #include "ui/base/ime/text_input_type.h" #include "ui/gfx/geometry/rect.h"
diff --git a/content/browser/devtools/protocol/color_picker.cc b/content/browser/devtools/protocol/color_picker.cc index 18faba8..a5b1777 100644 --- a/content/browser/devtools/protocol/color_picker.cc +++ b/content/browser/devtools/protocol/color_picker.cc
@@ -11,7 +11,7 @@ #include "content/common/cursors/webcursor.h" #include "content/public/common/screen_info.h" #include "third_party/WebKit/public/platform/WebCursorInfo.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkPaint.h" #include "third_party/skia/include/core/SkPath.h"
diff --git a/content/browser/devtools/protocol/input_handler.cc b/content/browser/devtools/protocol/input_handler.cc index b57eb8321..b963044 100644 --- a/content/browser/devtools/protocol/input_handler.cc +++ b/content/browser/devtools/protocol/input_handler.cc
@@ -15,7 +15,7 @@ #include "content/common/input/synthetic_pinch_gesture_params.h" #include "content/common/input/synthetic_smooth_scroll_gesture_params.h" #include "content/common/input/synthetic_tap_gesture_params.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/keycodes/dom/keycode_converter.h" #include "ui/gfx/geometry/point.h"
diff --git a/content/browser/dom_storage/dom_storage_context_wrapper.cc b/content/browser/dom_storage/dom_storage_context_wrapper.cc index 9c4e801f..f173f0e 100644 --- a/content/browser/dom_storage/dom_storage_context_wrapper.cc +++ b/content/browser/dom_storage/dom_storage_context_wrapper.cc
@@ -167,11 +167,10 @@ // We were given a subdirectory to write to. Get it and use a disk backed // database. file_service_connection_->GetInterface(&file_system_); - file_system_->GetSubDirectory( - mojo::String::From(subdirectory_.AsUTF8Unsafe()), - GetProxy(&directory_), - base::Bind(&MojoState::OnDirectoryOpened, - weak_ptr_factory_.GetWeakPtr())); + file_system_->GetSubDirectory(subdirectory_.AsUTF8Unsafe(), + GetProxy(&directory_), + base::Bind(&MojoState::OnDirectoryOpened, + weak_ptr_factory_.GetWeakPtr())); } else { // We were not given a subdirectory. Use a memory backed database. file_service_connection_->GetInterface(&leveldb_service_);
diff --git a/content/browser/frame_host/cross_process_frame_connector.cc b/content/browser/frame_host/cross_process_frame_connector.cc index 0711a32..d6fd0f7 100644 --- a/content/browser/frame_host/cross_process_frame_connector.cc +++ b/content/browser/frame_host/cross_process_frame_connector.cc
@@ -20,7 +20,7 @@ #include "content/browser/renderer_host/render_widget_host_view_base.h" #include "content/common/frame_messages.h" #include "gpu/ipc/common/gpu_messages.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/gfx/geometry/dip_util.h" namespace content {
diff --git a/content/browser/frame_host/debug_urls.cc b/content/browser/frame_host/debug_urls.cc index 34055e9..2e61cc1a 100644 --- a/content/browser/frame_host/debug_urls.cc +++ b/content/browser/frame_host/debug_urls.cc
@@ -75,7 +75,7 @@ #if BUILDFLAG(ENABLE_KASKO) return (url.is_valid() && url.SchemeIs(kChromeUIScheme) && url.DomainIs(kKaskoCrashDomain) && - url.path() == kKaskoSendReport); + url.path_piece() == kKaskoSendReport); #else return false; #endif @@ -127,14 +127,17 @@ return false; } - if (url.path() == kAsanHeapOverflow || url.path() == kAsanHeapUnderflow || - url.path() == kAsanUseAfterFree) { + if (url.path_piece() == kAsanHeapOverflow || + url.path_piece() == kAsanHeapUnderflow || + url.path_piece() == kAsanUseAfterFree) { return true; } #if defined(SYZYASAN) - if (url.path() == kAsanCorruptHeapBlock || url.path() == kAsanCorruptHeap) + if (url.path_piece() == kAsanCorruptHeapBlock || + url.path_piece() == kAsanCorruptHeap) { return true; + } #endif return false; @@ -145,21 +148,21 @@ if (!base::debug::IsBinaryInstrumented()) return false; - if (url.path() == kAsanCorruptHeapBlock) { + if (url.path_piece() == kAsanCorruptHeapBlock) { base::debug::AsanCorruptHeapBlock(); return true; - } else if (url.path() == kAsanCorruptHeap) { + } else if (url.path_piece() == kAsanCorruptHeap) { base::debug::AsanCorruptHeap(); return true; } #endif #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN) - if (url.path() == kAsanHeapOverflow) { + if (url.path_piece() == kAsanHeapOverflow) { base::debug::AsanHeapOverflow(); - } else if (url.path() == kAsanHeapUnderflow) { + } else if (url.path_piece() == kAsanHeapUnderflow) { base::debug::AsanHeapUnderflow(); - } else if (url.path() == kAsanUseAfterFree) { + } else if (url.path_piece() == kAsanUseAfterFree) { base::debug::AsanHeapUseAfterFree(); } else { return false;
diff --git a/content/browser/frame_host/interstitial_page_impl.cc b/content/browser/frame_host/interstitial_page_impl.cc index 63bba94..c8d1166 100644 --- a/content/browser/frame_host/interstitial_page_impl.cc +++ b/content/browser/frame_host/interstitial_page_impl.cc
@@ -884,7 +884,8 @@ const gfx::ImageSkia& image, const gfx::Vector2d& image_offset, const DragEventSourceInfo& event_info) { - interstitial_page_->render_view_host_->DragSourceSystemDragEnded(); + interstitial_page_->render_view_host_->GetWidget()-> + DragSourceSystemDragEnded(); DVLOG(1) << "InterstitialPage does not support dragging yet."; }
diff --git a/content/browser/frame_host/navigation_controller_impl.cc b/content/browser/frame_host/navigation_controller_impl.cc index eddc501..42d6032 100644 --- a/content/browser/frame_host/navigation_controller_impl.cc +++ b/content/browser/frame_host/navigation_controller_impl.cc
@@ -1790,22 +1790,6 @@ CancelForNavigation(); } - // Convert Enter-in-omnibox to a reload. This is what Blink does in - // FrameLoader, but we want to handle it here so that if the navigation is - // redirected or handled purely on the browser side in PlzNavigate we have the - // same behaviour as Blink would. Note that we don't want to convert to a - // reload for history navigations, so this must be above the retrieval of the - // pending_entry_ below when pending_entry_index_ is used. - if (reload_type == ReloadType::NONE && GetLastCommittedEntry() && - pending_entry_ && pending_entry_->frame_tree_node_id() == -1 && - pending_entry_->GetURL() == GetLastCommittedEntry()->GetURL() && - !pending_entry_->GetHasPostData() && - // This check is required for Android WebView loadDataWithBaseURL. - GetLastCommittedEntry()->GetVirtualURL() == - pending_entry_->GetVirtualURL()) { - reload_type = ReloadType::MAIN_RESOURCE; - } - // For session history navigations only the pending_entry_index_ is set. if (!pending_entry_) { CHECK_NE(pending_entry_index_, -1);
diff --git a/content/browser/frame_host/navigation_handle_impl.cc b/content/browser/frame_host/navigation_handle_impl.cc index 4875254..c58618c 100644 --- a/content/browser/frame_host/navigation_handle_impl.cc +++ b/content/browser/frame_host/navigation_handle_impl.cc
@@ -370,6 +370,18 @@ DidCommitNavigation(params, false, render_frame_host_); } +bool NavigationHandleImpl::WasStartedFromContextMenu() const { + return started_from_context_menu_; +} + +const GURL& NavigationHandleImpl::GetSearchableFormURL() { + return searchable_form_url_; +} + +const std::string& NavigationHandleImpl::GetSearchableFormEncoding() { + return searchable_form_encoding_; +} + NavigationData* NavigationHandleImpl::GetNavigationData() { return navigation_data_.get(); } @@ -761,8 +773,4 @@ } } -bool NavigationHandleImpl::WasStartedFromContextMenu() const { - return started_from_context_menu_; -} - } // namespace content
diff --git a/content/browser/frame_host/navigation_handle_impl.h b/content/browser/frame_host/navigation_handle_impl.h index 2d1f009..3eeed43 100644 --- a/content/browser/frame_host/navigation_handle_impl.h +++ b/content/browser/frame_host/navigation_handle_impl.h
@@ -128,6 +128,8 @@ const std::string& raw_response_header) override; void CallDidCommitNavigationForTesting(const GURL& url) override; bool WasStartedFromContextMenu() const override; + const GURL& GetSearchableFormURL() override; + const std::string& GetSearchableFormEncoding() override; NavigationData* GetNavigationData() override; @@ -281,6 +283,11 @@ return navigation_ui_data_.get(); } + void set_searchable_form_url(const GURL& url) { searchable_form_url_ = url; } + void set_searchable_form_encoding(const std::string& encoding) { + searchable_form_encoding_ = encoding; + } + private: friend class NavigationHandleImplTest; @@ -424,6 +431,9 @@ // False by default unless the navigation started within a context menu. bool started_from_context_menu_; + GURL searchable_form_url_; + std::string searchable_form_encoding_; + base::WeakPtrFactory<NavigationHandleImpl> weak_factory_; DISALLOW_COPY_AND_ASSIGN(NavigationHandleImpl);
diff --git a/content/browser/frame_host/navigation_request.cc b/content/browser/frame_host/navigation_request.cc index 6578b87..4c24485 100644 --- a/content/browser/frame_host/navigation_request.cc +++ b/content/browser/frame_host/navigation_request.cc
@@ -311,6 +311,13 @@ false, // is_srcdoc common_params_.navigation_start, pending_nav_entry_id, false); // started_in_context_menu + + if (!begin_params_.searchable_form_url.is_empty()) { + navigation_handle_->set_searchable_form_url( + begin_params_.searchable_form_url); + navigation_handle_->set_searchable_form_encoding( + begin_params_.searchable_form_encoding); + } } void NavigationRequest::TransferNavigationHandleOwnership(
diff --git a/content/browser/frame_host/render_frame_host_impl.cc b/content/browser/frame_host/render_frame_host_impl.cc index 4bbb482..23b5a24 100644 --- a/content/browser/frame_host/render_frame_host_impl.cc +++ b/content/browser/frame_host/render_frame_host_impl.cc
@@ -1225,6 +1225,23 @@ TakeNavigationHandleForCommit(validated_params); DCHECK(navigation_handle); + // PlzNavigate sends searchable form data in the BeginNavigation message + // while non-PlzNavigate sends it in the DidCommitProvisionalLoad message. + // Update |navigation_handle| if necessary. + if (!IsBrowserSideNavigationEnabled() && + !validated_params.searchable_form_url.is_empty()) { + navigation_handle->set_searchable_form_url( + validated_params.searchable_form_url); + navigation_handle->set_searchable_form_encoding( + validated_params.searchable_form_encoding); + + // Reset them so that they are consistent in both the PlzNavigate and + // non-PlzNavigate case. Users should use those values from + // NavigationHandle. + validated_params.searchable_form_url = GURL(); + validated_params.searchable_form_encoding = std::string(); + } + accessibility_reset_count_ = 0; frame_tree_node()->navigator()->DidNavigate(this, validated_params, std::move(navigation_handle)); @@ -1787,14 +1804,17 @@ CommonNavigationParams validated_params = common_params; GetProcess()->FilterURL(false, &validated_params.url); + BeginNavigationParams validated_begin_params = begin_params; + GetProcess()->FilterURL(true, &validated_begin_params.searchable_form_url); + if (waiting_for_init_) { - pendinging_navigate_ = - base::MakeUnique<PendingNavigation>(validated_params, begin_params); + pendinging_navigate_ = base::MakeUnique<PendingNavigation>( + validated_params, validated_begin_params); return; } frame_tree_node()->navigator()->OnBeginNavigation( - frame_tree_node(), validated_params, begin_params); + frame_tree_node(), validated_params, validated_begin_params); } void RenderFrameHostImpl::OnDispatchLoad() {
diff --git a/content/browser/frame_host/render_widget_host_view_child_frame.cc b/content/browser/frame_host/render_widget_host_view_child_frame.cc index 45141bc..e960e39 100644 --- a/content/browser/frame_host/render_widget_host_view_child_frame.cc +++ b/content/browser/frame_host/render_widget_host_view_child_frame.cc
@@ -33,7 +33,7 @@ #include "content/public/browser/guest_mode.h" #include "content/public/browser/render_process_host.h" #include "gpu/ipc/common/gpu_messages.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/gfx/geometry/size_conversions.h" #include "ui/gfx/geometry/size_f.h"
diff --git a/content/browser/frame_host/render_widget_host_view_guest.h b/content/browser/frame_host/render_widget_host_view_guest.h index 83bff4f..af8d734b 100644 --- a/content/browser/frame_host/render_widget_host_view_guest.h +++ b/content/browser/frame_host/render_widget_host_view_guest.h
@@ -16,7 +16,7 @@ #include "content/browser/frame_host/render_widget_host_view_child_frame.h" #include "content/common/content_export.h" #include "content/common/cursors/webcursor.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/event.h" #include "ui/events/gestures/gesture_recognizer.h" #include "ui/events/gestures/gesture_types.h"
diff --git a/content/browser/gpu/browser_gpu_memory_buffer_manager.cc b/content/browser/gpu/browser_gpu_memory_buffer_manager.cc index 51aeb5e..57170fc 100644 --- a/content/browser/gpu/browser_gpu_memory_buffer_manager.cc +++ b/content/browser/gpu/browser_gpu_memory_buffer_manager.cc
@@ -288,7 +288,7 @@ } callback.Run(gpu::GpuMemoryBufferImplSharedMemory::AllocateForChildProcess( - id, size, format, child_process_handle)); + id, size, format)); } void BrowserGpuMemoryBufferManager::SetDestructionSyncToken(
diff --git a/content/browser/gpu/gpu_data_manager_impl_private.cc b/content/browser/gpu/gpu_data_manager_impl_private.cc index 2ebba27b..0f517ce 100644 --- a/content/browser/gpu/gpu_data_manager_impl_private.cc +++ b/content/browser/gpu/gpu_data_manager_impl_private.cc
@@ -4,6 +4,8 @@ #include "content/browser/gpu/gpu_data_manager_impl_private.h" +#include <algorithm> +#include <iterator> #include <memory> #include <utility> @@ -347,12 +349,23 @@ // We only need to block GPU process if more features are disallowed other // than those in the preliminary gpu feature flags because the latter work - // through renderer commandline switches. - std::set<int> features = preliminary_blacklisted_features_; - gpu::MergeFeatureSets(&features, blacklisted_features_); - if (features.size() > preliminary_blacklisted_features_.size()) { + // through renderer commandline switches. WebGL and WebGL2 should not matter + // because their context creation can always be rejected on the GPU process + // side. + std::set<int> feature_diffs; + std::set_difference(blacklisted_features_.begin(), + blacklisted_features_.end(), + preliminary_blacklisted_features_.begin(), + preliminary_blacklisted_features_.end(), + std::inserter(feature_diffs, feature_diffs.begin())); + if (feature_diffs.size()) { + // TODO(zmo): Other features might also be OK to ignore here. + feature_diffs.erase(gpu::GPU_FEATURE_TYPE_WEBGL); + feature_diffs.erase(gpu::GPU_FEATURE_TYPE_WEBGL2); + } + if (feature_diffs.size()) { if (reason) { - *reason = "Features are disabled upon full but not preliminary GPU info."; + *reason = "Features are disabled on full but not preliminary GPU info."; } return false; }
diff --git a/content/browser/gpu/gpu_data_manager_impl_private_unittest.cc b/content/browser/gpu/gpu_data_manager_impl_private_unittest.cc index c92f37c..880a83f 100644 --- a/content/browser/gpu/gpu_data_manager_impl_private_unittest.cc +++ b/content/browser/gpu/gpu_data_manager_impl_private_unittest.cc
@@ -193,6 +193,63 @@ gpu::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS)); } +TEST_F(GpuDataManagerImplPrivateTest, GpuSideBlacklistingWebGL) { + // If a feature is allowed in preliminary step (browser side), but + // disabled when GPU process launches and collects full GPU info, + // it's too late to let renderer know, so we basically block all GPU + // access, to be on the safe side. + ScopedGpuDataManagerImplPrivate manager; + EXPECT_EQ(0u, manager->GetBlacklistedFeatureCount()); + std::string reason; + EXPECT_TRUE(manager->GpuAccessAllowed(&reason)); + EXPECT_TRUE(reason.empty()); + + const std::string blacklist_json = LONG_STRING_CONST( + { + "name": "gpu blacklist", + "version": "0.1", + "entries": [ + { + "id": 1, + "features": [ + "accelerated_2d_canvas" + ] + }, + { + "id": 2, + "gl_renderer": ".*GeForce.*", + "features": [ + "webgl", + "webgl2" + ] + } + ] + } + ); + + gpu::GPUInfo gpu_info; + gpu_info.gpu.vendor_id = 0x10de; + gpu_info.gpu.device_id = 0x0640; + manager->InitializeForTesting(blacklist_json, gpu_info); + + EXPECT_TRUE(manager->GpuAccessAllowed(&reason)); + EXPECT_TRUE(reason.empty()); + EXPECT_EQ(1u, manager->GetBlacklistedFeatureCount()); + EXPECT_TRUE(manager->IsFeatureBlacklisted( + gpu::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS)); + + gpu_info.gl_vendor = "NVIDIA"; + gpu_info.gl_renderer = "NVIDIA GeForce GT 120"; + manager->UpdateGpuInfo(gpu_info); + EXPECT_TRUE(manager->GpuAccessAllowed(&reason)); + EXPECT_TRUE(reason.empty()); + EXPECT_EQ(3u, manager->GetBlacklistedFeatureCount()); + EXPECT_TRUE(manager->IsFeatureBlacklisted( + gpu::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS)); + EXPECT_TRUE(manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_WEBGL)); + EXPECT_TRUE(manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_WEBGL2)); +} + TEST_F(GpuDataManagerImplPrivateTest, GpuSideExceptions) { ScopedGpuDataManagerImplPrivate manager; EXPECT_EQ(0u, manager->GetBlacklistedFeatureCount());
diff --git a/content/browser/loader/async_resource_handler_browsertest.cc b/content/browser/loader/async_resource_handler_browsertest.cc index d0e15f0..e1bc8fe 100644 --- a/content/browser/loader/async_resource_handler_browsertest.cc +++ b/content/browser/loader/async_resource_handler_browsertest.cc
@@ -69,9 +69,9 @@ IN_PROC_BROWSER_TEST_F(AsyncResourceHandlerBrowserTest, UploadProgress) { net::EmbeddedTestServer* test_server = embedded_test_server(); - ASSERT_TRUE(test_server->Start()); test_server->RegisterRequestHandler( base::Bind(&HandlePostAndRedirectURLs, kPostPath)); + ASSERT_TRUE(test_server->Start()); NavigateToURL(shell(), test_server->GetURL("/loader/async_resource_handler.html")); @@ -87,9 +87,9 @@ IN_PROC_BROWSER_TEST_F(AsyncResourceHandlerBrowserTest, UploadProgressRedirect) { net::EmbeddedTestServer* test_server = embedded_test_server(); - ASSERT_TRUE(test_server->Start()); test_server->RegisterRequestHandler( base::Bind(&HandlePostAndRedirectURLs, kRedirectPostPath)); + ASSERT_TRUE(test_server->Start()); NavigateToURL(shell(), test_server->GetURL("/loader/async_resource_handler.html"));
diff --git a/content/browser/loader/async_revalidation_manager_browsertest.cc b/content/browser/loader/async_revalidation_manager_browsertest.cc index a22a764..2646222 100644 --- a/content/browser/loader/async_revalidation_manager_browsertest.cc +++ b/content/browser/loader/async_revalidation_manager_browsertest.cc
@@ -45,15 +45,9 @@ void SetUp() override { scoped_feature_list_.InitAndEnableFeature(features::kStaleWhileRevalidate); - - ASSERT_TRUE(embedded_test_server()->InitializeAndListen()); ContentBrowserTest::SetUp(); } - void SetUpOnMainThread() override { - embedded_test_server()->StartAcceptingConnections(); - } - base::RunLoop* run_loop() { return &run_loop_; } int requests_counted() const { return requests_counted_; } @@ -157,11 +151,13 @@ // triggers an async revalidation. IN_PROC_BROWSER_TEST_F(AsyncRevalidationManagerBrowserTest, StaleWhileRevalidateIsApplied) { + RegisterCountingRequestHandler(); + ASSERT_TRUE(embedded_test_server()->Start()); + // PlzNavigate: Stale while revalidate is disabled. // TODO(clamy): Re-enable the test when there is support. if (IsBrowserSideNavigationEnabled()) return; - RegisterCountingRequestHandler(); GURL url(embedded_test_server()->GetURL(kCountedHtmlPath)); EXPECT_TRUE(TitleBecomes(url, "Version 1")); @@ -184,12 +180,14 @@ // The fresh cache entry must become visible once the async revalidation request // has been sent. IN_PROC_BROWSER_TEST_F(AsyncRevalidationManagerBrowserTest, CacheIsUpdated) { + RegisterCountingRequestHandler(); + ASSERT_TRUE(embedded_test_server()->Start()); + // PlzNavigate: Stale while revalidate is disabled. // TODO(clamy): Re-enable the test when there is support. if (IsBrowserSideNavigationEnabled()) return; using base::ASCIIToUTF16; - RegisterCountingRequestHandler(); GURL url(embedded_test_server()->GetURL(kCountedHtmlPath)); EXPECT_TRUE(TitleBecomes(url, "Version 1")); @@ -216,11 +214,13 @@ // applied immediately. IN_PROC_BROWSER_TEST_F(AsyncRevalidationManagerBrowserTest, CookieSetAsynchronously) { + RegisterCookieRequestHandler(); + ASSERT_TRUE(embedded_test_server()->Start()); + // PlzNavigate: Stale while revalidate is disabled. // TODO(clamy): Re-enable the test when there is support. if (IsBrowserSideNavigationEnabled()) return; - RegisterCookieRequestHandler(); GURL url(embedded_test_server()->GetURL(kCookieHtmlPath)); // Set cookie to version=1
diff --git a/content/browser/loader/cross_site_resource_handler_browsertest.cc b/content/browser/loader/cross_site_resource_handler_browsertest.cc index d245cca..e29556a 100644 --- a/content/browser/loader/cross_site_resource_handler_browsertest.cc +++ b/content/browser/loader/cross_site_resource_handler_browsertest.cc
@@ -193,8 +193,8 @@ &CrossSiteResourceHandlerTest::InjectResourceDispatcherHostDelegate, base::Unretained(this))); host_resolver()->AddRule("*", "127.0.0.1"); - ASSERT_TRUE(embedded_test_server()->Start()); content::SetupCrossSiteRedirector(embedded_test_server()); + ASSERT_TRUE(embedded_test_server()->Start()); } void TearDownOnMainThread() override {
diff --git a/content/browser/loader/resource_dispatcher_host_browsertest.cc b/content/browser/loader/resource_dispatcher_host_browsertest.cc index 92d0d9e..8b945a0 100644 --- a/content/browser/loader/resource_dispatcher_host_browsertest.cc +++ b/content/browser/loader/resource_dispatcher_host_browsertest.cc
@@ -297,6 +297,10 @@ // If this flakes use http://crbug.com/80596. IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest, CrossSiteNoUnloadOn204) { + const char kNoContentPath[] = "/nocontent"; + embedded_test_server()->RegisterRequestHandler( + base::Bind(&NoContentResponseHandler, kNoContentPath)); + ASSERT_TRUE(embedded_test_server()->Start()); // Start with a URL that sets a cookie in its unload handler. @@ -304,9 +308,6 @@ CheckTitleTest(url, "set cookie on unload"); // Navigate to a cross-site URL that returns a 204 No Content response. - const char kNoContentPath[] = "/nocontent"; - embedded_test_server()->RegisterRequestHandler( - base::Bind(&NoContentResponseHandler, kNoContentPath)); NavigateToURL(shell(), embedded_test_server()->GetURL(kNoContentPath)); // Check that the unload cookie was not set. @@ -480,9 +481,9 @@ // Test that we update the cookie policy URLs correctly when transferring // navigations. IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest, CookiePolicy) { - ASSERT_TRUE(embedded_test_server()->Start()); embedded_test_server()->RegisterRequestHandler( base::Bind(&HandleRedirectRequest, "/redirect?")); + ASSERT_TRUE(embedded_test_server()->Start()); std::string set_cookie_url(base::StringPrintf( "http://localhost:%u/set_cookie.html", embedded_test_server()->port()));
diff --git a/content/browser/loader/resource_dispatcher_host_impl.cc b/content/browser/loader/resource_dispatcher_host_impl.cc index d497078..6b3e770 100644 --- a/content/browser/loader/resource_dispatcher_host_impl.cc +++ b/content/browser/loader/resource_dispatcher_host_impl.cc
@@ -928,7 +928,7 @@ } if (loader->request()->url().SchemeIsCryptographic()) { - if (loader->request()->url().host() == "www.google.com") { + if (loader->request()->url().host_piece() == "www.google.com") { UMA_HISTOGRAM_SPARSE_SLOWLY("Net.ErrorCodesForHTTPSGoogleMainFrame2", -loader->request()->status().error()); }
diff --git a/content/browser/media/android/media_player_renderer.cc b/content/browser/media/android/media_player_renderer.cc index 58d7bfa..9f924dd 100644 --- a/content/browser/media/android/media_player_renderer.cc +++ b/content/browser/media/android/media_player_renderer.cc
@@ -21,6 +21,12 @@ namespace content { +namespace { + +media::MediaUrlInterceptor* g_media_url_interceptor = nullptr; + +} // namespace + MediaPlayerRenderer::MediaPlayerRenderer(RenderFrameHost* render_frame_host) : render_frame_host_(render_frame_host), has_error_(false), @@ -163,9 +169,7 @@ } media::MediaUrlInterceptor* MediaPlayerRenderer::GetMediaUrlInterceptor() { - // TODO(tguilbert): Offer a RegisterMediaUrlInterceptor equivalent for use in - // webview. See crbug.com/636588. - return nullptr; + return g_media_url_interceptor; } void MediaPlayerRenderer::OnTimeUpdate(int player_id, @@ -242,6 +246,12 @@ // See crbug.com/636615. } +// static +void MediaPlayerRenderer::RegisterMediaUrlInterceptor( + media::MediaUrlInterceptor* media_url_interceptor) { + g_media_url_interceptor = media_url_interceptor; +} + void MediaPlayerRenderer::CancelScopedSurfaceRequest() { if (!surface_request_token_) return;
diff --git a/content/browser/media/android/media_player_renderer.h b/content/browser/media/android/media_player_renderer.h index bd27299..0005074 100644 --- a/content/browser/media/android/media_player_renderer.h +++ b/content/browser/media/android/media_player_renderer.h
@@ -38,6 +38,10 @@ class CONTENT_EXPORT MediaPlayerRenderer : public media::Renderer, public media::MediaPlayerManager { public: + // Permits embedders to handle custom urls. + static void RegisterMediaUrlInterceptor( + media::MediaUrlInterceptor* media_url_interceptor); + explicit MediaPlayerRenderer(content::RenderFrameHost* render_frame_host); ~MediaPlayerRenderer() override;
diff --git a/content/browser/net/view_blob_internals_job_factory.cc b/content/browser/net/view_blob_internals_job_factory.cc index 2f00bede..409148f 100644 --- a/content/browser/net/view_blob_internals_job_factory.cc +++ b/content/browser/net/view_blob_internals_job_factory.cc
@@ -15,7 +15,7 @@ // static. bool ViewBlobInternalsJobFactory::IsSupportedURL(const GURL& url) { return url.SchemeIs(kChromeUIScheme) && - url.host() == kChromeUIBlobInternalsHost; + url.host_piece() == kChromeUIBlobInternalsHost; } // static.
diff --git a/content/browser/net/view_http_cache_job_factory.cc b/content/browser/net/view_http_cache_job_factory.cc index 3bd1f2c3..ca64341e 100644 --- a/content/browser/net/view_http_cache_job_factory.cc +++ b/content/browser/net/view_http_cache_job_factory.cc
@@ -194,7 +194,7 @@ // Static. bool ViewHttpCacheJobFactory::IsSupportedURL(const GURL& url) { return url.SchemeIs(kChromeUIScheme) && - url.host() == kChromeUINetworkViewCacheHost; + url.host_piece() == kChromeUINetworkViewCacheHost; } // Static.
diff --git a/content/browser/renderer_host/input/gesture_event_queue.h b/content/browser/renderer_host/input/gesture_event_queue.h index 9acfc3b..3f1e240 100644 --- a/content/browser/renderer_host/input/gesture_event_queue.h +++ b/content/browser/renderer_host/input/gesture_event_queue.h
@@ -18,7 +18,7 @@ #include "content/browser/renderer_host/input/touchscreen_tap_suppression_controller.h" #include "content/common/content_export.h" #include "content/common/input/input_event_ack_state.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/gfx/transform.h" namespace content {
diff --git a/content/browser/renderer_host/input/gesture_event_queue_unittest.cc b/content/browser/renderer_host/input/gesture_event_queue_unittest.cc index adb62bc..eb09b8e 100644 --- a/content/browser/renderer_host/input/gesture_event_queue_unittest.cc +++ b/content/browser/renderer_host/input/gesture_event_queue_unittest.cc
@@ -21,7 +21,7 @@ #include "content/common/input/input_event_ack_state.h" #include "content/common/input/synthetic_web_input_event_builders.h" #include "testing/gtest/include/gtest/gtest.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" using base::TimeDelta; using blink::WebGestureDevice;
diff --git a/content/browser/renderer_host/input/input_ack_handler.h b/content/browser/renderer_host/input/input_ack_handler.h index 2268681..63fa500 100644 --- a/content/browser/renderer_host/input/input_ack_handler.h +++ b/content/browser/renderer_host/input/input_ack_handler.h
@@ -8,7 +8,7 @@ #include "content/browser/renderer_host/event_with_latency_info.h" #include "content/common/input/input_event_ack_state.h" #include "content/public/browser/native_web_keyboard_event.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" namespace content {
diff --git a/content/browser/renderer_host/input/input_router.h b/content/browser/renderer_host/input/input_router.h index 8446f7c..60e77c9d 100644 --- a/content/browser/renderer_host/input/input_router.h +++ b/content/browser/renderer_host/input/input_router.h
@@ -9,7 +9,7 @@ #include "content/common/input/input_event_ack_state.h" #include "content/public/browser/native_web_keyboard_event.h" #include "ipc/ipc_listener.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" namespace content {
diff --git a/content/browser/renderer_host/input/input_router_client.h b/content/browser/renderer_host/input/input_router_client.h index 3c45aa8..0221533 100644 --- a/content/browser/renderer_host/input/input_router_client.h +++ b/content/browser/renderer_host/input/input_router_client.h
@@ -10,7 +10,7 @@ #include "content/common/input/input_event_ack_source.h" #include "content/common/input/input_event_ack_state.h" #include "content/public/browser/native_web_keyboard_event.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" namespace ui { class LatencyInfo;
diff --git a/content/browser/renderer_host/input/main_thread_event_queue_browsertest.cc b/content/browser/renderer_host/input/main_thread_event_queue_browsertest.cc index 7770447..1e703be 100644 --- a/content/browser/renderer_host/input/main_thread_event_queue_browsertest.cc +++ b/content/browser/renderer_host/input/main_thread_event_queue_browsertest.cc
@@ -25,7 +25,7 @@ #include "content/public/test/content_browser_test_utils.h" #include "content/public/test/test_utils.h" #include "content/shell/browser/shell.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/event_switches.h" #include "ui/events/latency_info.h"
diff --git a/content/browser/renderer_host/input/motion_event_web.h b/content/browser/renderer_host/input/motion_event_web.h index 320e31b..971e1a3 100644 --- a/content/browser/renderer_host/input/motion_event_web.h +++ b/content/browser/renderer_host/input/motion_event_web.h
@@ -10,7 +10,7 @@ #include "base/macros.h" #include "content/common/content_export.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/gesture_detection/motion_event.h" namespace content {
diff --git a/content/browser/renderer_host/input/mouse_wheel_event_queue.h b/content/browser/renderer_host/input/mouse_wheel_event_queue.h index 99d5af9..1f465b5 100644 --- a/content/browser/renderer_host/input/mouse_wheel_event_queue.h +++ b/content/browser/renderer_host/input/mouse_wheel_event_queue.h
@@ -13,7 +13,7 @@ #include "content/browser/renderer_host/event_with_latency_info.h" #include "content/common/content_export.h" #include "content/common/input/input_event_ack_state.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" namespace content {
diff --git a/content/browser/renderer_host/input/mouse_wheel_event_queue_unittest.cc b/content/browser/renderer_host/input/mouse_wheel_event_queue_unittest.cc index fc6995e..7bc5d63 100644 --- a/content/browser/renderer_host/input/mouse_wheel_event_queue_unittest.cc +++ b/content/browser/renderer_host/input/mouse_wheel_event_queue_unittest.cc
@@ -17,7 +17,7 @@ #include "content/browser/renderer_host/input/timeout_monitor.h" #include "content/common/input/synthetic_web_input_event_builders.h" #include "testing/gtest/include/gtest/gtest.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" using blink::WebGestureEvent; using blink::WebInputEvent;
diff --git a/content/browser/renderer_host/input/mouse_wheel_rails_filter_mac.h b/content/browser/renderer_host/input/mouse_wheel_rails_filter_mac.h index ffed162c9..76924471 100644 --- a/content/browser/renderer_host/input/mouse_wheel_rails_filter_mac.h +++ b/content/browser/renderer_host/input/mouse_wheel_rails_filter_mac.h
@@ -6,7 +6,7 @@ #define CONTENT_BROWSER_RENDERER_HOST_INPUT_MOUSE_WHEEL_RAILS_FILTER_MAC_H_ #include "content/common/content_export.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/gfx/geometry/vector2d_f.h" namespace content {
diff --git a/content/browser/renderer_host/input/non_blocking_event_browsertest.cc b/content/browser/renderer_host/input/non_blocking_event_browsertest.cc index 858a53a..d7bd563 100644 --- a/content/browser/renderer_host/input/non_blocking_event_browsertest.cc +++ b/content/browser/renderer_host/input/non_blocking_event_browsertest.cc
@@ -25,7 +25,7 @@ #include "content/public/test/content_browser_test_utils.h" #include "content/public/test/test_utils.h" #include "content/shell/browser/shell.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/event_switches.h" #include "ui/events/latency_info.h"
diff --git a/content/browser/renderer_host/input/synthetic_gesture_controller_unittest.cc b/content/browser/renderer_host/input/synthetic_gesture_controller_unittest.cc index c2e1670..e7c4947 100644 --- a/content/browser/renderer_host/input/synthetic_gesture_controller_unittest.cc +++ b/content/browser/renderer_host/input/synthetic_gesture_controller_unittest.cc
@@ -32,7 +32,7 @@ #include "content/public/test/test_browser_context.h" #include "content/test/test_render_view_host.h" #include "testing/gtest/include/gtest/gtest.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/point_f.h" #include "ui/gfx/geometry/vector2d.h"
diff --git a/content/browser/renderer_host/input/synthetic_gesture_target_android.cc b/content/browser/renderer_host/input/synthetic_gesture_target_android.cc index c132d0b..7c34adf 100644 --- a/content/browser/renderer_host/input/synthetic_gesture_target_android.cc +++ b/content/browser/renderer_host/input/synthetic_gesture_target_android.cc
@@ -7,7 +7,7 @@ #include "content/browser/android/content_view_core_impl.h" #include "content/browser/renderer_host/render_widget_host_impl.h" #include "jni/MotionEventSynthesizer_jni.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/gfx/android/view_configuration.h" using blink::WebTouchEvent;
diff --git a/content/browser/renderer_host/input/synthetic_gesture_target_base.cc b/content/browser/renderer_host/input/synthetic_gesture_target_base.cc index c21b88b..ae8f7e12 100644 --- a/content/browser/renderer_host/input/synthetic_gesture_target_base.cc +++ b/content/browser/renderer_host/input/synthetic_gesture_target_base.cc
@@ -8,7 +8,7 @@ #include "content/browser/renderer_host/render_widget_host_view_base.h" #include "content/browser/renderer_host/ui_events_helper.h" #include "content/common/input_messages.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/blink/web_input_event_traits.h" #include "ui/events/event.h" #include "ui/events/latency_info.h"
diff --git a/content/browser/renderer_host/input/synthetic_pointer.cc b/content/browser/renderer_host/input/synthetic_pointer.cc index f840c15..46d801d 100644 --- a/content/browser/renderer_host/input/synthetic_pointer.cc +++ b/content/browser/renderer_host/input/synthetic_pointer.cc
@@ -7,7 +7,7 @@ #include "base/memory/ptr_util.h" #include "content/browser/renderer_host/input/synthetic_mouse_pointer.h" #include "content/browser/renderer_host/input/synthetic_touch_pointer.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" namespace content {
diff --git a/content/browser/renderer_host/input/synthetic_pointer_action.cc b/content/browser/renderer_host/input/synthetic_pointer_action.cc index a701ce51..51453d6 100644 --- a/content/browser/renderer_host/input/synthetic_pointer_action.cc +++ b/content/browser/renderer_host/input/synthetic_pointer_action.cc
@@ -5,7 +5,7 @@ #include "content/browser/renderer_host/input/synthetic_pointer_action.h" #include "base/logging.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/latency_info.h" namespace content {
diff --git a/content/browser/renderer_host/input/synthetic_pointer_action_unittest.cc b/content/browser/renderer_host/input/synthetic_pointer_action_unittest.cc index e4b0f9d..334a163 100644 --- a/content/browser/renderer_host/input/synthetic_pointer_action_unittest.cc +++ b/content/browser/renderer_host/input/synthetic_pointer_action_unittest.cc
@@ -9,7 +9,7 @@ #include "content/browser/renderer_host/input/synthetic_pointer_action.h" #include "content/browser/renderer_host/input/synthetic_touch_pointer.h" #include "testing/gtest/include/gtest/gtest.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/point_f.h"
diff --git a/content/browser/renderer_host/input/synthetic_smooth_move_gesture.h b/content/browser/renderer_host/input/synthetic_smooth_move_gesture.h index b370ff5..3a79f49 100644 --- a/content/browser/renderer_host/input/synthetic_smooth_move_gesture.h +++ b/content/browser/renderer_host/input/synthetic_smooth_move_gesture.h
@@ -15,7 +15,7 @@ #include "content/common/content_export.h" #include "content/common/input/synthetic_smooth_drag_gesture_params.h" #include "content/common/input/synthetic_smooth_scroll_gesture_params.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/gfx/geometry/vector2d.h" #include "ui/gfx/geometry/vector2d_f.h"
diff --git a/content/browser/renderer_host/input/synthetic_tap_gesture.cc b/content/browser/renderer_host/input/synthetic_tap_gesture.cc index 46dc23ae..4c19027 100644 --- a/content/browser/renderer_host/input/synthetic_tap_gesture.cc +++ b/content/browser/renderer_host/input/synthetic_tap_gesture.cc
@@ -5,7 +5,7 @@ #include "content/browser/renderer_host/input/synthetic_tap_gesture.h" #include "base/logging.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/latency_info.h" namespace content {
diff --git a/content/browser/renderer_host/input/synthetic_touchpad_pinch_gesture.h b/content/browser/renderer_host/input/synthetic_touchpad_pinch_gesture.h index d2097634..761940f 100644 --- a/content/browser/renderer_host/input/synthetic_touchpad_pinch_gesture.h +++ b/content/browser/renderer_host/input/synthetic_touchpad_pinch_gesture.h
@@ -12,7 +12,7 @@ #include "content/common/content_export.h" #include "content/common/input/synthetic_pinch_gesture_params.h" #include "content/common/input/synthetic_web_input_event_builders.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" namespace content {
diff --git a/content/browser/renderer_host/input/synthetic_touchscreen_pinch_gesture.h b/content/browser/renderer_host/input/synthetic_touchscreen_pinch_gesture.h index de538912..610e9c39 100644 --- a/content/browser/renderer_host/input/synthetic_touchscreen_pinch_gesture.h +++ b/content/browser/renderer_host/input/synthetic_touchscreen_pinch_gesture.h
@@ -13,7 +13,7 @@ #include "content/common/content_export.h" #include "content/common/input/synthetic_pinch_gesture_params.h" #include "content/common/input/synthetic_web_input_event_builders.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" namespace content {
diff --git a/content/browser/renderer_host/input/touch_action_browsertest.cc b/content/browser/renderer_host/input/touch_action_browsertest.cc index 33845ae9..d17be7a 100644 --- a/content/browser/renderer_host/input/touch_action_browsertest.cc +++ b/content/browser/renderer_host/input/touch_action_browsertest.cc
@@ -30,7 +30,7 @@ #include "content/public/test/content_browser_test_utils.h" #include "content/public/test/test_utils.h" #include "content/shell/browser/shell.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/event_switches.h" #include "ui/events/latency_info.h"
diff --git a/content/browser/renderer_host/input/touch_action_filter.cc b/content/browser/renderer_host/input/touch_action_filter.cc index 19c1ce7..8f87bc0 100644 --- a/content/browser/renderer_host/input/touch_action_filter.cc +++ b/content/browser/renderer_host/input/touch_action_filter.cc
@@ -7,7 +7,7 @@ #include <math.h> #include "base/logging.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" using blink::WebInputEvent; using blink::WebGestureEvent;
diff --git a/content/browser/renderer_host/input/touch_action_filter_unittest.cc b/content/browser/renderer_host/input/touch_action_filter_unittest.cc index f200c4f..7647a791 100644 --- a/content/browser/renderer_host/input/touch_action_filter_unittest.cc +++ b/content/browser/renderer_host/input/touch_action_filter_unittest.cc
@@ -7,7 +7,7 @@ #include "content/common/input/input_event_ack_state.h" #include "content/common/input/synthetic_web_input_event_builders.h" #include "testing/gtest/include/gtest/gtest.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" using blink::WebGestureEvent; using blink::WebInputEvent;
diff --git a/content/browser/renderer_host/input/touch_emulator.h b/content/browser/renderer_host/input/touch_emulator.h index 48ba8b51..187dee7 100644 --- a/content/browser/renderer_host/input/touch_emulator.h +++ b/content/browser/renderer_host/input/touch_emulator.h
@@ -11,7 +11,7 @@ #include "content/browser/renderer_host/input/touch_emulator_client.h" #include "content/common/cursors/webcursor.h" #include "content/common/input/input_event_ack_state.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/gesture_detection/filtered_gesture_provider.h" #include "ui/events/gesture_detection/gesture_provider_config_helper.h" #include "ui/gfx/geometry/size_f.h"
diff --git a/content/browser/renderer_host/input/touch_emulator_client.h b/content/browser/renderer_host/input/touch_emulator_client.h index 89ce509a..6295372d 100644 --- a/content/browser/renderer_host/input/touch_emulator_client.h +++ b/content/browser/renderer_host/input/touch_emulator_client.h
@@ -7,7 +7,8 @@ #include "content/common/content_export.h" #include "content/common/cursors/webcursor.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" namespace content {
diff --git a/content/browser/renderer_host/input/touch_event_queue.h b/content/browser/renderer_host/input/touch_event_queue.h index 292f3d6..f039e14 100644 --- a/content/browser/renderer_host/input/touch_event_queue.h +++ b/content/browser/renderer_host/input/touch_event_queue.h
@@ -17,7 +17,7 @@ #include "content/browser/renderer_host/event_with_latency_info.h" #include "content/common/content_export.h" #include "content/common/input/input_event_ack_state.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/gfx/geometry/point_f.h" namespace content {
diff --git a/content/browser/renderer_host/input/touch_event_queue_unittest.cc b/content/browser/renderer_host/input/touch_event_queue_unittest.cc index 580e9a78b..d439f21 100644 --- a/content/browser/renderer_host/input/touch_event_queue_unittest.cc +++ b/content/browser/renderer_host/input/touch_event_queue_unittest.cc
@@ -19,7 +19,7 @@ #include "content/common/input/synthetic_web_input_event_builders.h" #include "content/common/input/web_touch_event_traits.h" #include "testing/gtest/include/gtest/gtest.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" using blink::WebGestureEvent; using blink::WebInputEvent;
diff --git a/content/browser/renderer_host/input/touch_input_browsertest.cc b/content/browser/renderer_host/input/touch_input_browsertest.cc index 9ee782e..05a0505 100644 --- a/content/browser/renderer_host/input/touch_input_browsertest.cc +++ b/content/browser/renderer_host/input/touch_input_browsertest.cc
@@ -23,7 +23,7 @@ #include "content/public/test/content_browser_test.h" #include "content/public/test/content_browser_test_utils.h" #include "content/shell/browser/shell.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/event_switches.h" #include "ui/events/latency_info.h"
diff --git a/content/browser/renderer_host/input/touchpad_tap_suppression_controller.h b/content/browser/renderer_host/input/touchpad_tap_suppression_controller.h index 4971963..1934ad6 100644 --- a/content/browser/renderer_host/input/touchpad_tap_suppression_controller.h +++ b/content/browser/renderer_host/input/touchpad_tap_suppression_controller.h
@@ -10,7 +10,7 @@ #include "content/browser/renderer_host/input/tap_suppression_controller.h" #include "content/browser/renderer_host/input/tap_suppression_controller_client.h" #include "content/common/content_export.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" namespace content {
diff --git a/content/browser/renderer_host/input/web_input_event_builders_android.h b/content/browser/renderer_host/input/web_input_event_builders_android.h index 1d8e0bc..ffba982 100644 --- a/content/browser/renderer_host/input/web_input_event_builders_android.h +++ b/content/browser/renderer_host/input/web_input_event_builders_android.h
@@ -9,7 +9,8 @@ #include "base/android/scoped_java_ref.h" #include "content/common/content_export.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" namespace content {
diff --git a/content/browser/renderer_host/input/web_input_event_builders_android_unittest.cc b/content/browser/renderer_host/input/web_input_event_builders_android_unittest.cc index d5cbebd..1edee9b 100644 --- a/content/browser/renderer_host/input/web_input_event_builders_android_unittest.cc +++ b/content/browser/renderer_host/input/web_input_event_builders_android_unittest.cc
@@ -9,7 +9,7 @@ #include "base/android/jni_android.h" #include "testing/gtest/include/gtest/gtest.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/android/key_event_utils.h" #include "ui/events/gesture_detection/motion_event.h" #include "ui/events/keycodes/dom/dom_code.h"
diff --git a/content/browser/renderer_host/input/web_input_event_builders_mac.h b/content/browser/renderer_host/input/web_input_event_builders_mac.h index dbab1d8..03a3d6ca 100644 --- a/content/browser/renderer_host/input/web_input_event_builders_mac.h +++ b/content/browser/renderer_host/input/web_input_event_builders_mac.h
@@ -6,7 +6,8 @@ #define CONTENT_BROWSER_RENDERER_HOST_INPUT_WEB_INPUT_EVENT_BUILDERS_MAC_H_ #include "content/common/content_export.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" @class NSEvent; @class NSView;
diff --git a/content/browser/renderer_host/input/web_input_event_builders_mac.mm b/content/browser/renderer_host/input/web_input_event_builders_mac.mm index ebc3fa5..41a9d27 100644 --- a/content/browser/renderer_host/input/web_input_event_builders_mac.mm +++ b/content/browser/renderer_host/input/web_input_event_builders_mac.mm
@@ -37,7 +37,7 @@ #include "base/mac/sdk_forward_declarations.h" #include "base/strings/string_util.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/base/cocoa/cocoa_base_utils.h" #include "ui/events/blink/blink_event_util.h" #import "ui/events/cocoa/cocoa_event_utils.h"
diff --git a/content/browser/renderer_host/overscroll_controller.h b/content/browser/renderer_host/overscroll_controller.h index 1d29180..62eca7e 100644 --- a/content/browser/renderer_host/overscroll_controller.h +++ b/content/browser/renderer_host/overscroll_controller.h
@@ -7,7 +7,8 @@ #include "base/compiler_specific.h" #include "base/macros.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" namespace content {
diff --git a/content/browser/renderer_host/render_message_filter.cc b/content/browser/renderer_host/render_message_filter.cc index 78db5e2..9b1c205 100644 --- a/content/browser/renderer_host/render_message_filter.cc +++ b/content/browser/renderer_host/render_message_filter.cc
@@ -340,8 +340,7 @@ uint32_t buffer_size, IPC::Message* reply_msg) { base::SharedMemoryHandle handle; - ChildProcessHostImpl::AllocateSharedMemory(buffer_size, PeerHandle(), - &handle); + ChildProcessHostImpl::AllocateSharedMemory(buffer_size, &handle); ChildProcessHostMsg_SyncAllocateSharedMemory::WriteReplyParams(reply_msg, handle); Send(reply_msg);
diff --git a/content/browser/renderer_host/render_view_host_impl.cc b/content/browser/renderer_host/render_view_host_impl.cc index 68cc3d7..e19736a 100644 --- a/content/browser/renderer_host/render_view_host_impl.cc +++ b/content/browser/renderer_host/render_view_host_impl.cc
@@ -46,7 +46,6 @@ #include "content/browser/renderer_host/render_widget_host_view_base.h" #include "content/common/browser_plugin/browser_plugin_messages.h" #include "content/common/content_switches_internal.h" -#include "content/common/drag_messages.h" #include "content/common/frame_messages.h" #include "content/common/input_messages.h" #include "content/common/inter_process_time_ticks_converter.h" @@ -103,7 +102,6 @@ using base::TimeDelta; using blink::WebConsoleMessage; -using blink::WebDragOperation; using blink::WebInputEvent; using blink::WebMediaPlayerAction; using blink::WebPluginAction; @@ -440,8 +438,6 @@ prefs.user_gesture_required_for_media_playback = !command_line.HasSwitch( switches::kDisableGestureRequirementForMediaPlayback) && (autoplay_group_name.empty() || autoplay_group_name != "Enabled"); - prefs.autoplay_muted_videos_enabled = - base::FeatureList::IsEnabled(features::kAutoplayMutedVideos); prefs.progress_bar_completion = GetProgressBarCompletionPolicy(); @@ -606,19 +602,6 @@ delegate_->RenderViewTerminated(this, status, exit_code); } -void RenderViewHostImpl::DragSourceEndedAt( - int client_x, int client_y, int screen_x, int screen_y, - WebDragOperation operation) { - Send(new DragMsg_SourceEnded(GetRoutingID(), - gfx::Point(client_x, client_y), - gfx::Point(screen_x, screen_y), - operation)); -} - -void RenderViewHostImpl::DragSourceSystemDragEnded() { - Send(new DragMsg_SourceSystemDragEnded(GetRoutingID())); -} - bool RenderViewHostImpl::Send(IPC::Message* msg) { return GetWidget()->Send(msg); } @@ -773,7 +756,6 @@ OnDidContentsPreferredSizeChange) IPC_MESSAGE_HANDLER(ViewHostMsg_RouteCloseEvent, OnRouteCloseEvent) - IPC_MESSAGE_HANDLER(DragHostMsg_UpdateDragCursor, OnUpdateDragCursor) IPC_MESSAGE_HANDLER(ViewHostMsg_TakeFocus, OnTakeFocus) IPC_MESSAGE_HANDLER(ViewHostMsg_FocusedNodeChanged, OnFocusedNodeChanged) IPC_MESSAGE_HANDLER(ViewHostMsg_ClosePage_ACK, OnClosePageACK) @@ -915,12 +897,6 @@ delegate_->RouteCloseEvent(this); } -void RenderViewHostImpl::OnUpdateDragCursor(WebDragOperation current_op) { - RenderViewHostDelegateView* view = delegate_->GetDelegateView(); - if (view) - view->UpdateDragCursor(current_op); -} - void RenderViewHostImpl::OnTakeFocus(bool reverse) { RenderViewHostDelegateView* view = delegate_->GetDelegateView(); if (view)
diff --git a/content/browser/renderer_host/render_view_host_impl.h b/content/browser/renderer_host/render_view_host_impl.h index 8990af9..e8890aa6 100644 --- a/content/browser/renderer_host/render_view_host_impl.h +++ b/content/browser/renderer_host/render_view_host_impl.h
@@ -101,12 +101,6 @@ int request_id, const std::vector<base::FilePath>& files) override; void DisableScrollbarsForThreshold(const gfx::Size& size) override; - void DragSourceEndedAt(int client_x, - int client_y, - int screen_x, - int screen_y, - blink::WebDragOperation operation) override; - void DragSourceSystemDragEnded() override; void EnableAutoResize(const gfx::Size& min_size, const gfx::Size& max_size) override; void DisableAutoResize(const gfx::Size& new_size) override; @@ -265,7 +259,6 @@ void OnDidContentsPreferredSizeChange(const gfx::Size& new_size); void OnPasteFromSelectionClipboard(); void OnRouteCloseEvent(); - void OnUpdateDragCursor(blink::WebDragOperation drag_operation); void OnTakeFocus(bool reverse); void OnFocusedNodeChanged(bool is_editable_node, const gfx::Rect& node_bounds_in_viewport);
diff --git a/content/browser/renderer_host/render_widget_host_delegate.cc b/content/browser/renderer_host/render_widget_host_delegate.cc index 17957ab..3ebbe1b 100644 --- a/content/browser/renderer_host/render_widget_host_delegate.cc +++ b/content/browser/renderer_host/render_widget_host_delegate.cc
@@ -83,4 +83,8 @@ return nullptr; } +bool RenderWidgetHostDelegate::OnUpdateDragCursor() { + return false; +} + } // namespace content
diff --git a/content/browser/renderer_host/render_widget_host_delegate.h b/content/browser/renderer_host/render_widget_host_delegate.h index 09cee961..46129fd 100644 --- a/content/browser/renderer_host/render_widget_host_delegate.h +++ b/content/browser/renderer_host/render_widget_host_delegate.h
@@ -16,7 +16,7 @@ #include "content/public/common/drop_data.h" #include "third_party/WebKit/public/platform/WebDisplayMode.h" #include "third_party/WebKit/public/platform/WebDragOperation.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/gfx/native_widget_types.h" namespace blink { @@ -216,6 +216,9 @@ // fullscreen, and will return nullptr for those cases. virtual RenderWidgetHostImpl* GetFullscreenRenderWidgetHost() const; + // Allow the delegate to handle the cursor update. Returns true if handled. + virtual bool OnUpdateDragCursor(); + protected: virtual ~RenderWidgetHostDelegate() {} };
diff --git a/content/browser/renderer_host/render_widget_host_impl.cc b/content/browser/renderer_host/render_widget_host_impl.cc index aa54fac..7887b5d7 100644 --- a/content/browser/renderer_host/render_widget_host_impl.cc +++ b/content/browser/renderer_host/render_widget_host_impl.cc
@@ -100,6 +100,7 @@ using base::Time; using base::TimeDelta; using base::TimeTicks; +using blink::WebDragOperation; using blink::WebDragOperationsMask; using blink::WebGestureEvent; using blink::WebInputEvent; @@ -545,6 +546,7 @@ OnForwardCompositorProto) IPC_MESSAGE_HANDLER(ViewHostMsg_SetNeedsBeginFrames, OnSetNeedsBeginFrames) IPC_MESSAGE_HANDLER(DragHostMsg_StartDragging, OnStartDragging) + IPC_MESSAGE_HANDLER(DragHostMsg_UpdateDragCursor, OnUpdateDragCursor) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() @@ -1376,6 +1378,19 @@ client_pt, screen_pt, key_modifiers)); } +void RenderWidgetHostImpl::DragSourceEndedAt( + int client_x, int client_y, int screen_x, int screen_y, + blink::WebDragOperation operation) { + Send(new DragMsg_SourceEnded(GetRoutingID(), + gfx::Point(client_x, client_y), + gfx::Point(screen_x, screen_y), + operation)); +} + +void RenderWidgetHostImpl::DragSourceSystemDragEnded() { + Send(new DragMsg_SourceSystemDragEnded(GetRoutingID())); +} + void RenderWidgetHostImpl::FilterDropData(DropData* drop_data) { #if DCHECK_IS_ON() drop_data->view_id = GetRoutingID(); @@ -1471,7 +1486,7 @@ RenderViewHostDelegateView* view = delegate_->GetDelegateView(); if (!view) { // Need to clear drag and drop state in blink. - rvh->DragSourceSystemDragEnded(); + DragSourceSystemDragEnded(); return; } @@ -1514,6 +1529,15 @@ bitmap_offset_in_dip, event_info); } +void RenderWidgetHostImpl::OnUpdateDragCursor(WebDragOperation current_op) { + if (delegate_ && delegate_->OnUpdateDragCursor()) + return; + + RenderViewHostDelegateView* view = delegate_->GetDelegateView(); + if (view) + view->UpdateDragCursor(current_op); +} + void RenderWidgetHostImpl::RendererExited(base::TerminationStatus status, int exit_code) { if (!renderer_initialized_)
diff --git a/content/browser/renderer_host/render_widget_host_impl.h b/content/browser/renderer_host/render_widget_host_impl.h index 7f809291..b465089c 100644 --- a/content/browser/renderer_host/render_widget_host_impl.h +++ b/content/browser/renderer_host/render_widget_host_impl.h
@@ -199,6 +199,12 @@ const gfx::Point& client_pt, const gfx::Point& screen_pt, int key_modifiers) override; + void DragSourceEndedAt(int client_x, + int client_y, + int screen_x, + int screen_y, + blink::WebDragOperation operation) override; + void DragSourceSystemDragEnded() override; void FilterDropData(DropData* drop_data) override; // Notification that the screen info has changed. @@ -637,6 +643,7 @@ const SkBitmap& bitmap, const gfx::Vector2d& bitmap_offset_in_dip, const DragEventSourceInfo& event_info); + void OnUpdateDragCursor(blink::WebDragOperation current_op); // Called (either immediately or asynchronously) after we're done with our // BackingStore and can send an ACK to the renderer so it can paint onto it
diff --git a/content/browser/renderer_host/render_widget_host_input_event_router.cc b/content/browser/renderer_host/render_widget_host_input_event_router.cc index 3603ae2d..48ea0f3 100644 --- a/content/browser/renderer_host/render_widget_host_input_event_router.cc +++ b/content/browser/renderer_host/render_widget_host_input_event_router.cc
@@ -15,7 +15,7 @@ #include "content/browser/renderer_host/render_widget_host_impl.h" #include "content/browser/renderer_host/render_widget_host_view_base.h" #include "content/common/frame_messages.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/blink/web_input_event_traits.h" namespace {
diff --git a/content/browser/renderer_host/render_widget_host_view_aura.cc b/content/browser/renderer_host/render_widget_host_view_aura.cc index c28aca4..e706f46 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura.cc +++ b/content/browser/renderer_host/render_widget_host_view_aura.cc
@@ -56,8 +56,8 @@ #include "content/public/common/child_process_host.h" #include "content/public/common/content_switches.h" #include "gpu/ipc/common/gpu_messages.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/web/WebCompositionUnderline.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/client/cursor_client.h" #include "ui/aura/client/cursor_client_observer.h"
diff --git a/content/browser/renderer_host/render_widget_host_view_mac.mm b/content/browser/renderer_host/render_widget_host_view_mac.mm index f418163..c7a78ff 100644 --- a/content/browser/renderer_host/render_widget_host_view_mac.mm +++ b/content/browser/renderer_host/render_widget_host_view_mac.mm
@@ -67,7 +67,7 @@ #include "gpu/ipc/common/gpu_messages.h" #include "skia/ext/platform_canvas.h" #include "skia/ext/skia_utils_mac.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #import "ui/base/clipboard/clipboard_util_mac.h" #include "ui/base/cocoa/animation_utils.h" #import "ui/base/cocoa/appkit_utils.h" @@ -3017,6 +3017,12 @@ return rect; } +- (NSRange)selectedRange { + if (selectedRange_.location == NSNotFound) + return NSMakeRange(NSNotFound, 0); + return selectedRange_; +} + - (NSRange)markedRange { // An input method calls this method to check if an application really has // a text being composed when hasMarkedText call returns true. @@ -3029,9 +3035,17 @@ - (NSAttributedString*)attributedSubstringForProposedRange:(NSRange)range actualRange:(NSRangePointer)actualRange { - // TODO(thakis): Pipe |actualRange| through TextInputClientMac machinery. + // Prepare |actualRange| as if the proposed range is invalid. If it is valid, + // then |actualRange| will be updated again. if (actualRange) - *actualRange = range; + *actualRange = NSMakeRange(NSNotFound, 0); + + // The caller of this method is allowed to pass nonsensical ranges. These + // can't even be converted into gfx::Ranges. + if (range.location == NSNotFound || range.length == 0) + return nil; + if (range.length >= std::numeric_limits<NSUInteger>::max() - range.location) + return nil; const gfx::Range requested_range(range); if (requested_range.is_reversed()) @@ -3049,15 +3063,16 @@ expected_range = gfx::Range(offset, offset + expected_text->size()); } - if (!expected_range.Contains(requested_range)) + gfx::Range actual_range = expected_range.Intersect(requested_range); + if (!actual_range.IsValid()) return nil; // Gets the raw bytes to avoid unnecessary string copies for generating // NSString. const base::char16* bytes = - &(*expected_text)[requested_range.start() - expected_range.start()]; + &(*expected_text)[actual_range.start() - expected_range.start()]; // Avoid integer overflow. - base::CheckedNumeric<size_t> requested_len = requested_range.length(); + base::CheckedNumeric<size_t> requested_len = actual_range.length(); requested_len *= sizeof(base::char16); NSUInteger bytes_len = base::strict_cast<NSUInteger, size_t>( requested_len.ValueOrDefault(0)); @@ -3065,6 +3080,9 @@ [[NSString alloc] initWithBytes:bytes length:bytes_len encoding:NSUTF16LittleEndianStringEncoding]); + if (actualRange) + *actualRange = actual_range.ToNSRange(); + return [[[NSAttributedString alloc] initWithString:ns_string] autorelease]; }
diff --git a/content/browser/renderer_host/render_widget_host_view_mac_unittest.mm b/content/browser/renderer_host/render_widget_host_view_mac_unittest.mm index d98d707a..50dcc692 100644 --- a/content/browser/renderer_host/render_widget_host_view_mac_unittest.mm +++ b/content/browser/renderer_host/render_widget_host_view_mac_unittest.mm
@@ -317,6 +317,29 @@ EXPECT_TRUE([rwhv_cocoa_.get() acceptsFirstResponder]); } +// This test verifies that RenderWidgetHostViewCocoa's implementation of +// NSTextInputClientConformance conforms to requirements. +TEST_F(RenderWidgetHostViewMacTest, NSTextInputClientConformance) { + NSRange selectedRange = [rwhv_cocoa_ selectedRange]; + EXPECT_EQ(0u, selectedRange.location); + EXPECT_EQ(0u, selectedRange.length); + + NSRange actualRange = NSMakeRange(1u, 2u); + NSAttributedString* actualString = [rwhv_cocoa_ + attributedSubstringForProposedRange:NSMakeRange(NSNotFound, 0u) + actualRange:&actualRange]; + EXPECT_EQ(nil, actualString); + EXPECT_EQ(NSNotFound, actualRange.location); + EXPECT_EQ(0u, actualRange.length); + + actualString = [rwhv_cocoa_ + attributedSubstringForProposedRange:NSMakeRange(NSNotFound, 15u) + actualRange:&actualRange]; + EXPECT_EQ(nil, actualString); + EXPECT_EQ(NSNotFound, actualRange.location); + EXPECT_EQ(0u, actualRange.length); +} + TEST_F(RenderWidgetHostViewMacTest, Fullscreen) { rwhv_mac_->InitAsFullscreen(NULL); EXPECT_TRUE(rwhv_mac_->pepper_fullscreen_window());
diff --git a/content/browser/renderer_host/ui_events_helper.cc b/content/browser/renderer_host/ui_events_helper.cc index 38c2b28b..01fbe15 100644 --- a/content/browser/renderer_host/ui_events_helper.cc +++ b/content/browser/renderer_host/ui_events_helper.cc
@@ -7,7 +7,7 @@ #include <stdint.h> #include "content/common/input/web_touch_event_traits.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/base_event_utils.h" #include "ui/events/blink/blink_event_util.h" #include "ui/events/event.h"
diff --git a/content/browser/site_per_process_browsertest.cc b/content/browser/site_per_process_browsertest.cc index 19f96d6..35c6b59 100644 --- a/content/browser/site_per_process_browsertest.cc +++ b/content/browser/site_per_process_browsertest.cc
@@ -60,8 +60,8 @@ #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/platform/WebInsecureRequestPolicy.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" #include "third_party/WebKit/public/web/WebSandboxFlags.h" #include "ui/display/display_switches.h" #include "ui/display/screen.h"
diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc index 367951ac..b3b4e82 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc
@@ -2488,6 +2488,12 @@ return text_input_manager_.get(); } +bool WebContentsImpl::OnUpdateDragCursor() { + if (browser_plugin_embedder_) + return browser_plugin_embedder_->OnUpdateDragCursor(); + return false; +} + BrowserAccessibilityManager* WebContentsImpl::GetRootBrowserAccessibilityManager() { RenderFrameHostImpl* rfh = GetMainFrame(); @@ -2953,14 +2959,19 @@ Close(GetRenderViewHost()); } -void WebContentsImpl::DragSourceEndedAt(int client_x, int client_y, - int screen_x, int screen_y, blink::WebDragOperation operation) { +void WebContentsImpl::DragSourceEndedAt(int client_x, + int client_y, + int screen_x, + int screen_y, + blink::WebDragOperation operation) { if (browser_plugin_embedder_.get()) - browser_plugin_embedder_->DragSourceEndedAt(client_x, client_y, - screen_x, screen_y, operation); + browser_plugin_embedder_->DragSourceEndedAt( + client_x, client_y, screen_x, screen_y, operation); + // TODO(paulmeyer): This will need to target the correct specific RWH to work + // with OOPIF. if (GetRenderViewHost()) - GetRenderViewHost()->DragSourceEndedAt(client_x, client_y, screen_x, - screen_y, operation); + GetRenderViewHost()->GetWidget()->DragSourceEndedAt( + client_x, client_y, screen_x, screen_y, operation); } void WebContentsImpl::LoadStateChanged( @@ -3012,8 +3023,10 @@ } void WebContentsImpl::SystemDragEnded() { + // TODO(paulmeyer): This will need to target the correct specific RWH to work + // with OOPIF. if (GetRenderViewHost()) - GetRenderViewHost()->DragSourceSystemDragEnded(); + GetRenderViewHost()->GetWidget()->DragSourceSystemDragEnded(); if (browser_plugin_embedder_.get()) browser_plugin_embedder_->SystemDragEnded(); }
diff --git a/content/browser/web_contents/web_contents_impl.h b/content/browser/web_contents/web_contents_impl.h index 91349dc..358b8a6a 100644 --- a/content/browser/web_contents/web_contents_impl.h +++ b/content/browser/web_contents/web_contents_impl.h
@@ -183,8 +183,11 @@ // Informs the render view host and the BrowserPluginEmbedder, if present, of // a Drag Source End. - void DragSourceEndedAt(int client_x, int client_y, int screen_x, - int screen_y, blink::WebDragOperation operation); + void DragSourceEndedAt(int client_x, + int client_y, + int screen_x, + int screen_y, + blink::WebDragOperation operation); // Notification that the RenderViewHost's load state changed. void LoadStateChanged(const GURL& url, @@ -662,6 +665,7 @@ void SendScreenRects() override; void OnFirstPaintAfterLoad(RenderWidgetHostImpl* render_widget_host) override; TextInputManager* GetTextInputManager() override; + bool OnUpdateDragCursor() override; // RenderFrameHostManager::Delegate ------------------------------------------
diff --git a/content/browser/web_contents/web_contents_view_android.cc b/content/browser/web_contents/web_contents_view_android.cc index 49a6e02..92ec947 100644 --- a/content/browser/web_contents/web_contents_view_android.cc +++ b/content/browser/web_contents/web_contents_view_android.cc
@@ -342,7 +342,7 @@ } void WebContentsViewAndroid::OnDragEnded() { - web_contents_->GetRenderViewHost()->DragSourceSystemDragEnded(); + web_contents_->GetRenderViewHost()->GetWidget()->DragSourceSystemDragEnded(); } void WebContentsViewAndroid::GotFocus() {
diff --git a/content/browser/web_contents/web_contents_view_aura.cc b/content/browser/web_contents/web_contents_view_aura.cc index bbbff9c43..dc643ee 100644 --- a/content/browser/web_contents/web_contents_view_aura.cc +++ b/content/browser/web_contents/web_contents_view_aura.cc
@@ -44,7 +44,7 @@ #include "content/public/common/content_switches.h" #include "content/public/common/drop_data.h" #include "net/base/filename_util.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/client/drag_drop_client.h" #include "ui/aura/client/drag_drop_delegate.h"
diff --git a/content/browser/web_contents/web_drag_dest_mac.mm b/content/browser/web_contents/web_drag_dest_mac.mm index efeaa5cd..9655f41a 100644 --- a/content/browser/web_contents/web_drag_dest_mac.mm +++ b/content/browser/web_contents/web_drag_dest_mac.mm
@@ -12,7 +12,7 @@ #include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_drag_dest_delegate.h" #include "content/public/common/drop_data.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #import "third_party/mozilla/NSPasteboard+Utils.h" #include "ui/base/clipboard/custom_data_helper.h" #include "ui/base/cocoa/cocoa_base_utils.h"
diff --git a/content/browser/webui/content_web_ui_controller_factory.cc b/content/browser/webui/content_web_ui_controller_factory.cc index bd5a9ae..1e52bc29 100644 --- a/content/browser/webui/content_web_ui_controller_factory.cc +++ b/content/browser/webui/content_web_ui_controller_factory.cc
@@ -29,17 +29,17 @@ if (!url.SchemeIs(kChromeUIScheme)) return WebUI::kNoWebUI; - if (url.host() == kChromeUIWebRTCInternalsHost || + if (url.host_piece() == kChromeUIWebRTCInternalsHost || #if !defined(OS_ANDROID) - url.host() == kChromeUITracingHost || + url.host_piece() == kChromeUITracingHost || #endif - url.host() == kChromeUIGpuHost || - url.host() == kChromeUIIndexedDBInternalsHost || - url.host() == kChromeUIMediaInternalsHost || - url.host() == kChromeUIServiceWorkerInternalsHost || - url.host() == kChromeUIAccessibilityHost || - url.host() == kChromeUIAppCacheInternalsHost || - url.host() == kChromeUINetworkErrorsListingHost) { + url.host_piece() == kChromeUIGpuHost || + url.host_piece() == kChromeUIIndexedDBInternalsHost || + url.host_piece() == kChromeUIMediaInternalsHost || + url.host_piece() == kChromeUIServiceWorkerInternalsHost || + url.host_piece() == kChromeUIAccessibilityHost || + url.host_piece() == kChromeUIAppCacheInternalsHost || + url.host_piece() == kChromeUINetworkErrorsListingHost) { return const_cast<ContentWebUIControllerFactory*>(this); } return WebUI::kNoWebUI; @@ -60,27 +60,27 @@ if (!url.SchemeIs(kChromeUIScheme)) return nullptr; - if (url.host() == kChromeUIAppCacheInternalsHost) + if (url.host_piece() == kChromeUIAppCacheInternalsHost) return new AppCacheInternalsUI(web_ui); - if (url.host() == kChromeUIGpuHost) + if (url.host_piece() == kChromeUIGpuHost) return new GpuInternalsUI(web_ui); - if (url.host() == kChromeUIIndexedDBInternalsHost) + if (url.host_piece() == kChromeUIIndexedDBInternalsHost) return new IndexedDBInternalsUI(web_ui); - if (url.host() == kChromeUIMediaInternalsHost) + if (url.host_piece() == kChromeUIMediaInternalsHost) return new MediaInternalsUI(web_ui); - if (url.host() == kChromeUIAccessibilityHost) + if (url.host_piece() == kChromeUIAccessibilityHost) return new AccessibilityUI(web_ui); - if (url.host() == kChromeUIServiceWorkerInternalsHost) + if (url.host_piece() == kChromeUIServiceWorkerInternalsHost) return new ServiceWorkerInternalsUI(web_ui); - if (url.host() == kChromeUINetworkErrorsListingHost) + if (url.host_piece() == kChromeUINetworkErrorsListingHost) return new NetworkErrorsListingUI(web_ui); #if !defined(OS_ANDROID) - if (url.host() == kChromeUITracingHost) + if (url.host_piece() == kChromeUITracingHost) return new TracingUI(web_ui); #endif #if defined(ENABLE_WEBRTC) - if (url.host() == kChromeUIWebRTCInternalsHost) + if (url.host_piece() == kChromeUIWebRTCInternalsHost) return new WebRTCInternalsUI(web_ui); #endif
diff --git a/content/browser/webui/url_data_manager_backend.cc b/content/browser/webui/url_data_manager_backend.cc index 92e84b1..72c035a2 100644 --- a/content/browser/webui/url_data_manager_backend.cc +++ b/content/browser/webui/url_data_manager_backend.cc
@@ -560,13 +560,13 @@ // Next check for chrome://histograms/, which uses its own job type. if (request->url().SchemeIs(kChromeUIScheme) && - request->url().host() == kChromeUIHistogramHost) { + request->url().host_piece() == kChromeUIHistogramHost) { return new HistogramInternalsRequestJob(request, network_delegate); } // Check for chrome://network-error/, which uses its own job type. if (request->url().SchemeIs(kChromeUIScheme) && - request->url().host() == kChromeUINetworkErrorHost) { + request->url().host_piece() == kChromeUINetworkErrorHost) { // Get the error code passed in via the request URL path. std::basic_string<char> error_code_string = request->url().path().substr(1);
diff --git a/content/child/BUILD.gn b/content/child/BUILD.gn index 93caaaa..ffbe01c 100644 --- a/content/child/BUILD.gn +++ b/content/child/BUILD.gn
@@ -4,6 +4,7 @@ import("//build/config/features.gni") import("//build/config/ui.gni") +import("//third_party/WebKit/public/public_features.gni") if (is_component_build) { link_target_type = "source_set" @@ -244,6 +245,7 @@ "//skia", "//storage/common", "//third_party/WebKit/public:blink_headers", + "//third_party/WebKit/public:features", "//third_party/WebKit/public:image_resources", "//third_party/WebKit/public:resources", "//third_party/ced",
diff --git a/content/child/blink_platform_impl.h b/content/child/blink_platform_impl.h index 5ee5049d..5444851 100644 --- a/content/child/blink_platform_impl.h +++ b/content/child/blink_platform_impl.h
@@ -20,9 +20,10 @@ #include "third_party/WebKit/public/platform/Platform.h" #include "third_party/WebKit/public/platform/WebGestureDevice.h" #include "third_party/WebKit/public/platform/WebURLError.h" +#include "third_party/WebKit/public/public_features.h" #include "ui/base/layout.h" -#if defined(USE_DEFAULT_RENDER_THEME) +#if BUILDFLAG(USE_DEFAULT_RENDER_THEME) #include "content/child/webthemeengine_impl_default.h" #elif defined(OS_WIN) #include "content/child/webthemeengine_impl_win.h"
diff --git a/content/child/indexed_db/indexed_db_database_callbacks_impl.cc b/content/child/indexed_db/indexed_db_database_callbacks_impl.cc index 4eab2f9..1ae0b2d0 100644 --- a/content/child/indexed_db/indexed_db_database_callbacks_impl.cc +++ b/content/child/indexed_db/indexed_db_database_callbacks_impl.cc
@@ -23,6 +23,13 @@ delete callbacks; } +void BuildErrorAndAbort(WebIDBDatabaseCallbacks* callbacks, + int64_t transaction_id, + int32_t code, + const base::string16& message) { + callbacks->onAbort(transaction_id, blink::WebIDBDatabaseError(code, message)); +} + } // namespace IndexedDBDatabaseCallbacksImpl::IndexedDBDatabaseCallbacksImpl( @@ -59,10 +66,11 @@ void IndexedDBDatabaseCallbacksImpl::Abort(int64_t transaction_id, int32_t code, const base::string16& message) { + // Indirect through BuildErrorAndAbort because it isn't safe to pass a + // WebIDBDatabaseError between threads. callback_runner_->PostTask( - FROM_HERE, base::Bind(&WebIDBDatabaseCallbacks::onAbort, - base::Unretained(callbacks_), transaction_id, - blink::WebIDBDatabaseError(code, message))); + FROM_HERE, base::Bind(&BuildErrorAndAbort, base::Unretained(callbacks_), + transaction_id, code, message)); } void IndexedDBDatabaseCallbacksImpl::Complete(int64_t transaction_id) {
diff --git a/content/child/runtime_features.cc b/content/child/runtime_features.cc index 66d67814..f12082f 100644 --- a/content/child/runtime_features.cc +++ b/content/child/runtime_features.cc
@@ -41,6 +41,7 @@ WebRuntimeFeatures::enableNotificationConstructor(false); // Android does not yet support switching of audio output devices WebRuntimeFeatures::enableAudioOutputDevices(false); + WebRuntimeFeatures::enableAutoplayMutedVideos(true); #else WebRuntimeFeatures::enableNavigatorContentUtils(true); #endif // defined(OS_ANDROID) @@ -260,8 +261,8 @@ if (base::FeatureList::IsEnabled(features::kPointerEventV1SpecCapturing)) WebRuntimeFeatures::enablePointerEventV1SpecCapturing(true); - if (base::FeatureList::IsEnabled(features::kPassiveDocumentEventListeners)) - WebRuntimeFeatures::enablePassiveDocumentEventListeners(true); + WebRuntimeFeatures::enablePassiveDocumentEventListeners( + base::FeatureList::IsEnabled(features::kPassiveDocumentEventListeners)); if (base::FeatureList::IsEnabled(features::kPassiveEventListenersDueToFling)) WebRuntimeFeatures::enablePassiveEventListenersDueToFling(true);
diff --git a/content/common/DEPS b/content/common/DEPS index c00eeb5f..66adccce 100644 --- a/content/common/DEPS +++ b/content/common/DEPS
@@ -18,8 +18,10 @@ "+third_party/WebKit/public/platform/WebFocusType.h", "+third_party/WebKit/public/platform/WebGamepad.h", "+third_party/WebKit/public/platform/WebGamepads.h", + "+third_party/WebKit/public/platform/WebGestureEvent.h", "+third_party/WebKit/public/platform/WebHTTPBody.h", "+third_party/WebKit/public/platform/WebHistoryScrollRestorationType.h", + "+third_party/WebKit/public/platform/WebInputEvent.h", "+third_party/WebKit/public/platform/WebInsecureRequestPolicy.h", "+third_party/WebKit/public/platform/WebOriginTrialTokenStatus.h", "+third_party/WebKit/public/platform/WebPageVisibilityState.h", @@ -58,7 +60,6 @@ "+third_party/WebKit/public/web/WebFindOptions.h", "+third_party/WebKit/public/web/WebFrameOwnerProperties.h", "+third_party/WebKit/public/web/WebFrameSerializerCacheControlPolicy.h", - "+third_party/WebKit/public/web/WebInputEvent.h", "+third_party/WebKit/public/web/WebMediaPlayerAction.h", "+third_party/WebKit/public/web/WebPluginAction.h", "+third_party/WebKit/public/web/WebPopupType.h",
diff --git a/content/common/android/sync_compositor_messages.h b/content/common/android/sync_compositor_messages.h index 5ef13bf..b8c6494 100644 --- a/content/common/android/sync_compositor_messages.h +++ b/content/common/android/sync_compositor_messages.h
@@ -12,7 +12,7 @@ #include "content/common/content_param_traits.h" #include "content/common/input/input_event_ack_state.h" #include "ipc/ipc_message_macros.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/scroll_offset.h"
diff --git a/content/common/child_process_host_impl.cc b/content/common/child_process_host_impl.cc index 71a34fc..a5c4e5ad 100644 --- a/content/common/child_process_host_impl.cc +++ b/content/common/child_process_host_impl.cc
@@ -186,7 +186,7 @@ } void ChildProcessHostImpl::AllocateSharedMemory( - size_t buffer_size, base::ProcessHandle child_process_handle, + size_t buffer_size, base::SharedMemoryHandle* shared_memory_handle) { base::SharedMemory shared_buf; if (!shared_buf.CreateAnonymous(buffer_size)) { @@ -194,7 +194,7 @@ NOTREACHED() << "Cannot create shared memory buffer"; return; } - shared_buf.GiveToProcess(child_process_handle, shared_memory_handle); + *shared_memory_handle = shared_buf.TakeHandle(); } int ChildProcessHostImpl::GenerateChildProcessUniqueId() { @@ -274,7 +274,7 @@ #ifdef IPC_MESSAGE_LOG_ENABLED if (logger->Enabled()) - logger->OnPostDispatchMessage(msg, channel_id_); + logger->OnPostDispatchMessage(msg); #endif return handled; } @@ -310,7 +310,7 @@ void ChildProcessHostImpl::OnAllocateSharedMemory( uint32_t buffer_size, base::SharedMemoryHandle* handle) { - AllocateSharedMemory(buffer_size, peer_process_.Handle(), handle); + AllocateSharedMemory(buffer_size, handle); } void ChildProcessHostImpl::OnShutdownRequest() { @@ -332,7 +332,7 @@ // sure |usage| is supported here. if (gpu::GpuMemoryBufferImplSharedMemory::IsUsageSupported(usage)) { *handle = gpu::GpuMemoryBufferImplSharedMemory::AllocateForChildProcess( - id, gfx::Size(width, height), format, peer_process_.Handle()); + id, gfx::Size(width, height), format); } }
diff --git a/content/common/child_process_host_impl.h b/content/common/child_process_host_impl.h index 2cd9967..a45eb6f 100644 --- a/content/common/child_process_host_impl.h +++ b/content/common/child_process_host_impl.h
@@ -43,7 +43,7 @@ // Public and static for reuse by RenderMessageFilter. static void AllocateSharedMemory( - size_t buffer_size, base::ProcessHandle child_process, + size_t buffer_size, base::SharedMemoryHandle* handle); // Returns a unique ID to identify a child process. On construction, this
diff --git a/content/common/content_param_traits.h b/content/common/content_param_traits.h index 8893fce..5ce29da 100644 --- a/content/common/content_param_traits.h +++ b/content/common/content_param_traits.h
@@ -16,7 +16,7 @@ #include "content/common/content_param_traits_macros.h" #include "content/common/cursors/webcursor.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" namespace IPC {
diff --git a/content/common/content_param_traits_macros.h b/content/common/content_param_traits_macros.h index f7521f0..40767e9 100644 --- a/content/common/content_param_traits_macros.h +++ b/content/common/content_param_traits_macros.h
@@ -15,10 +15,10 @@ #include "content/public/common/resource_type.h" #include "ipc/ipc_message_macros.h" #include "third_party/WebKit/public/platform/WebAddressSpace.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/platform/WebPageVisibilityState.h" #include "third_party/WebKit/public/web/WebCompositionUnderline.h" #include "third_party/WebKit/public/web/WebContentSecurityPolicy.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" #include "third_party/WebKit/public/web/WebSharedWorkerCreationContextType.h" #include "ui/gfx/gpu_memory_buffer.h"
diff --git a/content/common/frame_messages.h b/content/common/frame_messages.h index 5d0a671..cd2e4ee 100644 --- a/content/common/frame_messages.h +++ b/content/common/frame_messages.h
@@ -212,8 +212,6 @@ IPC_STRUCT_TRAITS_MEMBER(transition) IPC_STRUCT_TRAITS_MEMBER(redirects) IPC_STRUCT_TRAITS_MEMBER(should_update_history) - IPC_STRUCT_TRAITS_MEMBER(searchable_form_url) - IPC_STRUCT_TRAITS_MEMBER(searchable_form_encoding) IPC_STRUCT_TRAITS_MEMBER(contents_mime_type) IPC_STRUCT_TRAITS_MEMBER(socket_address) IPC_STRUCT_TRAITS_END() @@ -300,6 +298,12 @@ // True if the navigation originated as an srcdoc attribute. IPC_STRUCT_MEMBER(bool, is_srcdoc) + + // See WebSearchableFormData for a description of these. + // Not used by PlzNavigate: in that case these fields are sent to the browser + // in BeginNavigationParams. + IPC_STRUCT_MEMBER(GURL, searchable_form_url) + IPC_STRUCT_MEMBER(std::string, searchable_form_encoding) IPC_STRUCT_END() IPC_STRUCT_BEGIN(FrameMsg_PostMessage_Params) @@ -350,6 +354,8 @@ IPC_STRUCT_TRAITS_MEMBER(has_user_gesture) IPC_STRUCT_TRAITS_MEMBER(skip_service_worker) IPC_STRUCT_TRAITS_MEMBER(request_context_type) + IPC_STRUCT_TRAITS_MEMBER(searchable_form_url) + IPC_STRUCT_TRAITS_MEMBER(searchable_form_encoding) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(content::StartNavigationParams)
diff --git a/content/common/input/event_with_latency_info.h b/content/common/input/event_with_latency_info.h index 021b3bf..541b7ce4 100644 --- a/content/common/input/event_with_latency_info.h +++ b/content/common/input/event_with_latency_info.h
@@ -8,7 +8,8 @@ #include "base/compiler_specific.h" #include "base/logging.h" #include "content/common/content_export.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/blink/scoped_web_input_event.h" #include "ui/events/latency_info.h"
diff --git a/content/common/input/event_with_latency_info_unittest.cc b/content/common/input/event_with_latency_info_unittest.cc index ca6baef..5cd7030 100644 --- a/content/common/input/event_with_latency_info_unittest.cc +++ b/content/common/input/event_with_latency_info_unittest.cc
@@ -7,7 +7,7 @@ #include <limits> #include "testing/gtest/include/gtest/gtest.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" using blink::WebGestureEvent; using blink::WebInputEvent;
diff --git a/content/common/input/gesture_event_stream_validator.cc b/content/common/input/gesture_event_stream_validator.cc index ef80824..14028ca0 100644 --- a/content/common/input/gesture_event_stream_validator.cc +++ b/content/common/input/gesture_event_stream_validator.cc
@@ -6,7 +6,7 @@ #include "base/logging.h" #include "base/strings/stringprintf.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/blink/web_input_event_traits.h" using blink::WebInputEvent;
diff --git a/content/common/input/input_event_ack.h b/content/common/input/input_event_ack.h index 9540183..132ce7e9 100644 --- a/content/common/input/input_event_ack.h +++ b/content/common/input/input_event_ack.h
@@ -12,7 +12,7 @@ #include "content/common/content_export.h" #include "content/common/input/input_event_ack_source.h" #include "content/common/input/input_event_ack_state.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/blink/did_overscroll_params.h" #include "ui/events/latency_info.h"
diff --git a/content/common/input/input_event_stream_validator.cc b/content/common/input/input_event_stream_validator.cc index 1a1ffd36..8025fb8d 100644 --- a/content/common/input/input_event_stream_validator.cc +++ b/content/common/input/input_event_stream_validator.cc
@@ -7,7 +7,7 @@ #include "base/command_line.h" #include "base/logging.h" #include "content/public/common/content_switches.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/blink/web_input_event_traits.h" using blink::WebInputEvent;
diff --git a/content/common/input/input_param_traits_unittest.cc b/content/common/input/input_param_traits_unittest.cc index 01acafc..dfcdbff8 100644 --- a/content/common/input/input_param_traits_unittest.cc +++ b/content/common/input/input_param_traits_unittest.cc
@@ -17,7 +17,8 @@ #include "content/common/input_messages.h" #include "ipc/ipc_message.h" #include "testing/gtest/include/gtest/gtest.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" namespace content { namespace {
diff --git a/content/common/input/synthetic_web_input_event_builders.h b/content/common/input/synthetic_web_input_event_builders.h index 034ee49c..22558c9 100644 --- a/content/common/input/synthetic_web_input_event_builders.h +++ b/content/common/input/synthetic_web_input_event_builders.h
@@ -7,7 +7,8 @@ #include "base/time/time.h" #include "content/common/content_export.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" // Provides sensible creation of default WebInputEvents for testing purposes.
diff --git a/content/common/input/touch_event_stream_validator.h b/content/common/input/touch_event_stream_validator.h index 7cd6aa02..c58ab76 100644 --- a/content/common/input/touch_event_stream_validator.h +++ b/content/common/input/touch_event_stream_validator.h
@@ -9,7 +9,7 @@ #include "base/macros.h" #include "content/common/content_export.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" namespace content {
diff --git a/content/common/input/web_touch_event_traits.h b/content/common/input/web_touch_event_traits.h index 1f974ae..1cbe804 100644 --- a/content/common/input/web_touch_event_traits.h +++ b/content/common/input/web_touch_event_traits.h
@@ -6,7 +6,7 @@ #define CONTENT_COMMON_INPUT_WEB_TOUCH_EVENT_TRAITS_H_ #include "content/common/content_export.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/blink/scoped_web_input_event.h" namespace content {
diff --git a/content/common/input_messages.h b/content/common/input_messages.h index 1be02e1..ba3c213 100644 --- a/content/common/input_messages.h +++ b/content/common/input_messages.h
@@ -26,7 +26,7 @@ #include "content/common/input/synthetic_tap_gesture_params.h" #include "content/common/input/touch_action.h" #include "ipc/ipc_message_macros.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/blink/did_overscroll_params.h" #include "ui/events/ipc/latency_info_param_traits.h" #include "ui/gfx/geometry/point.h"
diff --git a/content/common/navigation_params.h b/content/common/navigation_params.h index ec5ec4191..98757a73 100644 --- a/content/common/navigation_params.h +++ b/content/common/navigation_params.h
@@ -163,6 +163,10 @@ // Indicates the request context type. RequestContextType request_context_type; + + // See WebSearchableFormData for a description of these. + GURL searchable_form_url; + std::string searchable_form_encoding; }; // Provided by the browser -----------------------------------------------------
diff --git a/content/public/browser/android/browser_media_player_manager_register.cc b/content/public/browser/android/browser_media_player_manager_register.cc index e151332..8362da59 100644 --- a/content/public/browser/android/browser_media_player_manager_register.cc +++ b/content/public/browser/android/browser_media_player_manager_register.cc
@@ -10,6 +10,9 @@ void RegisterMediaUrlInterceptor( media::MediaUrlInterceptor* media_url_interceptor) { + // TODO(tguilbert): Update this filename and the registration method to use + // MediaPlayerRenderer::RegisterMediaUrlInterceptor when turning on the + // MediaPlayerRenderer by default. See crbug.com/619729. content::BrowserMediaPlayerManager::RegisterMediaUrlInterceptor( media_url_interceptor); }
diff --git a/content/public/browser/native_web_keyboard_event.h b/content/public/browser/native_web_keyboard_event.h index c31681e..5f77ca8 100644 --- a/content/public/browser/native_web_keyboard_event.h +++ b/content/public/browser/native_web_keyboard_event.h
@@ -9,7 +9,7 @@ #include "base/strings/string16.h" #include "build/build_config.h" #include "content/common/content_export.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/gfx/native_widget_types.h" #if defined(OS_ANDROID)
diff --git a/content/public/browser/navigation_handle.h b/content/public/browser/navigation_handle.h index b6ae5c7..f2506c8 100644 --- a/content/public/browser/navigation_handle.h +++ b/content/public/browser/navigation_handle.h
@@ -94,6 +94,11 @@ // Whether or not the navigation was started within a context menu. virtual bool WasStartedFromContextMenu() const = 0; + // Returns the URL and encoding of an INPUT field that corresponds to a + // searchable form request. + virtual const GURL& GetSearchableFormURL() = 0; + virtual const std::string& GetSearchableFormEncoding() = 0; + // Parameters available at network request start time ------------------------ // // The following parameters are only available when the network request is
diff --git a/content/public/browser/render_view_host.h b/content/public/browser/render_view_host.h index bcdb2e33..5976eec 100644 --- a/content/public/browser/render_view_host.h +++ b/content/public/browser/render_view_host.h
@@ -105,16 +105,6 @@ // threshold. virtual void DisableScrollbarsForThreshold(const gfx::Size& size) = 0; - // Notifies the renderer that a a drag operation that it started has ended, - // either in a drop or by being cancelled. - virtual void DragSourceEndedAt( - int client_x, int client_y, int screen_x, int screen_y, - blink::WebDragOperation operation) = 0; - - // Notifies the renderer that we're done with the drag and drop operation. - // This allows the renderer to reset some state. - virtual void DragSourceSystemDragEnded() = 0; - // Instructs the RenderView to automatically resize and send back updates // for the new size. virtual void EnableAutoResize(const gfx::Size& min_size,
diff --git a/content/public/browser/render_widget_host.h b/content/public/browser/render_widget_host.h index 2c6c7c36..f1e4984 100644 --- a/content/public/browser/render_widget_host.h +++ b/content/public/browser/render_widget_host.h
@@ -15,7 +15,8 @@ #include "ipc/ipc_channel.h" #include "ipc/ipc_sender.h" #include "third_party/WebKit/public/platform/WebDragOperation.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/web/WebTextDirection.h" #include "third_party/skia/include/core/SkImageInfo.h" #include "ui/gfx/geometry/size.h" @@ -284,6 +285,16 @@ const gfx::Point& screen_pt, int key_modifiers) {} + // Notifies the renderer that a a drag operation that it started has ended, + // either in a drop or by being cancelled. + virtual void DragSourceEndedAt( + int client_x, int client_y, int screen_x, int screen_y, + blink::WebDragOperation operation) {}; + + // Notifies the renderer that we're done with the drag and drop operation. + // This allows the renderer to reset some state. + virtual void DragSourceSystemDragEnded() {}; + // Filters drop data before it is passed to RenderWidgetHost. virtual void FilterDropData(DropData* drop_data) {} };
diff --git a/content/public/browser/render_widget_host_view.h b/content/public/browser/render_widget_host_view.h index b0dcb430..f721d17 100644 --- a/content/public/browser/render_widget_host_view.h +++ b/content/public/browser/render_widget_host_view.h
@@ -10,7 +10,7 @@ #include "base/strings/string16.h" #include "build/build_config.h" #include "content/common/content_export.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/gfx/native_widget_types.h"
diff --git a/content/public/browser/web_contents_observer.h b/content/public/browser/web_contents_observer.h index b73f072..6c38d353 100644 --- a/content/public/browser/web_contents_observer.h +++ b/content/public/browser/web_contents_observer.h
@@ -18,8 +18,8 @@ #include "content/public/common/resource_type.h" #include "ipc/ipc_listener.h" #include "ipc/ipc_sender.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/platform/WebSecurityStyle.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/base/page_transition_types.h" #include "ui/base/window_open_disposition.h"
diff --git a/content/public/common/common_param_traits_macros.h b/content/public/common/common_param_traits_macros.h index 8f9eaca..86fcd13 100644 --- a/content/public/common/common_param_traits_macros.h +++ b/content/public/common/common_param_traits_macros.h
@@ -235,7 +235,6 @@ IPC_STRUCT_TRAITS_MEMBER(ignore_main_frame_overflow_hidden_quirk) IPC_STRUCT_TRAITS_MEMBER(report_screen_size_in_physical_pixels_quirk) IPC_STRUCT_TRAITS_MEMBER(resue_global_for_unowned_main_frame) - IPC_STRUCT_TRAITS_MEMBER(autoplay_muted_videos_enabled) IPC_STRUCT_TRAITS_MEMBER(progress_bar_completion) IPC_STRUCT_TRAITS_MEMBER(spellcheck_enabled_by_default) #endif
diff --git a/content/public/common/content_features.cc b/content/public/common/content_features.cc index 656b8fb7..d8368b2 100644 --- a/content/public/common/content_features.cc +++ b/content/public/common/content_features.cc
@@ -132,7 +132,7 @@ // Whether document level event listeners should default 'passive' to true. const base::Feature kPassiveDocumentEventListeners{ - "PassiveDocumentEventListeners", base::FEATURE_DISABLED_BY_DEFAULT}; + "PassiveDocumentEventListeners", base::FEATURE_ENABLED_BY_DEFAULT}; // Whether we should force a touchstart and first touchmove per scroll event // listeners to be 'passive' during fling. @@ -239,10 +239,6 @@ base::FEATURE_DISABLED_BY_DEFAULT}; #if defined(OS_ANDROID) -// Allow videos to autoplay without a user gesture if muted. -const base::Feature kAutoplayMutedVideos{"AutoplayMutedVideos", - base::FEATURE_ENABLED_BY_DEFAULT}; - // Use IME's own thread instead of using main UI thread. It also means that // we will not use replica editor and do a round trip to renderer to synchronize // with Blink data.
diff --git a/content/public/common/content_features.h b/content/public/common/content_features.h index d7a23376..e924a69 100644 --- a/content/public/common/content_features.h +++ b/content/public/common/content_features.h
@@ -66,7 +66,6 @@ extern const base::Feature kSendBeaconThrowForBlobWithNonSimpleType; #if defined(OS_ANDROID) -CONTENT_EXPORT extern const base::Feature kAutoplayMutedVideos; CONTENT_EXPORT extern const base::Feature kImeThread; CONTENT_EXPORT extern const base::Feature kSeccompSandboxAndroid; CONTENT_EXPORT extern const base::Feature kWebPayments;
diff --git a/content/public/common/frame_navigate_params.h b/content/public/common/frame_navigate_params.h index 620fc133..32efd4fc 100644 --- a/content/public/common/frame_navigate_params.h +++ b/content/public/common/frame_navigate_params.h
@@ -75,10 +75,6 @@ // the browser history. E.g., on unreachable urls. bool should_update_history; - // See SearchableFormData for a description of these. - GURL searchable_form_url; - std::string searchable_form_encoding; - // Contents MIME type of main frame. std::string contents_mime_type;
diff --git a/content/public/common/web_preferences.cc b/content/public/common/web_preferences.cc index 365db20..da49d44 100644 --- a/content/public/common/web_preferences.cc +++ b/content/public/common/web_preferences.cc
@@ -206,7 +206,6 @@ ignore_main_frame_overflow_hidden_quirk(false), report_screen_size_in_physical_pixels_quirk(false), resue_global_for_unowned_main_frame(false), - autoplay_muted_videos_enabled(false), progress_bar_completion(ProgressBarCompletion::LOAD_EVENT), spellcheck_enabled_by_default(true), #endif
diff --git a/content/public/common/web_preferences.h b/content/public/common/web_preferences.h index 9702484f..b853dd3 100644 --- a/content/public/common/web_preferences.h +++ b/content/public/common/web_preferences.h
@@ -242,7 +242,6 @@ // Used by Android_WebView only to support legacy apps that inject script into // a top-level initial empty document and expect it to persist on navigation. bool resue_global_for_unowned_main_frame; - bool autoplay_muted_videos_enabled; ProgressBarCompletion progress_bar_completion; // Specifies default setting for spellcheck when the spellcheck attribute is // not explicitly specified.
diff --git a/content/public/test/browser_test_utils.h b/content/public/test/browser_test_utils.h index 499a8da..9f04c066 100644 --- a/content/public/test/browser_test_utils.h +++ b/content/public/test/browser_test_utils.h
@@ -26,7 +26,7 @@ #include "content/public/browser/web_contents_observer.h" #include "content/public/common/page_type.h" #include "ipc/message_filter.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/accessibility/ax_node_data.h" #include "ui/accessibility/ax_tree_update.h" #include "ui/events/keycodes/dom/dom_code.h"
diff --git a/content/public/test/render_view_test.cc b/content/public/test/render_view_test.cc index 6a63403..6184d721 100644 --- a/content/public/test/render_view_test.cc +++ b/content/public/test/render_view_test.cc
@@ -37,12 +37,13 @@ #include "content/test/mock_render_process.h" #include "content/test/test_content_client.h" #include "content/test/test_render_frame.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/platform/WebURLRequest.h" #include "third_party/WebKit/public/platform/scheduler/renderer/renderer_scheduler.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebHistoryItem.h" #include "third_party/WebKit/public/web/WebInputElement.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" #include "third_party/WebKit/public/web/WebKit.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebScriptSource.h"
diff --git a/content/renderer/BUILD.gn b/content/renderer/BUILD.gn index 0428979..4006319 100644 --- a/content/renderer/BUILD.gn +++ b/content/renderer/BUILD.gn
@@ -448,6 +448,7 @@ "//skia", "//storage/common", "//third_party/WebKit/public:blink", + "//third_party/WebKit/public:features", "//third_party/WebKit/public:mojo_bindings", "//third_party/boringssl", "//third_party/icu",
diff --git a/content/renderer/browser_plugin/browser_plugin.cc b/content/renderer/browser_plugin/browser_plugin.cc index 6ada3a6..248b36b1 100644 --- a/content/renderer/browser_plugin/browser_plugin.cc +++ b/content/renderer/browser_plugin/browser_plugin.cc
@@ -28,11 +28,12 @@ #include "content/renderer/drop_data_builder.h" #include "content/renderer/render_thread_impl.h" #include "content/renderer/sad_plugin.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/platform/WebRect.h" #include "third_party/WebKit/public/web/WebAXObject.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebElement.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebPluginContainer.h" #include "third_party/WebKit/public/web/WebView.h"
diff --git a/content/renderer/input/input_event_filter.cc b/content/renderer/input/input_event_filter.cc index 063df1e..04fd216 100644 --- a/content/renderer/input/input_event_filter.cc +++ b/content/renderer/input/input_event_filter.cc
@@ -275,7 +275,7 @@ if (!sender_) return; // Filter was removed. - CHECK(sender_->Send(message.release())) << "Send message failed"; + sender_->Send(message.release()); } void InputEventFilter::HandleEventOnMainThread(
diff --git a/content/renderer/input/input_event_filter.h b/content/renderer/input/input_event_filter.h index 1418589..e4bbb72ea 100644 --- a/content/renderer/input/input_event_filter.h +++ b/content/renderer/input/input_event_filter.h
@@ -16,7 +16,7 @@ #include "content/renderer/input/input_handler_manager_client.h" #include "content/renderer/input/main_thread_event_queue.h" #include "ipc/message_filter.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" namespace base { class SingleThreadTaskRunner;
diff --git a/content/renderer/input/input_handler_manager_client.h b/content/renderer/input/input_handler_manager_client.h index 302c0e8..b24a47f 100644 --- a/content/renderer/input/input_handler_manager_client.h +++ b/content/renderer/input/input_handler_manager_client.h
@@ -10,7 +10,7 @@ #include "base/macros.h" #include "content/common/content_export.h" #include "content/common/input/input_event_ack_state.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/blink/scoped_web_input_event.h" #include "ui/gfx/geometry/vector2d_f.h"
diff --git a/content/renderer/input/main_thread_event_queue.h b/content/renderer/input/main_thread_event_queue.h index 9852b3d..3e256b1b 100644 --- a/content/renderer/input/main_thread_event_queue.h +++ b/content/renderer/input/main_thread_event_queue.h
@@ -13,8 +13,8 @@ #include "content/common/input/input_event_dispatch_type.h" #include "content/common/input/web_input_event_queue.h" #include "content/public/common/content_features.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/platform/scheduler/renderer/renderer_scheduler.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" #include "ui/events/blink/web_input_event_traits.h" #include "ui/events/latency_info.h"
diff --git a/content/renderer/input/render_widget_input_handler.cc b/content/renderer/input/render_widget_input_handler.cc index 7bda814..f9686ca 100644 --- a/content/renderer/input/render_widget_input_handler.cc +++ b/content/renderer/input/render_widget_input_handler.cc
@@ -24,6 +24,7 @@ #include "content/renderer/render_widget.h" #include "third_party/WebKit/public/platform/WebFloatPoint.h" #include "third_party/WebKit/public/platform/WebFloatSize.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" #include "third_party/WebKit/public/platform/scheduler/renderer/renderer_scheduler.h" #include "ui/events/blink/web_input_event_traits.h" #include "ui/events/latency_info.h"
diff --git a/content/renderer/input/render_widget_input_handler.h b/content/renderer/input/render_widget_input_handler.h index f79c8fa5..43b494f 100644 --- a/content/renderer/input/render_widget_input_handler.h +++ b/content/renderer/input/render_widget_input_handler.h
@@ -11,7 +11,7 @@ #include "base/time/time.h" #include "content/common/input/input_event_ack.h" #include "content/common/input/input_event_dispatch_type.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/base/ui_base_types.h" #include "ui/events/blink/did_overscroll_params.h"
diff --git a/content/renderer/mouse_lock_dispatcher.cc b/content/renderer/mouse_lock_dispatcher.cc index f72e1e0..f801e66 100644 --- a/content/renderer/mouse_lock_dispatcher.cc +++ b/content/renderer/mouse_lock_dispatcher.cc
@@ -5,7 +5,7 @@ #include "content/renderer/mouse_lock_dispatcher.h" #include "base/logging.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" namespace content {
diff --git a/content/renderer/mus/compositor_mus_connection.h b/content/renderer/mus/compositor_mus_connection.h index 6859b17..80f3ca5f 100644 --- a/content/renderer/mus/compositor_mus_connection.h +++ b/content/renderer/mus/compositor_mus_connection.h
@@ -17,7 +17,7 @@ #include "services/ui/public/cpp/window.h" #include "services/ui/public/cpp/window_tree_client.h" #include "services/ui/public/cpp/window_tree_client_delegate.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/blink/scoped_web_input_event.h" #include "ui/events/gestures/motion_event_aura.h"
diff --git a/content/renderer/pepper/content_decryptor_delegate.cc b/content/renderer/pepper/content_decryptor_delegate.cc index 57e1f8c..f75d394 100644 --- a/content/renderer/pepper/content_decryptor_delegate.cc +++ b/content/renderer/pepper/content_decryptor_delegate.cc
@@ -206,6 +206,19 @@ } } +media::VideoPixelFormat PpDecryptedFrameFormatToMediaVideoFormat( + PP_DecryptedFrameFormat format) { + switch (format) { + case PP_DECRYPTEDFRAMEFORMAT_YV12: + return media::PIXEL_FORMAT_YV12; + case PP_DECRYPTEDFRAMEFORMAT_I420: + return media::PIXEL_FORMAT_I420; + default: + NOTREACHED() << "Unknown decrypted frame format: " << format; + return media::PIXEL_FORMAT_UNKNOWN; + } +} + Decryptor::Status PpDecryptResultToMediaDecryptorStatus( PP_DecryptResult result) { switch (result) { @@ -989,11 +1002,18 @@ } gfx::Size frame_size(frame_info->width, frame_info->height); - DCHECK_EQ(frame_info->format, PP_DECRYPTEDFRAMEFORMAT_YV12); + + media::VideoPixelFormat video_pixel_format = + PpDecryptedFrameFormatToMediaVideoFormat(frame_info->format); + if (video_pixel_format == media::PIXEL_FORMAT_UNKNOWN) { + FreeBuffer(frame_info->tracking_info.buffer_id); + video_decode_cb.Run(Decryptor::kError, NULL); + return; + } scoped_refptr<media::VideoFrame> decoded_frame = media::VideoFrame::WrapExternalYuvData( - media::PIXEL_FORMAT_YV12, frame_size, gfx::Rect(frame_size), + video_pixel_format, frame_size, gfx::Rect(frame_size), natural_size_, frame_info->strides[PP_DECRYPTEDFRAMEPLANES_Y], frame_info->strides[PP_DECRYPTEDFRAMEPLANES_U], frame_info->strides[PP_DECRYPTEDFRAMEPLANES_V],
diff --git a/content/renderer/pepper/event_conversion.cc b/content/renderer/pepper/event_conversion.cc index d21f0cf..8039575 100644 --- a/content/renderer/pepper/event_conversion.cc +++ b/content/renderer/pepper/event_conversion.cc
@@ -22,7 +22,7 @@ #include "ppapi/c/pp_input_event.h" #include "ppapi/shared_impl/ppb_input_event_shared.h" #include "third_party/WebKit/public/platform/WebGamepads.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/keycodes/dom/keycode_converter.h" using ppapi::InputEventData;
diff --git a/content/renderer/pepper/event_conversion.h b/content/renderer/pepper/event_conversion.h index 3ffe24f0..414e868 100644 --- a/content/renderer/pepper/event_conversion.h +++ b/content/renderer/pepper/event_conversion.h
@@ -10,7 +10,7 @@ #include "content/common/content_export.h" #include "ppapi/c/ppb_input_event.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" struct PP_InputEvent;
diff --git a/content/renderer/pepper/pepper_plugin_instance_impl.cc b/content/renderer/pepper/pepper_plugin_instance_impl.cc index 6254e04..bb02dbe 100644 --- a/content/renderer/pepper/pepper_plugin_instance_impl.cc +++ b/content/renderer/pepper/pepper_plugin_instance_impl.cc
@@ -99,6 +99,7 @@ #include "third_party/WebKit/public/platform/WebCursorInfo.h" #include "third_party/WebKit/public/platform/WebFloatRect.h" #include "third_party/WebKit/public/platform/WebGamepads.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/platform/WebRect.h" #include "third_party/WebKit/public/platform/WebSecurityOrigin.h" #include "third_party/WebKit/public/platform/WebString.h" @@ -108,7 +109,6 @@ #include "third_party/WebKit/public/web/WebCompositionUnderline.h" #include "third_party/WebKit/public/web/WebDataSource.h" #include "third_party/WebKit/public/web/WebDocument.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebPluginContainer.h" #include "third_party/WebKit/public/web/WebPluginScriptForbiddenScope.h"
diff --git a/content/renderer/pepper/pepper_plugin_instance_impl.h b/content/renderer/pepper/pepper_plugin_instance_impl.h index cac1a75..dc08cff 100644 --- a/content/renderer/pepper/pepper_plugin_instance_impl.h +++ b/content/renderer/pepper/pepper_plugin_instance_impl.h
@@ -557,6 +557,9 @@ return *audio_controller_; } + // Should be used only for logging. + bool is_flash_plugin() const { return is_flash_plugin_; } + private: friend class base::RefCounted<PepperPluginInstanceImpl>; friend class PpapiPluginInstanceTest;
diff --git a/content/renderer/pepper/plugin_instance_throttler_impl.cc b/content/renderer/pepper/plugin_instance_throttler_impl.cc index b525309..7bf7d967 100644 --- a/content/renderer/pepper/plugin_instance_throttler_impl.cc +++ b/content/renderer/pepper/plugin_instance_throttler_impl.cc
@@ -12,8 +12,8 @@ #include "content/renderer/pepper/pepper_plugin_instance_impl.h" #include "content/renderer/render_frame_impl.h" #include "ppapi/shared_impl/ppapi_constants.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/platform/WebRect.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebPluginContainer.h" #include "third_party/WebKit/public/web/WebPluginParams.h"
diff --git a/content/renderer/pepper/plugin_instance_throttler_impl_unittest.cc b/content/renderer/pepper/plugin_instance_throttler_impl_unittest.cc index 62625d68..92b749e 100644 --- a/content/renderer/pepper/plugin_instance_throttler_impl_unittest.cc +++ b/content/renderer/pepper/plugin_instance_throttler_impl_unittest.cc
@@ -14,7 +14,7 @@ #include "content/public/renderer/render_frame.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/web/WebPluginParams.h" #include "ui/gfx/canvas.h" #include "url/gurl.h"
diff --git a/content/renderer/pepper/ppb_graphics_3d_impl.cc b/content/renderer/pepper/ppb_graphics_3d_impl.cc index 7c59611..6db7f7b 100644 --- a/content/renderer/pepper/ppb_graphics_3d_impl.cc +++ b/content/renderer/pepper/ppb_graphics_3d_impl.cc
@@ -8,6 +8,7 @@ #include "base/command_line.h" #include "base/feature_list.h" #include "base/location.h" +#include "base/metrics/histogram_macros.h" #include "base/single_thread_task_runner.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_task_runner_handle.h" @@ -252,6 +253,8 @@ attrib_helper.context_type = gpu::gles2::CONTEXT_TYPE_OPENGLES2; gpu::CommandBufferProxyImpl* share_buffer = NULL; + if (!plugin_instance->is_flash_plugin()) + UMA_HISTOGRAM_BOOLEAN("Pepper.Graphics3DHasShareGroup", !!share_context); if (share_context) { PPB_Graphics3D_Impl* share_graphics = static_cast<PPB_Graphics3D_Impl*>(share_context);
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index 9dfaccb..f822db34 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -6105,15 +6105,24 @@ GetRequestContextFrameTypeForWebURLRequest(info.urlRequest) == REQUEST_CONTEXT_FRAME_TYPE_NESTED); + BeginNavigationParams begin_navigation_params( + GetWebURLRequestHeaders(info.urlRequest), + GetLoadFlagsForWebURLRequest(info.urlRequest), + info.urlRequest.hasUserGesture(), + info.urlRequest.skipServiceWorker() != + blink::WebURLRequest::SkipServiceWorker::None, + GetRequestContextTypeForWebURLRequest(info.urlRequest)); + + if (!info.form.isNull()) { + WebSearchableFormData web_searchable_form_data(info.form); + begin_navigation_params.searchable_form_url = + web_searchable_form_data.url(); + begin_navigation_params.searchable_form_encoding = + web_searchable_form_data.encoding().utf8(); + } + Send(new FrameHostMsg_BeginNavigation( - routing_id_, MakeCommonNavigationParams(info), - BeginNavigationParams( - GetWebURLRequestHeaders(info.urlRequest), - GetLoadFlagsForWebURLRequest(info.urlRequest), - info.urlRequest.hasUserGesture(), - info.urlRequest.skipServiceWorker() != - blink::WebURLRequest::SkipServiceWorker::None, - GetRequestContextTypeForWebURLRequest(info.urlRequest)))); + routing_id_, MakeCommonNavigationParams(info), begin_navigation_params)); } void RenderFrameImpl::LoadDataURL(
diff --git a/content/renderer/render_view_impl.cc b/content/renderer/render_view_impl.cc index b045f2ec..3771ce0c 100644 --- a/content/renderer/render_view_impl.cc +++ b/content/renderer/render_view_impl.cc
@@ -112,6 +112,7 @@ #include "third_party/WebKit/public/platform/WebConnectionType.h" #include "third_party/WebKit/public/platform/WebHTTPBody.h" #include "third_party/WebKit/public/platform/WebImage.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/platform/WebMessagePortChannel.h" #include "third_party/WebKit/public/platform/WebPoint.h" #include "third_party/WebKit/public/platform/WebRect.h" @@ -123,6 +124,7 @@ #include "third_party/WebKit/public/platform/WebURLRequest.h" #include "third_party/WebKit/public/platform/WebURLResponse.h" #include "third_party/WebKit/public/platform/WebVector.h" +#include "third_party/WebKit/public/public_features.h" #include "third_party/WebKit/public/web/WebAXObject.h" #include "third_party/WebKit/public/web/WebColorSuggestion.h" #include "third_party/WebKit/public/web/WebDOMEvent.h" @@ -141,7 +143,6 @@ #include "third_party/WebKit/public/web/WebHistoryItem.h" #include "third_party/WebKit/public/web/WebHitTestResult.h" #include "third_party/WebKit/public/web/WebInputElement.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebMediaPlayerAction.h" #include "third_party/WebKit/public/web/WebNavigationPolicy.h" @@ -1017,6 +1018,7 @@ static_cast<WebSettings::ProgressBarCompletion>( prefs.progress_bar_completion)); settings->setPreferHiddenVolumeControls(true); + settings->setSpellCheckEnabledByDefault(prefs.spellcheck_enabled_by_default); // Force preload=none and disable autoplay on older or low end Android // platforms because their media pipelines are not stable enough to handle @@ -1025,10 +1027,8 @@ base::android::BuildInfo::GetInstance()->sdk_int() <= base::android::SDK_VERSION_JELLY_BEAN_MR2 || base::SysInfo::IsLowEndDevice(); + // TODO(mlamouri): rename this setting "isLowEndDevice". settings->setForcePreloadNoneForMediaElements(is_low_end_device); - WebRuntimeFeatures::enableAutoplayMutedVideos( - prefs.autoplay_muted_videos_enabled && !is_low_end_device); - settings->setSpellCheckEnabledByDefault(prefs.spellcheck_enabled_by_default); #endif settings->setAutoplayExperimentMode( @@ -1188,9 +1188,6 @@ OnScrollFocusedEditableNodeIntoRect) IPC_MESSAGE_HANDLER(ViewMsg_SetPageScale, OnSetPageScale) IPC_MESSAGE_HANDLER(ViewMsg_Zoom, OnZoom) - IPC_MESSAGE_HANDLER(DragMsg_SourceEnded, OnDragSourceEnded) - IPC_MESSAGE_HANDLER(DragMsg_SourceSystemDragEnded, - OnDragSourceSystemDragEnded) IPC_MESSAGE_HANDLER(ViewMsg_AllowBindings, OnAllowBindings) IPC_MESSAGE_HANDLER(ViewMsg_SetInitialFocus, OnSetInitialFocus) IPC_MESSAGE_HANDLER(ViewMsg_UpdateTargetURL_ACK, OnUpdateTargetURLAck) @@ -2119,17 +2116,6 @@ main_render_frame_->MaybeEnableMojoBindings(); } -void RenderViewImpl::OnDragSourceEnded(const gfx::Point& client_point, - const gfx::Point& screen_point, - WebDragOperation op) { - webview()->dragSourceEndedAt( - ConvertWindowPointToViewport(client_point), screen_point, op); -} - -void RenderViewImpl::OnDragSourceSystemDragEnded() { - webview()->dragSourceSystemDragEnded(); -} - void RenderViewImpl::OnUpdateWebPreferences(const WebPreferences& prefs) { webkit_preferences_ = prefs; ApplyWebPreferencesInternal(webkit_preferences_, webview(), compositor_deps_); @@ -2213,7 +2199,7 @@ UpdateThemePrefs(); blink::setCaretBlinkInterval(renderer_prefs.caret_blink_interval); -#if defined(USE_DEFAULT_RENDER_THEME) +#if BUILDFLAG(USE_DEFAULT_RENDER_THEME) if (renderer_prefs.use_custom_colors) { blink::setFocusRingColor(renderer_prefs.focus_ring_color); @@ -2226,7 +2212,7 @@ webview()->themeChanged(); } } -#endif // defined(USE_DEFAULT_RENDER_THEME) +#endif // BUILDFLAG(USE_DEFAULT_RENDER_THEME) if (webview() && old_accept_languages != renderer_preferences_.accept_languages) {
diff --git a/content/renderer/render_view_impl.h b/content/renderer/render_view_impl.h index 190effc4..02c975fb 100644 --- a/content/renderer/render_view_impl.h +++ b/content/renderer/render_view_impl.h
@@ -43,6 +43,7 @@ #include "content/renderer/render_widget_owner_delegate.h" #include "content/renderer/stats_collection_observer.h" #include "ipc/ipc_platform_file.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/platform/WebSecurityOrigin.h" #include "third_party/WebKit/public/web/WebAXObject.h" #include "third_party/WebKit/public/web/WebConsoleMessage.h" @@ -51,7 +52,6 @@ #include "third_party/WebKit/public/web/WebFrameWidget.h" #include "third_party/WebKit/public/web/WebHistoryItem.h" #include "third_party/WebKit/public/web/WebIconURL.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" #include "third_party/WebKit/public/web/WebNavigationType.h" #include "third_party/WebKit/public/web/WebNode.h" #include "third_party/WebKit/public/web/WebViewClient.h" @@ -530,10 +530,6 @@ void OnDeterminePageLanguage(); void OnDisableScrollbarsForSmallWindows( const gfx::Size& disable_scrollbars_size_limit); - void OnDragSourceEnded(const gfx::Point& client_point, - const gfx::Point& screen_point, - blink::WebDragOperation drag_operation); - void OnDragSourceSystemDragEnded(); void OnEnablePreferredSizeChangedMode(); void OnEnableAutoResize(const gfx::Size& min_size, const gfx::Size& max_size); void OnDisableAutoResize(const gfx::Size& new_size);
diff --git a/content/renderer/render_widget.cc b/content/renderer/render_widget.cc index 690331e..d62e8e9 100644 --- a/content/renderer/render_widget.cc +++ b/content/renderer/render_widget.cc
@@ -631,6 +631,9 @@ IPC_MESSAGE_HANDLER(DragMsg_TargetDragOver, OnDragTargetDragOver) IPC_MESSAGE_HANDLER(DragMsg_TargetDragLeave, OnDragTargetDragLeave) IPC_MESSAGE_HANDLER(DragMsg_TargetDrop, OnDragTargetDrop) + IPC_MESSAGE_HANDLER(DragMsg_SourceEnded, OnDragSourceEnded) + IPC_MESSAGE_HANDLER(DragMsg_SourceSystemDragEnded, + OnDragSourceSystemDragEnded) #if defined(OS_ANDROID) IPC_MESSAGE_HANDLER(InputMsg_ImeEventAck, OnImeEventAck) IPC_MESSAGE_HANDLER(InputMsg_RequestTextInputStateUpdate, @@ -1706,6 +1709,23 @@ screen_point, key_modifiers); } +void RenderWidget::OnDragSourceEnded(const gfx::Point& client_point, + const gfx::Point& screen_point, + WebDragOperation op) { + if (!GetWebWidget()) + return; + + static_cast<WebFrameWidget*>(GetWebWidget())->dragSourceEndedAt( + ConvertWindowPointToViewport(client_point), screen_point, op); +} + +void RenderWidget::OnDragSourceSystemDragEnded() { + if (!GetWebWidget()) + return; + + static_cast<WebFrameWidget*>(GetWebWidget())->dragSourceSystemDragEnded(); +} + void RenderWidget::showImeIfNeeded() { #if defined(OS_ANDROID) || defined(USE_AURA) UpdateTextInputState(ShowIme::IF_NEEDED, ChangeSource::FROM_NON_IME);
diff --git a/content/renderer/render_widget.h b/content/renderer/render_widget.h index 1cfacff..9435a21 100644 --- a/content/renderer/render_widget.h +++ b/content/renderer/render_widget.h
@@ -532,6 +532,10 @@ const gfx::Point& client_pt, const gfx::Point& screen_pt, int key_modifiers); + void OnDragSourceEnded(const gfx::Point& client_point, + const gfx::Point& screen_point, + blink::WebDragOperation drag_operation); + void OnDragSourceSystemDragEnded(); #if defined(OS_ANDROID) // Called when we send IME event that expects an ACK.
diff --git a/content/renderer/render_widget_fullscreen_pepper.cc b/content/renderer/render_widget_fullscreen_pepper.cc index 6436a25..65645be 100644 --- a/content/renderer/render_widget_fullscreen_pepper.cc +++ b/content/renderer/render_widget_fullscreen_pepper.cc
@@ -20,6 +20,7 @@ #include "skia/ext/platform_canvas.h" #include "third_party/WebKit/public/platform/WebCanvas.h" #include "third_party/WebKit/public/platform/WebCursorInfo.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" #include "third_party/WebKit/public/platform/WebLayer.h" #include "third_party/WebKit/public/platform/WebSize.h" #include "third_party/WebKit/public/web/WebWidget.h"
diff --git a/content/renderer/render_widget_unittest.cc b/content/renderer/render_widget_unittest.cc index 1cc29f4f..973071d 100644 --- a/content/renderer/render_widget_unittest.cc +++ b/content/renderer/render_widget_unittest.cc
@@ -19,8 +19,8 @@ #include "ipc/ipc_test_sink.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/web/WebDeviceEmulationParams.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" #include "ui/events/blink/web_input_event_traits.h" #include "ui/gfx/geometry/rect.h"
diff --git a/content/shell/browser/layout_test/layout_test_devtools_frontend.cc b/content/shell/browser/layout_test/layout_test_devtools_frontend.cc index bd30d22..d12ddd0e 100644 --- a/content/shell/browser/layout_test/layout_test_devtools_frontend.cc +++ b/content/shell/browser/layout_test/layout_test_devtools_frontend.cc
@@ -52,13 +52,20 @@ // We need to go up 3 directories to get to out/Release. dir_exe = dir_exe.AppendASCII("../../.."); #endif + base::FilePath dev_tools_path; bool is_debug_dev_tools = base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDebugDevTools); - std::string folder = is_debug_dev_tools ? "debug/" : ""; - base::FilePath dev_tools_path = - dir_exe.AppendASCII("resources/inspector/" + folder + "inspector.html"); + if (base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kCustomDevToolsFrontend)) { + dev_tools_path = base::CommandLine::ForCurrentProcess()->GetSwitchValuePath( + switches::kCustomDevToolsFrontend); + } else { + std::string folder = is_debug_dev_tools ? "debug/" : ""; + dev_tools_path = dir_exe.AppendASCII("resources/inspector/" + folder); + } - GURL result = net::FilePathToFileURL(dev_tools_path); + GURL result = + net::FilePathToFileURL(dev_tools_path.AppendASCII("inspector.html")); std::string url_string = base::StringPrintf("%s?experiments=true", result.spec().c_str()); if (is_debug_dev_tools)
diff --git a/content/shell/common/layout_test/layout_test_switches.cc b/content/shell/common/layout_test/layout_test_switches.cc index acd2e44c..2ef18ff3 100644 --- a/content/shell/common/layout_test/layout_test_switches.cc +++ b/content/shell/common/layout_test/layout_test_switches.cc
@@ -22,6 +22,9 @@ // Run devtools tests in debug mode (not bundled and minified) const char kDebugDevTools[] = "debug-devtools"; +// Specify a custom path to devtools for devtools tests +const char kCustomDevToolsFrontend[] = "custom-devtools-frontend"; + // Enable accelerated 2D canvas. const char kEnableAccelerated2DCanvas[] = "enable-accelerated-2d-canvas";
diff --git a/content/shell/common/layout_test/layout_test_switches.h b/content/shell/common/layout_test/layout_test_switches.h index d42b86c..3aaf54ca 100644 --- a/content/shell/common/layout_test/layout_test_switches.h +++ b/content/shell/common/layout_test/layout_test_switches.h
@@ -15,6 +15,7 @@ extern const char kAllowExternalPages[]; extern const char kCheckLayoutTestSysDeps[]; extern const char kCrashOnFailure[]; +extern const char kCustomDevToolsFrontend[]; extern const char kDebugDevTools[]; extern const char kEnableAccelerated2DCanvas[]; extern const char kEnableFontAntialiasing[];
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index 5e241dd0..f4166fd 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -9,6 +9,7 @@ import("//build/config/ui.gni") import("//mojo/public/tools/bindings/mojom.gni") import("//testing/test.gni") +import("//third_party/WebKit/public/public_features.gni") import("//v8/gni/v8.gni") # Use a static library here because many test binaries depend on this but don't
diff --git a/content/test/gpu/gpu_tests/webgl2_conformance_expectations.py b/content/test/gpu/gpu_tests/webgl2_conformance_expectations.py index f3c9b93c..e98d92a4 100644 --- a/content/test/gpu/gpu_tests/webgl2_conformance_expectations.py +++ b/content/test/gpu/gpu_tests/webgl2_conformance_expectations.py
@@ -435,6 +435,19 @@ self.Fail('deqp/functional/gles3/framebufferblit/rect_04.html', ['mac', 'intel'], bug=483282) + self.Fail('conformance2/textures/image_data/' + + 'tex-2d-rgba8ui-rgba_integer-unsigned_byte.html', + ['mac', 'intel'], bug=665197) + self.Fail('conformance2/textures/image_data/' + + 'tex-2d-rgb8ui-rgb_integer-unsigned_byte.html', + ['mac', 'intel'], bug=665197) + self.Fail('conformance2/textures/image_data/' + + 'tex-2d-rg8ui-rg_integer-unsigned_byte.html', + ['mac', 'intel'], bug=665197) + self.Fail('conformance2/textures/image_data/' + + 'tex-2d-r8ui-red_integer-unsigned_byte.html', + ['mac', 'intel'], bug=665197) + # Fixed on OSX 10.11 self.Fail('deqp/functional/gles3/uniformbuffers/random.html', ['mac', 'intel'], bug=618464) @@ -462,8 +475,6 @@ self.Flaky('deqp/functional/gles3/texturespecification/' + 'random_teximage2d_2d.html', ['linux', 'amd', 'intel'], bug=618447) - self.Fail('deqp/data/gles3/shaders/linkage.html', - ['linux', 'amd', 'intel'], bug=483282) # Linux NVIDIA # This test is flaky both with and without ANGLE. @@ -484,60 +495,11 @@ # Fails on Intel Mesa GL 3.3, passes on Intel Mesa GL 4.5. self.Fail('conformance2/misc/views-with-offsets.html', - ['linux', 'intel'], bug=664180) + ['linux', 'intel', 'no_angle'], bug=664180) # Linux Intel with ANGLE only - self.Fail('deqp/functional/gles3/framebufferblit/' + - 'default_framebuffer_00.html', - ['linux', 'intel', 'opengl'], bug=658832) - self.Fail('conformance2/textures/misc/copy-texture-image-luma-format.html', ['linux', 'intel', 'opengl'], bug=1492) # ANGLE bug id - self.Fail('conformance2/rendering/blitframebuffer-filter-srgb.html', - ['linux', 'intel', 'opengl'], bug=634525) - self.Fail('conformance2/rendering/blitframebuffer-filter-outofbounds.html', - ['linux', 'intel', 'opengl'], bug=655147) - self.Fail('conformance2/rendering/' + - 'blitframebuffer-multisampled-readbuffer.html', - ['linux', 'intel', 'opengl'], bug=658898) - self.Fail('conformance2/rendering/blitframebuffer-test.html', - ['linux', 'intel', 'opengl'], bug=658898) - - # The Intel Mesa driver only supports sRGB encoding in ES 3.x, see - # https://patchwork.freedesktop.org/patch/76903 - # So these tests fail on core profile. - self.Fail('deqp/functional/gles3/framebufferblit/conversion_04.html', - ['linux', 'intel', 'opengl'], bug=598902) - self.Fail('deqp/functional/gles3/framebufferblit/conversion_07.html', - ['linux', 'intel', 'opengl'], bug=598902) - self.Fail('deqp/functional/gles3/framebufferblit/conversion_08.html', - ['linux', 'intel', 'opengl'], bug=598902) - self.Fail('deqp/functional/gles3/framebufferblit/conversion_10.html', - ['linux', 'intel', 'opengl'], bug=598902) - self.Fail('deqp/functional/gles3/framebufferblit/conversion_11.html', - ['linux', 'intel', 'opengl'], bug=598902) - self.Fail('deqp/functional/gles3/framebufferblit/conversion_12.html', - ['linux', 'intel', 'opengl'], bug=598902) - self.Fail('deqp/functional/gles3/framebufferblit/conversion_13.html', - ['linux', 'intel', 'opengl'], bug=598902) - self.Fail('deqp/functional/gles3/framebufferblit/conversion_18.html', - ['linux', 'intel', 'opengl'], bug=598902) - self.Fail('deqp/functional/gles3/framebufferblit/conversion_25.html', - ['linux', 'intel', 'opengl'], bug=598902) - self.Fail('deqp/functional/gles3/framebufferblit/conversion_28.html', - ['linux', 'intel', 'opengl'], bug=598902) - self.Fail('deqp/functional/gles3/framebufferblit/conversion_29.html', - ['linux', 'intel', 'opengl'], bug=598902) - self.Fail('deqp/functional/gles3/framebufferblit/conversion_30.html', - ['linux', 'intel', 'opengl'], bug=598902) - self.Fail('deqp/functional/gles3/framebufferblit/conversion_31.html', - ['linux', 'intel', 'opengl'], bug=598902) - self.Fail('deqp/functional/gles3/framebufferblit/conversion_32.html', - ['linux', 'intel', 'opengl'], bug=598902) - self.Fail('deqp/functional/gles3/framebufferblit/conversion_33.html', - ['linux', 'intel', 'opengl'], bug=598902) - self.Fail('deqp/functional/gles3/framebufferblit/conversion_34.html', - ['linux', 'intel', 'opengl'], bug=598902) # Linux AMD only. # It looks like AMD shader compiler rejects many valid ES3 semantics.
diff --git a/device/gamepad/android/java/src/org/chromium/device/gamepad/GamepadMappings.java b/device/gamepad/android/java/src/org/chromium/device/gamepad/GamepadMappings.java index d917a07..1f067ec0 100644 --- a/device/gamepad/android/java/src/org/chromium/device/gamepad/GamepadMappings.java +++ b/device/gamepad/android/java/src/org/chromium/device/gamepad/GamepadMappings.java
@@ -25,8 +25,6 @@ static final String SAMSUNG_EI_GP20_DEVICE_NAME = "Samsung Game Pad EI-GP20"; @VisibleForTesting static final String AMAZON_FIRE_DEVICE_NAME = "Amazon Fire Game Controller"; - @VisibleForTesting - static final String MICROSOFT_XBOX_WIRELESS_DEVICE_NAME = "Xbox Wireless Controller"; public static GamepadMappings getMappings(String deviceName, int[] axes) { if (deviceName.startsWith(NVIDIA_SHIELD_DEVICE_NAME_PREFIX) @@ -38,8 +36,6 @@ return new SamsungEIGP20GamepadMappings(); } else if (deviceName.equals(AMAZON_FIRE_DEVICE_NAME)) { return new AmazonFireGamepadMappings(); - } else if (deviceName.equals(MICROSOFT_XBOX_WIRELESS_DEVICE_NAME)) { - return new XboxWirelessGamepadMappings(); } return new UnknownGamepadMappings(axes); @@ -218,74 +214,6 @@ } } - private static class XboxWirelessGamepadMappings extends GamepadMappings { - - private boolean mLeftTriggerActivated = false; - private boolean mRightTriggerActivated = false; - - /** - * Method for mapping Xbox One S controller (in Bluetooth mode) to - * standard gamepad button and axes values. - */ - @Override - public void mapToStandardGamepad(float[] mappedAxes, float[] mappedButtons, - float[] rawAxes, float[] rawButtons) { - mappedButtons[CanonicalButtonIndex.PRIMARY] = - rawButtons[KeyEvent.KEYCODE_BUTTON_A]; - mappedButtons[CanonicalButtonIndex.SECONDARY] = - rawButtons[KeyEvent.KEYCODE_BUTTON_B]; - mappedButtons[CanonicalButtonIndex.TERTIARY] = - rawButtons[KeyEvent.KEYCODE_BUTTON_C]; - mappedButtons[CanonicalButtonIndex.QUATERNARY] = - rawButtons[KeyEvent.KEYCODE_BUTTON_X]; - - mappedButtons[CanonicalButtonIndex.LEFT_SHOULDER] = - rawButtons[KeyEvent.KEYCODE_BUTTON_Y]; - mappedButtons[CanonicalButtonIndex.RIGHT_SHOULDER] = - rawButtons[KeyEvent.KEYCODE_BUTTON_Z]; - - mappedButtons[CanonicalButtonIndex.BACK_SELECT] = - rawButtons[KeyEvent.KEYCODE_BUTTON_L1]; - mappedButtons[CanonicalButtonIndex.START] = - rawButtons[KeyEvent.KEYCODE_BUTTON_R1]; - - mappedButtons[CanonicalButtonIndex.LEFT_THUMBSTICK] = - rawButtons[KeyEvent.KEYCODE_BUTTON_L2]; - mappedButtons[CanonicalButtonIndex.RIGHT_THUMBSTICK] = - rawButtons[KeyEvent.KEYCODE_BUTTON_R2]; - - // The left and right triggers on the Xbox One S controller - // are exposed as AXIS_Z and AXIS_RZ respectively. However, - // these nominally idle at -1 rather than 0, like other triggers. - // Unfortunately, the -1 value is only reported upon the first - // activation of each trigger axis. In order to prevent idling at - // 0.5 before trigger activation, we only expose trigger values - // when we've seen them report a non-zero value at least once. - if (rawAxes[MotionEvent.AXIS_Z] != 0) { - mLeftTriggerActivated = true; - } - if (rawAxes[MotionEvent.AXIS_RZ] != 0) { - mRightTriggerActivated = true; - } - if (mLeftTriggerActivated) { - mappedButtons[CanonicalButtonIndex.LEFT_TRIGGER] = - (rawAxes[MotionEvent.AXIS_Z] + 1) / 2; - } else { - mappedButtons[CanonicalButtonIndex.LEFT_TRIGGER] = 0.f; - } - if (mRightTriggerActivated) { - mappedButtons[CanonicalButtonIndex.RIGHT_TRIGGER] = - (rawAxes[MotionEvent.AXIS_RZ] + 1) / 2; - } else { - mappedButtons[CanonicalButtonIndex.RIGHT_TRIGGER] = 0.f; - } - - mapHatAxisToDpadButtons(mappedButtons, rawAxes); - mapXYAxes(mappedAxes, rawAxes); - mapRXAndRYAxesToRightStick(mappedAxes, rawAxes); - } - } - private static class PS3SixAxisGamepadMappings extends GamepadMappings { /**
diff --git a/device/gamepad/android/junit/src/org/chromium/device/gamepad/GamepadMappingsTest.java b/device/gamepad/android/junit/src/org/chromium/device/gamepad/GamepadMappingsTest.java index 728540f..6ed2941 100644 --- a/device/gamepad/android/junit/src/org/chromium/device/gamepad/GamepadMappingsTest.java +++ b/device/gamepad/android/junit/src/org/chromium/device/gamepad/GamepadMappingsTest.java
@@ -146,95 +146,6 @@ @Test @Feature({"Gamepad"}) - public void testXboxWirelessGamepadTriggerIdle() throws Exception { - GamepadMappings mappings = GamepadMappings.getMappings( - GamepadMappings.MICROSOFT_XBOX_WIRELESS_DEVICE_NAME, null); - - // Both triggers are inactive, because they haven't seen input yet. - mRawAxes[MotionEvent.AXIS_Z] = 0.f; - mRawAxes[MotionEvent.AXIS_RZ] = 0.f; - mappings.mapToStandardGamepad(mMappedAxes, mMappedButtons, mRawAxes, mRawButtons); - Assert.assertEquals(mMappedButtons[CanonicalButtonIndex.LEFT_TRIGGER], - 0.f, ERROR_TOLERANCE); - Assert.assertEquals(mMappedButtons[CanonicalButtonIndex.RIGHT_TRIGGER], - 0.f, ERROR_TOLERANCE); - - // This "activates" the left trigger, so it will begin reporting input. - // It will still be 0 because the triggers idle at -1. - mRawAxes[MotionEvent.AXIS_Z] = -1.f; - mappings.mapToStandardGamepad(mMappedAxes, mMappedButtons, mRawAxes, mRawButtons); - Assert.assertEquals(mMappedButtons[CanonicalButtonIndex.LEFT_TRIGGER], - 0.f, ERROR_TOLERANCE); - - // Since the left trigger is active, 0 should be reported as 0.5. - mRawAxes[MotionEvent.AXIS_Z] = 0.f; - mappings.mapToStandardGamepad(mMappedAxes, mMappedButtons, mRawAxes, mRawButtons); - Assert.assertEquals(mMappedButtons[CanonicalButtonIndex.LEFT_TRIGGER], - 0.5f, ERROR_TOLERANCE); - - // The right trigger should still read 0 because it's not active yet. - Assert.assertEquals(mMappedButtons[CanonicalButtonIndex.RIGHT_TRIGGER], - 0.f, ERROR_TOLERANCE); - - // Activate the right trigger - mRawAxes[MotionEvent.AXIS_RZ] = -1.f; - mappings.mapToStandardGamepad(mMappedAxes, mMappedButtons, mRawAxes, mRawButtons); - Assert.assertEquals(mMappedButtons[CanonicalButtonIndex.RIGHT_TRIGGER], - 0.f, ERROR_TOLERANCE); - - // Now the right trigger should also report 0 as 0.5. - mRawAxes[MotionEvent.AXIS_RZ] = 0.f; - mappings.mapToStandardGamepad(mMappedAxes, mMappedButtons, mRawAxes, mRawButtons); - Assert.assertEquals(mMappedButtons[CanonicalButtonIndex.RIGHT_TRIGGER], - 0.5f, ERROR_TOLERANCE); - } - - @Test - @Feature({"Gamepad"}) - public void testXboxWirelessGamepadMappings() throws Exception { - GamepadMappings mappings = GamepadMappings.getMappings( - GamepadMappings.MICROSOFT_XBOX_WIRELESS_DEVICE_NAME, null); - mappings.mapToStandardGamepad(mMappedAxes, mMappedButtons, mRawAxes, mRawButtons); - - Assert.assertEquals(mMappedButtons[CanonicalButtonIndex.PRIMARY], - mRawButtons[KeyEvent.KEYCODE_BUTTON_A], ERROR_TOLERANCE); - Assert.assertEquals(mMappedButtons[CanonicalButtonIndex.SECONDARY], - mRawButtons[KeyEvent.KEYCODE_BUTTON_B], ERROR_TOLERANCE); - Assert.assertEquals(mMappedButtons[CanonicalButtonIndex.TERTIARY], - mRawButtons[KeyEvent.KEYCODE_BUTTON_C], ERROR_TOLERANCE); - Assert.assertEquals(mMappedButtons[CanonicalButtonIndex.QUATERNARY], - mRawButtons[KeyEvent.KEYCODE_BUTTON_X], ERROR_TOLERANCE); - - Assert.assertEquals(mMappedButtons[CanonicalButtonIndex.LEFT_SHOULDER], - mRawButtons[KeyEvent.KEYCODE_BUTTON_Y], ERROR_TOLERANCE); - Assert.assertEquals(mMappedButtons[CanonicalButtonIndex.RIGHT_SHOULDER], - mRawButtons[KeyEvent.KEYCODE_BUTTON_Z], ERROR_TOLERANCE); - - Assert.assertEquals(mMappedButtons[CanonicalButtonIndex.BACK_SELECT], - mRawButtons[KeyEvent.KEYCODE_BUTTON_L1], ERROR_TOLERANCE); - Assert.assertEquals(mMappedButtons[CanonicalButtonIndex.START], - mRawButtons[KeyEvent.KEYCODE_BUTTON_R1], ERROR_TOLERANCE); - - Assert.assertEquals(mMappedButtons[CanonicalButtonIndex.LEFT_THUMBSTICK], - mRawButtons[KeyEvent.KEYCODE_BUTTON_L2], ERROR_TOLERANCE); - Assert.assertEquals(mMappedButtons[CanonicalButtonIndex.RIGHT_THUMBSTICK], - mRawButtons[KeyEvent.KEYCODE_BUTTON_R2], ERROR_TOLERANCE); - - Assert.assertEquals(mMappedButtons[CanonicalButtonIndex.LEFT_TRIGGER], - (mRawAxes[MotionEvent.AXIS_Z] + 1) / 2, ERROR_TOLERANCE); - Assert.assertEquals(mMappedButtons[CanonicalButtonIndex.RIGHT_TRIGGER], - (mRawAxes[MotionEvent.AXIS_RZ] + 1) / 2, ERROR_TOLERANCE); - - assertMappedHatAxisToDpadButtons(); - assertMappedXYAxes(); - assertMappedRXAndRYAxesToRightStick(); - - expectNoMetaButton(); - assertMapping(); - } - - @Test - @Feature({"Gamepad"}) public void testUnknownXBox360GamepadMappings() throws Exception { int[] axes = new int[] { MotionEvent.AXIS_X,
diff --git a/device/gamepad/gamepad_standard_mappings_linux.cc b/device/gamepad/gamepad_standard_mappings_linux.cc index c4b64221..b4de59f 100644 --- a/device/gamepad/gamepad_standard_mappings_linux.cc +++ b/device/gamepad/gamepad_standard_mappings_linux.cc
@@ -35,19 +35,25 @@ void MapperXboxOneHidGamepad(const blink::WebGamepad& input, blink::WebGamepad* mapped) { *mapped = input; - mapped->buttons[BUTTON_INDEX_LEFT_TRIGGER] = AxisToButton(input.axes[2]); - mapped->buttons[BUTTON_INDEX_RIGHT_TRIGGER] = AxisToButton(input.axes[5]); - mapped->buttons[BUTTON_INDEX_BACK_SELECT] = input.buttons[6]; - mapped->buttons[BUTTON_INDEX_START] = input.buttons[7]; - mapped->buttons[BUTTON_INDEX_LEFT_THUMBSTICK] = input.buttons[8]; - mapped->buttons[BUTTON_INDEX_RIGHT_THUMBSTICK] = input.buttons[9]; + + mapped->buttons[BUTTON_INDEX_PRIMARY] = input.buttons[0]; + mapped->buttons[BUTTON_INDEX_SECONDARY] = input.buttons[1]; + mapped->buttons[BUTTON_INDEX_TERTIARY] = input.buttons[3]; + mapped->buttons[BUTTON_INDEX_QUATERNARY] = input.buttons[4]; + mapped->buttons[BUTTON_INDEX_LEFT_SHOULDER] = input.buttons[6]; + mapped->buttons[BUTTON_INDEX_RIGHT_SHOULDER] = input.buttons[7]; + mapped->buttons[BUTTON_INDEX_LEFT_TRIGGER] = AxisToButton(input.axes[5]); + mapped->buttons[BUTTON_INDEX_RIGHT_TRIGGER] = AxisToButton(input.axes[4]); + mapped->buttons[BUTTON_INDEX_BACK_SELECT] = NullButton(); + mapped->buttons[BUTTON_INDEX_START] = input.buttons[11]; + mapped->buttons[BUTTON_INDEX_LEFT_THUMBSTICK] = input.buttons[13]; + mapped->buttons[BUTTON_INDEX_RIGHT_THUMBSTICK] = input.buttons[14]; mapped->buttons[BUTTON_INDEX_DPAD_UP] = AxisNegativeAsButton(input.axes[7]); mapped->buttons[BUTTON_INDEX_DPAD_DOWN] = AxisPositiveAsButton(input.axes[7]); mapped->buttons[BUTTON_INDEX_DPAD_LEFT] = AxisNegativeAsButton(input.axes[6]); mapped->buttons[BUTTON_INDEX_DPAD_RIGHT] = AxisPositiveAsButton(input.axes[6]); - mapped->axes[AXIS_INDEX_RIGHT_STICK_X] = input.axes[3]; - mapped->axes[AXIS_INDEX_RIGHT_STICK_Y] = input.axes[4]; + mapped->axes[AXIS_INDEX_RIGHT_STICK_Y] = input.axes[3]; mapped->buttonsLength = BUTTON_INDEX_COUNT - 1; /* no meta */ mapped->axesLength = AXIS_INDEX_COUNT; @@ -322,9 +328,9 @@ {"045e", "028f", MapperXInputStyleGamepad}, // Xbox 360 Wireless {"045e", "02d1", MapperXInputStyleGamepad}, // Xbox One Wired {"045e", "02dd", MapperXInputStyleGamepad}, // Xbox One Wired (2015 FW) - {"045e", "02e0", MapperXboxOneHidGamepad}, // Xbox One S (Bluetooth mode) {"045e", "02e3", MapperXInputStyleGamepad}, // Xbox One Elite Wired {"045e", "02ea", MapperXInputStyleGamepad}, // Xbox One S (USB) + {"045e", "02fd", MapperXboxOneHidGamepad}, // Xbox One S (Bluetooth) {"045e", "0719", MapperXInputStyleGamepad}, // Xbox 360 Wireless {"046d", "c21d", MapperXInputStyleGamepad}, // Logitech F310 {"046d", "c21e", MapperXInputStyleGamepad}, // Logitech F510
diff --git a/device/gamepad/gamepad_standard_mappings_mac.mm b/device/gamepad/gamepad_standard_mappings_mac.mm index a25ab4e..e3996416c 100644 --- a/device/gamepad/gamepad_standard_mappings_mac.mm +++ b/device/gamepad/gamepad_standard_mappings_mac.mm
@@ -34,14 +34,20 @@ void MapperXboxOneHidGamepad(const blink::WebGamepad& input, blink::WebGamepad* mapped) { *mapped = input; - mapped->buttons[BUTTON_INDEX_LEFT_TRIGGER] = AxisToButton(input.axes[2]); - mapped->buttons[BUTTON_INDEX_RIGHT_TRIGGER] = AxisToButton(input.axes[5]); - mapped->buttons[BUTTON_INDEX_BACK_SELECT] = input.buttons[6]; - mapped->buttons[BUTTON_INDEX_START] = input.buttons[7]; - mapped->buttons[BUTTON_INDEX_LEFT_THUMBSTICK] = input.buttons[8]; - mapped->buttons[BUTTON_INDEX_RIGHT_THUMBSTICK] = input.buttons[9]; - mapped->axes[AXIS_INDEX_RIGHT_STICK_X] = input.axes[3]; - mapped->axes[AXIS_INDEX_RIGHT_STICK_Y] = input.axes[4]; + + mapped->buttons[BUTTON_INDEX_PRIMARY] = input.buttons[0]; + mapped->buttons[BUTTON_INDEX_SECONDARY] = input.buttons[1]; + mapped->buttons[BUTTON_INDEX_TERTIARY] = input.buttons[3]; + mapped->buttons[BUTTON_INDEX_QUATERNARY] = input.buttons[4]; + mapped->buttons[BUTTON_INDEX_LEFT_SHOULDER] = input.buttons[6]; + mapped->buttons[BUTTON_INDEX_RIGHT_SHOULDER] = input.buttons[7]; + mapped->buttons[BUTTON_INDEX_LEFT_TRIGGER] = AxisToButton(input.axes[3]); + mapped->buttons[BUTTON_INDEX_RIGHT_TRIGGER] = AxisToButton(input.axes[4]); + mapped->buttons[BUTTON_INDEX_BACK_SELECT] = NullButton(); + mapped->buttons[BUTTON_INDEX_START] = input.buttons[11]; + mapped->buttons[BUTTON_INDEX_LEFT_THUMBSTICK] = input.buttons[13]; + mapped->buttons[BUTTON_INDEX_RIGHT_THUMBSTICK] = input.buttons[14]; + mapped->axes[AXIS_INDEX_RIGHT_STICK_Y] = input.axes[5]; DpadFromAxis(mapped, input.axes[9]); mapped->buttonsLength = BUTTON_INDEX_COUNT - 1; /* no meta */ @@ -378,9 +384,9 @@ {"045e", "028f", MapperXbox360Gamepad}, // Xbox 360 Wireless {"045e", "02d1", MapperXbox360Gamepad}, // Xbox One Wired {"045e", "02dd", MapperXbox360Gamepad}, // Xbox One Wired (2015 FW) - {"045e", "02e0", MapperXboxOneHidGamepad}, // Xbox One S (Bluetooth mode) {"045e", "02e3", MapperXbox360Gamepad}, // Xbox One Elite Wired {"045e", "02ea", MapperXbox360Gamepad}, // Xbox One S (USB) + {"045e", "02fd", MapperXboxOneHidGamepad}, // Xbox One S (Bluetooth) {"045e", "0719", MapperXbox360Gamepad}, // Xbox 360 Wireless {"046d", "c216", MapperDirectInputStyle}, // Logitech F310, D mode {"046d", "c218", MapperDirectInputStyle}, // Logitech F510, D mode
diff --git a/device/nfc/BUILD.gn b/device/nfc/BUILD.gn index fb6b506..45dd3691 100644 --- a/device/nfc/BUILD.gn +++ b/device/nfc/BUILD.gn
@@ -9,6 +9,4 @@ sources = [ "nfc.mojom", ] - - use_new_wrapper_types = false }
diff --git a/device/serial/BUILD.gn b/device/serial/BUILD.gn index 3fd7eb5..2881619 100644 --- a/device/serial/BUILD.gn +++ b/device/serial/BUILD.gn
@@ -89,6 +89,4 @@ sources = [ "serial.mojom", ] - - use_new_wrapper_types = false }
diff --git a/device/serial/serial_device_enumerator_linux.cc b/device/serial/serial_device_enumerator_linux.cc index 5b0faf2..dbeccecb 100644 --- a/device/serial/serial_device_enumerator_linux.cc +++ b/device/serial/serial_device_enumerator_linux.cc
@@ -87,7 +87,7 @@ info->has_product_id = true; } if (product_name) - info->display_name = product_name; + info->display_name.emplace(product_name); devices.push_back(std::move(info)); } }
diff --git a/device/serial/serial_device_enumerator_mac.cc b/device/serial/serial_device_enumerator_mac.cc index bea252e..4bf3e5ed 100644 --- a/device/serial/serial_device_enumerator_mac.cc +++ b/device/serial/serial_device_enumerator_mac.cc
@@ -137,7 +137,7 @@ mojo::String displayName; if (GetStringProperty(scoped_device.get(), CFSTR(kUSBProductString), &displayName)) { - callout_info->display_name = displayName; + callout_info->display_name = displayName.PassStorage(); } // Each serial device has two "paths" in /dev/ associated with it: a
diff --git a/device/serial/serial_device_enumerator_win.cc b/device/serial/serial_device_enumerator_win.cc index 24d1ed7..149331d 100644 --- a/device/serial/serial_device_enumerator_win.cc +++ b/device/serial/serial_device_enumerator_win.cc
@@ -113,7 +113,7 @@ std::string display_name; if (GetDisplayName(friendly_name, &display_name)) - info->display_name = display_name; + info->display_name = std::move(display_name); std::string hardware_id; // SPDRP_HARDWAREID looks like "FTDIBUS\COMPORT&VID_0403&PID_6001".
diff --git a/device/vr/BUILD.gn b/device/vr/BUILD.gn index bf2372b..df6aba9 100644 --- a/device/vr/BUILD.gn +++ b/device/vr/BUILD.gn
@@ -79,6 +79,4 @@ sources = [ "vr_service.mojom", ] - - use_new_wrapper_types = false }
diff --git a/device/vr/android/gvr/gvr_delegate.h b/device/vr/android/gvr/gvr_delegate.h index d7b4297..4e721cb 100644 --- a/device/vr/android/gvr/gvr_delegate.h +++ b/device/vr/android/gvr/gvr_delegate.h
@@ -5,6 +5,7 @@ #ifndef DEVICE_VR_ANDROID_GVR_DELEGATE_H #define DEVICE_VR_ANDROID_GVR_DELEGATE_H +#include "base/memory/weak_ptr.h" #include "device/vr/android/gvr/gvr_device_provider.h" #include "device/vr/vr_export.h" #include "third_party/gvr-android-sdk/src/ndk/include/vr/gvr/capi/include/gvr_types.h" @@ -34,9 +35,10 @@ static void SetInstance(GvrDelegateProvider* delegate_provider); static GvrDelegateProvider* GetInstance(); - virtual bool RequestWebVRPresent(GvrDeviceProvider* device_provider) = 0; + virtual bool RequestWebVRPresent( + base::WeakPtr<GvrDeviceProvider> device_provider) = 0; virtual void ExitWebVRPresent() = 0; - virtual GvrDelegate* GetNonPresentingDelegate() = 0; + virtual base::WeakPtr<GvrDelegate> GetNonPresentingDelegate() = 0; virtual void DestroyNonPresentingDelegate() = 0; private:
diff --git a/device/vr/android/gvr/gvr_device.cc b/device/vr/android/gvr/gvr_device.cc index be3d657..d369134c 100644 --- a/device/vr/android/gvr/gvr_device.cc +++ b/device/vr/android/gvr/gvr_device.cc
@@ -10,6 +10,7 @@ #include "base/time/time.h" #include "base/trace_event/trace_event.h" #include "device/vr/android/gvr/gvr_delegate.h" +#include "device/vr/android/gvr/gvr_device_provider.h" #include "device/vr/vr_device_manager.h" #include "third_party/gvr-android-sdk/src/ndk/include/vr/gvr/capi/include/gvr.h" #include "third_party/gvr-android-sdk/src/ndk/include/vr/gvr/capi/include/gvr_types.h" @@ -24,8 +25,9 @@ } // namespace -GvrDevice::GvrDevice(GvrDeviceProvider* provider, GvrDelegate* delegate) - : VRDevice(provider), delegate_(delegate), gvr_provider_(provider) {} +GvrDevice::GvrDevice(GvrDeviceProvider* provider, + const base::WeakPtr<GvrDelegate>& delegate) + : VRDevice(), delegate_(delegate), gvr_provider_(provider) {} GvrDevice::~GvrDevice() {} @@ -50,8 +52,8 @@ left_eye->fieldOfView = mojom::VRFieldOfView::New(); right_eye->fieldOfView = mojom::VRFieldOfView::New(); - left_eye->offset = mojo::Array<float>::New(3); - right_eye->offset = mojo::Array<float>::New(3); + left_eye->offset.resize(3); + right_eye->offset.resize(3); // TODO(bajones): GVR has a bug that causes it to return bad render target // sizes when the phone is in portait mode. Send arbitrary, @@ -127,12 +129,9 @@ return device; } -mojom::VRPosePtr GvrDevice::GetPose(VRServiceImpl* service) { +mojom::VRPosePtr GvrDevice::GetPose() { TRACE_EVENT0("input", "GvrDevice::GetSensorState"); - if (!IsAccessAllowed(service)) - return nullptr; - mojom::VRPosePtr pose = mojom::VRPose::New(); pose->timestamp = base::Time::Now().ToJsTime(); @@ -140,19 +139,22 @@ // Increment pose frame counter always, even if it's a faked pose. pose->poseIndex = ++pose_index_; - pose->orientation = mojo::Array<float>::New(4); + pose->orientation.emplace(4); gvr::GvrApi* gvr_api = GetGvrApi(); if (!gvr_api) { // If we don't have a GvrApi instance return a static forward orientation. - pose->orientation[0] = 0.0; - pose->orientation[1] = 0.0; - pose->orientation[2] = 0.0; - pose->orientation[3] = 1.0; + pose->orientation.value()[0] = 0.0; + pose->orientation.value()[1] = 0.0; + pose->orientation.value()[2] = 0.0; + pose->orientation.value()[3] = 1.0; return pose; } + if (!delegate_) + return nullptr; + gvr::ClockTimePoint target_time = gvr::GvrApi::GetTimePointNow(); target_time.monotonic_system_time_nanos += kPredictionTimeWithoutVsyncNanos; @@ -171,15 +173,15 @@ gfx::DecomposedTransform decomposed_transform; gfx::DecomposeTransform(&decomposed_transform, transform); - pose->orientation[0] = decomposed_transform.quaternion[0]; - pose->orientation[1] = decomposed_transform.quaternion[1]; - pose->orientation[2] = decomposed_transform.quaternion[2]; - pose->orientation[3] = decomposed_transform.quaternion[3]; + pose->orientation.value()[0] = decomposed_transform.quaternion[0]; + pose->orientation.value()[1] = decomposed_transform.quaternion[1]; + pose->orientation.value()[2] = decomposed_transform.quaternion[2]; + pose->orientation.value()[3] = decomposed_transform.quaternion[3]; - pose->position = mojo::Array<float>::New(3); - pose->position[0] = decomposed_transform.translate[0]; - pose->position[1] = decomposed_transform.translate[1]; - pose->position[2] = decomposed_transform.translate[2]; + pose->position.emplace(3); + pose->position.value()[0] = decomposed_transform.translate[0]; + pose->position.value()[1] = decomposed_transform.translate[1]; + pose->position.value()[2] = decomposed_transform.translate[2]; } // Save the underlying GVR pose for use by rendering. It can't use a @@ -189,10 +191,7 @@ return pose; } -void GvrDevice::ResetPose(VRServiceImpl* service) { - if (!IsAccessAllowed(service)) - return; - +void GvrDevice::ResetPose() { gvr::GvrApi* gvr_api = GetGvrApi(); // Should never call RecenterTracking when using with Daydream viewers. On @@ -201,15 +200,7 @@ gvr_api->RecenterTracking(); } -bool GvrDevice::RequestPresent(VRServiceImpl* service, bool secure_origin) { - if (!IsAccessAllowed(service)) - return false; - - // One service could present on several devices at the same time - // and different service could present on different devices the same time - if (presenting_service_ == nullptr) - presenting_service_ = service; - +bool GvrDevice::RequestPresent(bool secure_origin) { secure_origin_ = secure_origin; if (delegate_) delegate_->SetWebVRSecureOrigin(secure_origin_); @@ -217,24 +208,19 @@ return gvr_provider_->RequestPresent(); } -void GvrDevice::ExitPresent(VRServiceImpl* service) { - if (IsPresentingService(service)) - presenting_service_ = nullptr; - +void GvrDevice::ExitPresent() { gvr_provider_->ExitPresent(); - OnExitPresent(service); + OnExitPresent(); } -void GvrDevice::SubmitFrame(VRServiceImpl* service, mojom::VRPosePtr pose) { - if (!IsPresentingService(service) || !delegate_) - return; - delegate_->SubmitWebVRFrame(); +void GvrDevice::SubmitFrame(mojom::VRPosePtr pose) { + if (delegate_) + delegate_->SubmitWebVRFrame(); } -void GvrDevice::UpdateLayerBounds(VRServiceImpl* service, - mojom::VRLayerBoundsPtr leftBounds, +void GvrDevice::UpdateLayerBounds(mojom::VRLayerBoundsPtr leftBounds, mojom::VRLayerBoundsPtr rightBounds) { - if (!IsAccessAllowed(service) || !delegate_) + if (!delegate_) return; delegate_->UpdateWebVRTextureBounds(0, // Left eye @@ -245,7 +231,7 @@ rightBounds->width, rightBounds->height); } -void GvrDevice::SetDelegate(GvrDelegate* delegate) { +void GvrDevice::SetDelegate(const base::WeakPtr<GvrDelegate>& delegate) { delegate_ = delegate; // Notify the clients that this device has changed
diff --git a/device/vr/android/gvr/gvr_device.h b/device/vr/android/gvr/gvr_device.h index 339b30d..2ed799d4 100644 --- a/device/vr/android/gvr/gvr_device.h +++ b/device/vr/android/gvr/gvr_device.h
@@ -6,6 +6,7 @@ #define DEVICE_VR_ANDROID_GVR_DEVICE_H #include "base/macros.h" +#include "base/memory/weak_ptr.h" #include "device/vr/vr_device.h" namespace gvr { @@ -19,30 +20,30 @@ class GvrDevice : public VRDevice { public: - GvrDevice(GvrDeviceProvider* provider, GvrDelegate* delegate); + GvrDevice(GvrDeviceProvider* provider, + const base::WeakPtr<GvrDelegate>& delegate); ~GvrDevice() override; // VRDevice mojom::VRDisplayInfoPtr GetVRDevice() override; - mojom::VRPosePtr GetPose(VRServiceImpl* service) override; - void ResetPose(VRServiceImpl* service) override; + mojom::VRPosePtr GetPose() override; + void ResetPose() override; - bool RequestPresent(VRServiceImpl* service, bool secure_origin) override; - void ExitPresent(VRServiceImpl* service) override; + bool RequestPresent(bool secure_origin) override; + void ExitPresent() override; - void SubmitFrame(VRServiceImpl* service, mojom::VRPosePtr pose) override; - void UpdateLayerBounds(VRServiceImpl* service, - mojom::VRLayerBoundsPtr leftBounds, + void SubmitFrame(mojom::VRPosePtr pose) override; + void UpdateLayerBounds(mojom::VRLayerBoundsPtr leftBounds, mojom::VRLayerBoundsPtr rightBounds) override; - void SetDelegate(GvrDelegate* delegate); + void SetDelegate(const base::WeakPtr<GvrDelegate>& delegate); private: gvr::GvrApi* GetGvrApi(); - GvrDelegate* delegate_; + base::WeakPtr<GvrDelegate> delegate_; GvrDeviceProvider* gvr_provider_; - bool secure_origin_; + bool secure_origin_ = false; uint32_t pose_index_ = 0; DISALLOW_COPY_AND_ASSIGN(GvrDevice);
diff --git a/device/vr/android/gvr/gvr_device_provider.cc b/device/vr/android/gvr/gvr_device_provider.cc index 8a3637d..2581f7b6 100644 --- a/device/vr/android/gvr/gvr_device_provider.cc +++ b/device/vr/android/gvr/gvr_device_provider.cc
@@ -23,9 +23,7 @@ namespace device { -GvrDeviceProvider::GvrDeviceProvider() - : VRDeviceProvider(), - main_thread_task_runner_(base::ThreadTaskRunnerHandle::Get()) {} +GvrDeviceProvider::GvrDeviceProvider() : weak_ptr_factory_(this) {} GvrDeviceProvider::~GvrDeviceProvider() { device::GvrDelegateProvider* delegate_provider = @@ -62,48 +60,57 @@ return false; // RequestWebVRPresent is async as a render thread may be created. - return delegate_provider->RequestWebVRPresent(this); + return delegate_provider->RequestWebVRPresent(weak_ptr_factory_.GetWeakPtr()); } +// VR presentation exit requested by the API. void GvrDeviceProvider::ExitPresent() { - DCHECK(main_thread_task_runner_->BelongsToCurrentThread()); + SwitchToNonPresentingDelegate(); +} +void GvrDeviceProvider::OnGvrDelegateReady( + const base::WeakPtr<GvrDelegate>& delegate) { + if (!vr_device_) + return; + vr_device_->SetDelegate(delegate); + GamepadDataFetcherManager::GetInstance()->AddFactory( + new GvrGamepadDataFetcher::Factory(delegate, vr_device_->id())); +} + +// VR presentation exit requested by the delegate (probably via UI). +void GvrDeviceProvider::OnGvrDelegateRemoved() { if (!vr_device_) return; - device::GvrDelegateProvider* delegate_provider = - device::GvrDelegateProvider::GetInstance(); - if (!delegate_provider) + SwitchToNonPresentingDelegate(); + vr_device_->OnExitPresent(); +} + +void GvrDeviceProvider::OnDisplayBlur() { + if (!vr_device_) + return; + vr_device_->OnDisplayBlur(); +} + +void GvrDeviceProvider::OnDisplayFocus() { + if (!vr_device_) + return; + vr_device_->OnDisplayFocus(); +} + +void GvrDeviceProvider::SwitchToNonPresentingDelegate() { + GvrDelegateProvider* delegate_provider = GvrDelegateProvider::GetInstance(); + if (!vr_device_ || !delegate_provider) return; vr_device_->SetDelegate(delegate_provider->GetNonPresentingDelegate()); + // Remove GVR gamepad polling. GamepadDataFetcherManager::GetInstance()->RemoveSourceFactory( GAMEPAD_SOURCE_GVR); + // If we're presenting currently stop. delegate_provider->ExitWebVRPresent(); } -void GvrDeviceProvider::OnGvrDelegateReady(GvrDelegate* delegate) { - main_thread_task_runner_->PostTask( - FROM_HERE, - base::Bind(&GvrDeviceProvider::GvrDelegateReady, base::Unretained(this), - base::Unretained(delegate))); -} - -void GvrDeviceProvider::OnGvrDelegateRemoved() { - DCHECK(main_thread_task_runner_->BelongsToCurrentThread()); - if (!vr_device_) - return; - ExitPresent(); -} - -void GvrDeviceProvider::GvrDelegateReady(GvrDelegate* delegate) { - DCHECK(main_thread_task_runner_->BelongsToCurrentThread()); - - vr_device_->SetDelegate(delegate); - GamepadDataFetcherManager::GetInstance()->AddFactory( - new GvrGamepadDataFetcher::Factory(delegate, vr_device_->id())); -} - } // namespace device
diff --git a/device/vr/android/gvr/gvr_device_provider.h b/device/vr/android/gvr/gvr_device_provider.h index 02f7758..1eaa987 100644 --- a/device/vr/android/gvr/gvr_device_provider.h +++ b/device/vr/android/gvr/gvr_device_provider.h
@@ -8,6 +8,7 @@ #include <memory> #include "base/macros.h" +#include "base/memory/weak_ptr.h" #include "base/single_thread_task_runner.h" #include "device/vr/vr_device.h" #include "device/vr/vr_device_provider.h" @@ -15,6 +16,7 @@ namespace device { +class GvrDelegateProvider; class GvrDelegate; class GvrDevice; class VRServiceImpl; @@ -27,21 +29,21 @@ void GetDevices(std::vector<VRDevice*>* devices) override; void Initialize() override; - // Called from GvrDevice + // Called from GvrDevice. bool RequestPresent(); void ExitPresent(); - // Called from GvrDelegate - void OnGvrDelegateReady(GvrDelegate* delegate); + void OnGvrDelegateReady(const base::WeakPtr<GvrDelegate>& delegate); void OnGvrDelegateRemoved(); + void OnDisplayBlur(); + void OnDisplayFocus(); private: - void GvrDelegateReady(GvrDelegate* delegate); - void GvrDelegateRemoved(); + void SwitchToNonPresentingDelegate(); std::unique_ptr<GvrDevice> vr_device_; - scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner_; + base::WeakPtrFactory<GvrDeviceProvider> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(GvrDeviceProvider); };
diff --git a/device/vr/android/gvr/gvr_gamepad_data_fetcher.cc b/device/vr/android/gvr/gvr_gamepad_data_fetcher.cc index 17bc49a..219897a6 100644 --- a/device/vr/android/gvr/gvr_gamepad_data_fetcher.cc +++ b/device/vr/android/gvr/gvr_gamepad_data_fetcher.cc
@@ -28,16 +28,18 @@ using namespace blink; -GvrGamepadDataFetcher::Factory::Factory(GvrDelegate* delegate, - unsigned int display_id) +GvrGamepadDataFetcher::Factory::Factory( + const base::WeakPtr<GvrDelegate>& delegate, + unsigned int display_id) : delegate_(delegate), display_id_(display_id) {} GvrGamepadDataFetcher::Factory::~Factory() {} std::unique_ptr<GamepadDataFetcher> GvrGamepadDataFetcher::Factory::CreateDataFetcher() { - return std::unique_ptr<GamepadDataFetcher>( - new GvrGamepadDataFetcher(delegate_, display_id_)); + if (!delegate_) + return nullptr; + return base::MakeUnique<GvrGamepadDataFetcher>(delegate_.get(), display_id_); } GamepadSource GvrGamepadDataFetcher::Factory::source() {
diff --git a/device/vr/android/gvr/gvr_gamepad_data_fetcher.h b/device/vr/android/gvr/gvr_gamepad_data_fetcher.h index 4c5452f..2e16c0b 100644 --- a/device/vr/android/gvr/gvr_gamepad_data_fetcher.h +++ b/device/vr/android/gvr/gvr_gamepad_data_fetcher.h
@@ -7,6 +7,7 @@ #include <string> +#include "base/memory/weak_ptr.h" #include "device/gamepad/gamepad_data_fetcher.h" #include "third_party/gvr-android-sdk/src/ndk/include/vr/gvr/capi/include/gvr_controller.h" #include "third_party/gvr-android-sdk/src/ndk/include/vr/gvr/capi/include/gvr_types.h" @@ -19,13 +20,14 @@ public: class Factory : public GamepadDataFetcherFactory { public: - Factory(GvrDelegate* delegate, unsigned int display_id); + Factory(const base::WeakPtr<GvrDelegate>& delegate, + unsigned int display_id); ~Factory() override; std::unique_ptr<GamepadDataFetcher> CreateDataFetcher() override; GamepadSource source() override; private: - GvrDelegate* delegate_; + base::WeakPtr<GvrDelegate> delegate_; unsigned int display_id_; };
diff --git a/device/vr/test/fake_vr_device.cc b/device/vr/test/fake_vr_device.cc index a011c77..2f438676 100644 --- a/device/vr/test/fake_vr_device.cc +++ b/device/vr/test/fake_vr_device.cc
@@ -6,7 +6,7 @@ namespace device { -FakeVRDevice::FakeVRDevice(VRDeviceProvider* provider) : VRDevice(provider) { +FakeVRDevice::FakeVRDevice() { device_ = mojom::VRDisplayInfo::New(); pose_ = mojom::VRPose::New(); @@ -39,7 +39,7 @@ eye->fieldOfView->leftDegrees = fov; eye->fieldOfView->rightDegrees = fov; - eye->offset = mojo::Array<float>::New(3); + eye->offset.resize(3); eye->offset[0] = offset; eye->offset[1] = 0.0f; eye->offset[2] = 0.0f; @@ -63,23 +63,22 @@ return display.Clone(); } -mojom::VRPosePtr FakeVRDevice::GetPose(VRServiceImpl* service) { +mojom::VRPosePtr FakeVRDevice::GetPose() { return pose_.Clone(); } -void FakeVRDevice::ResetPose(VRServiceImpl* service) {} +void FakeVRDevice::ResetPose() {} // TODO(shaobo.yan@intel.com): Will implemenate for VRDeviceServiceImpl tests. -bool FakeVRDevice::RequestPresent(VRServiceImpl* service, bool secure_origin) { +bool FakeVRDevice::RequestPresent(bool secure_origin) { return true; } -void FakeVRDevice::ExitPresent(VRServiceImpl* service) {} +void FakeVRDevice::ExitPresent() {} -void FakeVRDevice::SubmitFrame(VRServiceImpl* service, mojom::VRPosePtr pose) {} +void FakeVRDevice::SubmitFrame(mojom::VRPosePtr pose) {} -void FakeVRDevice::UpdateLayerBounds(VRServiceImpl* service, - mojom::VRLayerBoundsPtr leftBounds, +void FakeVRDevice::UpdateLayerBounds(mojom::VRLayerBoundsPtr leftBounds, mojom::VRLayerBoundsPtr rightBounds) {} } // namespace device
diff --git a/device/vr/test/fake_vr_device.h b/device/vr/test/fake_vr_device.h index 8b3d31d..c9de699 100644 --- a/device/vr/test/fake_vr_device.h +++ b/device/vr/test/fake_vr_device.h
@@ -6,6 +6,7 @@ #define DEVICE_VR_TEST_FAKE_VR_DEVICE_H_ #include "base/macros.h" +#include "base/memory/ref_counted.h" #include "device/vr/vr_device.h" #include "device/vr/vr_device_provider.h" @@ -13,7 +14,7 @@ class FakeVRDevice : public VRDevice { public: - explicit FakeVRDevice(VRDeviceProvider* provider); + explicit FakeVRDevice(); ~FakeVRDevice() override; void InitBasicDevice(); @@ -22,14 +23,13 @@ void SetPose(const mojom::VRPosePtr& state); mojom::VRDisplayInfoPtr GetVRDevice() override; - mojom::VRPosePtr GetPose(VRServiceImpl* service) override; - void ResetPose(VRServiceImpl* service) override; + mojom::VRPosePtr GetPose() override; + void ResetPose() override; - bool RequestPresent(VRServiceImpl* service, bool secure_origin) override; - void ExitPresent(VRServiceImpl* service) override; - void SubmitFrame(VRServiceImpl* service, mojom::VRPosePtr pose) override; - void UpdateLayerBounds(VRServiceImpl* service, - mojom::VRLayerBoundsPtr leftBounds, + bool RequestPresent(bool secure_origin) override; + void ExitPresent() override; + void SubmitFrame(mojom::VRPosePtr pose) override; + void UpdateLayerBounds(mojom::VRLayerBoundsPtr leftBounds, mojom::VRLayerBoundsPtr rightBounds) override; private:
diff --git a/device/vr/vr_device.cc b/device/vr/vr_device.cc index c580d5f..59abe73 100644 --- a/device/vr/vr_device.cc +++ b/device/vr/vr_device.cc
@@ -10,8 +10,7 @@ unsigned int VRDevice::next_id_ = 1; -VRDevice::VRDevice(VRDeviceProvider* provider) - : presenting_service_(nullptr), provider_(provider), id_(next_id_) { +VRDevice::VRDevice() : presenting_service_(nullptr), id_(next_id_) { // Prevent wraparound. Devices with this ID will be treated as invalid. if (next_id_ != VR_DEVICE_LAST_ID) next_id_++; @@ -19,7 +18,7 @@ VRDevice::~VRDevice() {} -bool VRDevice::RequestPresent(VRServiceImpl* service, bool secure_origin) { +bool VRDevice::RequestPresent(bool secure_origin) { return true; }; @@ -30,7 +29,8 @@ } void VRDevice::RemoveService(VRServiceImpl* service) { - ExitPresent(service); + if (IsPresentingService(service)) + ExitPresent(); displays_.erase(service); } @@ -47,20 +47,30 @@ if (vr_device_info.is_null()) return; - for (const auto& display : displays_) { - mojom::VRDisplayClient* client = display.second->client(); - if (client) - client->OnDisplayChanged(vr_device_info.Clone()); - } + for (const auto& display : displays_) + display.second->client()->OnDisplayChanged(vr_device_info.Clone()); } -void VRDevice::OnExitPresent(VRServiceImpl* service) { - DisplayClientMap::iterator it = displays_.find(service); - if (it != displays_.end()) { - mojom::VRDisplayClient* client = it->second->client(); - if (client) - client->OnExitPresent(); - } +void VRDevice::OnExitPresent() { + DisplayClientMap::iterator it = displays_.find(presenting_service_); + if (it != displays_.end()) + it->second->client()->OnExitPresent(); + + SetPresentingService(nullptr); +} + +void VRDevice::OnDisplayBlur() { + for (const auto& display : displays_) + display.second->client()->OnDisplayBlur(); +} + +void VRDevice::OnDisplayFocus() { + for (const auto& display : displays_) + display.second->client()->OnDisplayFocus(); +} + +void VRDevice::SetPresentingService(VRServiceImpl* service) { + presenting_service_ = service; } } // namespace device
diff --git a/device/vr/vr_device.h b/device/vr/vr_device.h index 81bbf5e..2d05b6d9a 100644 --- a/device/vr/vr_device.h +++ b/device/vr/vr_device.h
@@ -19,7 +19,6 @@ namespace device { -class VRDeviceProvider; class VRDisplayImpl; class VRServiceImpl; @@ -27,21 +26,19 @@ class DEVICE_VR_EXPORT VRDevice { public: - explicit VRDevice(VRDeviceProvider* provider); + VRDevice(); virtual ~VRDevice(); - VRDeviceProvider* provider() const { return provider_; } unsigned int id() const { return id_; } virtual mojom::VRDisplayInfoPtr GetVRDevice() = 0; - virtual mojom::VRPosePtr GetPose(VRServiceImpl* service) = 0; - virtual void ResetPose(VRServiceImpl* service) = 0; + virtual mojom::VRPosePtr GetPose() = 0; + virtual void ResetPose() = 0; - virtual bool RequestPresent(VRServiceImpl* service, bool secure_origin) = 0; - virtual void ExitPresent(VRServiceImpl* service) = 0; - virtual void SubmitFrame(VRServiceImpl* service, mojom::VRPosePtr pose) = 0; - virtual void UpdateLayerBounds(VRServiceImpl* service, - mojom::VRLayerBoundsPtr leftBounds, + virtual bool RequestPresent(bool secure_origin) = 0; + virtual void ExitPresent() = 0; + virtual void SubmitFrame(mojom::VRPosePtr pose) = 0; + virtual void UpdateLayerBounds(mojom::VRLayerBoundsPtr leftBounds, mojom::VRLayerBoundsPtr rightBounds) = 0; virtual void AddService(VRServiceImpl* service); @@ -53,9 +50,16 @@ virtual bool IsPresentingService(VRServiceImpl* service); virtual void OnDisplayChanged(); - virtual void OnExitPresent(VRServiceImpl* service); + virtual void OnExitPresent(); + virtual void OnDisplayBlur(); + virtual void OnDisplayFocus(); protected: + friend class VRDisplayImpl; + + void SetPresentingService(VRServiceImpl* service); + + private: // Each Service have one VRDisplay with one VRDevice. // TODO(shaobo.yan@intel.com): Since the VRDisplayImpl knows its VRServiceImpl // we should @@ -66,8 +70,6 @@ // TODO(shaobo.yan@intel.com): Should track presenting VRDisplayImpl instead. VRServiceImpl* presenting_service_; - private: - VRDeviceProvider* provider_; unsigned int id_; static unsigned int next_id_;
diff --git a/device/vr/vr_device_manager.cc b/device/vr/vr_device_manager.cc index 530feb8..a1d0144f 100644 --- a/device/vr/vr_device_manager.cc +++ b/device/vr/vr_device_manager.cc
@@ -27,14 +27,12 @@ has_scheduled_poll_(false) { // Register VRDeviceProviders for the current platform #if defined(OS_ANDROID) - RegisterProvider(base::WrapUnique(new GvrDeviceProvider())); + RegisterProvider(base::MakeUnique<GvrDeviceProvider>()); #endif } VRDeviceManager::VRDeviceManager(std::unique_ptr<VRDeviceProvider> provider) - : vr_initialized_(false), - keep_alive_(true), - has_scheduled_poll_(false) { + : vr_initialized_(false), keep_alive_(true), has_scheduled_poll_(false) { thread_checker_.DetachFromThread(); RegisterProvider(std::move(provider)); SetInstance(this); @@ -55,7 +53,7 @@ void VRDeviceManager::SetInstance(VRDeviceManager* instance) { // Unit tests can create multiple instances but only one should exist at any // given time so g_vr_device_manager should only go from nullptr to - // non-nullptr and vica versa. + // non-nullptr and vice versa. CHECK_NE(!!instance, !!g_vr_device_manager); g_vr_device_manager = instance; } @@ -147,7 +145,7 @@ void VRDeviceManager::RegisterProvider( std::unique_ptr<VRDeviceProvider> provider) { - providers_.push_back(make_linked_ptr(provider.release())); + providers_.push_back(std::move(provider)); } void VRDeviceManager::SchedulePollEvents() {
diff --git a/device/vr/vr_device_manager.h b/device/vr/vr_device_manager.h index b8b9fda..4417470d 100644 --- a/device/vr/vr_device_manager.h +++ b/device/vr/vr_device_manager.h
@@ -12,7 +12,7 @@ #include <vector> #include "base/macros.h" -#include "base/memory/linked_ptr.h" +#include "base/memory/ref_counted.h" #include "base/threading/thread_checker.h" #include "base/timer/timer.h" #include "device/vr/vr_device.h" @@ -60,7 +60,7 @@ void PollEvents(); void StopSchedulingPollEvents(); - using ProviderList = std::vector<linked_ptr<VRDeviceProvider>>; + using ProviderList = std::vector<std::unique_ptr<VRDeviceProvider>>; ProviderList providers_; // Devices are owned by their providers.
diff --git a/device/vr/vr_device_manager_unittest.cc b/device/vr/vr_device_manager_unittest.cc index 5298f72..6ff7a473 100644 --- a/device/vr/vr_device_manager_unittest.cc +++ b/device/vr/vr_device_manager_unittest.cc
@@ -30,7 +30,7 @@ } protected: - FakeVRDeviceProvider* provider_; + FakeVRDeviceProvider* provider_ = nullptr; std::unique_ptr<VRDeviceManager> device_manager_; std::unique_ptr<VRServiceImpl> vr_service_; @@ -42,9 +42,8 @@ VRDeviceManagerTest::~VRDeviceManagerTest() {} void VRDeviceManagerTest::SetUp() { - std::unique_ptr<FakeVRDeviceProvider> provider(new FakeVRDeviceProvider()); - provider_ = provider.get(); - device_manager_.reset(new VRDeviceManager(std::move(provider))); + provider_ = new FakeVRDeviceProvider(); + device_manager_.reset(new VRDeviceManager(base::WrapUnique(provider_))); vr_service_.reset(new VRServiceImpl()); } @@ -69,23 +68,21 @@ VRDevice* queried_device = GetDevice(1); EXPECT_EQ(nullptr, queried_device); - std::unique_ptr<FakeVRDevice> device1(new FakeVRDevice(provider_)); - provider_->AddDevice(device1.get()); + FakeVRDevice device1; + provider_->AddDevice(&device1); success = device_manager_->GetVRDevices(vr_service_.get()); EXPECT_TRUE(success); // Should have successfully returned one device. - EXPECT_EQ(device1.get(), GetDevice(device1->id())); + EXPECT_EQ(&device1, GetDevice(device1.id())); - std::unique_ptr<FakeVRDevice> device2(new FakeVRDevice(provider_)); - provider_->AddDevice(device2.get()); + FakeVRDevice device2; + provider_->AddDevice(&device2); success = device_manager_->GetVRDevices(vr_service_.get()); EXPECT_TRUE(success); // Querying the WebVRDevice index should return the correct device. - VRDevice* queried_device1 = GetDevice(device1->id()); - EXPECT_EQ(device1.get(), queried_device1); - VRDevice* queried_device2 = GetDevice(device2->id()); - EXPECT_EQ(device2.get(), queried_device2); + EXPECT_EQ(&device1, GetDevice(device1.id())); + EXPECT_EQ(&device2, GetDevice(device2.id())); } } // namespace device
diff --git a/device/vr/vr_display_impl.cc b/device/vr/vr_display_impl.cc index c074205..1449c55 100644 --- a/device/vr/vr_display_impl.cc +++ b/device/vr/vr_display_impl.cc
@@ -21,29 +21,51 @@ VRDisplayImpl::~VRDisplayImpl() {} void VRDisplayImpl::GetPose(const GetPoseCallback& callback) { - callback.Run(device_->GetPose(service_.get())); + if (!device_->IsAccessAllowed(service_.get())) { + callback.Run(nullptr); + return; + } + + callback.Run(device_->GetPose()); } void VRDisplayImpl::ResetPose() { - device_->ResetPose(service_.get()); + if (!device_->IsAccessAllowed(service_.get())) + return; + + device_->ResetPose(); } void VRDisplayImpl::RequestPresent(bool secureOrigin, const RequestPresentCallback& callback) { - callback.Run(device_->RequestPresent(service_.get(), secureOrigin)); + if (!device_->IsAccessAllowed(service_.get())) { + callback.Run(false); + return; + } + + bool success = device_->RequestPresent(secureOrigin); + if (success) { + device_->SetPresentingService(service_.get()); + } + callback.Run(success); } void VRDisplayImpl::ExitPresent() { - device_->ExitPresent(service_.get()); + if (device_->IsPresentingService(service_.get())) + device_->ExitPresent(); } void VRDisplayImpl::SubmitFrame(mojom::VRPosePtr pose) { - device_->SubmitFrame(service_.get(), std::move(pose)); + if (!device_->IsPresentingService(service_.get())) + return; + device_->SubmitFrame(std::move(pose)); } void VRDisplayImpl::UpdateLayerBounds(mojom::VRLayerBoundsPtr leftBounds, mojom::VRLayerBoundsPtr rightBounds) { - device_->UpdateLayerBounds(service_.get(), std::move(leftBounds), - std::move(rightBounds)); + if (!device_->IsAccessAllowed(service_.get())) + return; + + device_->UpdateLayerBounds(std::move(leftBounds), std::move(rightBounds)); } }
diff --git a/device/vr/vr_service.mojom b/device/vr/vr_service.mojom index ca297d3..08d6e68 100644 --- a/device/vr/vr_service.mojom +++ b/device/vr/vr_service.mojom
@@ -89,4 +89,6 @@ interface VRDisplayClient { OnDisplayChanged(VRDisplayInfo display); OnExitPresent(); + OnDisplayBlur(); + OnDisplayFocus(); };
diff --git a/device/vr/vr_service_impl_unittest.cc b/device/vr/vr_service_impl_unittest.cc index f0b8ce2..96b7e81 100644 --- a/device/vr/vr_service_impl_unittest.cc +++ b/device/vr/vr_service_impl_unittest.cc
@@ -4,6 +4,7 @@ #include "device/vr/vr_service_impl.h" +#include "base/memory/ref_counted.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "device/vr/test/fake_vr_device.h" @@ -69,9 +70,8 @@ protected: void SetUp() override { - std::unique_ptr<FakeVRDeviceProvider> provider(new FakeVRDeviceProvider()); - provider_ = provider.get(); - device_manager_.reset(new VRDeviceManager(std::move(provider))); + provider_ = new FakeVRDeviceProvider(); + device_manager_.reset(new VRDeviceManager(base::WrapUnique(provider_))); } void TearDown() override { base::RunLoop().RunUntilIdle(); } @@ -85,7 +85,7 @@ size_t ServiceCount() { return device_manager_->services_.size(); } base::MessageLoop message_loop_; - FakeVRDeviceProvider* provider_; + FakeVRDeviceProvider* provider_ = nullptr; std::unique_ptr<VRDeviceManager> device_manager_; DISALLOW_COPY_AND_ASSIGN(VRServiceImplTest);
diff --git a/docs/memory-infra/README.md b/docs/memory-infra/README.md new file mode 100644 index 0000000..edb5732 --- /dev/null +++ b/docs/memory-infra/README.md
@@ -0,0 +1,171 @@ +# MemoryInfra + +MemoryInfra is a timeline-based profiling system integrated in chrome://tracing. +It aims at creating Chrome-scale memory measurement tooling so that on any +Chrome in the world --- desktop, mobile, Chrome OS or any other --- with the +click of a button you can understand where memory is being used in your system. + +[TOC] + +## Getting Started + + 1. Get a bleeding-edge or tip-of-tree build of Chrome. + + 2. [Record a trace as usual][record-trace]: open [chrome://tracing][tracing] + on Desktop Chrome or [chrome://inspect?tracing][inspect-tracing] to trace + Chrome for Android. + + 3. Make sure to enable the **memory-infra** category on the right. + + ![Tick the memory-infra checkbox when recording a trace.][memory-infra-box] + + 4. For now, some subsystems only work if Chrome is started with the + `--no-sandbox` flag. + <!-- TODO(primiano) TODO(ssid): https://crbug.com/461788 --> + +[record-trace]: https://sites.google.com/a/chromium.org/dev/developers/how-tos/trace-event-profiling-tool/recording-tracing-runs +[tracing]: chrome://tracing +[inspect-tracing]: chrome://inspect?tracing +[memory-infra-box]: https://storage.googleapis.com/chromium-docs.appspot.com/1c6d1886584e7cc6ffed0d377f32023f8da53e02 + +![Timeline View and Analysis View][tracing-views] + +After recording a trace, you will see the **timeline view**. Timeline view +shows: + + * Total resident memory grouped by process (at the top). + * Total resident memory grouped by subsystem (at the top). + * Allocated memory per subsystem for every process. + +Click one of the ![M][m-blue] dots to bring up the **analysis view**. Click +on a cell in analysis view to reveal more information about its subsystem. +PartitionAlloc for instance, has more details about its partitions. + +![Component details for PartitionAlloc][partalloc-details] + +The purple ![M][m-purple] dots represent heavy dumps. In these dumps, components +can provide more details than in the regular dumps. The full details of the +MemoryInfra UI are explained in its [design doc][mi-ui-doc]. + +[tracing-views]: https://storage.googleapis.com/chromium-docs.appspot.com/db12015bd262385f0f8bd69133330978a99da1ca +[m-blue]: https://storage.googleapis.com/chromium-docs.appspot.com/b60f342e38ff3a3767bbe4c8640d96a2d8bc864b +[partalloc-details]: https://storage.googleapis.com/chromium-docs.appspot.com/02eade61d57c83f8ef8227965513456555fc3324 +[m-purple]: https://storage.googleapis.com/chromium-docs.appspot.com/d7bdf4d16204c293688be2e5a0bcb2bf463dbbc3 +[mi-ui-doc]: https://docs.google.com/document/d/1b5BSBEd1oB-3zj_CBAQWiQZ0cmI0HmjmXG-5iNveLqw/edit + +## Columns + +**Columns in blue** reflect the amount of actual physical memory used by the +process. This is what exerts memory pressure on the system. + + * **Total Resident**: (TODO: document this). + * **Peak Total Resident**: (TODO: document this). + * **PSS**: (TODO: document this). + * **Private Dirty**: (TODO: document this). + * **Swapped**: (TODO: document this). + +**Columns in black** reflect a best estimation of the the amount of physical +memory used by various subsystems of Chrome. + + * **Blink GC**: Memory used by [Oilpan][oilpan]. + * **CC**: Memory used by the compositor. + See [cc/memory][cc-memory] for the full details. + * **Discardable**: (TODO: document this). + * **Font Caches**: (TODO: document this). + * **GPU** and **GPU Memory Buffer**: GPU memory and RAM used for GPU purposes. + See [GPU Memory Tracing][gpu-memory]. + * **LevelDB**: (TODO: document this). + * **Malloc**: Memory allocated by calls to `malloc`, or `new` for most + non-Blink objects. + * **PartitionAlloc**: Memory allocated via [PartitionAlloc][partalloc]. + Blink objects that are not managed by Oilpan are allocated with + PartitionAlloc. + * **Skia**: (TODO: document this). + * **SQLite**: (TODO: document this). + * **V8**: (TODO: document this). + * **Web Cache**: (TODO: document this). + +The **tracing column in gray** reports memory that is used to collect all of the +above information. This memory would not be used if tracing were not enabled, +and it is discounted from malloc and the blue columns. + +<!-- TODO(primiano): Improve this. https://crbug.com/??? --> + +[oilpan]: /third_party/WebKit/Source/platform/heap/BlinkGCDesign.md +[cc-memory]: probe-cc.md +[gpu-memory]: probe-gpu.md +[partalloc]: /third_party/WebKit/Source/wtf/allocator/PartitionAlloc.md + +## Related Pages + + * [Adding MemoryInfra Tracing to a Component](adding_memory_infra_tracing.md) + * [GPU Memory Tracing](probe-gpu.md) + * [Heap Profiler Internals](heap_profiler_internals.md) + * [Heap Profiling with MemoryInfra](heap_profiler.md) + * [Startup Tracing with MemoryInfra](memory_infra_startup_tracing.md) + +## Rationale + +Another memory profiler? What is wrong with tool X? +Most of the existing tools: + + * Are hard to get working with Chrome. (Massive symbols, require OS-specific + tricks.) + * Lack Chrome-related context. + * Don't deal with multi-process scenarios. + +MemoryInfra leverages the existing tracing infrastructure in Chrome and provides +contextual data: + + * **It speaks Chrome slang.** + The Chromium codebase is instrumented. Its memory subsystems (allocators, + caches, etc.) uniformly report their stats into the trace in a way that can + be understood by Chrome developers. No more + `__gnu_cxx::new_allocator< std::_Rb_tree_node< std::pair< std::string const, base::Value*>>> ::allocate`. + * **Timeline data that can be correlated with other events.** + Did memory suddenly increase during a specific Blink / V8 / HTML parsing + event? Which subsystem increased? Did memory not go down as expected after + closing a tab? Which other threads were active during a bloat? + * **Works out of the box on desktop and mobile.** + No recompilations with unmaintained `GYP_DEFINES`, no time-consuming + symbolizations stages. All the logic is already into Chrome, ready to dump at + any time. + * **The same technology is used for telemetry and the ChromePerf dashboard.** + See [the slides][chromeperf-slides] and take a look at + [some ChromePerf dashboards][chromeperf] and + [telemetry documentation][telemetry]. + +[chromeperf-slides]: https://docs.google.com/presentation/d/1OyxyT1sfg50lA36A7ibZ7-bBRXI1kVlvCW0W9qAmM_0/present?slide=id.gde150139b_0_137 +[chromeperf]: https://chromeperf.appspot.com/report?sid=3b54e60c9951656574e19252fadeca846813afe04453c98a49136af4c8820b8d +[telemetry]: https://catapult.gsrc.io/telemetry + +## Development + +MemoryInfra is based on a simple and extensible architecture. See +[the slides][dp-slides] on how to get your subsystem reported in MemoryInfra, +or take a look at one of the existing examples such as +[malloc_dump_provider.cc][malloc-dp]. The crbug label is +[Hotlist-MemoryInfra][hotlist]. Don't hesitate to contact +[tracing@chromium.org][mailtracing] for questions and support. + +[dp-slides]: https://docs.google.com/presentation/d/1GI3HY3Mm5-Mvp6eZyVB0JiaJ-u3L1MMJeKHJg4lxjEI/present?slide=id.g995514d5c_1_45 +[malloc-dp]: https://chromium.googlesource.com/chromium/src.git/+/master/base/trace_event/malloc_dump_provider.cc +[hotlist]: https://code.google.com/p/chromium/issues/list?q=label:Hotlist-MemoryInfra +[mailtracing]: mailto:tracing@chromium.org + +## Design documents + +Architectural: + +<iframe width="100%" height="300px" src="https://docs.google.com/a/google.com/embeddedfolderview?id=0B3KuDeqD-lVJfmp0cW1VcE5XVWNxZndxelV5T19kT2NFSndYZlNFbkFpc3pSa2VDN0hlMm8"> +</iframe> + +Chrome-side design docs: + +<iframe width="100%" height="300px" src="https://docs.google.com/a/google.com/embeddedfolderview?id=0B3KuDeqD-lVJfndSa2dleUQtMnZDeWpPZk1JV0QtbVM5STkwWms4YThzQ0pGTmU1QU9kNVk"> +</iframe> + +Catapult-side design docs: + +<iframe width="100%" height="300px" src="https://docs.google.com/a/google.com/embeddedfolderview?id=0B3KuDeqD-lVJfm10bXd5YmRNWUpKOElOWS0xdU1tMmV1S3F4aHo0ZDJLTmtGRy1qVnQtVWM"> +</iframe>
diff --git a/docs/memory-infra/adding_memory_infra_tracing.md b/docs/memory-infra/adding_memory_infra_tracing.md new file mode 100644 index 0000000..7960e153 --- /dev/null +++ b/docs/memory-infra/adding_memory_infra_tracing.md
@@ -0,0 +1,178 @@ +# Adding MemoryInfra Tracing to a Component + +If you have a component that manages memory allocations, you should be +registering and tracking those allocations with Chrome's MemoryInfra system. +This lets you: + + * See an overview of your allocations, giving insight into total size and + breakdown. + * Understand how your allocations change over time and how they are impacted by + other parts of Chrome. + * Catch regressions in your component's allocations size by setting up + telemetry tests which monitor your allocation sizes under certain + circumstances. + +Some existing components that use MemoryInfra: + + * **Discardable Memory**: Tracks usage of discardable memory throughout Chrome. + * **GPU**: Tracks OpenGL and other GPU object allocations. + * **V8**: Tracks the heap size for JS. + +[TOC] + +## Overview + +In order to hook into Chrome's MemoryInfra system, your component needs to do +two things: + + 1. Create a [`MemoryDumpProvider`][mdp] for your component. + 2. Register and unregister you dump provider with the + [`MemoryDumpManager`][mdm]. + +[mdp]: https://chromium.googlesource.com/chromium/src/+/master/base/trace_event/memory_dump_provider.h +[mdm]: https://chromium.googlesource.com/chromium/src/+/master/base/trace_event/memory_dump_manager.h + +## Creating a Memory Dump Provider + +You can implement a [`MemoryDumpProvider`][mdp] as a stand-alone class, or as an +additional interface on an existing class. For example, this interface is +frequently implemented on classes which manage a pool of allocations (see +[`cc::ResourcePool`][resource-pool] for an example). + +A `MemoryDumpProvider` has one basic job, to implement `OnMemoryDump`. This +function is responsible for iterating over the resources allocated or tracked by +your component, and creating a [`MemoryAllocatorDump`][mem-alloc-dump] for each +using [`ProcessMemoryDump::CreateAllocatorDump`][pmd]. A simple example: + +```cpp +bool MyComponent::OnMemoryDump(const MemoryDumpArgs& args, + ProcessMemoryDump* process_memory_dump) { + for (const auto& allocation : my_allocations_) { + auto* dump = process_memory_dump->CreateAllocatorDump( + "path/to/my/component/allocation_" + allocation.id().ToString()); + dump->AddScalar(base::trace_event::MemoryAllocatorDump::kNameSize, + base::trace_event::MemoryAllocatorDump::kUnitsBytes, + allocation.size_bytes()); + + // While you will typically have a kNameSize entry, you can add additional + // entries to your dump with free-form names. In this example we also dump + // an object's "free_size", assuming the object may not be entirely in use. + dump->AddScalar("free_size", + base::trace_event::MemoryAllocatorDump::kUnitsBytes, + allocation.free_size_bytes()); + } +} +``` + +For many components, this may be all that is needed. See +[Handling Shared Memory Allocations](#Handling-Shared-Memory-Allocations) and +[Suballocations](#Suballocations) for information on more complex use cases. + +[resource-pool]: https://chromium.googlesource.com/chromium/src/+/master/cc/resources/resource_pool.h +[mem-alloc-dump]: https://chromium.googlesource.com/chromium/src/+/master/base/trace_event/memory_allocator_dump.h +[pmd]: https://chromium.googlesource.com/chromium/src/+/master/base/trace_event/process_memory_dump.h + +## Registering a Memory Dump Provider + +Once you have created a [`MemoryDumpProvider`][mdp], you need to register it +with the [`MemoryDumpManager`][mdm] before the system can start polling it for +memory information. Registration is generally straightforward, and involves +calling `MemoryDumpManager::RegisterDumpProvider`: + +```cpp +// Each process uses a singleton |MemoryDumpManager|. +base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider( + my_memory_dump_provider_, my_single_thread_task_runner_); +``` + +In the above code, `my_memory_dump_provider_` is the `MemoryDumpProvider` +outlined in the previous section. `my_single_thread_task_runner_` is more +complex and may be a number of things: + + * Most commonly, if your component is always used from the main message loop, + `my_single_thread_task_runner_` may just be + [`base::ThreadTaskRunnerHandle::Get()`][task-runner-handle]. + * If your component already uses a custom `base::SingleThreadTaskRunner` for + executing tasks on a specific thread, you should likely use this runner. + +[task-runner-handle]: https://chromium.googlesource.com/chromium/src/+/master/base/thread_task_runner_handle.h + +## Unregistration + +Unregistration must happen on the thread belonging to the +`SingleThreadTaskRunner` provided at registration time. Unregistering on another +thread can lead to race conditions if tracing is active when the provider is +unregistered. + +```cpp +base::trace_event::MemoryDumpManager::GetInstance()->UnregisterDumpProvider( + my_memory_dump_provider_); +``` + +## Handling Shared Memory Allocations + +When an allocation is shared between two components, it may be useful to dump +the allocation in both components, but you also want to avoid double-counting +the allocation. This can be achieved using the concept of _ownership edges_. +An ownership edge represents that the _source_ memory allocator dump owns a +_target_ memory allocator dump. If multiple source dumps own a single target, +then the cost of that target allocation will be split between the sources. +Additionally, importance can be added to a specific ownership edge, allowing +the highest importance source of that edge to claim the entire cost of the +target. + +In the typical case, you will use [`ProcessMemoryDump`][pmd] to create a shared +global allocator dump. This dump will act as the target of all +component-specific dumps of a specific resource: + +```cpp +// Component 1 is going to create a dump, source_mad, for an allocation, +// alloc_, which may be shared with other components / processes. +MyAllocationType* alloc_; +base::trace_event::MemoryAllocatorDump* source_mad; + +// Component 1 creates and populates source_mad; +... + +// In addition to creating a source dump, we must create a global shared +// target dump. This dump should be created with a unique global ID which can be +// generated any place the allocation is used. I recommend adding a global ID +// generation function to the allocation type. +base::trace_event::MemoryAllocatorDumpGUID guid(alloc_->GetGUIDString()); + +// From this global ID we can generate the parent allocator dump. +base::trace_event::MemoryAllocatorDump* target_mad = + process_memory_dump->CreateSharedGlobalAllocatorDump(guid); + +// We now create an ownership edge from the source dump to the target dump. +// When creating an edge, you can assign an importance to this edge. If all +// edges have the same importance, the size of the allocation will be split +// between all sources which create a dump for the allocation. If one +// edge has higher importance than the others, its source will be assigned the +// full size of the allocation. +const int kImportance = 1; +process_memory_dump->AddOwnershipEdge( + source_mad->guid(), target_mad->guid(), kImportance); +``` + +If an allocation is being shared across process boundaries, it may be useful to +generate a global ID which incorporates the ID of the local process, preventing +two processes from generating colliding IDs. As it is not recommended to pass a +process ID between processes for security reasons, a function +`MemoryDumpManager::GetTracingProcessId` is provided which generates a unique ID +per process that can be passed with the resource without security concerns. +Frequently this ID is used to generate a global ID that is based on the +allocated resource's ID combined with the allocating process' tracing ID. + +## Suballocations + +Another advanced use case involves tracking sub-allocations of a larger +allocation. For instance, this is used in +[`gpu::gles2::TextureManager`][texture-manager] to dump both the suballocations +which make up a texture. To create a suballocation, instead of calling +[`ProcessMemoryDump::CreateAllocatorDump`][pmd] to create a +[`MemoryAllocatorDump`][mem-alloc-dump], you call +[`ProcessMemoryDump::AddSubAllocation`][pmd], providing the ID of the parent +allocation as the first parameter. + +[texture-manager]: https://chromium.googlesource.com/chromium/src/+/master/gpu/command_buffer/service/texture_manager.cc
diff --git a/docs/memory-infra/heap_profiler.md b/docs/memory-infra/heap_profiler.md new file mode 100644 index 0000000..57961d3 --- /dev/null +++ b/docs/memory-infra/heap_profiler.md
@@ -0,0 +1,168 @@ +# Heap Profiling with MemoryInfra + +As of Chrome 48, MemoryInfra supports heap profiling. The core principle is +a solution that JustWorks™ on all platforms without patching or rebuilding, +intergrated with the chrome://tracing ecosystem. + +[TOC] + +## How to Use + + 1. Start Chrome with the `--enable-heap-profiling` switch. This will make + Chrome keep track of all allocations. + + 2. Grab a [MemoryInfra][memory-infra] trace. For best results, start tracing + first, and _then_ open a new tab that you want to trace. Furthermore, + enabling more categories (besides memory-infra) will yield more detailed + information in the heap profiler backtraces. + + 3. When the trace has been collected, select a heavy memory dump indicated by + a purple ![M][m-purple] dot. Heap dumps are only included in heavy memory + dumps. + + 4. In the analysis view, cells marked with a triple bar icon (☰) contain heap + dumps. Select such a cell. + + ![Cells containing a heap dump][cells-heap-dump] + + 5. Scroll down all the way to _Heap Details_. + + 6. Pinpoint the memory bug and live happily ever after. + +[memory-infra]: README.md +[m-purple]: https://storage.googleapis.com/chromium-docs.appspot.com/d7bdf4d16204c293688be2e5a0bcb2bf463dbbc3 +[cells-heap-dump]: https://storage.googleapis.com/chromium-docs.appspot.com/a24d80d6a08da088e2e9c8b2b64daa215be4dacb + +### Native stack traces + +By default heap profiling collects pseudo allocation traces, which are based +on trace events. I.e. frames in allocation traces correspond to trace events +that were active at the time of allocations, and are not real function names. +However, you can build a special Linux / Android build that will collect +real C/C++ stack traces. + + 1. Build with the following GN flags: + + Linux + + enable_profiling = true + + + Android + + arm_use_thumb = false + enable_profiling = true + + 2. Start Chrome with `--enable-heap-profiling=native` switch (notice + `=native` part). + + On Android use the command line tool before starting the app: + + build/android/adb_chrome_public_command_line --enable-heap-profiling=native + + (run the tool with an empty argument `''` to clear the command line) + + 3. Grab a [MemoryInfra][memory-infra] trace. You don't need any other + categories besides `memory-infra`. + + 4. Save the grabbed trace file. This step is needed because freshly + taken trace file contains raw addresses (which look like `pc:dcf5dbf8`) + instead of function names, and needs to be symbolized. + + 4. Symbolize the trace file. During symbolization addresses are resolved to + the corresponding function names and trace file is rewritten (but a backup + is saved with `.BACKUP` extension). + + Linux + + third_party/catapult/tracing/bin/symbolize_trace <trace file> + + Android + + third_party/catapult/tracing/bin/symbolize_trace --output-directory out/Release <trace file> + + (note `--output-directory` and make sure it's right for your setup) + + 5. Load the trace file in `chrome://tracing`. Locate a purple ![M][m-purple] + dot, and continue from step *3* from the instructions above. Native stack + traces will be shown in the _Heap Details_ pane. + +## Heap Details + +The heap details view contains a tree that represents the heap. The size of the +root node corresponds to the selected allocator cell. + +*** aside +The size value in the heap details view will not match the value in the selected +analysis view cell exactly. There are three reasons for this. First, the heap +profiler reports the memory that _the program requested_, whereas the allocator +reports the memory that it _actually allocated_ plus its own bookkeeping +overhead. Second, allocations that happen early --- before Chrome knows that +heap profiling is enabled --- are not captured by the heap profiler, but they +are reported by the allocator. Third, tracing overhead is not discounted by the +heap profiler. +*** + +The heap can be broken down in two ways: by _backtrace_ (marked with an ƒ), and +by _type_ (marked with a Ⓣ). When tracing is enabled, Chrome records trace +events, most of which appear in the flame chart in timeline view. At every +point in time these trace events form a pseudo stack, and a vertical slice +through the flame chart is like a backtrace. This corresponds to the ƒ nodes in +the heap details view. Hence enabling more tracing categories will give a more +detailed breakdown of the heap. + +The other way to break down the heap is by object type. At the moment this is +only supported for PartitionAlloc. + +*** aside +In official builds, only the most common type names are included due to binary +size concerns. Development builds have full type information. +*** + +To keep the trace log small, uninteresting information is omitted from heap +dumps. The long tail of small nodes is not dumped, but grouped in an `<other>` +node instead. Note that altough these small nodes are insignificant on their +own, together they can be responsible for a significant portion of the heap. The +`<other>` node is large in that case. + +## Example + +In the trace below, `ParseAuthorStyleSheet` is called at some point. + +![ParseAuthorStyleSheet pseudo stack][pseudo-stack] + +The pseudo stack of trace events corresponds to the tree of ƒ nodes below. Of +the 23.5 MiB of memory allocated with PartitionAlloc, 1.9 MiB was allocated +inside `ParseAuthorStyleSheet`, either directly, or at a deeper level (like +`CSSParserImpl::parseStyleSheet`). + +![Memory Allocated in ParseAuthorStyleSheet][break-down-by-backtrace] + +By expanding `ParseAuthorStyleSheet`, we can see which types were allocated +there. Of the 1.9 MiB, 371 KiB was spent on `ImmutableStylePropertySet`s, and +238 KiB was spent on `StringImpl`s. + +![ParseAuthorStyleSheet broken down by type][break-down-by-type] + +It is also possible to break down by type first, and then by backtrace. Below +we see that of the 23.5 MiB allocated with PartitionAlloc, 1 MiB is spent on +`Node`s, and about half of the memory spent on nodes was allocated in +`HTMLDocumentParser`. + +![The PartitionAlloc heap broken down by type first and then by backtrace][type-then-backtrace] + +Heap dump diffs are fully supported by trace viewer. Select a heavy memory dump +(a purple dot), then with the control key select a heavy memory dump earlier in +time. Below is a diff of theverge.com before and in the middle of loading ads. +We can see that 4 MiB were allocated when parsing the documents in all those +iframes, almost a megabyte of which was due to JavaScript. (Note that this is +memory allocated by PartitionAlloc alone, the total renderer memory increase was +around 72 MiB.) + +![Diff of The Verge before and after loading ads][diff] + +[pseudo-stack]: https://storage.googleapis.com/chromium-docs.appspot.com/058e50350836f55724e100d4dbbddf4b9803f550 +[break-down-by-backtrace]: https://storage.googleapis.com/chromium-docs.appspot.com/ec61c5f15705f5bcf3ca83a155ed647a0538bbe1 +[break-down-by-type]: https://storage.googleapis.com/chromium-docs.appspot.com/2236e61021922c0813908c6745136953fa20a37b +[type-then-backtrace]: https://storage.googleapis.com/chromium-docs.appspot.com/c5367dde11476bdbf2d5a1c51674148915573d11 +[diff]: https://storage.googleapis.com/chromium-docs.appspot.com/802141906869cd533bb613da5f91bd0b071ceb24
diff --git a/docs/memory-infra/heap_profiler_internals.md b/docs/memory-infra/heap_profiler_internals.md new file mode 100644 index 0000000..d1019c8 --- /dev/null +++ b/docs/memory-infra/heap_profiler_internals.md
@@ -0,0 +1,184 @@ +# Heap Profiler Internals + +This document describes how the heap profiler works and how to add heap +profiling support to your allocator. If you just want to know how to use it, +see [Heap Profiling with MemoryInfra](heap_profiler.md) + +[TOC] + +## Overview + +The heap profiler consists of tree main components: + + * **The Context Tracker**: Responsible for providing context (pseudo stack + backtrace) when an allocation occurs. + * **The Allocation Register**: A specialized hash table that stores allocation + details by address. + * **The Heap Dump Writer**: Extracts the most important information from a set + of recorded allocations and converts it into a format that can be dumped into + the trace log. + +These components are designed to work well together, but to be usable +independently as well. + +When there is a way to get notified of all allocations and frees, this is the +normal flow: + + 1. When an allocation occurs, call + [`AllocationContextTracker::GetInstanceForCurrentThread()->GetContextSnapshot()`][context-tracker] + to get an [`AllocationContext`][alloc-context]. + 2. Insert that context together with the address and size into an + [`AllocationRegister`][alloc-register] by calling `Insert()`. + 3. When memory is freed, remove it from the register with `Remove()`. + 4. On memory dump, collect the allocations from the register, call + [`ExportHeapDump()`][export-heap-dump], and add the generated heap dump to + the memory dump. + +[context-tracker]: https://chromium.googlesource.com/chromium/src/+/master/base/trace_event/heap_profiler_allocation_context_tracker.h +[alloc-context]: https://chromium.googlesource.com/chromium/src/+/master/base/trace_event/heap_profiler_allocation_context.h +[alloc-register]: https://chromium.googlesource.com/chromium/src/+/master/base/trace_event/heap_profiler_allocation_register.h +[export-heap-dump]: https://chromium.googlesource.com/chromium/src/+/master/base/trace_event/heap_profiler_heap_dump_writer.h + +*** aside +An allocator can skip step 2 and 3 if it is able to store the context itself, +and if it is able to enumerate all allocations for step 4. +*** + +When heap profiling is enabled (the `--enable-heap-profiling` flag is passed), +the memory dump manager calls `OnHeapProfilingEnabled()` on every +`MemoryDumpProvider` as early as possible, so allocators can start recording +allocations. This should be done even when tracing has not been started, +because these allocations might still be around when a heap dump happens during +tracing. + +## Context Tracker + +The [`AllocationContextTracker`][context-tracker] is a thread-local object. Its +main purpose is to keep track of a pseudo stack of trace events. Chrome has +been instrumented with lots of `TRACE_EVENT` macros. These trace events push +their name to a thread-local stack when they go into scope, and pop when they +go out of scope, if all of the following conditions have been met: + + * A trace is being recorded. + * The category of the event is enabled in the trace config. + * Heap profiling is enabled (with the `--enable-heap-profiling` flag). + +This means that allocations that occur before tracing is started will not have +backtrace information in their context. + +A thread-local instance of the context tracker is initialized lazily when it is +first accessed. This might be because a trace event pushed or popped, or because +`GetContextSnapshot()` was called when an allocation occurred. + +[`AllocationContext`][alloc-context] is what is used to group and break down +allocations. Currently `AllocationContext` has the following fields: + + * Backtrace: filled by the context tracker, obtained from the thread-local + pseudo stack. + * Type name: to be filled in at a point where the type of a pointer is known, + set to _[unknown]_ by default. + +It is possible to modify this context after insertion into the register, for +instance to set the type name if it was not known at the time of allocation. + +## Allocation Register + +The [`AllocationRegister`][alloc-register] is a hash table specialized for +storing `(size, AllocationContext)` pairs by address. It has been optimized for +Chrome's typical number of unfreed allocations, and it is backed by `mmap` +memory directly so there are no reentrancy issues when using it to record +`malloc` allocations. + +The allocation register is threading-agnostic. Access must be synchronised +properly. + +## Heap Dump Writer + +Dumping every single allocation in the allocation register straight into the +trace log is not an option due to the sheer volume (~300k unfreed allocations). +The role of the [`ExportHeapDump()`][export-heap-dump] function is to group +allocations, striking a balance between trace log size and detail. + +See the [Heap Dump Format][heap-dump-format] document for more details about the +structure of the heap dump in the trace log. + +[heap-dump-format]: https://docs.google.com/document/d/1NqBg1MzVnuMsnvV1AKLdKaPSPGpd81NaMPVk5stYanQ + +## Instrumenting an Allocator + +Below is an example of adding heap profiling support to an allocator that has +an existing memory dump provider. + +```cpp +class FooDumpProvider : public MemoryDumpProvider { + + // Kept as pointer because |AllocationRegister| allocates a lot of virtual + // address space when constructed, so only construct it when heap profiling is + // enabled. + scoped_ptr<AllocationRegister> allocation_register_; + Lock allocation_register_lock_; + + static FooDumpProvider* GetInstance(); + + void InsertAllocation(void* address, size_t size) { + AllocationContext context = AllocationContextTracker::GetInstanceForCurrentThread()->GetContextSnapshot(); + AutoLock lock(allocation_register_lock_); + allocation_register_->Insert(address, size, context); + } + + void RemoveAllocation(void* address) { + AutoLock lock(allocation_register_lock_); + allocation_register_->Remove(address); + } + + // Will be called as early as possible by the memory dump manager. + void OnHeapProfilingEnabled(bool enabled) override { + AutoLock lock(allocation_register_lock_); + allocation_register_.reset(new AllocationRegister()); + + // At this point, make sure that from now on, for every allocation and + // free, |FooDumpProvider::GetInstance()->InsertAllocation()| and + // |RemoveAllocation| are called. + } + + bool OnMemoryDump(const MemoryDumpArgs& args, + ProcessMemoryDump& pmd) override { + // Do regular dumping here. + + // Dump the heap only for detailed dumps. + if (args.level_of_detail == MemoryDumpLevelOfDetail::DETAILED) { + TraceEventMemoryOverhead overhead; + hash_map<AllocationContext, size_t> bytes_by_context; + + { + AutoLock lock(allocation_register_lock_); + if (allocation_register_) { + // Group allocations in the register into |bytes_by_context|, but do + // no additional processing inside the lock. + for (const auto& alloc_size : *allocation_register_) + bytes_by_context[alloc_size.context] += alloc_size.size; + + allocation_register_->EstimateTraceMemoryOverhead(&overhead); + } + } + + if (!bytes_by_context.empty()) { + scoped_refptr<TracedValue> heap_dump = ExportHeapDump( + bytes_by_context, + pmd->session_state()->stack_frame_deduplicator(), + pmb->session_state()->type_name_deduplicator()); + pmd->AddHeapDump("foo_allocator", heap_dump); + overhead.DumpInto("tracing/heap_profiler", pmd); + } + } + + return true; + } +}; + +``` + +*** aside +The implementation for `malloc` is more complicated because it needs to deal +with reentrancy. +***
diff --git a/docs/memory-infra/memory_infra_startup_tracing.md b/docs/memory-infra/memory_infra_startup_tracing.md new file mode 100644 index 0000000..c036c05 --- /dev/null +++ b/docs/memory-infra/memory_infra_startup_tracing.md
@@ -0,0 +1,74 @@ +# Startup Tracing with MemoryInfra + +[MemoryInfra](README.md) supports startup tracing. + +## The Simple Way + +Start Chrome as follows: + + $ chrome --no-sandbox \ + --trace-startup=-*,disabled-by-default-memory-infra \ + --trace-startup-file=/tmp/trace.json \ + --trace-startup-duration=7 + +On Android, enable startup tracing and start Chrome as follows: + + $ build/android/adb_chrome_public_command_line \ + --trace-startup=-*,disabled-by-default-memory-infra \ + --trace-startup-file=/sdcard/Download/trace.json \ + --trace-startup-duration=7 + + $ build/android/adb_run_chrome_public + + $ adb pull /sdcard/Download/trace.json # After tracing. + +Note that startup tracing will be enabled upon every Chrome launch until you +delete the command-line flags: + + $ build/android/adb_chrome_public_command_line "" + +This will use the default configuration: one memory dump every 250 ms with a +detailed dump ever two seconds. + +## The Advanced Way + +If you need more control over the granularity of the memory dumps, you can +specify a custom trace config file as follows: + + $ cat > /tmp/trace.config + { + "startup_duration": 4, + "result_file": "/tmp/trace.json", + "trace_config": { + "included_categories": ["disabled-by-default-memory-infra"], + "excluded_categories": ["*"], + "memory_dump_config": { + "triggers": [ + { "mode": "light", "periodic_interval_ms": 50 }, + { "mode": "detailed", "periodic_interval_ms": 1000 } + ] + } + } + } + + $ chrome --no-sandbox --trace-config-file=/tmp/trace.config + +On Android, the config file has to be pushed to a fixed file location: + + $ adb root + $ adb push /tmp/trace.config /data/local/chrome-trace-config.json + + $ build/android/adb_run_chrome_public + + $ adb pull /sdcard/Download/trace.json # After tracing. + +Make sure that the "result_file" location is writable by the Chrome process on +Android (e.g. "/sdcard/Download/trace.json"). Note that startup tracing will be +enabled upon every Chrome launch until you delete the config file: + + $ adb shell rm /data/local/chrome-trace-config.json + +## Related Pages + + * [General information about startup tracing](https://sites.google.com/a/chromium.org/dev/developers/how-tos/trace-event-profiling-tool/recording-tracing-runs) + * [Memory tracing with MemoryInfra](README.md)
diff --git a/docs/memory-infra/probe-cc.md b/docs/memory-infra/probe-cc.md new file mode 100644 index 0000000..1fb9f01 --- /dev/null +++ b/docs/memory-infra/probe-cc.md
@@ -0,0 +1,125 @@ +# Memory Usage in CC + +This document gives an overview of memory usage in the CC component, as well as +information on how to analyze that memory. + +[TOC] + +## Types of Memory in Use + +CC uses a number of types of memory: + +1. Malloc Memory - Standard system memory used for all manner of objects in CC. +2. Discardable Memory - Memory allocated by the discardable memory system. + Designed to be freeable by the system at any time (under memory pressure). + In most cases, only pinned discardable memory should be considered to + have a cost; however, the implementation of discardable memory is platform + dependent, and on certain platforms unpinned memory can contribute to + memory pressure to some degree. +3. Shared Memory - Memory which is allocated by the Browser and can safely + be transferred between processes. This memory is allocated by the browser + but may count against a renderer process depending on who logically "owns" + the memory. +4. GPU Memory - Memory which is allocated on the GPU and typically does not + count against system memory. This mainly includes OpenGL objects. + +## Categories Of Memory + +Memory-infra tracing will grab dumps of CC memory in several categories. + +### CC Category + +The CC category contains resource allocations made by ResourceProvider. All +resource allocations are enumerated under cc/resource_memory. A subset of +resources are used as tile memory, and are also enumerated under cc/tile_memory. +For resources that appear in both cc/tile_memory and cc/resource_memory, the +size will be attributed to cc/tile_memory (effective_size of cc/resource_memory +will not include these resources). + +If the one-copy tile update path is in use, the cc category will also enumerate +staging resources used as intermediates when drawing tiles. These resources are +like tile_memory, in that they are shared with cc/resource_memory. + +Note that depending on the path being used, CC memory may be either shared +memory or GPU memory: + +Path | Tile Memory Type | Staging Memory Type +-------------|------------------------------------------- +Bitmap | Shared Memory | N/A +One Copy | GPU Memory | Shared Memory +Zero Copy | GPU or Shared Memory | N/A +GPU | GPU Memory | N/A + +Note that these values can be determined from a memory-infra dump. For a given +resource, hover over the small green arrow next to it's "size". This will show +the other allocations that this resource is aliased with. If you see an +allocation in the GPU process, the memory is generally GPU memory. Otherwise, +the resource is typically Shared Memory. + +Tile and Staging memory managers are set up to evict any resource not used +within 1s. + +### GPU Category + +This category lists the memory allocations needed to support CC's GPU path. +Despite the name, the data in this category (within a Renderer process) is not +GPU memory but Shared Memory. + +Allocations tracked here include GL command buffer support allocations such as: + +1. Command Buffer Memory - memory used to send commands across the GL command + buffer. This is backed by Shared Memory. +2. Mapped Memory - memory used in certain image upload paths to share data + with the GPU process. This is backed by Shared Memory. +3. Transfer Buffer Memory - memory used to transfer data to the GPU - used in + different paths than mapped memory. Also backed by Shared Memory. + +### Discardable Category + +Cached images make use of Discardable memory. These allocations are managed by +Skia and a better summary of these allocations can likely be found in the Skia +category. + +### Malloc Category + +The malloc category shows a summary of all memory allocated through malloc. + +Currently the information here is not granular enough to be useful, and a +good project would be to track down and instrument any large pools of memory +using malloc. + +Some Skia caches also make use of malloc memory. For these allocations, a better +summary can be seen in the Skia category. + +### Skia Category + +The Skia category shows all resources used by the Skia rendering system. These +can be divided into a few subcategories. skia/gpu_resources/* includes all +resources using GPU memory. All other categories draw from either Shared or +malloc memory. To determine which type of memory a resource is using, hover +over the green arrow next to its size. This will show the other allocations +which the resource is aliased with. + +## Other Areas of Interest + +Many of the allocations under CC are aliased with memory in the Browser or GPU +process. When investigating CC memory it may be worth looking at the following +external categories: + +1. GPU Process / GPU Category - All GPU resources allocated by CC have a + counterpart in the GPU/GPU category. This includes GL Textures, buffers, and + other GPU backed objects such as Native GPU Memory Buffers. +2. Browser Process / GpuMemoryBuffer Category - Resources backed by Shared + Memory GpuMemoryBuffers are allocated by the browser and will be tracked + in this category. +3. Browser Process / SharedMemory Category - Resources backed by Bitmap and + Shared Memory GpuMemoryBuffer objects are allocated by the browser and will + also tracked in this category. + +## Memory TODOs + +The following areas have insufficient memory instrumentation. + +1. DisplayLists - DisplayLists can be quite large and are currently + un-instrumented. These use malloc memory and currently contribute to + malloc/allocated_objects/<unspecified>. [BUG](http://crbug.com/567465)
diff --git a/docs/memory-infra/probe-gpu.md b/docs/memory-infra/probe-gpu.md new file mode 100644 index 0000000..17fa5a8 --- /dev/null +++ b/docs/memory-infra/probe-gpu.md
@@ -0,0 +1,93 @@ +# GPU Memory Tracing + +This is an overview of the GPU column in [MemoryInfra][memory-infra]. + +[TOC] + +## Quick Start + +If you want an overview of total GPU memory usage, select the GPU process' GPU +category and look at the _size_ column. (Not _effective size_.) + +![Look at the size column for total GPU memory][gpu-size-column] + +[memory-infra]: README.md +[gpu-size-column]: https://storage.googleapis.com/chromium-docs.appspot.com/c7d632c18d90d99e393ad0ade929f96e7d8243fe + +## In Depth + +GPU Memory in Chrome involves several different types of allocations. These +include, but are not limited to: + + * **Raw OpenGL Objects**: These objects are allocated by Chrome using the + OpenGL API. Chrome itself has handles to these objects, but the actual + backing memory may live in a variety of places (CPU side in the GPU process, + CPU side in the kernel, GPU side). Because most OpenGL operations occur over + IPC, communicating with Chrome's GPU process, these allocations are almost + always shared between a renderer or browser process and the GPU process. + * **GPU Memory Buffers**: These objects provide a chunk of writable memory + which can be handed off cross-process. While GPUMemoryBuffers represent a + platform-independent way to access this memory, they have a number of + possible platform-specific implementations (EGL surfaces on Linux, + IOSurfaces on Mac, or CPU side shared memory). Because of their cross + process use case, these objects will almost always be shared between a + renderer or browser process and the GPU process. + * **GLImages**: GLImages are a platform-independent abstraction around GPU + memory, similar to GPU Memory Buffers. In many cases, GLImages are created + from GPUMemoryBuffers. The primary difference is that GLImages are designed + to be bound to an OpenGL texture using the image extension. + +GPU Memory can be found across a number of different processes, in a few +different categories. + +Renderer or browser process: + + * **CC Category**: The CC category contains all resource allocations used in + the Chrome Compositor. When GPU rasterization is enabled, these resource + allocations will be GPU allocations as well. See also + [docs/memory-infra/probe-cc.md][cc-memory]. + * **Skia/gpu_resources Category**: All GPU resources used by Skia. + * **GPUMemoryBuffer Category**: All GPUMemoryBuffers in use in the current + process. + +GPU process: + + * **GPU Category**: All GPU allocations, many shared with other processes. + * **GPUMemoryBuffer Category**: All GPUMemoryBuffers. + +## Example + +Many of the objects listed above are shared between multiple processes. +Consider a GL texture used by CC --- this texture is shared between a renderer +and the GPU process. Additionally, the texture may be backed by a GLImage which +was created from a GPUMemoryBuffer, which is also shared between the renderer +and GPU process. This means that the single texture may show up in the memory +logs of two different processes multiple times. + +To make things easier to understand, each GPU allocation is only ever "owned" +by a single process and category. For instance, in the above example, the +texture would be owned by the CC category of the renderer process. Each +allocation has (at least) two sizes recorded --- _size_ and _effective size_. +In the owning allocation, these two numbers will match: + +![Matching size and effective size][owner-size] + +Note that the allocation also gives information on what other processes it is +shared with (seen by hovering over the green arrow). If we navigate to the +other allocation (in this case, gpu/gl/textures/client_25/texture_216) we will +see a non-owning allocation. In this allocation the size is the same, but the +_effective size_ is 0: + +![Effective size of zero][non-owner-size] + +Other types, such as GPUMemoryBuffers and GLImages have similar sharing +patterns. + +When trying to get an overview of the absolute memory usage tied to the GPU, +you can look at the size column (not effective size) of just the GPU process' +GPU category. This will show all GPU allocations, whether or not they are owned +by another process. + +[cc-memory]: /docs/memory-infra/probe-cc.md +[owner-size]: https://storage.googleapis.com/chromium-docs.appspot.com/a325c4426422e53394a322d31b652cfa34231189 +[non-owner-size]: https://storage.googleapis.com/chromium-docs.appspot.com/b8cf464636940d0925f29a102e99aabb9af40b13
diff --git a/extensions/browser/DEPS b/extensions/browser/DEPS index 6a045e55..ac3be95 100644 --- a/extensions/browser/DEPS +++ b/extensions/browser/DEPS
@@ -25,6 +25,7 @@ "+storage/browser/fileapi", "+third_party/leveldatabase", "+third_party/re2", + "+third_party/WebKit/public/platform", "+third_party/WebKit/public/web", "+third_party/zlib/google", "+ui/display",
diff --git a/extensions/browser/api/serial/serial_api.cc b/extensions/browser/api/serial/serial_api.cc index 2dfc1b66..6ef93a77 100644 --- a/extensions/browser/api/serial/serial_api.cc +++ b/extensions/browser/api/serial/serial_api.cc
@@ -488,7 +488,7 @@ if (device->has_product_id) info.product_id.reset(new int(static_cast<int>(device->product_id))); if (device->display_name) - info.display_name.reset(new std::string(device->display_name)); + info.display_name.reset(new std::string(device->display_name.value())); return info; }
diff --git a/extensions/browser/api/socket/app_firewall_hole_manager.cc b/extensions/browser/api/socket/app_firewall_hole_manager.cc index 1f076c3..bf6a2c4 100644 --- a/extensions/browser/api/socket/app_firewall_hole_manager.cc +++ b/extensions/browser/api/socket/app_firewall_hole_manager.cc
@@ -7,7 +7,6 @@ #include <utility> #include "base/bind.h" -#include "base/stl_util.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "content/public/browser/browser_context.h" #include "extensions/browser/app_window/app_window.h" @@ -69,19 +68,20 @@ } // namespace AppFirewallHole::~AppFirewallHole() { - manager_->Close(this); + if (manager_) + manager_->Close(this); } -AppFirewallHole::AppFirewallHole(AppFirewallHoleManager* manager, - PortType type, - uint16_t port, - const std::string& extension_id) +AppFirewallHole::AppFirewallHole( + const base::WeakPtr<AppFirewallHoleManager>& manager, + PortType type, + uint16_t port, + const std::string& extension_id) : type_(type), port_(port), extension_id_(extension_id), manager_(manager), - weak_factory_(this) { -} + weak_factory_(this) {} void AppFirewallHole::SetVisible(bool app_visible) { app_visible_ = app_visible; @@ -105,13 +105,11 @@ } AppFirewallHoleManager::AppFirewallHoleManager(BrowserContext* context) - : context_(context), observer_(this) { + : context_(context), observer_(this), weak_factory_(this) { observer_.Add(AppWindowRegistry::Get(context)); } -AppFirewallHoleManager::~AppFirewallHoleManager() { - base::STLDeleteValues(&tracked_holes_); -} +AppFirewallHoleManager::~AppFirewallHoleManager() {} AppFirewallHoleManager* AppFirewallHoleManager::Get(BrowserContext* context) { return AppFirewallHoleManagerFactory::GetForBrowserContext(context, true); @@ -121,8 +119,8 @@ AppFirewallHole::PortType type, uint16_t port, const std::string& extension_id) { - std::unique_ptr<AppFirewallHole> hole( - new AppFirewallHole(this, type, port, extension_id)); + std::unique_ptr<AppFirewallHole> hole(new AppFirewallHole( + weak_factory_.GetWeakPtr(), type, port, extension_id)); tracked_holes_.insert(std::make_pair(extension_id, hole.get())); if (HasVisibleAppWindows(context_, extension_id)) { hole->SetVisible(true);
diff --git a/extensions/browser/api/socket/app_firewall_hole_manager.h b/extensions/browser/api/socket/app_firewall_hole_manager.h index d839071a..5beff081 100644 --- a/extensions/browser/api/socket/app_firewall_hole_manager.h +++ b/extensions/browser/api/socket/app_firewall_hole_manager.h
@@ -9,6 +9,7 @@ #include <map> +#include "base/memory/weak_ptr.h" #include "base/scoped_observer.h" #include "chromeos/network/firewall_hole.h" #include "extensions/browser/app_window/app_window_registry.h" @@ -26,7 +27,7 @@ // closed on destruction. class AppFirewallHole { public: - typedef chromeos::FirewallHole::PortType PortType; + using PortType = chromeos::FirewallHole::PortType; ~AppFirewallHole(); @@ -37,7 +38,7 @@ private: friend class AppFirewallHoleManager; - AppFirewallHole(AppFirewallHoleManager* manager, + AppFirewallHole(const base::WeakPtr<AppFirewallHoleManager>& manager, PortType type, uint16_t port, const std::string& extension_id); @@ -51,9 +52,7 @@ std::string extension_id_; bool app_visible_ = false; - // This object is destroyed when the AppFirewallHoleManager that owns it is - // destroyed and so a raw pointer is okay here. - AppFirewallHoleManager* manager_; + base::WeakPtr<AppFirewallHoleManager> manager_; // This will hold the FirewallHole object if one is opened. std::unique_ptr<chromeos::FirewallHole> firewall_hole_; @@ -73,8 +72,8 @@ // Returns the instance for a given browser context, or NULL if none. static AppFirewallHoleManager* Get(content::BrowserContext* context); - // Takes ownership of the AppFirewallHole and will open a port on the system - // firewall if the associated application is currently visible. + // Opens a port on the system firewall if the associated application is + // currently visible. std::unique_ptr<AppFirewallHole> Open(AppFirewallHole::PortType type, uint16_t port, const std::string& extension_id); @@ -92,6 +91,8 @@ content::BrowserContext* context_; ScopedObserver<AppWindowRegistry, AppWindowRegistry::Observer> observer_; std::multimap<std::string, AppFirewallHole*> tracked_holes_; + + base::WeakPtrFactory<AppFirewallHoleManager> weak_factory_; }; } // namespace extensions
diff --git a/extensions/browser/app_window/app_web_contents_helper.cc b/extensions/browser/app_window/app_web_contents_helper.cc index 2a64ce7..1dbbcd0 100644 --- a/extensions/browser/app_window/app_web_contents_helper.cc +++ b/extensions/browser/app_window/app_web_contents_helper.cc
@@ -14,6 +14,7 @@ #include "extensions/browser/extension_registry.h" #include "extensions/browser/suggest_permission_util.h" #include "extensions/common/permissions/api_permission.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" namespace extensions {
diff --git a/extensions/browser/extension_error.cc b/extensions/browser/extension_error.cc index 0b8aa386..15559e0e 100644 --- a/extensions/browser/extension_error.cc +++ b/extensions/browser/extension_error.cc
@@ -148,7 +148,7 @@ // background page in this case. GURL source_url = GURL(source_); if (context_url_.is_empty() && - source_url.path() == + source_url.path_piece() == std::string("/") + kGeneratedBackgroundPageFilename) { context_url_ = source_url; }
diff --git a/extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.cc b/extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.cc index 8da2fac..64134dc 100644 --- a/extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.cc +++ b/extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.cc
@@ -29,7 +29,7 @@ #include "ipc/ipc_message_macros.h" #include "net/base/url_util.h" #include "services/service_manager/public/cpp/interface_registry.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" using content::WebContents; using guest_view::GuestViewBase;
diff --git a/extensions/browser/process_manager.cc b/extensions/browser/process_manager.cc index f6687a8d4..3e4d106 100644 --- a/extensions/browser/process_manager.cc +++ b/extensions/browser/process_manager.cc
@@ -12,7 +12,6 @@ #include "base/macros.h" #include "base/metrics/histogram_macros.h" #include "base/single_thread_task_runner.h" -#include "base/stl_util.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "content/public/browser/browser_context.h" @@ -611,7 +610,19 @@ } void ProcessManager::CloseBackgroundHosts() { - base::STLDeleteElements(&background_hosts_); + // Delete from a copy because deletion of the ExtensionHosts will trigger + // callbacks to modify the |background_hosts_| set. + ExtensionHostSet hosts_copy = background_hosts_; + for (auto* host : hosts_copy) { + // Deleting the host will cause a NOTIFICATION_EXTENSION_HOST_DESTROYED + // which will cause the removal of the host from the |background_hosts_| set + // in the Observe() method below. + delete host; + DCHECK_EQ(0u, background_hosts_.count(host)); + } + + // At this point there should be nothing left in |background_hosts_|. + DCHECK(background_hosts_.empty()); } void ProcessManager::SetKeepaliveImpulseCallbackForTesting(
diff --git a/extensions/common/event_filter.cc b/extensions/common/event_filter.cc index 2a16678..fa587016 100644 --- a/extensions/common/event_filter.cc +++ b/extensions/common/event_filter.cc
@@ -7,6 +7,7 @@ #include <string> #include <utility> +#include "base/memory/ptr_util.h" #include "components/url_matcher/url_matcher_factory.h" #include "ipc/ipc_message.h" @@ -67,8 +68,8 @@ std::make_pair((*it)->id(), id)); } id_to_event_name_[id] = event_name; - event_matchers_[event_name][id] = linked_ptr<EventMatcherEntry>( - new EventMatcherEntry(std::move(matcher), &url_matcher_, condition_sets)); + event_matchers_[event_name][id] = base::MakeUnique<EventMatcherEntry>( + std::move(matcher), &url_matcher_, condition_sets); return id; }
diff --git a/extensions/common/event_filter.h b/extensions/common/event_filter.h index 567c1d08..52bd1b04 100644 --- a/extensions/common/event_filter.h +++ b/extensions/common/event_filter.h
@@ -6,10 +6,10 @@ #define EXTENSIONS_COMMON_EVENT_FILTER_H_ #include <map> +#include <memory> #include <set> #include "base/macros.h" -#include "base/memory/linked_ptr.h" #include "components/url_matcher/url_matcher.h" #include "extensions/common/event_filtering_info.h" #include "extensions/common/event_matcher.h" @@ -88,10 +88,11 @@ }; // Maps from a matcher id to an event matcher entry. - typedef std::map<MatcherID, linked_ptr<EventMatcherEntry> > EventMatcherMap; + using EventMatcherMap = + std::map<MatcherID, std::unique_ptr<EventMatcherEntry>>; // Maps from event name to the map of matchers that are registered for it. - typedef std::map<std::string, EventMatcherMap> EventMatcherMultiMap; + using EventMatcherMultiMap = std::map<std::string, EventMatcherMap>; // Adds the list of URL filters in |matcher| to the URL matcher, having // matches for those URLs map to |id|.
diff --git a/extensions/common/extension_l10n_util.cc b/extensions/common/extension_l10n_util.cc index 9701ea43..bf0194a4 100644 --- a/extensions/common/extension_l10n_util.cc +++ b/extensions/common/extension_l10n_util.cc
@@ -15,7 +15,6 @@ #include "base/files/file_util.h" #include "base/json/json_file_value_serializer.h" #include "base/logging.h" -#include "base/memory/linked_ptr.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" @@ -36,9 +35,10 @@ // Loads contents of the messages file for given locale. If file is not found, // or there was parsing error we return NULL and set |error|. // Caller owns the returned object. -base::DictionaryValue* LoadMessageFile(const base::FilePath& locale_path, - const std::string& locale, - std::string* error) { +std::unique_ptr<base::DictionaryValue> LoadMessageFile( + const base::FilePath& locale_path, + const std::string& locale, + std::string* error) { base::FilePath file = locale_path.AppendASCII(locale).Append(extensions::kMessagesFilename); JSONFileValueDeserializer messages_deserializer(file); @@ -59,7 +59,7 @@ } } - return dictionary.release(); + return dictionary; } // Localizes manifest value of string type for a given key. @@ -376,21 +376,21 @@ GetAllFallbackLocales( application_locale, default_locale, &all_fallback_locales); - std::vector<linked_ptr<base::DictionaryValue> > catalogs; + std::vector<std::unique_ptr<base::DictionaryValue>> catalogs; for (size_t i = 0; i < all_fallback_locales.size(); ++i) { // Skip all parent locales that are not supplied. base::FilePath this_locale_path = locale_path.AppendASCII(all_fallback_locales[i]); if (!base::PathExists(this_locale_path)) continue; - linked_ptr<base::DictionaryValue> catalog( - LoadMessageFile(locale_path, all_fallback_locales[i], error)); + std::unique_ptr<base::DictionaryValue> catalog = + LoadMessageFile(locale_path, all_fallback_locales[i], error); if (!catalog.get()) { // If locale is valid, but messages.json is corrupted or missing, return // an error. - return NULL; + return nullptr; } else { - catalogs.push_back(catalog); + catalogs.push_back(std::move(catalog)); } } @@ -415,8 +415,8 @@ locale != valid_locales.end(); ++locale) { std::string locale_error; - std::unique_ptr<base::DictionaryValue> catalog( - LoadMessageFile(locale_path, *locale, &locale_error)); + std::unique_ptr<base::DictionaryValue> catalog = + LoadMessageFile(locale_path, *locale, &locale_error); if (!locale_error.empty()) { if (!error->empty())
diff --git a/extensions/common/extension_l10n_util_unittest.cc b/extensions/common/extension_l10n_util_unittest.cc index f23b424..3caba36 100644 --- a/extensions/common/extension_l10n_util_unittest.cc +++ b/extensions/common/extension_l10n_util_unittest.cc
@@ -9,7 +9,6 @@ #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" -#include "base/memory/linked_ptr.h" #include "base/memory/ptr_util.h" #include "base/path_service.h" #include "base/strings/utf_string_conversions.h" @@ -211,7 +210,7 @@ // Caller owns the returned object. MessageBundle* CreateManifestBundle() { - linked_ptr<base::DictionaryValue> catalog(new base::DictionaryValue); + std::unique_ptr<base::DictionaryValue> catalog(new base::DictionaryValue); base::DictionaryValue* name_tree = new base::DictionaryValue(); name_tree->SetString("message", "name"); @@ -259,8 +258,8 @@ url_country_tree->SetString("message", "de"); catalog->Set("country", url_country_tree); - std::vector<linked_ptr<base::DictionaryValue> > catalogs; - catalogs.push_back(catalog); + std::vector<std::unique_ptr<base::DictionaryValue>> catalogs; + catalogs.push_back(std::move(catalog)); std::string error; MessageBundle* bundle = MessageBundle::Create(catalogs, &error);
diff --git a/extensions/common/extension_messages.h b/extensions/common/extension_messages.h index e2a9c917..ad613fd 100644 --- a/extensions/common/extension_messages.h +++ b/extensions/common/extension_messages.h
@@ -685,6 +685,15 @@ bool /* include_tls_channel_id */, int /* request_id */) +// Same as ExtensionHostMsg_OpenChannelToExtension, but assigns the port id +// synchronously. +IPC_SYNC_MESSAGE_CONTROL4_1(ExtensionHostMsg_OpenChannelToExtensionSync, + int /* frame_routing_id */, + ExtensionMsg_ExternalConnectionInfo, + std::string /* channel_name */, + bool /* include_tls_channel_id */, + int /* port_id */) + // The response to a request to open an extension message port, including the // global port id and the request id. IPC_MESSAGE_ROUTED2(ExtensionMsg_AssignPortId,
diff --git a/extensions/common/message_bundle.cc b/extensions/common/message_bundle.cc index 28d7098..3fa75c0c 100644 --- a/extensions/common/message_bundle.cc +++ b/extensions/common/message_bundle.cc
@@ -11,7 +11,6 @@ #include "base/containers/hash_tables.h" #include "base/i18n/rtl.h" #include "base/lazy_instance.h" -#include "base/memory/linked_ptr.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h"
diff --git a/extensions/common/message_bundle.h b/extensions/common/message_bundle.h index 9c0bde7..d0e3746b 100644 --- a/extensions/common/message_bundle.h +++ b/extensions/common/message_bundle.h
@@ -8,11 +8,10 @@ #include <stddef.h> #include <map> +#include <memory> #include <string> #include <vector> -#include "base/memory/linked_ptr.h" - namespace base { class DictionaryValue; class Value; @@ -24,8 +23,8 @@ // locale does not provide are pulled from the default locale. class MessageBundle { public: - typedef std::map<std::string, std::string> SubstitutionMap; - typedef std::vector<linked_ptr<base::DictionaryValue> > CatalogVector; + using SubstitutionMap = std::map<std::string, std::string>; + using CatalogVector = std::vector<std::unique_ptr<base::DictionaryValue>>; // JSON keys of interest for messages file. static const char kContentKey[];
diff --git a/extensions/common/message_bundle_unittest.cc b/extensions/common/message_bundle_unittest.cc index 45bd0e1..bafbf9d 100644 --- a/extensions/common/message_bundle_unittest.cc +++ b/extensions/common/message_bundle_unittest.cc
@@ -12,7 +12,6 @@ #include "base/i18n/rtl.h" #include "base/macros.h" -#include "base/memory/linked_ptr.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" @@ -74,29 +73,28 @@ SetDictionary(name, message_tree, dict); } - // Caller owns the memory. - base::DictionaryValue* CreateGoodDictionary() { - base::DictionaryValue* dict = new base::DictionaryValue; - CreateMessageTree("n1", "message1 $a$ $b$", true, dict); - CreateMessageTree("n2", "message2 $c$", true, dict); - CreateMessageTree("n3", "message3", false, dict); + std::unique_ptr<base::DictionaryValue> CreateGoodDictionary() { + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + CreateMessageTree("n1", "message1 $a$ $b$", true, dict.get()); + CreateMessageTree("n2", "message2 $c$", true, dict.get()); + CreateMessageTree("n3", "message3", false, dict.get()); return dict; } - // Caller owns the memory. - base::DictionaryValue* CreateBadDictionary(enum BadDictionary what_is_bad) { - base::DictionaryValue* dict = CreateGoodDictionary(); + std::unique_ptr<base::DictionaryValue> CreateBadDictionary( + enum BadDictionary what_is_bad) { + std::unique_ptr<base::DictionaryValue> dict = CreateGoodDictionary(); // Now remove/break things. switch (what_is_bad) { case INVALID_NAME: - CreateMessageTree("n 5", "nevermind", false, dict); + CreateMessageTree("n 5", "nevermind", false, dict.get()); break; case NAME_NOT_A_TREE: dict->SetString("n4", "whatever"); break; case EMPTY_NAME_TREE: { base::DictionaryValue* empty_tree = new base::DictionaryValue; - SetDictionary("n4", empty_tree, dict); + SetDictionary("n4", empty_tree, dict.get()); } break; case MISSING_MESSAGE: @@ -107,7 +105,7 @@ break; case EMPTY_PLACEHOLDER_TREE: { base::DictionaryValue* empty_tree = new base::DictionaryValue; - SetDictionary("n1.placeholders", empty_tree, dict); + SetDictionary("n1.placeholders", empty_tree, dict.get()); } break; case CONTENT_MISSING: @@ -161,7 +159,7 @@ } std::unique_ptr<MessageBundle> handler_; - std::vector<linked_ptr<base::DictionaryValue> > catalogs_; + std::vector<std::unique_ptr<base::DictionaryValue>> catalogs_; }; TEST_F(MessageBundleTest, ReservedMessagesCount) { @@ -176,8 +174,7 @@ } TEST_F(MessageBundleTest, InitGoodDefaultDict) { - catalogs_.push_back( - linked_ptr<base::DictionaryValue>(CreateGoodDictionary())); + catalogs_.push_back(CreateGoodDictionary()); CreateMessageBundle(); EXPECT_TRUE(handler_.get() != NULL); @@ -190,10 +187,8 @@ } TEST_F(MessageBundleTest, InitAppDictConsultedFirst) { - catalogs_.push_back( - linked_ptr<base::DictionaryValue>(CreateGoodDictionary())); - catalogs_.push_back( - linked_ptr<base::DictionaryValue>(CreateGoodDictionary())); + catalogs_.push_back(CreateGoodDictionary()); + catalogs_.push_back(CreateGoodDictionary()); base::DictionaryValue* app_dict = catalogs_[0].get(); // Flip placeholders in message of n1 tree. @@ -216,10 +211,8 @@ } TEST_F(MessageBundleTest, InitBadAppDict) { - catalogs_.push_back( - linked_ptr<base::DictionaryValue>(CreateBadDictionary(INVALID_NAME))); - catalogs_.push_back( - linked_ptr<base::DictionaryValue>(CreateGoodDictionary())); + catalogs_.push_back(CreateBadDictionary(INVALID_NAME)); + catalogs_.push_back(CreateGoodDictionary()); std::string error = CreateMessageBundle(); @@ -227,45 +220,44 @@ EXPECT_EQ("Name of a key \"n 5\" is invalid. Only ASCII [a-z], " "[A-Z], [0-9] and \"_\" are allowed.", error); - catalogs_[0].reset(CreateBadDictionary(NAME_NOT_A_TREE)); + catalogs_[0] = CreateBadDictionary(NAME_NOT_A_TREE); handler_.reset(MessageBundle::Create(catalogs_, &error)); EXPECT_TRUE(handler_.get() == NULL); EXPECT_EQ("Not a valid tree for key n4.", error); - catalogs_[0].reset(CreateBadDictionary(EMPTY_NAME_TREE)); + catalogs_[0] = CreateBadDictionary(EMPTY_NAME_TREE); handler_.reset(MessageBundle::Create(catalogs_, &error)); EXPECT_TRUE(handler_.get() == NULL); EXPECT_EQ("There is no \"message\" element for key n4.", error); - catalogs_[0].reset(CreateBadDictionary(MISSING_MESSAGE)); + catalogs_[0] = CreateBadDictionary(MISSING_MESSAGE); handler_.reset(MessageBundle::Create(catalogs_, &error)); EXPECT_TRUE(handler_.get() == NULL); EXPECT_EQ("There is no \"message\" element for key n1.", error); - catalogs_[0].reset(CreateBadDictionary(PLACEHOLDER_NOT_A_TREE)); + catalogs_[0] = CreateBadDictionary(PLACEHOLDER_NOT_A_TREE); handler_.reset(MessageBundle::Create(catalogs_, &error)); EXPECT_TRUE(handler_.get() == NULL); EXPECT_EQ("Not a valid \"placeholders\" element for key n1.", error); - catalogs_[0].reset(CreateBadDictionary(EMPTY_PLACEHOLDER_TREE)); + catalogs_[0] = CreateBadDictionary(EMPTY_PLACEHOLDER_TREE); handler_.reset(MessageBundle::Create(catalogs_, &error)); EXPECT_TRUE(handler_.get() == NULL); EXPECT_EQ("Variable $a$ used but not defined.", error); - catalogs_[0].reset(CreateBadDictionary(CONTENT_MISSING)); + catalogs_[0] = CreateBadDictionary(CONTENT_MISSING); handler_.reset(MessageBundle::Create(catalogs_, &error)); EXPECT_TRUE(handler_.get() == NULL); EXPECT_EQ("Invalid \"content\" element for key n1.", error); - catalogs_[0].reset(CreateBadDictionary(MESSAGE_PLACEHOLDER_DOESNT_MATCH)); + catalogs_[0] = CreateBadDictionary(MESSAGE_PLACEHOLDER_DOESNT_MATCH); handler_.reset(MessageBundle::Create(catalogs_, &error)); EXPECT_TRUE(handler_.get() == NULL); EXPECT_EQ("Variable $a$ used but not defined.", error); } TEST_F(MessageBundleTest, ReservedMessagesOverrideDeveloperMessages) { - catalogs_.push_back( - linked_ptr<base::DictionaryValue>(CreateGoodDictionary())); + catalogs_.push_back(CreateGoodDictionary()); base::DictionaryValue* dict = catalogs_[0].get(); CreateMessageTree(MessageBundle::kUILocaleKey, "x", false, dict);
diff --git a/extensions/common/url_pattern_set.cc b/extensions/common/url_pattern_set.cc index 2ec0074..5686092 100644 --- a/extensions/common/url_pattern_set.cc +++ b/extensions/common/url_pattern_set.cc
@@ -8,7 +8,6 @@ #include <ostream> #include "base/logging.h" -#include "base/memory/linked_ptr.h" #include "base/memory/ptr_util.h" #include "base/stl_util.h" #include "base/values.h"
diff --git a/extensions/renderer/extension_frame_helper.cc b/extensions/renderer/extension_frame_helper.cc index 2583798..ba81d4097 100644 --- a/extensions/renderer/extension_frame_helper.cc +++ b/extensions/renderer/extension_frame_helper.cc
@@ -241,6 +241,17 @@ } } +int ExtensionFrameHelper::RequestSyncPortId( + const ExtensionMsg_ExternalConnectionInfo& info, + const std::string& channel_name, + bool include_tls_channel_id) { + int port_id = 0; + render_frame()->Send(new ExtensionHostMsg_OpenChannelToExtensionSync( + render_frame()->GetRoutingID(), info, channel_name, + include_tls_channel_id, &port_id)); + return port_id; +} + void ExtensionFrameHelper::DidMatchCSS( const blink::WebVector<blink::WebString>& newly_matching_selectors, const blink::WebVector<blink::WebString>& stopped_matching_selectors) {
diff --git a/extensions/renderer/extension_frame_helper.h b/extensions/renderer/extension_frame_helper.h index 01794e37a..26f0271 100644 --- a/extensions/renderer/extension_frame_helper.h +++ b/extensions/renderer/extension_frame_helper.h
@@ -94,6 +94,9 @@ const base::Callback<void(int)>& callback); void RequestNativeAppPortId(const std::string& native_app_name, const base::Callback<void(int)>& callback); + int RequestSyncPortId(const ExtensionMsg_ExternalConnectionInfo& info, + const std::string& channel_name, + bool include_tls_channel_id); private: struct PendingPortRequest;
diff --git a/extensions/renderer/messaging_bindings.cc b/extensions/renderer/messaging_bindings.cc index 5462e373..b82e84b 100644 --- a/extensions/renderer/messaging_bindings.cc +++ b/extensions/renderer/messaging_bindings.cc
@@ -269,6 +269,18 @@ MessagingBindings::~MessagingBindings() { g_messaging_map.Get().erase(context()); + if (ports_created_normal_ > 0 || ports_created_in_before_unload_ > 0 || + ports_created_in_unload_ > 0) { + UMA_HISTOGRAM_COUNTS_1000( + "Extensions.Messaging.ExtensionPortsCreated.InBeforeUnload", + ports_created_in_before_unload_); + UMA_HISTOGRAM_COUNTS_1000( + "Extensions.Messaging.ExtensionPortsCreated.InUnload", + ports_created_in_unload_); + UMA_HISTOGRAM_COUNTS_1000( + "Extensions.Messaging.ExtensionPortsCreated.Normal", + ports_created_normal_); + } } // static @@ -450,10 +462,30 @@ ExtensionFrameHelper* frame_helper = ExtensionFrameHelper::Get(render_frame); DCHECK(frame_helper); - frame_helper->RequestPortId( - info, channel_name, include_tls_channel_id, - base::Bind(&MessagingBindings::SetGlobalPortId, - weak_ptr_factory_.GetWeakPtr(), local_id)); + + blink::WebLocalFrame* web_frame = render_frame->GetWebFrame(); + // If the frame is unloading, we need to assign the port id synchronously to + // avoid dropping the message on the floor; see crbug.com/660706. + // TODO(devlin): Investigate whether we need to continue supporting this long- + // term, and, if so, find an alternative that doesn't require synchronous + // IPCs. + if (!web_frame->document().isNull() && + (web_frame->document().unloadStartedDoNotUse() || + web_frame->document().processingBeforeUnloadDoNotUse())) { + ports_created_in_before_unload_ += + web_frame->document().processingBeforeUnloadDoNotUse() ? 1 : 0; + ports_created_in_unload_ += + web_frame->document().unloadStartedDoNotUse() ? 1 : 0; + int global_id = frame_helper->RequestSyncPortId(info, channel_name, + include_tls_channel_id); + ports_[local_id]->SetGlobalId(global_id); + } else { + ++ports_created_normal_; + frame_helper->RequestPortId( + info, channel_name, include_tls_channel_id, + base::Bind(&MessagingBindings::SetGlobalPortId, + weak_ptr_factory_.GetWeakPtr(), local_id)); + } args.GetReturnValue().Set(static_cast<int32_t>(local_id)); }
diff --git a/extensions/renderer/messaging_bindings.h b/extensions/renderer/messaging_bindings.h index b0e9fe7..758187e 100644 --- a/extensions/renderer/messaging_bindings.h +++ b/extensions/renderer/messaging_bindings.h
@@ -115,7 +115,17 @@ PortMap disconnected_ports_; // The next available local id for a port. - int next_local_id_ = 0; + size_t next_local_id_ = 0; + + // The number of ports created in the 'beforeunload' event handler. + size_t ports_created_in_before_unload_ = 0; + + // The number of ports created in the 'unload' event handler. + size_t ports_created_in_unload_ = 0; + + // The number of ports created during during any time that isn't in the unload + // or beforeunload handlers. + int ports_created_normal_ = 0; base::WeakPtrFactory<MessagingBindings> weak_ptr_factory_;
diff --git a/gpu/BUILD.gn b/gpu/BUILD.gn index 04db1806..4fc3219 100644 --- a/gpu/BUILD.gn +++ b/gpu/BUILD.gn
@@ -371,6 +371,14 @@ "//ui/gl/init", ] + data = [ + # Needed for isolate script to execute. + "//testing/scripts/common.py", + "//testing/xvfb.py", + "//testing/scripts/run_gtest_perf_test.py", + "//tools/perf/generate_legacy_perf_dashboard_json.py", + ] + # This target should not require the Chrome executable to run. assert_no_deps = [ "//chrome" ] }
diff --git a/gpu/command_buffer/service/gles2_cmd_decoder.cc b/gpu/command_buffer/service/gles2_cmd_decoder.cc index 6f0d2e8d..fb89982c 100644 --- a/gpu/command_buffer/service/gles2_cmd_decoder.cc +++ b/gpu/command_buffer/service/gles2_cmd_decoder.cc
@@ -17538,29 +17538,31 @@ "MAP_FLUSH_EXPLICIT_BIT set without MAP_WRITE_BIT"); return error::kNoError; } - if (AllBitsSet(access, GL_MAP_INVALIDATE_BUFFER_BIT)) { + GLbitfield filtered_access = access; + if (AllBitsSet(filtered_access, GL_MAP_INVALIDATE_BUFFER_BIT)) { // To be on the safe side, always map GL_MAP_INVALIDATE_BUFFER_BIT to // GL_MAP_INVALIDATE_RANGE_BIT. - access = (access & ~GL_MAP_INVALIDATE_BUFFER_BIT); - access = (access | GL_MAP_INVALIDATE_RANGE_BIT); + filtered_access = (filtered_access & ~GL_MAP_INVALIDATE_BUFFER_BIT); + filtered_access = (filtered_access | GL_MAP_INVALIDATE_RANGE_BIT); } // Always filter out GL_MAP_UNSYNCHRONIZED_BIT to get rid of undefined // behaviors. - access = (access & ~GL_MAP_UNSYNCHRONIZED_BIT); - if (AllBitsSet(access, GL_MAP_WRITE_BIT) && - !AllBitsSet(access, GL_MAP_INVALIDATE_RANGE_BIT)) { - access = (access | GL_MAP_READ_BIT); + filtered_access = (filtered_access & ~GL_MAP_UNSYNCHRONIZED_BIT); + if (AllBitsSet(filtered_access, GL_MAP_WRITE_BIT) && + !AllBitsSet(filtered_access, GL_MAP_INVALIDATE_RANGE_BIT)) { + filtered_access = (filtered_access | GL_MAP_READ_BIT); } - void* ptr = glMapBufferRange(target, offset, size, access); + void* ptr = glMapBufferRange(target, offset, size, filtered_access); if (ptr == nullptr) { // This should mean GL_OUT_OF_MEMORY (or context loss). LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER(func_name); return error::kNoError; } + // The un-filtered bits in |access| are deliberately used here. buffer->SetMappedRange(offset, size, access, ptr, GetSharedMemoryBuffer(data_shm_id), static_cast<unsigned int>(data_shm_offset)); - if ((access & GL_MAP_INVALIDATE_RANGE_BIT) == 0) { + if ((filtered_access & GL_MAP_INVALIDATE_RANGE_BIT) == 0) { memcpy(mem, ptr, size); } *result = 1;
diff --git a/gpu/command_buffer/tests/gl_map_buffer_range_unittest.cc b/gpu/command_buffer/tests/gl_map_buffer_range_unittest.cc index b781f836..bd32e45 100644 --- a/gpu/command_buffer/tests/gl_map_buffer_range_unittest.cc +++ b/gpu/command_buffer/tests/gl_map_buffer_range_unittest.cc
@@ -473,6 +473,29 @@ GLTestHelper::CheckGLError("no errors", __LINE__); } +TEST_F(ES3MapBufferRangeTest, GetBufferParameteriv) { + if (ShouldSkipTest()) + return; + + GLuint buffer; + glGenBuffers(1, &buffer); + EXPECT_LT(0u, buffer); + glBindBuffer(GL_ARRAY_BUFFER, buffer); + glBufferData(GL_ARRAY_BUFFER, 64, 0, GL_STATIC_READ); + + GLbitfield access = GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT; + glMapBufferRange(GL_ARRAY_BUFFER, 16, 32, access); + GLint param = 0; + glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_ACCESS_FLAGS, ¶m); + EXPECT_EQ(access, static_cast<GLbitfield>(param)); + glUnmapBuffer(GL_ARRAY_BUFFER); + param = 0; + glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_ACCESS_FLAGS, ¶m); + EXPECT_EQ(0u, static_cast<GLbitfield>(param)); + + GLTestHelper::CheckGLError("no errors", __LINE__); +} + // TODO(zmo): add tests for uniform buffer mapping. // TODO(zmo): add tests for CopyBufferSubData case.
diff --git a/gpu/config/gpu_util.cc b/gpu/config/gpu_util.cc index e27c292..49eb25b 100644 --- a/gpu/config/gpu_util.cc +++ b/gpu/config/gpu_util.cc
@@ -61,13 +61,6 @@ } // namespace anonymous -void MergeFeatureSets(std::set<int>* dst, const std::set<int>& src) { - DCHECK(dst); - if (src.empty()) - return; - dst->insert(src.begin(), src.end()); -} - void ApplyGpuDriverBugWorkarounds(const GPUInfo& gpu_info, base::CommandLine* command_line) { std::unique_ptr<GpuDriverBugList> list(GpuDriverBugList::Create());
diff --git a/gpu/config/gpu_util.h b/gpu/config/gpu_util.h index 7f4372b..8c82555 100644 --- a/gpu/config/gpu_util.h +++ b/gpu/config/gpu_util.h
@@ -20,10 +20,6 @@ struct GPUInfo; -// Merge features in src into dst. -GPU_EXPORT void MergeFeatureSets( - std::set<int>* dst, const std::set<int>& src); - // With provided GPUInfo, compute the driver bug workarounds and disabled // extensions for the current system, and append the |command_line|. GPU_EXPORT void ApplyGpuDriverBugWorkarounds(
diff --git a/gpu/config/gpu_util_unittest.cc b/gpu/config/gpu_util_unittest.cc index da52c18..4b28ac64 100644 --- a/gpu/config/gpu_util_unittest.cc +++ b/gpu/config/gpu_util_unittest.cc
@@ -18,46 +18,6 @@ namespace gpu { -TEST(GpuUtilTest, MergeFeatureSets) { - { - // Merge two empty sets. - std::set<int> src; - std::set<int> dst; - EXPECT_TRUE(dst.empty()); - MergeFeatureSets(&dst, src); - EXPECT_TRUE(dst.empty()); - } - { - // Merge an empty set into a set with elements. - std::set<int> src; - std::set<int> dst; - dst.insert(1); - EXPECT_EQ(1u, dst.size()); - MergeFeatureSets(&dst, src); - EXPECT_EQ(1u, dst.size()); - } - { - // Merge two sets where the source elements are already in the target set. - std::set<int> src; - std::set<int> dst; - src.insert(1); - dst.insert(1); - EXPECT_EQ(1u, dst.size()); - MergeFeatureSets(&dst, src); - EXPECT_EQ(1u, dst.size()); - } - { - // Merge two sets with different elements. - std::set<int> src; - std::set<int> dst; - src.insert(1); - dst.insert(2); - EXPECT_EQ(1u, dst.size()); - MergeFeatureSets(&dst, src); - EXPECT_EQ(2u, dst.size()); - } -} - TEST(GpuUtilTest, StringToFeatureSet) { { // zero feature.
diff --git a/gpu/ipc/client/gpu_memory_buffer_impl_shared_memory.cc b/gpu/ipc/client/gpu_memory_buffer_impl_shared_memory.cc index 2641b8bf..910cbe9 100644 --- a/gpu/ipc/client/gpu_memory_buffer_impl_shared_memory.cc +++ b/gpu/ipc/client/gpu_memory_buffer_impl_shared_memory.cc
@@ -62,8 +62,7 @@ GpuMemoryBufferImplSharedMemory::AllocateForChildProcess( gfx::GpuMemoryBufferId id, const gfx::Size& size, - gfx::BufferFormat format, - base::ProcessHandle child_process) { + gfx::BufferFormat format) { size_t buffer_size = 0u; if (!gfx::BufferSizeForBufferFormatChecked(size, format, &buffer_size)) return gfx::GpuMemoryBufferHandle(); @@ -78,7 +77,7 @@ handle.offset = 0; handle.stride = static_cast<int32_t>( gfx::RowSizeForBufferFormat(size.width(), format, 0)); - shared_memory.GiveToProcess(child_process, &handle.handle); + handle.handle = shared_memory.TakeHandle(); return handle; }
diff --git a/gpu/ipc/client/gpu_memory_buffer_impl_shared_memory.h b/gpu/ipc/client/gpu_memory_buffer_impl_shared_memory.h index 0ad9e3f..b991f95 100644 --- a/gpu/ipc/client/gpu_memory_buffer_impl_shared_memory.h +++ b/gpu/ipc/client/gpu_memory_buffer_impl_shared_memory.h
@@ -29,8 +29,7 @@ static gfx::GpuMemoryBufferHandle AllocateForChildProcess( gfx::GpuMemoryBufferId id, const gfx::Size& size, - gfx::BufferFormat format, - base::ProcessHandle child_process); + gfx::BufferFormat format); static std::unique_ptr<GpuMemoryBufferImplSharedMemory> CreateFromHandle( const gfx::GpuMemoryBufferHandle& handle,
diff --git a/headless/lib/browser/headless_browser_manifest_overlay.json b/headless/lib/browser/headless_browser_manifest_overlay_template.json similarity index 63% rename from headless/lib/browser/headless_browser_manifest_overlay.json rename to headless/lib/browser/headless_browser_manifest_overlay_template.json index 0706492..f2344b7 100644 --- a/headless/lib/browser/headless_browser_manifest_overlay.json +++ b/headless/lib/browser/headless_browser_manifest_overlay_template.json
@@ -3,9 +3,7 @@ "interface_provider_specs": { "navigation:frame": { "provides": { - "renderer": [ - "embedder_test::TestEmbedderService" - ] + "renderer": [] } } }
diff --git a/headless/lib/browser/headless_content_browser_client.cc b/headless/lib/browser/headless_content_browser_client.cc index b863c60f..b6c2f05 100644 --- a/headless/lib/browser/headless_content_browser_client.cc +++ b/headless/lib/browser/headless_content_browser_client.cc
@@ -5,6 +5,7 @@ #include "headless/lib/browser/headless_content_browser_client.h" #include <memory> +#include <unordered_set> #include "base/callback.h" #include "base/json/json_reader.h" @@ -23,6 +24,11 @@ namespace headless { +namespace { +const char kCapabilityPath[] = + "interface_provider_specs.navigation:frame.provides.renderer"; +} // namespace + HeadlessContentBrowserClient::HeadlessContentBrowserClient( HeadlessBrowserImpl* browser) : browser_(browser) {} @@ -56,12 +62,28 @@ std::unique_ptr<base::Value> HeadlessContentBrowserClient::GetServiceManifestOverlay( const std::string& name) { - if (name != content::kBrowserServiceName) + if (name != content::kBrowserServiceName || + browser_->options()->mojo_service_names.empty()) return nullptr; - base::StringPiece manifest_contents = + + base::StringPiece manifest_template = ui::ResourceBundle::GetSharedInstance().GetRawDataResource( - IDR_HEADLESS_BROWSER_MANIFEST_OVERLAY); - return base::JSONReader::Read(manifest_contents); + IDR_HEADLESS_BROWSER_MANIFEST_OVERLAY_TEMPLATE); + std::unique_ptr<base::Value> manifest = + base::JSONReader::Read(manifest_template); + + // Add mojo_service_names to renderer capability specified in options. + base::DictionaryValue* manifest_dictionary = nullptr; + CHECK(manifest->GetAsDictionary(&manifest_dictionary)); + + base::ListValue* capability_list = nullptr; + CHECK(manifest_dictionary->GetList(kCapabilityPath, &capability_list)); + + for (std::string service_name : browser_->options()->mojo_service_names) { + capability_list->AppendString(service_name); + } + + return manifest; } } // namespace headless
diff --git a/headless/lib/embedder_mojo_browsertest.cc b/headless/lib/embedder_mojo_browsertest.cc index 512a8745..3fb4ed1 100644 --- a/headless/lib/embedder_mojo_browsertest.cc +++ b/headless/lib/embedder_mojo_browsertest.cc
@@ -5,6 +5,7 @@ #include <memory> #include "base/optional.h" #include "base/path_service.h" +#include "base/strings/string_piece.h" #include "base/strings/stringprintf.h" #include "base/threading/thread_restrictions.h" #include "content/public/test/browser_test.h" @@ -49,6 +50,13 @@ ~EmbedderMojoTest() override {} + void SetUp() override { + // Set service names before they are used during main thread initialization. + options()->mojo_service_names.insert("embedder_test::TestEmbedderService"); + + HeadlessBrowserTest::SetUp(); + } + void SetUpOnMainThread() override { base::ThreadRestrictions::SetIOAllowed(true); base::FilePath pak_path;
diff --git a/headless/lib/resources/headless_lib_resources.grd b/headless/lib/resources/headless_lib_resources.grd index 8a3ff266..9a0e2b0e 100644 --- a/headless/lib/resources/headless_lib_resources.grd +++ b/headless/lib/resources/headless_lib_resources.grd
@@ -10,7 +10,7 @@ <release seq="1"> <includes> <include name="IDR_HEADLESS_LIB_DEVTOOLS_DISCOVERY_PAGE" file="devtools_discovery_page.html" type="BINDATA" /> - <include name="IDR_HEADLESS_BROWSER_MANIFEST_OVERLAY" file="../browser/headless_browser_manifest_overlay.json" type="BINDATA" /> + <include name="IDR_HEADLESS_BROWSER_MANIFEST_OVERLAY_TEMPLATE" file="../browser/headless_browser_manifest_overlay_template.json" type="BINDATA" /> </includes> </release> </grit>
diff --git a/headless/public/headless_browser.cc b/headless/public/headless_browser.cc index cbfbc5e..2b4270b 100644 --- a/headless/public/headless_browser.cc +++ b/headless/public/headless_browser.cc
@@ -82,6 +82,11 @@ return *this; } +Builder& Builder::AddMojoServiceName(const std::string& mojo_service_name) { + options_.mojo_service_names.insert(mojo_service_name); + return *this; +} + Builder& Builder::SetUserDataDir(const base::FilePath& user_data_dir) { options_.user_data_dir = user_data_dir; return *this;
diff --git a/headless/public/headless_browser.h b/headless/public/headless_browser.h index 954b79e..021e910 100644 --- a/headless/public/headless_browser.h +++ b/headless/public/headless_browser.h
@@ -8,6 +8,7 @@ #include <memory> #include <string> #include <unordered_map> +#include <unordered_set> #include <vector> #include "base/callback.h" @@ -115,6 +116,10 @@ // string can be used to disable GL rendering (e.g., WebGL support). std::string gl_implementation; + // Names of mojo services exposed by the browser to the renderer. These + // services will be added to the browser's service manifest. + std::unordered_set<std::string> mojo_service_names; + // Default per-context options, can be specialized on per-context basis. std::string user_agent; @@ -159,6 +164,7 @@ Builder& SetSingleProcessMode(bool single_process_mode); Builder& SetDisableSandbox(bool disable_sandbox); Builder& SetGLImplementation(const std::string& gl_implementation); + Builder& AddMojoServiceName(const std::string& mojo_service_name); // Per-context settings.
diff --git a/headless/public/util/http_url_fetcher.cc b/headless/public/util/http_url_fetcher.cc index cbb2c0a..af54512 100644 --- a/headless/public/util/http_url_fetcher.cc +++ b/headless/public/util/http_url_fetcher.cc
@@ -6,6 +6,7 @@ #include "net/base/io_buffer.h" #include "net/cert/cert_status_flags.h" +#include "net/http/http_response_headers.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_context.h" @@ -165,9 +166,13 @@ return; } - result_listener_->OnFetchCompleteExtractHeaders( - request->url(), request->GetResponseCode(), bytes_read_so_far_.c_str(), - bytes_read_so_far_.size()); + // TODO(alexclarke) apart from the headers there's a lot of stuff in + // |request->response_info()| that we drop here. Find a way to pipe it + // through. + result_listener_->OnFetchComplete( + request->url(), request->GetResponseCode(), + request->response_info().headers, + bytes_read_so_far_.c_str(), bytes_read_so_far_.size()); } HttpURLFetcher::HttpURLFetcher(
diff --git a/headless/test/headless_browser_test.cc b/headless/test/headless_browser_test.cc index e259d9b..090a704 100644 --- a/headless/test/headless_browser_test.cc +++ b/headless/test/headless_browser_test.cc
@@ -151,6 +151,10 @@ return HeadlessContentMainDelegate::GetInstance()->browser(); } +HeadlessBrowser::Options* HeadlessBrowserTest::options() const { + return HeadlessContentMainDelegate::GetInstance()->browser()->options(); +} + bool HeadlessBrowserTest::WaitForLoad(HeadlessWebContents* web_contents) { SynchronousLoadObserver load_observer(this, web_contents); RunAsynchronousTest();
diff --git a/headless/test/headless_browser_test.h b/headless/test/headless_browser_test.h index 8b6cb75..c787859 100644 --- a/headless/test/headless_browser_test.h +++ b/headless/test/headless_browser_test.h
@@ -80,6 +80,10 @@ // Returns the browser for the test. HeadlessBrowser* browser() const; + // Returns the options used by the browser. Modify with caution, since some + // options only take effect if they were set before browser creation. + HeadlessBrowser::Options* options() const; + private: std::unique_ptr<base::RunLoop> run_loop_;
diff --git a/headless/test/headless_test_launcher.cc b/headless/test/headless_test_launcher.cc index da455005..57015f4 100644 --- a/headless/test/headless_test_launcher.cc +++ b/headless/test/headless_test_launcher.cc
@@ -47,7 +47,8 @@ protected: content::ContentMainDelegate* CreateContentMainDelegate() override { - // Use HeadlessBrowserTest::SetBrowserOptions to override these defaults. + // Use HeadlessBrowserTest::options() or HeadlessBrowserContextOptions to + // modify these defaults. HeadlessBrowser::Options::Builder options_builder; std::unique_ptr<HeadlessBrowserImpl> browser( new HeadlessBrowserImplForTest(options_builder.Build()));
diff --git a/infra/config/recipes.cfg b/infra/config/recipes.cfg index d70e73e..33b1322 100644 --- a/infra/config/recipes.cfg +++ b/infra/config/recipes.cfg
@@ -5,17 +5,17 @@ project_id: "build" url: "https://chromium.googlesource.com/chromium/tools/build.git" branch: "master" - revision: "8fd361c4e7d3249be7d9c167a3024ebb83c2fb37" + revision: "dc28812f851076af869a12aa078df51a680345b7" } deps { project_id: "depot_tools" url: "https://chromium.googlesource.com/chromium/tools/depot_tools.git" branch: "master" - revision: "9b654aa0848af49cc42985476acb58e03f0b72f5" + revision: "1a60c9c78698d5bcbca3ef071d5c361010651780" } deps { project_id: "recipe_engine" url: "https://chromium.googlesource.com/external/github.com/luci/recipes-py.git" branch: "master" - revision: "d6020a7ef29d3f7fb77d16a1cd6b32c7b2f09dc2" + revision: "672570bf06c6b438b353a4c42d4d38ceab089eea" }
diff --git a/ios/chrome/browser/physical_web/BUILD.gn b/ios/chrome/browser/physical_web/BUILD.gn index 5ad2547..b402e29c 100644 --- a/ios/chrome/browser/physical_web/BUILD.gn +++ b/ios/chrome/browser/physical_web/BUILD.gn
@@ -6,6 +6,8 @@ sources = [ "create_physical_web_data_source.h", "create_physical_web_data_source.mm", + "ios_chrome_physical_web_data_source.h", + "ios_chrome_physical_web_data_source.mm", "physical_web_constants.h", "start_physical_web_discovery.h", "start_physical_web_discovery.mm",
diff --git a/ios/chrome/browser/physical_web/create_physical_web_data_source.mm b/ios/chrome/browser/physical_web/create_physical_web_data_source.mm index 055952a..307728e91 100644 --- a/ios/chrome/browser/physical_web/create_physical_web_data_source.mm +++ b/ios/chrome/browser/physical_web/create_physical_web_data_source.mm
@@ -5,7 +5,7 @@ #include "ios/chrome/browser/physical_web/create_physical_web_data_source.h" #include "base/memory/ptr_util.h" -#import "ios/chrome/common/physical_web/ios_chrome_physical_web_data_source.h" +#import "ios/chrome/browser/physical_web/ios_chrome_physical_web_data_source.h" std::unique_ptr<PhysicalWebDataSource> CreateIOSChromePhysicalWebDataSource() { return base::MakeUnique<IOSChromePhysicalWebDataSource>();
diff --git a/ios/chrome/common/physical_web/ios_chrome_physical_web_data_source.h b/ios/chrome/browser/physical_web/ios_chrome_physical_web_data_source.h similarity index 90% rename from ios/chrome/common/physical_web/ios_chrome_physical_web_data_source.h rename to ios/chrome/browser/physical_web/ios_chrome_physical_web_data_source.h index a21a2a6..e5278f5b 100644 --- a/ios/chrome/common/physical_web/ios_chrome_physical_web_data_source.h +++ b/ios/chrome/browser/physical_web/ios_chrome_physical_web_data_source.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef IOS_CHROME_COMMON_PHYSICAL_WEB_IOS_CHROME_PHYSICAL_WEB_DATA_SOURCE_H_ -#define IOS_CHROME_COMMON_PHYSICAL_WEB_IOS_CHROME_PHYSICAL_WEB_DATA_SOURCE_H_ +#ifndef IOS_CHROME_BROWSER_PHYSICAL_WEB_IOS_CHROME_PHYSICAL_WEB_DATA_SOURCE_H_ +#define IOS_CHROME_BROWSER_PHYSICAL_WEB_IOS_CHROME_PHYSICAL_WEB_DATA_SOURCE_H_ #include "base/macros.h" #import "base/mac/scoped_nsobject.h"
diff --git a/ios/chrome/common/physical_web/ios_chrome_physical_web_data_source.mm b/ios/chrome/browser/physical_web/ios_chrome_physical_web_data_source.mm similarity index 94% rename from ios/chrome/common/physical_web/ios_chrome_physical_web_data_source.mm rename to ios/chrome/browser/physical_web/ios_chrome_physical_web_data_source.mm index 12edafa..80c0744 100644 --- a/ios/chrome/common/physical_web/ios_chrome_physical_web_data_source.mm +++ b/ios/chrome/browser/physical_web/ios_chrome_physical_web_data_source.mm
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#import "ios/chrome/common/physical_web/ios_chrome_physical_web_data_source.h" +#import "ios/chrome/browser/physical_web/ios_chrome_physical_web_data_source.h" #include "base/memory/ptr_util.h" #include "base/values.h"
diff --git a/ios/chrome/browser/reading_list/reading_list_download_service.cc b/ios/chrome/browser/reading_list/reading_list_download_service.cc index c6a2a0b..fcd3851 100644 --- a/ios/chrome/browser/reading_list/reading_list_download_service.cc +++ b/ios/chrome/browser/reading_list/reading_list_download_service.cc
@@ -177,13 +177,13 @@ void ReadingListDownloadService::OnDownloadEnd( const GURL& url, URLDownloader::SuccessState success, - const GURL& distilled_url, + const base::FilePath& distilled_path, const std::string& title) { DCHECK(reading_list_model_->loaded()); if ((success == URLDownloader::DOWNLOAD_SUCCESS || success == URLDownloader::DOWNLOAD_EXISTS) && - distilled_url.is_valid()) { - reading_list_model_->SetEntryDistilledURL(url, distilled_url); + !distilled_path.empty()) { + reading_list_model_->SetEntryDistilledPath(url, distilled_path); } else if (success == URLDownloader::ERROR_RETRY) { reading_list_model_->SetEntryDistilledState(url,
diff --git a/ios/chrome/browser/reading_list/reading_list_download_service.h b/ios/chrome/browser/reading_list/reading_list_download_service.h index bbe0810..f8bc2882 100644 --- a/ios/chrome/browser/reading_list/reading_list_download_service.h +++ b/ios/chrome/browser/reading_list/reading_list_download_service.h
@@ -80,7 +80,7 @@ // Callback for entry download. void OnDownloadEnd(const GURL& url, URLDownloader::SuccessState success, - const GURL& distilled_url, + const base::FilePath& distilled_path, const std::string& title); // Callback for entry deletion.
diff --git a/ios/chrome/browser/reading_list/reading_list_entry.cc b/ios/chrome/browser/reading_list/reading_list_entry.cc index bea3f83..5ff3dbc 100644 --- a/ios/chrome/browser/reading_list/reading_list_entry.cc +++ b/ios/chrome/browser/reading_list/reading_list_entry.cc
@@ -6,6 +6,12 @@ #include "base/memory/ptr_util.h" +namespace { +// URL used to open offline pages. +// This variable will be moved to chrome_url_constants. +const char kChromeUIOfflineURL[] = "chrome://offline/"; +} + // The backoff time is the following: 10min, 10min, 1h, 2h, 2h..., starting // after the first failure. const net::BackoffEntry::Policy ReadingListEntry::kBackoffPolicy = { @@ -55,7 +61,7 @@ ReadingListEntry::ReadingListEntry(ReadingListEntry&& entry) : url_(std::move(entry.url_)), title_(std::move(entry.title_)), - distilled_url_(std::move(entry.distilled_url_)), + distilled_path_(std::move(entry.distilled_path_)), distilled_state_(std::move(entry.distilled_state_)), backoff_(std::move(entry.backoff_)), failed_download_counter_(std::move(entry.failed_download_counter_)) {} @@ -74,8 +80,15 @@ return distilled_state_; } -const GURL& ReadingListEntry::DistilledURL() const { - return distilled_url_; +const base::FilePath& ReadingListEntry::DistilledPath() const { + return distilled_path_; +} + +const GURL ReadingListEntry::DistilledURL() const { + if (distilled_path_.empty()) { + return GURL(); + } + return GURL(kChromeUIOfflineURL + distilled_path_.value()); } base::TimeDelta ReadingListEntry::TimeUntilNextTry() const { @@ -89,7 +102,7 @@ ReadingListEntry& ReadingListEntry::operator=(ReadingListEntry&& other) { url_ = std::move(other.url_); title_ = std::move(other.title_); - distilled_url_ = std::move(other.distilled_url_); + distilled_path_ = std::move(other.distilled_path_); distilled_state_ = std::move(other.distilled_state_); backoff_ = std::move(other.backoff_); failed_download_counter_ = std::move(other.failed_download_counter_); @@ -104,16 +117,16 @@ title_ = title; } -void ReadingListEntry::SetDistilledURL(const GURL& url) { - DCHECK(url.is_valid()); - distilled_url_ = url; +void ReadingListEntry::SetDistilledPath(const base::FilePath& path) { + DCHECK(!path.empty()); + distilled_path_ = path; distilled_state_ = PROCESSED; backoff_->Reset(); failed_download_counter_ = 0; } void ReadingListEntry::SetDistilledState(DistillationState distilled_state) { - DCHECK(distilled_state != PROCESSED); // use SetDistilledURL instead. + DCHECK(distilled_state != PROCESSED); // use SetDistilledPath instead. DCHECK(distilled_state != WAITING); // Increase time until next retry exponentially if the state change from a // non-error state to an error state. @@ -124,5 +137,5 @@ } distilled_state_ = distilled_state; - distilled_url_ = GURL(); + distilled_path_ = base::FilePath(); }
diff --git a/ios/chrome/browser/reading_list/reading_list_entry.h b/ios/chrome/browser/reading_list/reading_list_entry.h index 3ed4903e..c99c8496 100644 --- a/ios/chrome/browser/reading_list/reading_list_entry.h +++ b/ios/chrome/browser/reading_list/reading_list_entry.h
@@ -7,6 +7,7 @@ #include <string> +#include "base/files/file_path.h" #include "base/macros.h" #include "net/base/backoff_entry.h" #include "url/gurl.h" @@ -37,9 +38,11 @@ const std::string& Title() const; // What state this entry is in. DistillationState DistilledState() const; - // The local file URL for the distilled version of the page. This should only + // The local file path for the distilled version of the page. This should only // be called if the state is "PROCESSED". - const GURL& DistilledURL() const; + const base::FilePath& DistilledPath() const; + // The URL to the distilled file. + const GURL DistilledURL() const; // The time before the next try. This is automatically increased when the // state is set to WILL_RETRY or ERROR from a non-error state. base::TimeDelta TimeUntilNextTry() const; @@ -55,14 +58,14 @@ void SetTitle(const std::string& title); // Sets the distilled URL and switch the state to PROCESSED and reset the time // until the next try. - void SetDistilledURL(const GURL& url); + void SetDistilledPath(const base::FilePath& path); // Sets the state to one of PROCESSING, WILL_RETRY or ERROR. void SetDistilledState(DistillationState distilled_state); private: GURL url_; std::string title_; - GURL distilled_url_; + base::FilePath distilled_path_; DistillationState distilled_state_; std::unique_ptr<net::BackoffEntry> backoff_; int failed_download_counter_;
diff --git a/ios/chrome/browser/reading_list/reading_list_entry_unittest.cc b/ios/chrome/browser/reading_list/reading_list_entry_unittest.cc index 73b48bc..efdb0bc3 100644 --- a/ios/chrome/browser/reading_list/reading_list_entry_unittest.cc +++ b/ios/chrome/browser/reading_list/reading_list_entry_unittest.cc
@@ -42,14 +42,15 @@ EXPECT_EQ(e3.Title(), e2.Title()); } -TEST(ReadingListEntry, DistilledURL) { +TEST(ReadingListEntry, DistilledPathAndURL) { ReadingListEntry e(GURL("http://example.com"), "bar"); EXPECT_FALSE(e.DistilledURL().is_valid()); - const GURL distilled_url("http://distilled.example.com"); - e.SetDistilledURL(distilled_url); - EXPECT_EQ(distilled_url, e.DistilledURL()); + const base::FilePath distilled_path("distilled/page.html"); + e.SetDistilledPath(distilled_path); + EXPECT_EQ(distilled_path, e.DistilledPath()); + EXPECT_EQ(GURL("chrome://offline/distilled/page.html"), e.DistilledURL()); } TEST(ReadingListEntry, DistilledState) { @@ -60,8 +61,8 @@ e.SetDistilledState(ReadingListEntry::ERROR); EXPECT_EQ(ReadingListEntry::ERROR, e.DistilledState()); - const GURL distilled_url("http://distilled.example.com"); - e.SetDistilledURL(distilled_url); + const base::FilePath distilled_path("distilled/page.html"); + e.SetDistilledPath(distilled_path); EXPECT_EQ(ReadingListEntry::PROCESSED, e.DistilledState()); } @@ -153,7 +154,7 @@ kFirstBackoff * fuzzing); // Action. - e.SetDistilledURL(GURL("http://example.com")); + e.SetDistilledPath(base::FilePath("distilled/page.html")); // Test. EXPECT_EQ(0, e.TimeUntilNextTry().InSeconds());
diff --git a/ios/chrome/browser/reading_list/reading_list_model.h b/ios/chrome/browser/reading_list/reading_list_model.h index f84f861..28a8fe7 100644 --- a/ios/chrome/browser/reading_list/reading_list_model.h +++ b/ios/chrome/browser/reading_list/reading_list_model.h
@@ -92,8 +92,8 @@ // Methods to mutate an entry. Will locate the relevant entry by URL. Does // nothing if the entry is not found. virtual void SetEntryTitle(const GURL& url, const std::string& title) = 0; - virtual void SetEntryDistilledURL(const GURL& url, - const GURL& distilled_url) = 0; + virtual void SetEntryDistilledPath(const GURL& url, + const base::FilePath& distilled_path) = 0; virtual void SetEntryDistilledState( const GURL& url, ReadingListEntry::DistillationState state) = 0;
diff --git a/ios/chrome/browser/reading_list/reading_list_model_bridge_observer.mm b/ios/chrome/browser/reading_list/reading_list_model_bridge_observer.mm index c37a1e09d..dfdbea21 100644 --- a/ios/chrome/browser/reading_list/reading_list_model_bridge_observer.mm +++ b/ios/chrome/browser/reading_list/reading_list_model_bridge_observer.mm
@@ -105,7 +105,7 @@ const ReadingListModel* model, size_t index) { if ([observer_ respondsToSelector:@selector(readingListModel: - willRemoveUnreadEntryAtIndex:)]) { + willUpdateUnreadEntryAtIndex:)]) { [observer_ readingListModel:model willUpdateUnreadEntryAtIndex:index]; } } @@ -114,7 +114,7 @@ const ReadingListModel* model, size_t index) { if ([observer_ respondsToSelector:@selector(readingListModel: - willRemoveReadEntryAtIndex:)]) { + willUpdateReadEntryAtIndex:)]) { [observer_ readingListModel:model willUpdateReadEntryAtIndex:index]; } }
diff --git a/ios/chrome/browser/reading_list/reading_list_model_impl.cc b/ios/chrome/browser/reading_list/reading_list_model_impl.cc index adb0c8c6..e67ea6e 100644 --- a/ios/chrome/browser/reading_list/reading_list_model_impl.cc +++ b/ios/chrome/browser/reading_list/reading_list_model_impl.cc
@@ -234,8 +234,9 @@ } } -void ReadingListModelImpl::SetEntryDistilledURL(const GURL& url, - const GURL& distilled_url) { +void ReadingListModelImpl::SetEntryDistilledPath( + const GURL& url, + const base::FilePath& distilled_path) { DCHECK(loaded()); const ReadingListEntry entry(url, std::string()); @@ -245,7 +246,7 @@ observer.ReadingListWillUpdateUnreadEntry( this, std::distance(unread_.begin(), result)); } - result->SetDistilledURL(distilled_url); + result->SetDistilledPath(distilled_path); if (storage_layer_ && !IsPerformingBatchUpdates()) storage_layer_->SavePersistentUnreadList(unread_); for (auto& observer : observers_) @@ -259,7 +260,7 @@ observer.ReadingListWillUpdateReadEntry( this, std::distance(read_.begin(), result)); } - result->SetDistilledURL(distilled_url); + result->SetDistilledPath(distilled_path); if (storage_layer_ && !IsPerformingBatchUpdates()) storage_layer_->SavePersistentReadList(read_); for (auto& observer : observers_)
diff --git a/ios/chrome/browser/reading_list/reading_list_model_impl.h b/ios/chrome/browser/reading_list/reading_list_model_impl.h index a558d9e..0660fb9a 100644 --- a/ios/chrome/browser/reading_list/reading_list_model_impl.h +++ b/ios/chrome/browser/reading_list/reading_list_model_impl.h
@@ -58,8 +58,8 @@ void MarkUnreadByURL(const GURL& url) override; void SetEntryTitle(const GURL& url, const std::string& title) override; - void SetEntryDistilledURL(const GURL& url, - const GURL& distilled_url) override; + void SetEntryDistilledPath(const GURL& url, + const base::FilePath& distilled_path) override; void SetEntryDistilledState( const GURL& url, ReadingListEntry::DistillationState state) override;
diff --git a/ios/chrome/browser/reading_list/reading_list_model_storage_defaults.mm b/ios/chrome/browser/reading_list/reading_list_model_storage_defaults.mm index 993b5d5d..9b68342 100644 --- a/ios/chrome/browser/reading_list/reading_list_model_storage_defaults.mm +++ b/ios/chrome/browser/reading_list/reading_list_model_storage_defaults.mm
@@ -17,7 +17,7 @@ NSString* const kReadingListEntryTitleKey = @"title"; NSString* const kReadingListEntryURLKey = @"URL"; NSString* const kReadingListEntryStateKey = @"state"; -NSString* const kReadingListEntryDistilledURLKey = @"distilledURL"; +NSString* const kReadingListEntryDistilledPathKey = @"distilledPath"; ReadingListEntry DecodeReadingListEntry(NSData* data) { NSError* error = nil; @@ -36,12 +36,13 @@ switch (state) { case ReadingListEntry::PROCESSED: { - NSURL* distilled_url = base::mac::ObjCCastStrict<NSURL>( - [dictionary objectForKey:kReadingListEntryDistilledURLKey]); - DCHECK(distilled_url); - GURL distilled_gurl(net::GURLWithNSURL(distilled_url)); - DCHECK(distilled_gurl.is_valid()); - entry.SetDistilledURL(distilled_gurl); + NSString* distilled_path = base::mac::ObjCCastStrict<NSString>( + [dictionary objectForKey:kReadingListEntryDistilledPathKey]); + if (distilled_path) { + base::FilePath path = + base::FilePath(base::SysNSStringToUTF8(distilled_path)); + entry.SetDistilledPath(path); + } break; } case ReadingListEntry::PROCESSING: @@ -65,12 +66,12 @@ [NSNumber numberWithInt:entry.DistilledState()] }]; - const GURL distilled_gurl(entry.DistilledURL()); - if (distilled_gurl.is_valid()) { - NSURL* distilled_url = net::NSURLWithGURL(distilled_gurl); - if (distilled_url) - [dictionary setObject:distilled_url - forKey:kReadingListEntryDistilledURLKey]; + const base::FilePath path(entry.DistilledPath()); + if (!path.empty()) { + NSString* distilled_path = base::SysUTF8ToNSString(path.value()); + if (distilled_path) + [dictionary setObject:distilled_path + forKey:kReadingListEntryDistilledPathKey]; } return [NSKeyedArchiver archivedDataWithRootObject:dictionary]; }
diff --git a/ios/chrome/browser/reading_list/reading_list_model_storage_unittest.mm b/ios/chrome/browser/reading_list/reading_list_model_storage_unittest.mm index da7bbf3..793ec4ae 100644 --- a/ios/chrome/browser/reading_list/reading_list_model_storage_unittest.mm +++ b/ios/chrome/browser/reading_list/reading_list_model_storage_unittest.mm
@@ -76,7 +76,7 @@ ReadingListEntry(GURL("http://unread.example.com"), "unread title")); { ReadingListModelStorageDefaults storage(defaults); - entries[0].SetDistilledURL(GURL("http://distilled.example.com")); + entries[0].SetDistilledPath(base::FilePath("distilled/page.html")); storage.SavePersistentUnreadList(entries); } @@ -85,7 +85,9 @@ storage.LoadPersistentUnreadList()); EXPECT_EQ(1ul, restored_entries.size()); EXPECT_EQ(GURL("http://unread.example.com"), restored_entries[0].URL()); - EXPECT_EQ(GURL("http://distilled.example.com"), + EXPECT_EQ(base::FilePath("distilled/page.html"), + restored_entries[0].DistilledPath()); + EXPECT_EQ(GURL("chrome://offline/distilled/page.html"), restored_entries[0].DistilledURL()); EXPECT_EQ("unread title", restored_entries[0].Title()); }
diff --git a/ios/chrome/browser/reading_list/reading_list_model_unittest.cc b/ios/chrome/browser/reading_list/reading_list_model_unittest.cc index 1e97064e..f1cfd4a 100644 --- a/ios/chrome/browser/reading_list/reading_list_model_unittest.cc +++ b/ios/chrome/browser/reading_list/reading_list_model_unittest.cc
@@ -272,15 +272,15 @@ EXPECT_EQ(ReadingListEntry::PROCESSING, entry.DistilledState()); } -TEST_F(ReadingListModelTest, UpdateDistilledURL) { +TEST_F(ReadingListModelTest, UpdateDistilledPath) { const GURL gurl("http://example.com"); const ReadingListEntry& entry = model_->AddEntry(gurl, "sample"); ClearCounts(); - model_->SetEntryDistilledURL(gurl, gurl); + model_->SetEntryDistilledPath(gurl, base::FilePath("distilled/page.html")); AssertObserverCount(0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1); EXPECT_EQ(ReadingListEntry::PROCESSED, entry.DistilledState()); - EXPECT_EQ(gurl, entry.DistilledURL()); + EXPECT_EQ(base::FilePath("distilled/page.html"), entry.DistilledPath()); } TEST_F(ReadingListModelTest, UpdateReadEntryTitle) { @@ -307,17 +307,17 @@ EXPECT_EQ(ReadingListEntry::PROCESSING, entry.DistilledState()); } -TEST_F(ReadingListModelTest, UpdateReadDistilledURL) { +TEST_F(ReadingListModelTest, UpdateReadDistilledPath) { const GURL gurl("http://example.com"); model_->AddEntry(gurl, "sample"); model_->MarkReadByURL(gurl); const ReadingListEntry& entry = model_->GetReadEntryAtIndex(0); ClearCounts(); - model_->SetEntryDistilledURL(gurl, gurl); + model_->SetEntryDistilledPath(gurl, base::FilePath("distilled/page.html")); AssertObserverCount(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1); EXPECT_EQ(ReadingListEntry::PROCESSED, entry.DistilledState()); - EXPECT_EQ(gurl, entry.DistilledURL()); + EXPECT_EQ(GURL("chrome://offline/distilled/page.html"), entry.DistilledURL()); } // Tests that the callback is called when the entry is unread.
diff --git a/ios/chrome/browser/reading_list/url_downloader.cc b/ios/chrome/browser/reading_list/url_downloader.cc index 02a68d6d..6ccfe3e 100644 --- a/ios/chrome/browser/reading_list/url_downloader.cc +++ b/ios/chrome/browser/reading_list/url_downloader.cc
@@ -46,7 +46,7 @@ base::Callback<void(bool)> callback) { task_tracker_.PostTaskAndReplyWithResult( web::WebThread::GetTaskRunnerForThread(web::WebThread::FILE).get(), - FROM_HERE, base::Bind(&base::PathExists, OfflineURLPagePath(url)), + FROM_HERE, base::Bind(&base::PathExists, OfflinePageAbsolutePath(url)), callback); } @@ -75,11 +75,8 @@ auto post_delete = base::Bind( [](URLDownloader* _this, const GURL& url, const std::string& title, SuccessState success) { - _this->download_completion_.Run( - url, success, - GURL(std::string(url::kFileScheme) + url::kStandardSchemeSeparator + - _this->OfflineURLPagePath(url).value()), - title); + _this->download_completion_.Run(url, success, + _this->OfflinePagePath(url), title); _this->distiller_.reset(); _this->working_ = false; _this->HandleNextTask(); @@ -94,7 +91,7 @@ [](const base::FilePath& offline_directory_path) { base::DeleteFile(offline_directory_path, true); }, - OfflineURLDirectoryPath(url)), + OfflineURLDirectoryAbsolutePath(url)), post_delete); } else { post_delete.Run(); @@ -121,8 +118,8 @@ if (task.first == DELETE) { task_tracker_.PostTaskAndReplyWithResult( web::WebThread::GetTaskRunnerForThread(web::WebThread::FILE).get(), - FROM_HERE, - base::Bind(&base::DeleteFile, OfflineURLDirectoryPath(url), true), + FROM_HERE, base::Bind(&base::DeleteFile, + OfflineURLDirectoryAbsolutePath(url), true), base::Bind(&URLDownloader::DeleteCompletionHandler, base::Unretained(this), url)); } else if (task.first == DOWNLOAD) { @@ -178,21 +175,29 @@ return ERROR_PERMANENT; } -base::FilePath URLDownloader::OfflineDirectoryPath() { +base::FilePath URLDownloader::OfflineRootDirectoryPath() { return base_directory_.Append(FILE_PATH_LITERAL(kOfflineDirectory)); } -base::FilePath URLDownloader::OfflineURLDirectoryPath(const GURL& url) { - std::string hash = base::MD5String(url.spec()); - return OfflineDirectoryPath().AppendASCII(hash); +std::string URLDownloader::OfflineURLDirectoryID(const GURL& url) { + return base::MD5String(url.spec()); } -base::FilePath URLDownloader::OfflineURLPagePath(const GURL& url) { - return OfflineURLDirectoryPath(url).Append(FILE_PATH_LITERAL("page.html")); +base::FilePath URLDownloader::OfflinePagePath(const GURL& url) { + base::FilePath directory(OfflineURLDirectoryID(url)); + return directory.Append(FILE_PATH_LITERAL("page.html")); +} + +base::FilePath URLDownloader::OfflineURLDirectoryAbsolutePath(const GURL& url) { + return OfflineRootDirectoryPath().Append(OfflineURLDirectoryID(url)); +} + +base::FilePath URLDownloader::OfflinePageAbsolutePath(const GURL& url) { + return OfflineRootDirectoryPath().Append(OfflinePagePath(url)); } bool URLDownloader::CreateOfflineURLDirectory(const GURL& url) { - base::FilePath path = OfflineURLDirectoryPath(url); + base::FilePath path = OfflineURLDirectoryAbsolutePath(url); if (!DirectoryExists(path)) { return CreateDirectoryAndGetError(path, nil); } @@ -205,7 +210,7 @@ std::string* image_name) { std::string image_hash = base::MD5String(image_url.spec()); *image_name = image_hash; - base::FilePath path = OfflineURLDirectoryPath(url).Append(image_hash); + base::FilePath path = OfflineURLDirectoryAbsolutePath(url).Append(image_hash); if (!base::PathExists(path)) { return base::WriteFile(path, data.c_str(), data.length()) > 0; } @@ -239,6 +244,6 @@ if (html.empty()) { return false; } - base::FilePath path = OfflineURLPagePath(url); + base::FilePath path = OfflinePageAbsolutePath(url); return base::WriteFile(path, html.c_str(), html.length()) > 0; }
diff --git a/ios/chrome/browser/reading_list/url_downloader.h b/ios/chrome/browser/reading_list/url_downloader.h index 14df230..b378c76 100644 --- a/ios/chrome/browser/reading_list/url_downloader.h +++ b/ios/chrome/browser/reading_list/url_downloader.h
@@ -45,10 +45,14 @@ // A download completion callback that takes, in order, the GURL that was // downloaded, a SuccessState indicating the outcome of the download, the - // offline GURL for the download, and the title of the url, and returns void. - // The offline GURL and title should not be used in case of failure. - using DownloadCompletion = base::Callback< - void(const GURL&, SuccessState, const GURL&, const std::string&)>; + // path to the downloaded page (relative to |OfflineRootDirectoryPath()|, and + // the title of the url, and returns void. + // The path to downloaded file and title should not be used in case of + // failure. + using DownloadCompletion = base::Callback<void(const GURL&, + SuccessState, + const base::FilePath&, + const std::string&)>; // Create a URL downloader with completion callbacks for downloads and // deletions. The completion callbacks will be called with the original url @@ -83,16 +87,24 @@ // Callback for completed (or failed) deletion, handles calling // deleteCompletion and starting the next task. void DeleteCompletionHandler(const GURL& url, bool success); - // The path of the directory where offline URLs are saved. - base::FilePath OfflineDirectoryPath(); - // The path of the directory where a specific URL is saved offline. Contains - // the page and supporting files (images). - base::FilePath OfflineURLDirectoryPath(const GURL& url); - // The path of the offline webpage for the URL. The file may not exist. - base::FilePath OfflineURLPagePath(const GURL& url); + // The absolute path of the directory where offline URLs are saved. + base::FilePath OfflineRootDirectoryPath(); + + // The absolute path of the directory where a specific URL is saved offline. + // Contains the page and supporting files (images). + base::FilePath OfflineURLDirectoryAbsolutePath(const GURL& url); + // The absolute path of the offline webpage for the URL. The file may not + // exist. + base::FilePath OfflinePageAbsolutePath(const GURL& url); + // The relative path to the distilled page. The result is relative to + // |OfflineRootDirectoryPath()|. + base::FilePath OfflinePagePath(const GURL& url); // Creates the offline directory for |url|. Returns true if successful or if // the directory already exists. bool CreateOfflineURLDirectory(const GURL& url); + // The name of the directory containing offline data for |url|. + std::string OfflineURLDirectoryID(const GURL& url); + // Saves the |data| for image at |imageURL| to disk, for main URL |url|; // puts path of saved file in |path| and returns whether save was successful. bool SaveImage(const GURL& url,
diff --git a/ios/chrome/browser/reading_list/url_downloader_unittest.cc b/ios/chrome/browser/reading_list/url_downloader_unittest.cc index f71220b..e5df3ed 100644 --- a/ios/chrome/browser/reading_list/url_downloader_unittest.cc +++ b/ios/chrome/browser/reading_list/url_downloader_unittest.cc
@@ -47,7 +47,7 @@ base::Unretained(this))) {} void RemoveOfflineFilesDirectory() { - base::DeleteFile(OfflineDirectoryPath(), true); + base::DeleteFile(OfflineRootDirectoryPath(), true); } void ClearCompletionTrackers() { @@ -56,7 +56,7 @@ } bool CheckExistenceOfOfflineURLPagePath(const GURL& url) { - return base::PathExists(OfflineURLPagePath(url)); + return base::PathExists(OfflinePageAbsolutePath(url)); } void FakeWorking() { working_ = true; } @@ -82,7 +82,7 @@ void OnEndDownload(const GURL& url, SuccessState success, - const GURL& distilledURL, + const base::FilePath& distilled_path, const std::string& title) { downloaded_files_.push_back(url); }
diff --git a/ios/chrome/common/physical_web/BUILD.gn b/ios/chrome/common/physical_web/BUILD.gn index f56f06b2..0afdd5b 100644 --- a/ios/chrome/common/physical_web/BUILD.gn +++ b/ios/chrome/common/physical_web/BUILD.gn
@@ -4,8 +4,6 @@ source_set("physical_web") { sources = [ - "ios_chrome_physical_web_data_source.h", - "ios_chrome_physical_web_data_source.mm", "physical_web_device.h", "physical_web_device.mm", "physical_web_request.h",
diff --git a/ipc/BUILD.gn b/ipc/BUILD.gn index cd1f365..fa3f81c8 100644 --- a/ipc/BUILD.gn +++ b/ipc/BUILD.gn
@@ -9,8 +9,6 @@ component("ipc") { sources = [ - "brokerable_attachment.cc", - "brokerable_attachment.h", "export_template.h", "handle_attachment_win.cc", "handle_attachment_win.h",
diff --git a/ipc/brokerable_attachment.cc b/ipc/brokerable_attachment.cc deleted file mode 100644 index a0746e1..0000000 --- a/ipc/brokerable_attachment.cc +++ /dev/null
@@ -1,34 +0,0 @@ -// Copyright 2015 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 "ipc/brokerable_attachment.h" - -#include <stddef.h> - -#include "build/build_config.h" - -namespace IPC { - -// BrokerableAttachment::BrokerableAttachment ---------------------------------- - -BrokerableAttachment::BrokerableAttachment() = default; - -BrokerableAttachment::~BrokerableAttachment() = default; - -bool BrokerableAttachment::NeedsBrokering() const { - return GetBrokerableType() == PLACEHOLDER; -} - -BrokerableAttachment::Type BrokerableAttachment::GetType() const { - return TYPE_BROKERABLE_ATTACHMENT; -} - -#if defined(OS_POSIX) -base::PlatformFile BrokerableAttachment::TakePlatformFile() { - NOTREACHED(); - return base::PlatformFile(); -} -#endif // OS_POSIX - -} // namespace IPC
diff --git a/ipc/brokerable_attachment.h b/ipc/brokerable_attachment.h deleted file mode 100644 index a926d5b..0000000 --- a/ipc/brokerable_attachment.h +++ /dev/null
@@ -1,54 +0,0 @@ -// Copyright 2015 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 IPC_BROKERABLE_ATTACHMENT_H_ -#define IPC_BROKERABLE_ATTACHMENT_H_ - -#include <stddef.h> -#include <stdint.h> - -#include <algorithm> - -#include "base/macros.h" -#include "build/build_config.h" -#include "ipc/ipc_export.h" -#include "ipc/ipc_message_attachment.h" - -namespace IPC { - -// This subclass of MessageAttachment requires an AttachmentBroker to be -// attached to a Chrome IPC message. -class IPC_EXPORT BrokerableAttachment : public MessageAttachment { - public: - enum BrokerableType { - PLACEHOLDER, - WIN_HANDLE, - MACH_PORT, - }; - - // Whether the attachment still needs information from the broker before it - // can be used. - bool NeedsBrokering() const; - - // Returns TYPE_BROKERABLE_ATTACHMENT - Type GetType() const override; - - virtual BrokerableType GetBrokerableType() const = 0; - -// MessageAttachment override. -#if defined(OS_POSIX) - base::PlatformFile TakePlatformFile() override; -#endif // OS_POSIX - - protected: - BrokerableAttachment(); - ~BrokerableAttachment() override; - - private: - DISALLOW_COPY_AND_ASSIGN(BrokerableAttachment); -}; - -} // namespace IPC - -#endif // IPC_BROKERABLE_ATTACHMENT_H_
diff --git a/ipc/handle_attachment_win.cc b/ipc/handle_attachment_win.cc index 53d589bc..9249a5a 100644 --- a/ipc/handle_attachment_win.cc +++ b/ipc/handle_attachment_win.cc
@@ -28,24 +28,13 @@ FromWire from_wire) : handle_(handle), permissions_(HandleWin::INVALID), owns_handle_(true) {} -HandleAttachmentWin::HandleAttachmentWin(const WireFormat& wire_format) - : handle_(LongToHandle(wire_format.handle)), - permissions_(wire_format.permissions), - owns_handle_(true) {} - HandleAttachmentWin::~HandleAttachmentWin() { if (handle_ != INVALID_HANDLE_VALUE && owns_handle_) ::CloseHandle(handle_); } -HandleAttachmentWin::BrokerableType HandleAttachmentWin::GetBrokerableType() - const { - return WIN_HANDLE; -} - -HandleAttachmentWin::WireFormat HandleAttachmentWin::GetWireFormat( - const base::ProcessId& destination) const { - return WireFormat(HandleToLong(handle_), destination, permissions_); +MessageAttachment::Type HandleAttachmentWin::GetType() const { + return Type::WIN_HANDLE; } } // namespace internal
diff --git a/ipc/handle_attachment_win.h b/ipc/handle_attachment_win.h index cfe56a36b..ef3b8965 100644 --- a/ipc/handle_attachment_win.h +++ b/ipc/handle_attachment_win.h
@@ -8,48 +8,16 @@ #include <stdint.h> #include "base/process/process_handle.h" -#include "ipc/brokerable_attachment.h" #include "ipc/handle_win.h" #include "ipc/ipc_export.h" +#include "ipc/ipc_message_attachment.h" namespace IPC { namespace internal { // This class represents a Windows HANDLE attached to a Chrome IPC message. -class IPC_EXPORT HandleAttachmentWin : public BrokerableAttachment { +class IPC_EXPORT HandleAttachmentWin : public MessageAttachment { public: - // The wire format for this handle. - struct IPC_EXPORT WireFormat { - // IPC translation requires that classes passed through IPC have a default - // constructor. - WireFormat() - : handle(0), - destination_process(0), - permissions(HandleWin::INVALID) {} - - WireFormat(int32_t handle, - const base::ProcessId& destination_process, - HandleWin::Permissions permissions) - : handle(handle), - destination_process(destination_process), - permissions(permissions) {} - - // The HANDLE that is intended for duplication, or the HANDLE that has been - // duplicated, depending on context. - // The type is int32_t instead of HANDLE because HANDLE gets typedefed to - // void*, whose size varies between 32 and 64-bit processes. Using a - // int32_t means that 64-bit processes will need to perform both up-casting - // and down-casting. This is performed using the appropriate Windows APIs. - // A value of 0 is equivalent to an invalid handle. - int32_t handle; - - // The id of the destination process that the handle is duplicated into. - base::ProcessId destination_process; - - // The permissions to use when duplicating the handle. - HandleWin::Permissions permissions; - }; - // This constructor makes a copy of |handle| and takes ownership of the // result. Should only be called by the sender of a Chrome IPC message. HandleAttachmentWin(const HANDLE& handle, HandleWin::Permissions permissions); @@ -61,14 +29,7 @@ // receiver of a Chrome IPC message. HandleAttachmentWin(const HANDLE& handle, FromWire from_wire); - // This constructor takes ownership of |wire_format.handle| without making a - // copy. Should only be called by the receiver of a Chrome IPC message. - explicit HandleAttachmentWin(const WireFormat& wire_format); - - BrokerableType GetBrokerableType() const override; - - // Returns the wire format of this attachment. - WireFormat GetWireFormat(const base::ProcessId& destination) const; + Type GetType() const override; HANDLE get_handle() const { return handle_; }
diff --git a/ipc/handle_win.cc b/ipc/handle_win.cc index 60fa54c7..c8511e2 100644 --- a/ipc/handle_win.cc +++ b/ipc/handle_win.cc
@@ -38,16 +38,10 @@ return false; MessageAttachment* attachment = static_cast<MessageAttachment*>(base_attachment.get()); - if (attachment->GetType() != MessageAttachment::TYPE_BROKERABLE_ATTACHMENT) + if (attachment->GetType() != MessageAttachment::Type::WIN_HANDLE) return false; - BrokerableAttachment* brokerable_attachment = - static_cast<BrokerableAttachment*>(attachment); - if (brokerable_attachment->GetBrokerableType() != - BrokerableAttachment::WIN_HANDLE) { - return false; - } IPC::internal::HandleAttachmentWin* handle_attachment = - static_cast<IPC::internal::HandleAttachmentWin*>(brokerable_attachment); + static_cast<IPC::internal::HandleAttachmentWin*>(attachment); r->set_handle(handle_attachment->get_handle()); handle_attachment->reset_handle_ownership(); return true;
diff --git a/ipc/ipc_channel_factory.cc b/ipc/ipc_channel_factory.cc index 274989f0..775ac33 100644 --- a/ipc/ipc_channel_factory.cc +++ b/ipc/ipc_channel_factory.cc
@@ -19,8 +19,6 @@ const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner) : handle_(handle), mode_(mode), ipc_task_runner_(ipc_task_runner) {} - std::string GetName() const override { return ""; } - std::unique_ptr<Channel> BuildChannel(Listener* listener) override { #if defined(OS_NACL_SFI) return Channel::Create(handle_, mode_, listener);
diff --git a/ipc/ipc_channel_factory.h b/ipc/ipc_channel_factory.h index 8fb18b3..688a366 100644 --- a/ipc/ipc_channel_factory.h +++ b/ipc/ipc_channel_factory.h
@@ -28,7 +28,6 @@ const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner); virtual ~ChannelFactory() { } - virtual std::string GetName() const = 0; virtual std::unique_ptr<Channel> BuildChannel(Listener* listener) = 0; virtual scoped_refptr<base::SingleThreadTaskRunner> GetIPCTaskRunner() = 0; };
diff --git a/ipc/ipc_channel_mojo.cc b/ipc/ipc_channel_mojo.cc index e71baff8..4189b9c0 100644 --- a/ipc/ipc_channel_mojo.cc +++ b/ipc/ipc_channel_mojo.cc
@@ -54,8 +54,6 @@ mode_(mode), ipc_task_runner_(ipc_task_runner) {} - std::string GetName() const override { return ""; } - std::unique_ptr<Channel> BuildChannel(Listener* listener) override { return ChannelMojo::Create( std::move(handle_), mode_, listener, ipc_task_runner_); @@ -126,14 +124,14 @@ MojoResult WrapAttachmentImpl(MessageAttachment* attachment, mojom::SerializedHandlePtr* serialized) { - if (attachment->GetType() == MessageAttachment::TYPE_MOJO_HANDLE) { + if (attachment->GetType() == MessageAttachment::Type::MOJO_HANDLE) { *serialized = CreateSerializedHandle( static_cast<internal::MojoHandleAttachment&>(*attachment).TakeHandle(), mojom::SerializedHandle::Type::MOJO_HANDLE); return MOJO_RESULT_OK; } #if defined(OS_POSIX) - if (attachment->GetType() == MessageAttachment::TYPE_PLATFORM_FILE) { + if (attachment->GetType() == MessageAttachment::Type::PLATFORM_FILE) { // We dup() the handles in IPC::Message to transmit. // IPC::MessageAttachmentSet has intricate lifecycle semantics // of FDs, so just to dup()-and-own them is the safest option. @@ -150,10 +148,7 @@ } #endif #if defined(OS_MACOSX) - DCHECK_EQ(attachment->GetType(), - MessageAttachment::TYPE_BROKERABLE_ATTACHMENT); - DCHECK_EQ(static_cast<BrokerableAttachment&>(*attachment).GetBrokerableType(), - BrokerableAttachment::MACH_PORT); + DCHECK_EQ(attachment->GetType(), MessageAttachment::Type::MACH_PORT); internal::MachPortAttachmentMac& mach_port_attachment = static_cast<internal::MachPortAttachmentMac&>(*attachment); MojoResult result = WrapMachPort(mach_port_attachment.get_mach_port(), @@ -161,10 +156,7 @@ mach_port_attachment.reset_mach_port_ownership(); return result; #elif defined(OS_WIN) - DCHECK_EQ(attachment->GetType(), - MessageAttachment::TYPE_BROKERABLE_ATTACHMENT); - DCHECK_EQ(static_cast<BrokerableAttachment&>(*attachment).GetBrokerableType(), - BrokerableAttachment::WIN_HANDLE); + DCHECK_EQ(attachment->GetType(), MessageAttachment::Type::WIN_HANDLE); internal::HandleAttachmentWin& handle_attachment = static_cast<internal::HandleAttachmentWin&>(*attachment); MojoResult result = WrapPlatformHandle( @@ -411,18 +403,9 @@ std::vector<mojom::SerializedHandlePtr> output_handles; MessageAttachmentSet* set = message->attachment_set(); - for (unsigned i = 0; - result == MOJO_RESULT_OK && i < set->num_non_brokerable_attachments(); - ++i) { - result = WrapAttachment(set->GetNonBrokerableAttachmentAt(i).get(), - &output_handles); + for (unsigned i = 0; result == MOJO_RESULT_OK && i < set->size(); ++i) { + result = WrapAttachment(set->GetAttachmentAt(i).get(), &output_handles); } - for (unsigned i = 0; - result == MOJO_RESULT_OK && i < set->num_brokerable_attachments(); ++i) { - result = WrapAttachment(set->GetBrokerableAttachmentAt(i).get(), - &output_handles); - } - set->CommitAllDescriptors(); if (!output_handles.empty())
diff --git a/ipc/ipc_channel_mojo_unittest.cc b/ipc/ipc_channel_mojo_unittest.cc index 229716e..5c23ea3 100644 --- a/ipc/ipc_channel_mojo_unittest.cc +++ b/ipc/ipc_channel_mojo_unittest.cc
@@ -289,11 +289,12 @@ base::ScopedFD fd; scoped_refptr<base::Pickle::Attachment> attachment; EXPECT_TRUE(message.ReadAttachment(iter, &attachment)); - EXPECT_EQ(IPC::MessageAttachment::TYPE_PLATFORM_FILE, - static_cast<IPC::MessageAttachment*>(attachment.get()) - ->GetType()); - base::File file(static_cast<IPC::MessageAttachment*>(attachment.get()) - ->TakePlatformFile()); + EXPECT_EQ( + IPC::MessageAttachment::Type::PLATFORM_FILE, + static_cast<IPC::MessageAttachment*>(attachment.get())->GetType()); + base::File file( + static_cast<IPC::internal::PlatformFileAttachment*>(attachment.get()) + ->TakePlatformFile()); std::string content(GetSendingFileContent().size(), ' '); file.Read(0, &content[0], content.size()); EXPECT_EQ(content, GetSendingFileContent());
diff --git a/ipc/ipc_channel_nacl.cc b/ipc/ipc_channel_nacl.cc index 2e1ab16..1fa8e69 100644 --- a/ipc/ipc_channel_nacl.cc +++ b/ipc/ipc_channel_nacl.cc
@@ -23,6 +23,7 @@ #include "ipc/ipc_listener.h" #include "ipc/ipc_logging.h" #include "ipc/ipc_message_attachment_set.h" +#include "ipc/ipc_platform_file_attachment_posix.h" #include "native_client/src/public/imc_syscalls.h" #include "native_client/src/public/imc_types.h" @@ -199,7 +200,7 @@ std::unique_ptr<Message> message_ptr(message); #ifdef IPC_MESSAGE_LOG_ENABLED - Logging::GetInstance()->OnSendMessage(message_ptr.get(), ""); + Logging::GetInstance()->OnSendMessage(message_ptr.get()); #endif // IPC_MESSAGE_LOG_ENABLED TRACE_EVENT_WITH_FLOW0(TRACE_DISABLED_BY_DEFAULT("ipc.flow"), @@ -223,8 +224,11 @@ data->swap(contents->data); read_queue_.push_back(data); - input_fds_.insert(input_fds_.end(), - contents->fds.begin(), contents->fds.end()); + input_attachments_.reserve(contents->fds.size()); + for (int fd : contents->fds) { + input_attachments_.push_back( + new internal::PlatformFileAttachment(base::ScopedFD(fd))); + } contents->fds.clear(); // In POSIX, we would be told when there are bytes to read by implementing @@ -272,16 +276,22 @@ linked_ptr<Message> msg = output_queue_.front(); output_queue_.pop_front(); - int fds[MessageAttachmentSet::kMaxDescriptorsPerMessage]; - const size_t num_fds = - msg->attachment_set()->num_non_brokerable_attachments(); + const size_t num_fds = msg->attachment_set()->size(); DCHECK(num_fds <= MessageAttachmentSet::kMaxDescriptorsPerMessage); - msg->attachment_set()->PeekDescriptors(fds); + std::vector<int> fds; + fds.reserve(num_fds); + for (size_t i = 0; i < num_fds; i++) { + scoped_refptr<MessageAttachment> attachment = + msg->attachment_set()->GetAttachmentAt(i); + DCHECK_EQ(MessageAttachment::Type::PLATFORM_FILE, attachment->GetType()); + fds.push_back(static_cast<internal::PlatformFileAttachment&>(*attachment) + .TakePlatformFile()); + } NaClAbiNaClImcMsgIoVec iov = { const_cast<void*>(msg->data()), msg->size() }; - NaClAbiNaClImcMsgHdr msgh = { &iov, 1, fds, num_fds }; + NaClAbiNaClImcMsgHdr msgh = {&iov, 1, fds.data(), num_fds}; ssize_t bytes_written = imc_sendmsg(pipe_, &msgh, 0); DCHECK(bytes_written); // The trusted side shouldn't return 0. @@ -345,23 +355,22 @@ return true; } -bool ChannelNacl::GetNonBrokeredAttachments(Message* msg) { +bool ChannelNacl::GetAttachments(Message* msg) { uint16_t header_fds = msg->header()->num_fds; - CHECK(header_fds == input_fds_.size()); + CHECK(header_fds == input_attachments_.size()); if (header_fds == 0) return true; // Nothing to do. - // The shenaniganery below with &foo.front() requires input_fds_ to have - // contiguous underlying storage (such as a simple array or a std::vector). - // This is why the header warns not to make input_fds_ a deque<>. - msg->attachment_set()->AddDescriptorsToOwn(&input_fds_.front(), header_fds); - input_fds_.clear(); + for (auto& attachment : input_attachments_) { + msg->attachment_set()->AddAttachment(std::move(attachment)); + } + input_attachments_.clear(); return true; } bool ChannelNacl::DidEmptyInputBuffers() { - // When the input data buffer is empty, the fds should be too. - return input_fds_.empty(); + // When the input data buffer is empty, the attachments should be too. + return input_attachments_.empty(); } void ChannelNacl::HandleInternalMessage(const Message& msg) {
diff --git a/ipc/ipc_channel_nacl.h b/ipc/ipc_channel_nacl.h index 2e4d42f..34afe6e 100644 --- a/ipc/ipc_channel_nacl.h +++ b/ipc/ipc_channel_nacl.h
@@ -62,7 +62,7 @@ int buffer_len, int* bytes_read) override; bool ShouldDispatchInputMessage(Message* msg) override; - bool GetNonBrokeredAttachments(Message* msg) override; + bool GetAttachments(Message* msg) override; bool DidEmptyInputBuffers() override; void HandleInternalMessage(const Message& msg) override; @@ -96,11 +96,8 @@ // 2 above in NaCl eventually. // When ReadData is called, it pulls the bytes out of this queue in order. std::deque<linked_ptr<std::vector<char> > > read_queue_; - // Queue of file descriptors extracted from imc_recvmsg messages. - // NOTE: The implementation assumes underlying storage here is contiguous, so - // don't change to something like std::deque<> without changing the - // implementation! - std::vector<int> input_fds_; + // Queue of file descriptor attachments extracted from imc_recvmsg messages. + std::vector<scoped_refptr<MessageAttachment>> input_attachments_; // This queue is used when a message is sent prior to Connect having been // called. Normally after we're connected, the queue is empty.
diff --git a/ipc/ipc_channel_proxy.cc b/ipc/ipc_channel_proxy.cc index a089a4d..3365aef 100644 --- a/ipc/ipc_channel_proxy.cc +++ b/ipc/ipc_channel_proxy.cc
@@ -73,7 +73,6 @@ base::AutoLock l(channel_lifetime_lock_); DCHECK(!channel_); DCHECK_EQ(factory->GetIPCTaskRunner(), ipc_task_runner_); - channel_id_ = factory->GetName(); channel_ = factory->BuildChannel(this); Channel::AssociatedInterfaceSupport* support = @@ -103,7 +102,7 @@ } #ifdef IPC_MESSAGE_LOG_ENABLED if (logger->Enabled()) - logger->OnPostDispatchMessage(message, channel_id_); + logger->OnPostDispatchMessage(message); #endif return true; } @@ -344,7 +343,7 @@ #ifdef IPC_MESSAGE_LOG_ENABLED if (logger->Enabled()) - logger->OnPostDispatchMessage(message, channel_id_); + logger->OnPostDispatchMessage(message); #endif } @@ -565,7 +564,7 @@ #endif #ifdef IPC_MESSAGE_LOG_ENABLED - Logging::GetInstance()->OnSendMessage(message, context_->channel_id()); + Logging::GetInstance()->OnSendMessage(message); #endif context_->Send(message);
diff --git a/ipc/ipc_channel_proxy.h b/ipc/ipc_channel_proxy.h index 9f6932d..5765630 100644 --- a/ipc/ipc_channel_proxy.h +++ b/ipc/ipc_channel_proxy.h
@@ -250,8 +250,6 @@ base::SingleThreadTaskRunner* ipc_task_runner() const { return ipc_task_runner_.get(); } - const std::string& channel_id() const { return channel_id_; } - // Dispatches a message on the listener thread. void OnDispatchMessage(const Message& message); @@ -339,7 +337,6 @@ // thread. // One exception is the thread-safe send. See the class comment. std::unique_ptr<Channel> channel_; - std::string channel_id_; bool channel_connected_called_; // Lock for |channel_| value. This is only relevant in the context of
diff --git a/ipc/ipc_channel_reader.cc b/ipc/ipc_channel_reader.cc index 6907979..fa26734c 100644 --- a/ipc/ipc_channel_reader.cc +++ b/ipc/ipc_channel_reader.cc
@@ -192,7 +192,7 @@ } bool ChannelReader::HandleExternalMessage(Message* external_message) { - if (!GetNonBrokeredAttachments(external_message)) + if (!GetAttachments(external_message)) return false; DispatchMessage(external_message);
diff --git a/ipc/ipc_channel_reader.h b/ipc/ipc_channel_reader.h index 73cea04..04a95dd 100644 --- a/ipc/ipc_channel_reader.h +++ b/ipc/ipc_channel_reader.h
@@ -12,7 +12,6 @@ #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/memory/scoped_vector.h" -#include "ipc/brokerable_attachment.h" #include "ipc/ipc_channel.h" #include "ipc/ipc_export.h" @@ -101,9 +100,9 @@ virtual bool ShouldDispatchInputMessage(Message* msg) = 0; // Overridden by subclasses to get attachments that are sent alongside the IPC - // channel (as opposed to through a broker). + // channel. // Returns true on success. False means a fatal channel error. - virtual bool GetNonBrokeredAttachments(Message* msg) = 0; + virtual bool GetAttachments(Message* msg) = 0; // Performs post-dispatch checks. Called when all input buffers are empty, // though there could be more data ready to be read from the OS.
diff --git a/ipc/ipc_channel_reader_unittest.cc b/ipc/ipc_channel_reader_unittest.cc index 16c6649..a3d80dc 100644 --- a/ipc/ipc_channel_reader_unittest.cc +++ b/ipc/ipc_channel_reader_unittest.cc
@@ -12,7 +12,6 @@ #include <set> #include "base/run_loop.h" -#include "ipc/brokerable_attachment.h" #include "ipc/ipc_channel_reader.h" #include "testing/gtest/include/gtest/gtest.h" @@ -39,7 +38,7 @@ bool ShouldDispatchInputMessage(Message* msg) override { return true; } - bool GetNonBrokeredAttachments(Message* msg) override { return true; } + bool GetAttachments(Message* msg) override { return true; } bool DidEmptyInputBuffers() override { return true; }
diff --git a/ipc/ipc_logging.cc b/ipc/ipc_logging.cc index 5e131495..af532cd 100644 --- a/ipc/ipc_logging.cc +++ b/ipc/ipc_logging.cc
@@ -122,7 +122,7 @@ } } -void Logging::OnSendMessage(Message* message, const std::string& channel_id) { +void Logging::OnSendMessage(Message* message) { if (!Enabled()) return; @@ -134,8 +134,7 @@ // This is actually the delayed reply to a sync message. Create a string // of the output parameters, add it to the LogData that was earlier stashed // with the reply, and log the result. - GenerateLogData("", *message, data, true); - data->channel = channel_id; + GenerateLogData(*message, data, true); Log(*data); delete data; message->set_sync_log_data(NULL); @@ -151,8 +150,7 @@ message.set_received_time(Time::Now().ToInternalValue()); } -void Logging::OnPostDispatchMessage(const Message& message, - const std::string& channel_id) { +void Logging::OnPostDispatchMessage(const Message& message) { if (!Enabled() || !message.sent_time() || !message.received_time() || @@ -160,7 +158,7 @@ return; LogData data; - GenerateLogData(channel_id, message, &data, true); + GenerateLogData(message, &data, true); if (main_thread_->BelongsToCurrentThread()) { Log(data); @@ -255,8 +253,7 @@ (Time::FromInternalValue(data.dispatch) - Time::FromInternalValue(data.sent)).InSecondsF(); fprintf(stderr, - "ipc %s %d %s %s%s %s%s\n %18.5f %s%18.5f %s%18.5f%s\n", - data.channel.c_str(), + "ipc %d %s %s%s %s%s\n %18.5f %s%18.5f %s%18.5f%s\n", data.routing_id, data.flags.c_str(), ANSIEscape(sender_ ? ANSI_COLOR_BLUE : ANSI_COLOR_CYAN), @@ -273,8 +270,7 @@ } } -void GenerateLogData(const std::string& channel, const Message& message, - LogData* data, bool get_params) { +void GenerateLogData(const Message& message, LogData* data, bool get_params) { if (message.is_reply()) { // "data" should already be filled in. std::string params; @@ -301,7 +297,6 @@ Logging::GetMessageText(message.type(), &message_name, &message, get_params ? ¶ms : NULL); - data->channel = channel; data->routing_id = message.routing_id(); data->type = message.type(); data->flags = flags;
diff --git a/ipc/ipc_logging.h b/ipc/ipc_logging.h index e5679216..af490f0 100644 --- a/ipc/ipc_logging.h +++ b/ipc/ipc_logging.h
@@ -67,10 +67,9 @@ // received. void OnReceivedLoggingMessage(const Message& message); - void OnSendMessage(Message* message, const std::string& channel_id); + void OnSendMessage(Message* message); void OnPreDispatchMessage(const Message& message); - void OnPostDispatchMessage(const Message& message, - const std::string& channel_id); + void OnPostDispatchMessage(const Message& message); // Like the *MsgLog functions declared for each message class, except this // calls the correct one based on the message type automatically. Defined in
diff --git a/ipc/ipc_message.cc b/ipc/ipc_message.cc index 008401f..f5e9ac7a 100644 --- a/ipc/ipc_message.cc +++ b/ipc/ipc_message.cc
@@ -166,19 +166,15 @@ bool Message::WriteAttachment( scoped_refptr<base::Pickle::Attachment> attachment) { - bool brokerable; size_t index; bool success = attachment_set()->AddAttachment( make_scoped_refptr(static_cast<MessageAttachment*>(attachment.get())), - &index, &brokerable); + &index); DCHECK(success); // NOTE: If you add more data to the pickle, make sure to update // PickleSizer::AddAttachment. - // Write the type of descriptor. - WriteBool(brokerable); - // Write the index of the descriptor so that we don't have to // keep the current descriptor as extra decoding state when deserialising. WriteInt(static_cast<int>(index)); @@ -189,10 +185,6 @@ bool Message::ReadAttachment( base::PickleIterator* iter, scoped_refptr<base::Pickle::Attachment>* attachment) const { - bool brokerable; - if (!iter->ReadBool(&brokerable)) - return false; - int index; if (!iter->ReadInt(&index)) return false; @@ -201,9 +193,7 @@ if (!attachment_set) return false; - *attachment = brokerable - ? attachment_set->GetBrokerableAttachmentAt(index) - : attachment_set->GetNonBrokerableAttachmentAt(index); + *attachment = attachment_set->GetAttachmentAt(index); return nullptr != attachment->get(); } @@ -212,13 +202,4 @@ return attachment_set_.get() && !attachment_set_->empty(); } -bool Message::HasMojoHandles() const { - return attachment_set_.get() && attachment_set_->num_mojo_handles() > 0; -} - -bool Message::HasBrokerableAttachments() const { - return attachment_set_.get() && - attachment_set_->num_brokerable_attachments() > 0; -} - } // namespace IPC
diff --git a/ipc/ipc_message.h b/ipc/ipc_message.h index 6bf18dec..41f57af 100644 --- a/ipc/ipc_message.h +++ b/ipc/ipc_message.h
@@ -15,7 +15,6 @@ #include "base/pickle.h" #include "base/trace_event/trace_event.h" #include "build/build_config.h" -#include "ipc/brokerable_attachment.h" #include "ipc/ipc_export.h" #if !defined(NDEBUG) @@ -208,10 +207,6 @@ scoped_refptr<base::Pickle::Attachment>* attachment) const override; // Returns true if there are any attachment in this message. bool HasAttachments() const override; - // Returns true if there are any MojoHandleAttachments in this message. - bool HasMojoHandles() const; - // Whether the message has any brokerable attachments. - bool HasBrokerableAttachments() const; #ifdef IPC_MESSAGE_LOG_ENABLED // Adds the outgoing time from Time::Now() at the end of the message and sets
diff --git a/ipc/ipc_message_attachment.h b/ipc/ipc_message_attachment.h index 7f7137d..9ff1de8c 100644 --- a/ipc/ipc_message_attachment.h +++ b/ipc/ipc_message_attachment.h
@@ -10,6 +10,7 @@ #include "base/memory/ref_counted.h" #include "base/pickle.h" #include "build/build_config.h" +#include "ipc/ipc.mojom.h" #include "ipc/ipc_export.h" namespace IPC { @@ -18,18 +19,10 @@ // or a mojo |MessagePipe|. |GetType()| returns the type of the subclass. class IPC_EXPORT MessageAttachment : public base::Pickle::Attachment { public: - enum Type { - TYPE_PLATFORM_FILE, // The instance is |PlatformFileAttachment|. - TYPE_MOJO_HANDLE, // The instance is |MojoHandleAttachment|. - TYPE_BROKERABLE_ATTACHMENT, // The instance is |BrokerableAttachment|. - }; + using Type = mojom::SerializedHandle::Type; virtual Type GetType() const = 0; -#if defined(OS_POSIX) - virtual base::PlatformFile TakePlatformFile() = 0; -#endif // OS_POSIX - protected: friend class base::RefCountedThreadSafe<MessageAttachment>; MessageAttachment();
diff --git a/ipc/ipc_message_attachment_set.cc b/ipc/ipc_message_attachment_set.cc index 068e9d2..b9a990da 100644 --- a/ipc/ipc_message_attachment_set.cc +++ b/ipc/ipc_message_attachment_set.cc
@@ -11,16 +11,8 @@ #include "base/logging.h" #include "base/posix/eintr_wrapper.h" #include "build/build_config.h" -#include "ipc/brokerable_attachment.h" #include "ipc/ipc_message_attachment.h" -#if defined(OS_POSIX) -#include <sys/stat.h> -#include <sys/types.h> -#include <unistd.h> -#include "ipc/ipc_platform_file_attachment_posix.h" -#endif // OS_POSIX - namespace IPC { namespace { @@ -43,7 +35,7 @@ } MessageAttachmentSet::~MessageAttachmentSet() { - if (consumed_descriptor_highwater_ == num_non_brokerable_attachments()) + if (consumed_descriptor_highwater_ == size()) return; // We close all the owning descriptors. If this message should have @@ -54,39 +46,24 @@ // (which could a DOS against the browser by a rogue renderer) then all // the descriptors have their close flag set and we free all the extra // kernel resources. - LOG(WARNING) << "MessageAttachmentSet destroyed with unconsumed descriptors: " - << consumed_descriptor_highwater_ << "/" << num_descriptors(); + LOG(WARNING) << "MessageAttachmentSet destroyed with unconsumed attachments: " + << consumed_descriptor_highwater_ << "/" << size(); } unsigned MessageAttachmentSet::num_descriptors() const { return count_attachments_of_type(attachments_, - MessageAttachment::TYPE_PLATFORM_FILE); -} - -unsigned MessageAttachmentSet::num_mojo_handles() const { - return count_attachments_of_type(attachments_, - MessageAttachment::TYPE_MOJO_HANDLE); -} - -unsigned MessageAttachmentSet::num_brokerable_attachments() const { - return static_cast<unsigned>(brokerable_attachments_.size()); -} - -unsigned MessageAttachmentSet::num_non_brokerable_attachments() const { - return static_cast<unsigned>(attachments_.size()); + MessageAttachment::Type::PLATFORM_FILE); } unsigned MessageAttachmentSet::size() const { - return static_cast<unsigned>(attachments_.size() + - brokerable_attachments_.size()); + return static_cast<unsigned>(attachments_.size()); } bool MessageAttachmentSet::AddAttachment( scoped_refptr<MessageAttachment> attachment, - size_t* index, - bool* brokerable) { + size_t* index) { #if defined(OS_POSIX) - if (attachment->GetType() == MessageAttachment::TYPE_PLATFORM_FILE && + if (attachment->GetType() == MessageAttachment::Type::PLATFORM_FILE && num_descriptors() == kMaxDescriptorsPerMessage) { DLOG(WARNING) << "Cannot add file descriptor. MessageAttachmentSet full."; return false; @@ -94,19 +71,12 @@ #endif switch (attachment->GetType()) { - case MessageAttachment::TYPE_PLATFORM_FILE: - case MessageAttachment::TYPE_MOJO_HANDLE: + case MessageAttachment::Type::PLATFORM_FILE: + case MessageAttachment::Type::MOJO_HANDLE: + case MessageAttachment::Type::WIN_HANDLE: + case MessageAttachment::Type::MACH_PORT: attachments_.push_back(attachment); *index = attachments_.size() - 1; - *brokerable = false; - return true; - case MessageAttachment::TYPE_BROKERABLE_ATTACHMENT: - BrokerableAttachment* brokerable_attachment = - static_cast<BrokerableAttachment*>(attachment.get()); - scoped_refptr<BrokerableAttachment> a(brokerable_attachment); - brokerable_attachments_.push_back(a); - *index = brokerable_attachments_.size() - 1; - *brokerable = true; return true; } return false; @@ -114,16 +84,14 @@ bool MessageAttachmentSet::AddAttachment( scoped_refptr<MessageAttachment> attachment) { - bool brokerable; size_t index; - return AddAttachment(attachment, &index, &brokerable); + return AddAttachment(attachment, &index); } -scoped_refptr<MessageAttachment> -MessageAttachmentSet::GetNonBrokerableAttachmentAt(unsigned index) { - if (index >= num_non_brokerable_attachments()) { - DLOG(WARNING) << "Accessing out of bound index:" << index << "/" - << num_non_brokerable_attachments(); +scoped_refptr<MessageAttachment> MessageAttachmentSet::GetAttachmentAt( + unsigned index) { + if (index >= size()) { + DLOG(WARNING) << "Accessing out of bound index:" << index << "/" << size(); return scoped_refptr<MessageAttachment>(); } @@ -148,8 +116,7 @@ // end of the array and index 0 is requested, we reset the highwater value. // TODO(morrita): This is absurd. This "wringle" disallow to introduce clearer // ownership model. Only client is NaclIPCAdapter. See crbug.com/415294 - if (index == 0 && - consumed_descriptor_highwater_ == num_non_brokerable_attachments()) { + if (index == 0 && consumed_descriptor_highwater_ == size()) { consumed_descriptor_highwater_ = 0; } @@ -161,73 +128,9 @@ return attachments_[index]; } -scoped_refptr<MessageAttachment> -MessageAttachmentSet::GetBrokerableAttachmentAt(unsigned index) { - if (index >= num_brokerable_attachments()) { - DLOG(WARNING) << "Accessing out of bound index:" << index << "/" - << num_brokerable_attachments(); - return scoped_refptr<MessageAttachment>(); - } - - scoped_refptr<BrokerableAttachment> brokerable_attachment( - brokerable_attachments_[index]); - return scoped_refptr<MessageAttachment>(brokerable_attachment.get()); -} - void MessageAttachmentSet::CommitAllDescriptors() { attachments_.clear(); consumed_descriptor_highwater_ = 0; } -std::vector<scoped_refptr<IPC::BrokerableAttachment>> -MessageAttachmentSet::GetBrokerableAttachments() const { - return brokerable_attachments_; -} - -#if defined(OS_POSIX) - -void MessageAttachmentSet::PeekDescriptors(base::PlatformFile* buffer) const { - for (size_t i = 0; i != attachments_.size(); ++i) - buffer[i] = internal::GetPlatformFile(attachments_[i]); -} - -bool MessageAttachmentSet::ContainsDirectoryDescriptor() const { - struct stat st; - - for (auto i = attachments_.begin(); i != attachments_.end(); ++i) { - if (fstat(internal::GetPlatformFile(*i), &st) == 0 && S_ISDIR(st.st_mode)) - return true; - } - - return false; -} - -void MessageAttachmentSet::ReleaseFDsToClose( - std::vector<base::PlatformFile>* fds) { - for (size_t i = 0; i < attachments_.size(); ++i) { - internal::PlatformFileAttachment* file = - static_cast<internal::PlatformFileAttachment*>(attachments_[i].get()); - if (file->Owns()) - fds->push_back(file->TakePlatformFile()); - } - - CommitAllDescriptors(); -} - -void MessageAttachmentSet::AddDescriptorsToOwn(const base::PlatformFile* buffer, - unsigned count) { - DCHECK(count <= kMaxDescriptorsPerMessage); - DCHECK_EQ(num_descriptors(), 0u); - DCHECK_EQ(consumed_descriptor_highwater_, 0u); - - attachments_.reserve(count); - for (unsigned i = 0; i < count; ++i) - AddAttachment( - new internal::PlatformFileAttachment(base::ScopedFD(buffer[i]))); -} - -#endif // OS_POSIX - } // namespace IPC - -
diff --git a/ipc/ipc_message_attachment_set.h b/ipc/ipc_message_attachment_set.h index 09ff2e3..de37211 100644 --- a/ipc/ipc_message_attachment_set.h +++ b/ipc/ipc_message_attachment_set.h
@@ -14,31 +14,17 @@ #include "build/build_config.h" #include "ipc/ipc_export.h" -#if defined(OS_POSIX) -#include "base/files/file.h" -#endif - namespace IPC { -class BrokerableAttachment; class MessageAttachment; // ----------------------------------------------------------------------------- // A MessageAttachmentSet is an ordered set of MessageAttachment objects -// associated with an IPC message. There are three types of MessageAttachments: -// 1) TYPE_PLATFORM_FILE is transmitted over the Channel's underlying -// UNIX domain socket -// 2) TYPE_MOJO_HANDLE is transmitted over the Mojo MessagePipe. -// 3) TYPE_BROKERABLE_ATTACHMENT is transmitted by the Attachment Broker. -// Any given IPC Message can have attachments of type (1) or (2), but not both. -// These are stored in |attachments_|. Attachments of type (3) are stored in -// |brokerable_attachments_|. +// associated with an IPC message. All attachments are wrapped in a mojo handle +// if necessary and sent over the mojo message pipe. // -// To produce a deterministic ordering, all attachments in |attachments_| are -// considered to come before those in |brokerable_attachments_|. These -// attachments are transmitted across different communication channels, and -// multiplexed by the receiver, so ordering between them cannot be guaranteed. -// +// For ChannelNacl under SFI NaCl, only Type::PLATFORM_FILE is supported. In +// that case, the FD is sent over socket. // ----------------------------------------------------------------------------- class IPC_EXPORT MessageAttachmentSet : public base::RefCountedThreadSafe<MessageAttachmentSet> { @@ -47,52 +33,31 @@ // Return the number of attachments unsigned size() const; - // Return the number of file descriptors - unsigned num_descriptors() const; - // Return the number of mojo handles in the attachment set - unsigned num_mojo_handles() const; - // Return the number of brokerable attachments in the attachment set. - unsigned num_brokerable_attachments() const; - // Return the number of non-brokerable attachments in the attachment set. - unsigned num_non_brokerable_attachments() const; // Return true if no unconsumed descriptors remain - bool empty() const { return 0 == size(); } + bool empty() const { return attachments_.empty(); } // Returns whether the attachment was successfully added. // |index| is an output variable. On success, it contains the index of the // newly added attachment. - // |brokerable| is an output variable. On success, it describes which vector - // the attachment was added to. bool AddAttachment(scoped_refptr<MessageAttachment> attachment, - size_t* index, - bool* brokerable); + size_t* index); // Similar to the above method, but without output variables. bool AddAttachment(scoped_refptr<MessageAttachment> attachment); - // Take the nth non-brokerable attachment from the beginning of the vector, - // Code using this /must/ access the attachments in order, and must do it at - // most once. + // Take the nth from the beginning of the vector, Code using this /must/ + // access the attachments in order, and must do it at most once. // // This interface is designed for the deserialising code as it doesn't // support close flags. // returns: an attachment, or nullptr on error - scoped_refptr<MessageAttachment> GetNonBrokerableAttachmentAt(unsigned index); + scoped_refptr<MessageAttachment> GetAttachmentAt(unsigned index); - // Similar to GetNonBrokerableAttachmentAt, but there are no ordering - // requirements. - scoped_refptr<MessageAttachment> GetBrokerableAttachmentAt(unsigned index); - - // This must be called after transmitting the descriptors returned by - // PeekDescriptors. It marks all the non-brokerable descriptors as consumed - // and closes those which are auto-close. + // Marks all the descriptors as consumed and closes those which are + // auto-close. void CommitAllDescriptors(); - // Returns a vector of all brokerable attachments. - std::vector<scoped_refptr<IPC::BrokerableAttachment>> - GetBrokerableAttachments() const; - #if defined(OS_POSIX) // This is the maximum number of descriptors per message. We need to know this // because the control message kernel interface has to be given a buffer which @@ -103,32 +68,6 @@ // In debugging mode, it's a fatal error to try and add more than this number // of descriptors to a MessageAttachmentSet. static const size_t kMaxDescriptorsPerMessage = 7; - - // --------------------------------------------------------------------------- - // Interfaces for transmission... - - // Fill an array with file descriptors without 'consuming' them. - // CommitAllDescriptors must be called after these descriptors have been - // transmitted. - // buffer: (output) a buffer of, at least, size() integers. - void PeekDescriptors(base::PlatformFile* buffer) const; - // Returns true if any contained file descriptors appear to be handles to a - // directory. - bool ContainsDirectoryDescriptor() const; - // Fetch all filedescriptors with the "auto close" property. Used instead of - // CommitAllDescriptors() when closing must be handled manually. - void ReleaseFDsToClose(std::vector<base::PlatformFile>* fds); - - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Interfaces for receiving... - - // Set the contents of the set from the given buffer. This set must be empty - // before calling. The auto-close flag is set on all the descriptors so that - // unconsumed descriptors are closed on destruction. - void AddDescriptorsToOwn(const base::PlatformFile* buffer, unsigned count); - #endif // OS_POSIX // --------------------------------------------------------------------------- @@ -138,17 +77,16 @@ ~MessageAttachmentSet(); - // All elements either have type TYPE_PLATFORM_FILE or TYPE_MOJO_HANDLE. - std::vector<scoped_refptr<MessageAttachment>> attachments_; + // Return the number of file descriptors + unsigned num_descriptors() const; - // All elements have type TYPE_BROKERABLE_ATTACHMENT. - std::vector<scoped_refptr<BrokerableAttachment>> brokerable_attachments_; + std::vector<scoped_refptr<MessageAttachment>> attachments_; // This contains the index of the next descriptor which should be consumed. // It's used in a couple of ways. Firstly, at destruction we can check that // all the descriptors have been read (with GetNthDescriptor). Secondly, we // can check that they are read in order. - mutable unsigned consumed_descriptor_highwater_; + unsigned consumed_descriptor_highwater_; DISALLOW_COPY_AND_ASSIGN(MessageAttachmentSet); };
diff --git a/ipc/ipc_message_attachment_set_posix_unittest.cc b/ipc/ipc_message_attachment_set_posix_unittest.cc index 5ebed84..0bd143df 100644 --- a/ipc/ipc_message_attachment_set_posix_unittest.cc +++ b/ipc/ipc_message_attachment_set_posix_unittest.cc
@@ -34,6 +34,12 @@ return true; } +int GetFdAt(MessageAttachmentSet* set, int id) { + return static_cast<internal::PlatformFileAttachment&>( + *set->GetAttachmentAt(id)) + .TakePlatformFile(); +} + // The MessageAttachmentSet will try and close some of the descriptor numbers // which we given it. This is the base descriptor value. It's great enough such // that no real descriptor will accidently be closed. @@ -82,44 +88,6 @@ set->CommitAllDescriptors(); } -#if defined(OS_ANDROID) -#define MAYBE_SetDescriptors DISABLED_SetDescriptors -#else -#define MAYBE_SetDescriptors SetDescriptors -#endif -TEST(MessageAttachmentSet, MAYBE_SetDescriptors) { - scoped_refptr<MessageAttachmentSet> set(new MessageAttachmentSet); - - ASSERT_TRUE(set->empty()); - set->AddDescriptorsToOwn(NULL, 0); - ASSERT_TRUE(set->empty()); - - const int fd = GetSafeFd(); - static const int fds[] = {fd}; - set->AddDescriptorsToOwn(fds, 1); - ASSERT_TRUE(!set->empty()); - ASSERT_EQ(set->size(), 1u); - - set->CommitAllDescriptors(); - - ASSERT_TRUE(VerifyClosed(fd)); -} - -TEST(MessageAttachmentSet, PeekDescriptors) { - scoped_refptr<MessageAttachmentSet> set(new MessageAttachmentSet); - - set->PeekDescriptors(NULL); - ASSERT_TRUE( - set->AddAttachment(new internal::PlatformFileAttachment(kFDBase))); - - int fds[1]; - fds[0] = 0; - set->PeekDescriptors(fds); - ASSERT_EQ(fds[0], kFDBase); - set->CommitAllDescriptors(); - ASSERT_TRUE(set->empty()); -} - TEST(MessageAttachmentSet, WalkInOrder) { scoped_refptr<MessageAttachmentSet> set(new MessageAttachmentSet); @@ -132,11 +100,9 @@ ASSERT_TRUE( set->AddAttachment(new internal::PlatformFileAttachment(kFDBase + 2))); - ASSERT_EQ(set->GetNonBrokerableAttachmentAt(0)->TakePlatformFile(), kFDBase); - ASSERT_EQ(set->GetNonBrokerableAttachmentAt(1)->TakePlatformFile(), - kFDBase + 1); - ASSERT_EQ(set->GetNonBrokerableAttachmentAt(2)->TakePlatformFile(), - kFDBase + 2); + ASSERT_EQ(GetFdAt(set.get(), 0), kFDBase); + ASSERT_EQ(GetFdAt(set.get(), 1), kFDBase + 1); + ASSERT_EQ(GetFdAt(set.get(), 2), kFDBase + 2); set->CommitAllDescriptors(); } @@ -153,8 +119,8 @@ ASSERT_TRUE( set->AddAttachment(new internal::PlatformFileAttachment(kFDBase + 2))); - ASSERT_EQ(set->GetNonBrokerableAttachmentAt(0)->TakePlatformFile(), kFDBase); - ASSERT_FALSE(set->GetNonBrokerableAttachmentAt(2)); + ASSERT_EQ(GetFdAt(set.get(), 0), kFDBase); + ASSERT_FALSE(set->GetAttachmentAt(2)); set->CommitAllDescriptors(); } @@ -171,21 +137,15 @@ ASSERT_TRUE( set->AddAttachment(new internal::PlatformFileAttachment(kFDBase + 2))); - ASSERT_EQ(set->GetNonBrokerableAttachmentAt(0)->TakePlatformFile(), kFDBase); - ASSERT_EQ(set->GetNonBrokerableAttachmentAt(1)->TakePlatformFile(), - kFDBase + 1); - ASSERT_EQ(set->GetNonBrokerableAttachmentAt(2)->TakePlatformFile(), - kFDBase + 2); - ASSERT_EQ(set->GetNonBrokerableAttachmentAt(0)->TakePlatformFile(), kFDBase); - ASSERT_EQ(set->GetNonBrokerableAttachmentAt(1)->TakePlatformFile(), - kFDBase + 1); - ASSERT_EQ(set->GetNonBrokerableAttachmentAt(2)->TakePlatformFile(), - kFDBase + 2); - ASSERT_EQ(set->GetNonBrokerableAttachmentAt(0)->TakePlatformFile(), kFDBase); - ASSERT_EQ(set->GetNonBrokerableAttachmentAt(1)->TakePlatformFile(), - kFDBase + 1); - ASSERT_EQ(set->GetNonBrokerableAttachmentAt(2)->TakePlatformFile(), - kFDBase + 2); + ASSERT_EQ(GetFdAt(set.get(), 0), kFDBase); + ASSERT_EQ(GetFdAt(set.get(), 1), kFDBase + 1); + ASSERT_EQ(GetFdAt(set.get(), 2), kFDBase + 2); + ASSERT_EQ(GetFdAt(set.get(), 0), kFDBase); + ASSERT_EQ(GetFdAt(set.get(), 1), kFDBase + 1); + ASSERT_EQ(GetFdAt(set.get(), 2), kFDBase + 2); + ASSERT_EQ(GetFdAt(set.get(), 0), kFDBase); + ASSERT_EQ(GetFdAt(set.get(), 1), kFDBase + 1); + ASSERT_EQ(GetFdAt(set.get(), 2), kFDBase + 2); set->CommitAllDescriptors(); }
diff --git a/ipc/ipc_message_utils.cc b/ipc/ipc_message_utils.cc index f814727..be83e5a 100644 --- a/ipc/ipc_message_utils.cc +++ b/ipc/ipc_message_utils.cc
@@ -658,8 +658,14 @@ if (!m->ReadAttachment(iter, &attachment)) return false; + if (static_cast<MessageAttachment*>(attachment.get())->GetType() != + MessageAttachment::Type::PLATFORM_FILE) { + return false; + } + *r = base::FileDescriptor( - static_cast<MessageAttachment*>(attachment.get())->TakePlatformFile(), + static_cast<internal::PlatformFileAttachment*>(attachment.get()) + ->TakePlatformFile(), true); return true; }
diff --git a/ipc/ipc_message_utils.h b/ipc/ipc_message_utils.h index 366ab5f..58d6aa26 100644 --- a/ipc/ipc_message_utils.h +++ b/ipc/ipc_message_utils.h
@@ -27,7 +27,6 @@ #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "build/build_config.h" -#include "ipc/brokerable_attachment.h" #include "ipc/ipc_message_start.h" #include "ipc/ipc_param_traits.h" #include "ipc/ipc_sync_message.h" @@ -1100,10 +1099,9 @@ // Generic message subclasses // defined in ipc_logging.cc -IPC_EXPORT void GenerateLogData(const std::string& channel, - const Message& message, - LogData* data, bool get_params); - +IPC_EXPORT void GenerateLogData(const Message& message, + LogData* data, + bool get_params); #if defined(IPC_MESSAGE_LOG_ENABLED) inline void AddOutputParamsToLog(const Message* msg, std::string* l) { @@ -1130,7 +1128,7 @@ // output parameters at that point. Instead, save its data and log it // with the outgoing reply message when it's sent. LogData* data = new LogData; - GenerateLogData("", *msg, data, true); + GenerateLogData(*msg, data, true); msg->set_dont_log(); reply->set_sync_log_data(data); }
diff --git a/ipc/ipc_mojo_handle_attachment.cc b/ipc/ipc_mojo_handle_attachment.cc index 819a12b..e3421c3 100644 --- a/ipc/ipc_mojo_handle_attachment.cc +++ b/ipc/ipc_mojo_handle_attachment.cc
@@ -18,16 +18,9 @@ } MessageAttachment::Type MojoHandleAttachment::GetType() const { - return TYPE_MOJO_HANDLE; + return Type::MOJO_HANDLE; } -#if defined(OS_POSIX) -base::PlatformFile MojoHandleAttachment::TakePlatformFile() { - NOTREACHED(); - return base::kInvalidPlatformFile; -} -#endif // OS_POSIX - mojo::ScopedHandle MojoHandleAttachment::TakeHandle() { return std::move(handle_); }
diff --git a/ipc/ipc_mojo_handle_attachment.h b/ipc/ipc_mojo_handle_attachment.h index 6aa1888c..d615276 100644 --- a/ipc/ipc_mojo_handle_attachment.h +++ b/ipc/ipc_mojo_handle_attachment.h
@@ -26,11 +26,6 @@ Type GetType() const override; -#if defined(OS_POSIX) - // Should not be called. - base::PlatformFile TakePlatformFile() override; -#endif // OS_POSIX - // Returns the owning handle transferring the ownership. mojo::ScopedHandle TakeHandle();
diff --git a/ipc/ipc_mojo_message_helper.cc b/ipc/ipc_mojo_message_helper.cc index 8f86945..a87a2d69 100644 --- a/ipc/ipc_mojo_message_helper.cc +++ b/ipc/ipc_mojo_message_helper.cc
@@ -32,7 +32,7 @@ MessageAttachment::Type type = static_cast<MessageAttachment*>(attachment.get())->GetType(); - if (type != MessageAttachment::TYPE_MOJO_HANDLE) { + if (type != MessageAttachment::Type::MOJO_HANDLE) { LOG(ERROR) << "Unxpected attachment type:" << type; return false; }
diff --git a/ipc/ipc_platform_file_attachment_posix.cc b/ipc/ipc_platform_file_attachment_posix.cc index b130ab2..7111cfa0 100644 --- a/ipc/ipc_platform_file_attachment_posix.cc +++ b/ipc/ipc_platform_file_attachment_posix.cc
@@ -20,7 +20,7 @@ } MessageAttachment::Type PlatformFileAttachment::GetType() const { - return TYPE_PLATFORM_FILE; + return Type::PLATFORM_FILE; } base::PlatformFile PlatformFileAttachment::TakePlatformFile() { @@ -30,7 +30,7 @@ base::PlatformFile GetPlatformFile( scoped_refptr<MessageAttachment> attachment) { - DCHECK_EQ(attachment->GetType(), MessageAttachment::TYPE_PLATFORM_FILE); + DCHECK_EQ(attachment->GetType(), MessageAttachment::Type::PLATFORM_FILE); return static_cast<PlatformFileAttachment*>(attachment.get())->file(); }
diff --git a/ipc/ipc_platform_file_attachment_posix.h b/ipc/ipc_platform_file_attachment_posix.h index d1eff60..9b079009 100644 --- a/ipc/ipc_platform_file_attachment_posix.h +++ b/ipc/ipc_platform_file_attachment_posix.h
@@ -23,7 +23,7 @@ explicit PlatformFileAttachment(base::ScopedFD file); Type GetType() const override; - base::PlatformFile TakePlatformFile() override; + base::PlatformFile TakePlatformFile(); base::PlatformFile file() const { return file_; } bool Owns() const { return owning_.is_valid(); }
diff --git a/ipc/mach_port_attachment_mac.cc b/ipc/mach_port_attachment_mac.cc index 215afa96..55a85cb 100644 --- a/ipc/mach_port_attachment_mac.cc +++ b/ipc/mach_port_attachment_mac.cc
@@ -24,10 +24,6 @@ FromWire from_wire) : mach_port_(mach_port), owns_mach_port_(true) {} -MachPortAttachmentMac::MachPortAttachmentMac(const WireFormat& wire_format) - : mach_port_(static_cast<mach_port_t>(wire_format.mach_port)), - owns_mach_port_(true) {} - MachPortAttachmentMac::~MachPortAttachmentMac() { if (mach_port_ != MACH_PORT_NULL && owns_mach_port_) { kern_return_t kr = mach_port_mod_refs(mach_task_self(), mach_port_, @@ -37,14 +33,8 @@ } } -MachPortAttachmentMac::BrokerableType MachPortAttachmentMac::GetBrokerableType() - const { - return MACH_PORT; -} - -MachPortAttachmentMac::WireFormat MachPortAttachmentMac::GetWireFormat( - const base::ProcessId& destination) const { - return WireFormat(static_cast<uint32_t>(mach_port_), destination); +MessageAttachment::Type MachPortAttachmentMac::GetType() const { + return Type::MACH_PORT; } } // namespace internal
diff --git a/ipc/mach_port_attachment_mac.h b/ipc/mach_port_attachment_mac.h index efc2c11..861c4e3 100644 --- a/ipc/mach_port_attachment_mac.h +++ b/ipc/mach_port_attachment_mac.h
@@ -10,36 +10,16 @@ #include "base/macros.h" #include "base/process/process_handle.h" -#include "ipc/brokerable_attachment.h" #include "ipc/ipc_export.h" +#include "ipc/ipc_message_attachment.h" #include "ipc/mach_port_mac.h" namespace IPC { namespace internal { // This class represents an OSX mach_port_t attached to a Chrome IPC message. -class IPC_EXPORT MachPortAttachmentMac : public BrokerableAttachment { +class IPC_EXPORT MachPortAttachmentMac : public MessageAttachment { public: - struct IPC_EXPORT WireFormat { - // IPC translation requires that classes passed through IPC have a default - // constructor. - WireFormat() : mach_port(0), destination_process(0) {} - - WireFormat(uint32_t mach_port, const base::ProcessId& destination_process) - : mach_port(mach_port), destination_process(destination_process) {} - - // The mach port that is intended for duplication, or the mach port that has - // been duplicated, depending on context. - // The type is uint32_t instead of mach_port_t to ensure that the wire - // format stays consistent. - uint32_t mach_port; - static_assert(sizeof(mach_port_t) <= sizeof(uint32_t), - "mach_port_t must be smaller than uint32_t"); - - // The id of the destination process that the handle is duplicated into. - base::ProcessId destination_process; - }; - // This constructor increments the ref count of |mach_port_| and takes // ownership of the result. Should only be called by the sender of a Chrome // IPC message. @@ -52,15 +32,7 @@ // ref count. Should only be called by the receiver of a Chrome IPC message. MachPortAttachmentMac(mach_port_t mach_port, FromWire from_wire); - // This constructor takes ownership of |wire_format.mach_port|, but does not - // modify its ref count. Should only be called by the receiver of a Chrome IPC - // message. - explicit MachPortAttachmentMac(const WireFormat& wire_format); - - BrokerableType GetBrokerableType() const override; - - // Returns the wire format of this attachment. - WireFormat GetWireFormat(const base::ProcessId& destination) const; + Type GetType() const override; mach_port_t get_mach_port() const { return mach_port_; }
diff --git a/ipc/mach_port_mac.cc b/ipc/mach_port_mac.cc index a482d24..6d3045a 100644 --- a/ipc/mach_port_mac.cc +++ b/ipc/mach_port_mac.cc
@@ -34,16 +34,10 @@ return false; MessageAttachment* attachment = static_cast<MessageAttachment*>(base_attachment.get()); - if (attachment->GetType() != MessageAttachment::TYPE_BROKERABLE_ATTACHMENT) + if (attachment->GetType() != MessageAttachment::Type::MACH_PORT) return false; - BrokerableAttachment* brokerable_attachment = - static_cast<BrokerableAttachment*>(attachment); - if (brokerable_attachment->GetBrokerableType() != - BrokerableAttachment::MACH_PORT) { - return false; - } IPC::internal::MachPortAttachmentMac* mach_port_attachment = - static_cast<IPC::internal::MachPortAttachmentMac*>(brokerable_attachment); + static_cast<IPC::internal::MachPortAttachmentMac*>(attachment); r->set_mach_port(mach_port_attachment->get_mach_port()); mach_port_attachment->reset_mach_port_ownership(); return true;
diff --git a/media/base/android/media_codec_util.cc b/media/base/android/media_codec_util.cc index 467449f1..b29cc168 100644 --- a/media/base/android/media_codec_util.cc +++ b/media/base/android/media_codec_util.cc
@@ -101,12 +101,13 @@ // http://crbug.com/365494, http://crbug.com/615872 // Blacklist Lenovo A6600 / A6800 on KitKat, which tends to crash a lot. // See crbug.com/628059 . We include < K since they don't exist. + // Blacklist Samsung Galaxy Star Pro (GT-S7262) (crbug.com/634920). // GT-S5282 and GT-I8552 are for crbug.com/634920 . if (base::android::BuildInfo::GetInstance()->sdk_int() <= 19) { std::string model(base::android::BuildInfo::GetInstance()->model()); return model != "GT-I9100" && model != "GT-I9300" && model != "GT-N7000" && model != "GT-N7100" && model != "A6600" && model != "A6800" && - model != "GT-S5282" && model != "GT-I8552"; + model != "GT-S7262" && model != "GT-S5282" && model != "GT-I8552"; } return true;
diff --git a/media/base/sinc_resampler.cc b/media/base/sinc_resampler.cc index ec35b74..99ef3741 100644 --- a/media/base/sinc_resampler.cc +++ b/media/base/sinc_resampler.cc
@@ -81,6 +81,7 @@ #include <cmath> #include <limits> +#include "base/debug/alias.h" #include "base/logging.h" #include "build/build_config.h" @@ -239,6 +240,10 @@ buffer_primed_ = true; } + // TODO(dalecurtis): Temporary debugging for http://crbug.com/663814 + const double starting_idx = virtual_source_idx_; + CHECK(!std::isnan(virtual_source_idx_)); + // Step (2) -- Resample! const what we can outside of the loop for speed. It // actually has an impact on ARM performance. See inner loop comment below. const double current_io_ratio = io_sample_rate_ratio_; @@ -247,6 +252,8 @@ // Note: The loop construct here can severely impact performance on ARM // or when built with clang. See https://codereview.chromium.org/18566009/ int source_idx = static_cast<int>(virtual_source_idx_); + // TODO(dalecurtis): Temporary debugging for http://crbug.com/663814 + CHECK_GE(source_idx, 0); while (source_idx < block_size_) { // |virtual_source_idx_| lies in between two kernel offsets so figure out // what they are. @@ -279,6 +286,10 @@ virtual_source_idx_ += current_io_ratio; source_idx = static_cast<int>(virtual_source_idx_); + // TODO(dalecurtis): Temporary debugging for http://crbug.com/663814 + base::debug::Alias(&starting_idx); + CHECK(!std::isnan(virtual_source_idx_)); + CHECK_GE(source_idx, 0); if (!--remaining_frames) return; } @@ -287,6 +298,10 @@ DCHECK_GE(virtual_source_idx_, block_size_); virtual_source_idx_ -= block_size_; + // TODO(dalecurtis): Temporary debugging for http://crbug.com/663814 + base::debug::Alias(&starting_idx); + CHECK(!std::isnan(virtual_source_idx_)); + // Step (3) -- Copy r3_, r4_ to r1_, r2_. // This wraps the last input frames back to the start of the buffer. memcpy(r1_, r3_, sizeof(*input_buffer_.get()) * kKernelSize);
diff --git a/media/blink/webmediaplayer_impl.cc b/media/blink/webmediaplayer_impl.cc index c746292..88934a4 100644 --- a/media/blink/webmediaplayer_impl.cc +++ b/media/blink/webmediaplayer_impl.cc
@@ -1761,12 +1761,11 @@ if (IsNetworkStateError(network_state_)) return; -#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) && !defined(OS_MACOSX) +#if defined(OS_LINUX) // TODO(sandersd): idle suspend is disabled if decoder owns video frame. - // Used on Windows+Chromecast. Since GetCurrentFrameFromCompositor is a - // synchronous cross-thread post, avoid the cost on platforms that always - // allow suspend. Need to find a better mechanism for this. See - // http://crbug.com/602708 + // Used on Chromecast. Since GetCurrentFrameFromCompositor is a synchronous + // cross-thread post, avoid the cost on platforms that always allow suspend. + // Need to find a better mechanism for this. See http://crbug.com/602708 if (can_suspend_state_ == CanSuspendState::UNKNOWN) { scoped_refptr<VideoFrame> frame = GetCurrentFrameFromCompositor(); if (frame) {
diff --git a/media/capture/video/video_capture_device_factory.h b/media/capture/video/video_capture_device_factory.h index 652320af..49d9519f 100644 --- a/media/capture/video/video_capture_device_factory.h +++ b/media/capture/video/video_capture_device_factory.h
@@ -20,6 +20,9 @@ // used to either obtain the supported formats of a device using // GetSupportedFormats(), or to create an instance of VideoCaptureDevice for // the device using CreateDevice(). +// TODO(chfremer): Add a layer on top of the platform-specific implementations +// that uses strings instead of descriptors as keys for accessing devices. +// crbug.com/665065 class CAPTURE_EXPORT VideoCaptureDeviceFactory { public: static std::unique_ptr<VideoCaptureDeviceFactory> CreateFactory(
diff --git a/media/cdm/ppapi/external_clear_key/clear_key_cdm.cc b/media/cdm/ppapi/external_clear_key/clear_key_cdm.cc index aaf7c221..fbdda3da 100644 --- a/media/cdm/ppapi/external_clear_key/clear_key_cdm.cc +++ b/media/cdm/ppapi/external_clear_key/clear_key_cdm.cc
@@ -46,14 +46,6 @@ #if !defined COMPONENT_BUILD static base::AtExitManager g_at_exit_manager; #endif - -// Prepare media library. -static bool InitializeFFmpegLibraries() { - media::InitializeMediaLibrary(); - return true; -} -static bool g_ffmpeg_lib_initialized = InitializeFFmpegLibraries(); - #endif // CLEAR_KEY_CDM_USE_FFMPEG_DECODER const char kClearKeyCdmVersion[] = "0.1.0.1"; @@ -221,6 +213,7 @@ void INITIALIZE_CDM_MODULE() { DVLOG(1) << __FUNCTION__; #if defined(CLEAR_KEY_CDM_USE_FFMPEG_DECODER) + media::InitializeMediaLibrary(); av_register_all(); #endif // CLEAR_KEY_CDM_USE_FFMPEG_DECODER }
diff --git a/media/gpu/dxva_picture_buffer_win.cc b/media/gpu/dxva_picture_buffer_win.cc index e0a3783..df29c8a 100644 --- a/media/gpu/dxva_picture_buffer_win.cc +++ b/media/gpu/dxva_picture_buffer_win.cc
@@ -10,6 +10,7 @@ #include "ui/gl/gl_bindings.h" #include "ui/gl/gl_context.h" #include "ui/gl/gl_fence.h" +#include "ui/gl/gl_image.h" #include "ui/gl/gl_surface_egl.h" #include "ui/gl/scoped_binders.h" @@ -21,6 +22,73 @@ LOG(ERROR) << "Error in dxva_picture_buffer_win.cc on line " << line; } +// These GLImage subclasses are just used to hold references to the underlying +// image content so it can be destroyed when the textures are. +class DummyGLImage : public gl::GLImage { + public: + DummyGLImage(const gfx::Size& size) : size_(size) {} + + // gl::GLImage implementation. + gfx::Size GetSize() override { return size_; } + unsigned GetInternalFormat() override { return GL_BGRA_EXT; } + bool BindTexImage(unsigned target) override { return false; } + void ReleaseTexImage(unsigned target) override {} + bool CopyTexImage(unsigned target) override { return false; } + bool CopyTexSubImage(unsigned target, + const gfx::Point& offset, + const gfx::Rect& rect) override { + return false; + } + bool ScheduleOverlayPlane(gfx::AcceleratedWidget widget, + int z_order, + gfx::OverlayTransform transform, + const gfx::Rect& bounds_rect, + const gfx::RectF& crop_rect) override { + return false; + } + void Flush() override {} + void OnMemoryDump(base::trace_event::ProcessMemoryDump* pmd, + uint64_t process_tracing_id, + const std::string& dump_name) override {} + + protected: + ~DummyGLImage() override {} + + private: + gfx::Size size_; +}; + +class GLImagePbuffer : public DummyGLImage { + public: + GLImagePbuffer(const gfx::Size& size, EGLSurface surface) + : DummyGLImage(size), surface_(surface) {} + + private: + ~GLImagePbuffer() override { + EGLDisplay egl_display = gl::GLSurfaceEGL::GetHardwareDisplay(); + + eglReleaseTexImage(egl_display, surface_, EGL_BACK_BUFFER); + + eglDestroySurface(egl_display, surface_); + } + + EGLSurface surface_; +}; + +class GLImageEGLStream : public DummyGLImage { + public: + GLImageEGLStream(const gfx::Size& size, EGLStreamKHR stream) + : DummyGLImage(size), stream_(stream) {} + + private: + ~GLImageEGLStream() override { + EGLDisplay egl_display = gl::GLSurfaceEGL::GetHardwareDisplay(); + eglDestroyStreamKHR(egl_display, stream_); + } + + EGLStreamKHR stream_; +}; + } // namespace #define RETURN_ON_FAILURE(result, log, ret) \ @@ -138,6 +206,7 @@ egl_display, EGL_D3D_TEXTURE_2D_SHARE_HANDLE_ANGLE, texture_share_handle_, egl_config, attrib_list); RETURN_ON_FAILURE(decoding_surface_, "Failed to create surface", false); + gl_image_ = make_scoped_refptr(new GLImagePbuffer(size(), decoding_surface_)); if (decoder.d3d11_device_ && decoder.use_keyed_mutex_) { void* keyed_mutex = nullptr; EGLBoolean ret = @@ -313,14 +382,7 @@ use_rgb_(true) {} PbufferPictureBuffer::~PbufferPictureBuffer() { - if (decoding_surface_) { - EGLDisplay egl_display = gl::GLSurfaceEGL::GetHardwareDisplay(); - - eglReleaseTexImage(egl_display, decoding_surface_, EGL_BACK_BUFFER); - - eglDestroySurface(egl_display, decoding_surface_); - decoding_surface_ = NULL; - } + // decoding_surface_ will be deleted by gl_image_. } bool PbufferPictureBuffer::ReusePictureBuffer() { @@ -344,11 +406,7 @@ : DXVAPictureBuffer(buffer), stream_(nullptr) {} EGLStreamPictureBuffer::~EGLStreamPictureBuffer() { - if (stream_) { - EGLDisplay egl_display = gl::GLSurfaceEGL::GetHardwareDisplay(); - eglDestroyStreamKHR(egl_display, stream_); - stream_ = nullptr; - } + // stream_ will be deleted by gl_image_. } bool EGLStreamPictureBuffer::Initialize() { @@ -365,6 +423,7 @@ }; stream_ = eglCreateStreamKHR(egl_display, stream_attributes); RETURN_ON_FAILURE(!!stream_, "Could not create stream", false); + gl_image_ = make_scoped_refptr(new GLImageEGLStream(size(), stream_)); gl::ScopedActiveTexture texture0(GL_TEXTURE0); gl::ScopedTextureBinder texture0_binder( GL_TEXTURE_EXTERNAL_OES, picture_buffer_.service_texture_ids()[0]); @@ -453,11 +512,7 @@ : DXVAPictureBuffer(buffer), stream_(nullptr) {} EGLStreamCopyPictureBuffer::~EGLStreamCopyPictureBuffer() { - if (stream_) { - EGLDisplay egl_display = gl::GLSurfaceEGL::GetHardwareDisplay(); - eglDestroyStreamKHR(egl_display, stream_); - stream_ = nullptr; - } + // stream_ will be deleted by gl_image_. } bool EGLStreamCopyPictureBuffer::Initialize( @@ -475,6 +530,7 @@ }; stream_ = eglCreateStreamKHR(egl_display, stream_attributes); RETURN_ON_FAILURE(!!stream_, "Could not create stream", false); + gl_image_ = make_scoped_refptr(new GLImageEGLStream(size(), stream_)); gl::ScopedActiveTexture texture0(GL_TEXTURE0); gl::ScopedTextureBinder texture0_binder( GL_TEXTURE_EXTERNAL_OES, picture_buffer_.service_texture_ids()[0]);
diff --git a/media/gpu/dxva_picture_buffer_win.h b/media/gpu/dxva_picture_buffer_win.h index da658a9..959504f 100644 --- a/media/gpu/dxva_picture_buffer_win.h +++ b/media/gpu/dxva_picture_buffer_win.h
@@ -17,6 +17,7 @@ #include "third_party/angle/include/EGL/egl.h" #include "third_party/angle/include/EGL/eglext.h" #include "ui/gl/gl_fence.h" +#include "ui/gl/gl_image.h" interface IMFSample; @@ -53,6 +54,8 @@ gfx::Size size() const { return picture_buffer_.size(); } void set_bound(); + scoped_refptr<gl::GLImage> gl_image() { return gl_image_; } + const gfx::ColorSpace& color_space() const { return color_space_; } void set_color_space(const gfx::ColorSpace& color_space) { color_space_ = color_space; @@ -73,6 +76,7 @@ State state_ = UNUSED; PictureBuffer picture_buffer_; gfx::ColorSpace color_space_; + scoped_refptr<gl::GLImage> gl_image_; DISALLOW_COPY_AND_ASSIGN(DXVAPictureBuffer); };
diff --git a/media/gpu/dxva_video_decode_accelerator_win.cc b/media/gpu/dxva_video_decode_accelerator_win.cc index e368dd3..6297e26 100644 --- a/media/gpu/dxva_video_decode_accelerator_win.cc +++ b/media/gpu/dxva_video_decode_accelerator_win.cc
@@ -486,6 +486,7 @@ DXVAVideoDecodeAccelerator::DXVAVideoDecodeAccelerator( const GetGLContextCallback& get_gl_context_cb, const MakeGLContextCurrentCallback& make_context_current_cb, + const BindGLImageCallback& bind_image_cb, const gpu::GpuDriverBugWorkarounds& workarounds, const gpu::GpuPreferences& gpu_preferences) : client_(NULL), @@ -498,6 +499,7 @@ sent_drain_message_(false), get_gl_context_cb_(get_gl_context_cb), make_context_current_cb_(make_context_current_cb), + bind_image_cb_(bind_image_cb), codec_(kUnknownVideoCodec), decoder_thread_("DXVAVideoDecoderThread"), pending_flush_(false), @@ -869,7 +871,7 @@ RETURN_AND_NOTIFY_ON_FAILURE((state != kUninitialized), "Invalid state: " << state, ILLEGAL_STATE, ); RETURN_AND_NOTIFY_ON_FAILURE( - (kNumPictureBuffers >= buffers.size()), + (kNumPictureBuffers <= buffers.size()), "Failed to provide requested picture buffers. (Got " << buffers.size() << ", requested " << kNumPictureBuffers << ")", INVALID_ARGUMENT, ); @@ -885,6 +887,15 @@ RETURN_AND_NOTIFY_ON_FAILURE(picture_buffer.get(), "Failed to allocate picture buffer", PLATFORM_FAILURE, ); + if (bind_image_cb_) { + for (uint32_t client_id : buffers[buffer_index].client_texture_ids()) { + // The picture buffer handles the actual binding of its contents to + // texture ids. This call just causes the texture manager to hold a + // reference to the GLImage as long as either texture exists. + bind_image_cb_.Run(client_id, GetTextureTarget(), + picture_buffer->gl_image(), true); + } + } bool inserted = output_picture_buffers_ @@ -1936,7 +1947,7 @@ kNumPictureBuffers, provide_nv12_textures ? PIXEL_FORMAT_NV12 : PIXEL_FORMAT_UNKNOWN, provide_nv12_textures ? 2 : 1, gfx::Size(width, height), - provide_nv12_textures ? GL_TEXTURE_EXTERNAL_OES : GL_TEXTURE_2D); + GetTextureTarget()); } } @@ -2226,7 +2237,7 @@ } void DXVAVideoDecodeAccelerator::StartDecoderThread() { - decoder_thread_.init_com_with_mta(false); + decoder_thread_.init_com_with_mta(true); decoder_thread_.Start(); decoder_thread_task_runner_ = decoder_thread_.task_runner(); } @@ -2749,4 +2760,9 @@ base::Unretained(this))); } +uint32_t DXVAVideoDecodeAccelerator::GetTextureTarget() const { + bool provide_nv12_textures = share_nv12_textures_ || copy_nv12_textures_; + return provide_nv12_textures ? GL_TEXTURE_EXTERNAL_OES : GL_TEXTURE_2D; +} + } // namespace media
diff --git a/media/gpu/dxva_video_decode_accelerator_win.h b/media/gpu/dxva_video_decode_accelerator_win.h index fbcf804..f320ec9 100644 --- a/media/gpu/dxva_video_decode_accelerator_win.h +++ b/media/gpu/dxva_video_decode_accelerator_win.h
@@ -116,6 +116,7 @@ DXVAVideoDecodeAccelerator( const GetGLContextCallback& get_gl_context_cb, const MakeGLContextCurrentCallback& make_context_current_cb, + const BindGLImageCallback& bind_image_cb, const gpu::GpuDriverBugWorkarounds& workarounds, const gpu::GpuPreferences& gpu_preferences); ~DXVAVideoDecodeAccelerator() override; @@ -359,6 +360,8 @@ // decoder here. void ConfigChanged(const Config& config); + uint32_t GetTextureTarget() const; + // To expose client callbacks from VideoDecodeAccelerator. VideoDecodeAccelerator::Client* client_; @@ -453,6 +456,7 @@ GetGLContextCallback get_gl_context_cb_; // Callback to set the correct gl context. MakeGLContextCurrentCallback make_context_current_cb_; + BindGLImageCallback bind_image_cb_; // Which codec we are decoding with hardware acceleration. VideoCodec codec_;
diff --git a/media/gpu/gpu_video_decode_accelerator_factory.cc b/media/gpu/gpu_video_decode_accelerator_factory.cc index 28bd65e5..a7db56f5 100644 --- a/media/gpu/gpu_video_decode_accelerator_factory.cc +++ b/media/gpu/gpu_video_decode_accelerator_factory.cc
@@ -161,9 +161,9 @@ std::unique_ptr<VideoDecodeAccelerator> decoder; if (base::win::GetVersion() >= base::win::VERSION_WIN7) { DVLOG(0) << "Initializing DXVA HW decoder for windows."; - decoder.reset(new DXVAVideoDecodeAccelerator(get_gl_context_cb_, - make_context_current_cb_, - workarounds, gpu_preferences)); + decoder.reset(new DXVAVideoDecodeAccelerator( + get_gl_context_cb_, make_context_current_cb_, bind_image_cb_, + workarounds, gpu_preferences)); } return decoder; }
diff --git a/media/gpu/ipc/service/gpu_video_decode_accelerator.cc b/media/gpu/ipc/service/gpu_video_decode_accelerator.cc index bfd03924d..d6d18b1 100644 --- a/media/gpu/ipc/service/gpu_video_decode_accelerator.cc +++ b/media/gpu/ipc/service/gpu_video_decode_accelerator.cc
@@ -58,7 +58,8 @@ return true; } -#if (defined(OS_CHROMEOS) && defined(ARCH_CPU_X86_FAMILY)) || defined(OS_MACOSX) +#if (defined(OS_CHROMEOS) && defined(ARCH_CPU_X86_FAMILY)) || \ + defined(OS_MACOSX) || defined(OS_WIN) static bool BindImage(const base::WeakPtr<gpu::GpuCommandBufferStub>& stub, uint32_t client_texture_id, uint32_t texture_target, @@ -171,7 +172,8 @@ get_gl_context_cb_ = base::Bind(&GetGLContext, stub_->AsWeakPtr()); make_context_current_cb_ = base::Bind(&MakeDecoderContextCurrent, stub_->AsWeakPtr()); -#if (defined(OS_CHROMEOS) && defined(ARCH_CPU_X86_FAMILY)) || defined(OS_MACOSX) +#if (defined(OS_CHROMEOS) && defined(ARCH_CPU_X86_FAMILY)) || \ + defined(OS_MACOSX) || defined(OS_WIN) bind_image_cb_ = base::Bind(&BindImage, stub_->AsWeakPtr()); #endif get_gles2_decoder_cb_ = base::Bind(&GetGLES2Decoder, stub_->AsWeakPtr());
diff --git a/media/gpu/rendering_helper.cc b/media/gpu/rendering_helper.cc index 0625ea6..ecf79806 100644 --- a/media/gpu/rendering_helper.cc +++ b/media/gpu/rendering_helper.cc
@@ -213,16 +213,7 @@ } void RenderingHelper::Setup() { -#if defined(OS_WIN) - window_ = CreateWindowEx(0, - L"Static", - L"VideoDecodeAcceleratorTest", - WS_OVERLAPPEDWINDOW | WS_VISIBLE, - 0, 0, - GetSystemMetrics(SM_CXSCREEN), - GetSystemMetrics(SM_CYSCREEN), - NULL, NULL, NULL, NULL); -#elif defined(USE_X11) +#if defined(USE_X11) Display* display = gfx::GetXDisplay(); Screen* screen = DefaultScreenOfDisplay(display); @@ -296,17 +287,13 @@ // wait for the window to resized and therefore associated with // display output to be sure that we will get such events. wait_window_resize.RunUntilIdle(); -#else +#elif !defined(OS_WIN) #error unknown platform #endif - CHECK(window_ != gfx::kNullAcceleratedWidget); } void RenderingHelper::TearDown() { -#if defined(OS_WIN) - if (window_) - DestroyWindow(window_); -#elif defined(USE_X11) +#if defined(USE_X11) // Destroy resources acquired in Initialize, in reverse-acquisition order. if (window_) { CHECK(XUnmapWindow(gfx::GetXDisplay(), window_)); @@ -324,6 +311,13 @@ void RenderingHelper::Initialize(const RenderingHelperParams& params, base::WaitableEvent* done) { +#if defined(OS_WIN) + window_ = CreateWindowEx( + 0, L"Static", L"VideoDecodeAcceleratorTest", + WS_OVERLAPPEDWINDOW | WS_VISIBLE, 0, 0, GetSystemMetrics(SM_CXSCREEN), + GetSystemMetrics(SM_CYSCREEN), NULL, NULL, NULL, NULL); +#endif + CHECK(window_ != gfx::kNullAcceleratedWidget); // Use videos_.size() != 0 as a proxy for the class having already been // Initialize()'d, and UnInitialize() before continuing. if (videos_.size()) { @@ -419,7 +413,7 @@ gl_Position = in_pos; }); -#if GL_VARIANT_EGL +#if GL_VARIANT_EGL && !defined(OS_WIN) static const char kFragmentShader[] = "#extension GL_OES_EGL_image_external : enable\n" "precision mediump float;\n" @@ -437,11 +431,14 @@ "}\n"; #else static const char kFragmentShader[] = - STRINGIZE(varying vec2 interp_tc; - uniform sampler2D tex; - void main() { - gl_FragColor = texture2D(tex, interp_tc); - }); + "#ifdef GL_ES\n" + "precision mediump float;\n" + "#endif\n" + "varying vec2 interp_tc;\n" + "uniform sampler2D tex;\n" + "void main() {\n" + " gl_FragColor = texture2D(tex, interp_tc);\n" + "}\n"; #endif program_ = glCreateProgram(); CreateShader(program_, GL_VERTEX_SHADER, kVertexShader, @@ -554,6 +551,13 @@ gl_surface_ = NULL; Clear(); + +#if defined(OS_WIN) + if (window_) + DestroyWindow(window_); + window_ = gfx::kNullAcceleratedWidget; +#endif + done->Signal(); }
diff --git a/media/gpu/video_decode_accelerator_unittest.cc b/media/gpu/video_decode_accelerator_unittest.cc index 305872d33..d76bc61 100644 --- a/media/gpu/video_decode_accelerator_unittest.cc +++ b/media/gpu/video_decode_accelerator_unittest.cc
@@ -238,7 +238,11 @@ : rendering_thread_("GLRenderingVDAClientThread") {} void SetUp() override { - rendering_thread_.Start(); + base::Thread::Options options; +#if defined(OS_WIN) + options.message_loop_type = base::MessageLoop::TYPE_UI; +#endif + rendering_thread_.StartWithOptions(options); base::WaitableEvent done(base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED); @@ -1715,7 +1719,11 @@ int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); // Removes gtest-specific args. +#if defined(OS_WIN) + base::CommandLine::InitUsingArgvForTesting(argc, argv); +#else base::CommandLine::Init(argc, argv); +#endif // Needed to enable DVLOG through --vmodule. logging::LoggingSettings settings; @@ -1792,6 +1800,8 @@ #if defined(OS_CHROMEOS) && defined(ARCH_CPU_X86_FAMILY) media::VaapiWrapper::PreSandboxInitialization(); +#elif defined(OS_WIN) + media::DXVAVideoDecodeAccelerator::PreSandboxInitialization(); #endif media::g_env =
diff --git a/mojo/edk/embedder/embedder_unittest.cc b/mojo/edk/embedder/embedder_unittest.cc index f371f2a3..4521f80 100644 --- a/mojo/edk/embedder/embedder_unittest.cc +++ b/mojo/edk/embedder/embedder_unittest.cc
@@ -224,15 +224,7 @@ nullptr)); } -#if defined(OS_ANDROID) -// This test is suspected to be flaky on android https://crbug.com/663998. -#define MAYBE_PipeSetup_LaunchFailure \ - DISABLED_PipeSetup_LaunchFailure -#else -#define MAYBE_PipeSetup_LaunchFailure \ - PipeSetup_LaunchFailure -#endif -TEST_F(EmbedderTest, MAYBE_PipeSetup_LaunchFailure) { +TEST_F(EmbedderTest, PipeSetup_LaunchFailure) { PlatformChannelPair pair; std::string child_token = GenerateRandomToken();
diff --git a/mojo/edk/system/multiprocess_message_pipe_unittest.cc b/mojo/edk/system/multiprocess_message_pipe_unittest.cc index 897c6d9..011d8249 100644 --- a/mojo/edk/system/multiprocess_message_pipe_unittest.cc +++ b/mojo/edk/system/multiprocess_message_pipe_unittest.cc
@@ -875,9 +875,6 @@ CloseHandle(echo_proxy_c); } -#if !defined(OS_ANDROID) -// This test is suspected to be flaky on android https://crbug.com/663998 -// and thus disabled on android. TEST_P(MultiprocessMessagePipeTestWithPeerSupport, ChannelPipesWithMultipleChildren) { RUN_CHILD_ON_PIPE(ChannelEchoClient, a) @@ -890,7 +887,6 @@ END_CHILD() END_CHILD() } -#endif // Reads and turns a pipe handle some number of times to create lots of // transient proxies.
diff --git a/native_client_sdk/src/tests/nacl_io_test/fake_ppapi/fake_pepper_interface_url_loader.cc b/native_client_sdk/src/tests/nacl_io_test/fake_ppapi/fake_pepper_interface_url_loader.cc index e209e39..00ff725 100644 --- a/native_client_sdk/src/tests/nacl_io_test/fake_ppapi/fake_pepper_interface_url_loader.cc +++ b/native_client_sdk/src/tests/nacl_io_test/fake_ppapi/fake_pepper_interface_url_loader.cc
@@ -5,7 +5,6 @@ #include "fake_ppapi/fake_pepper_interface_url_loader.h" #include <string.h> -#include <strings.h> #include <algorithm> #include <sstream> @@ -17,38 +16,6 @@ namespace { -bool GetHeaderValue(const std::string& headers, - const std::string& key, - std::string* out_value) { - out_value->clear(); - - size_t offset = 0; - while (offset != std::string::npos) { - // Find the next colon; this separates the key from the value. - size_t colon = headers.find(':', offset); - if (colon == std::string::npos) - return false; - - // Find the newline; this separates the value from the next header. - size_t newline = headers.find('\n', offset); - if (strncasecmp(key.c_str(), &headers.data()[offset], key.size()) != 0) { - // Key doesn't match, skip to next header. - offset = newline; - continue; - } - - // Key matches, extract value. First, skip leading spaces. - size_t nonspace = headers.find_first_not_of(' ', colon + 1); - if (nonspace == std::string::npos) - return false; - - out_value->assign(headers, nonspace, newline - nonspace); - return true; - } - - return false; -} - class FakeInstanceResource : public FakeResource { public: FakeInstanceResource() : server_template(NULL) {} @@ -83,26 +50,6 @@ off_t read_end; }; -class FakeURLRequestInfoResource : public FakeResource { - public: - FakeURLRequestInfoResource() {} - static const char* classname() { return "FakeURLRequestInfoResource"; } - - std::string url; - std::string method; - std::string headers; -}; - -class FakeURLResponseInfoResource : public FakeResource { - public: - FakeURLResponseInfoResource() : status_code(0) {} - static const char* classname() { return "FakeURLResponseInfoResource"; } - - int status_code; - std::string url; - std::string headers; -}; - void HandleContentLength(FakeURLLoaderResource* loader, FakeURLResponseInfoResource* response, FakeURLLoaderEntity* entity) {
diff --git a/native_client_sdk/src/tests/nacl_io_test/fake_ppapi/fake_util.cc b/native_client_sdk/src/tests/nacl_io_test/fake_ppapi/fake_util.cc index c26c898..32b3251 100644 --- a/native_client_sdk/src/tests/nacl_io_test/fake_ppapi/fake_util.cc +++ b/native_client_sdk/src/tests/nacl_io_test/fake_ppapi/fake_util.cc
@@ -4,6 +4,10 @@ #include "fake_ppapi/fake_util.h" +#include <strings.h> + +#include <string> + #include <ppapi/c/pp_completion_callback.h> #include <ppapi/c/pp_errors.h> @@ -24,3 +28,35 @@ } return result; } + +bool GetHeaderValue(const std::string& headers, + const std::string& key, + std::string* out_value) { + out_value->clear(); + + size_t offset = 0; + while (offset != std::string::npos) { + // Find the next colon; this separates the key from the value. + size_t colon = headers.find(':', offset); + if (colon == std::string::npos) + return false; + + // Find the newline; this separates the value from the next header. + size_t newline = headers.find('\n', offset); + if (strncasecmp(key.c_str(), &headers.data()[offset], key.size()) != 0) { + // Key doesn't match, skip to next header. + offset = newline + 1; + continue; + } + + // Key matches, extract value. First, skip leading spaces. + size_t nonspace = headers.find_first_not_of(' ', colon + 1); + if (nonspace == std::string::npos) + return false; + + out_value->assign(headers, nonspace, newline - nonspace); + return true; + } + + return false; +}
diff --git a/native_client_sdk/src/tests/nacl_io_test/fake_ppapi/fake_util.h b/native_client_sdk/src/tests/nacl_io_test/fake_ppapi/fake_util.h index 6713988b..545d9e4d 100644 --- a/native_client_sdk/src/tests/nacl_io_test/fake_ppapi/fake_util.h +++ b/native_client_sdk/src/tests/nacl_io_test/fake_ppapi/fake_util.h
@@ -40,6 +40,29 @@ FakeFilesystem* filesystem_template; // Weak reference. }; +class FakeURLRequestInfoResource : public FakeResource { + public: + FakeURLRequestInfoResource() {} + static const char* classname() { return "FakeURLRequestInfoResource"; } + + std::string url; + std::string method; + std::string headers; +}; + +class FakeURLResponseInfoResource : public FakeResource { + public: + FakeURLResponseInfoResource() : status_code(0) {} + static const char* classname() { return "FakeURLResponseInfoResource"; } + + int status_code; + std::string url; + std::string headers; +}; + int32_t RunCompletionCallback(PP_CompletionCallback* callback, int32_t result); +bool GetHeaderValue(const std::string& headers, + const std::string& key, + std::string* out_value); #endif // LIBRARIES_NACL_IO_TEST_FAKE_UTIL_H_
diff --git a/net/base/registry_controlled_domains/registry_controlled_domain.cc b/net/base/registry_controlled_domains/registry_controlled_domain.cc index 493ea686..5af090a8 100644 --- a/net/base/registry_controlled_domains/registry_controlled_domain.cc +++ b/net/base/registry_controlled_domains/registry_controlled_domain.cc
@@ -329,23 +329,20 @@ const GURL& gurl1, const GURL& gurl2, PrivateRegistryFilter filter) { - // See if both URLs have a known domain + registry, and those values are the - // same. - const base::StringPiece domain1 = - GetDomainAndRegistryAsStringPiece(gurl1, filter); - const base::StringPiece domain2 = - GetDomainAndRegistryAsStringPiece(gurl2, filter); - if (!domain1.empty() || !domain2.empty()) - return domain1 == domain2; - - // No domains. See if the hosts are identical. - const url::Component host1 = gurl1.parsed_for_possibly_invalid_spec().host; - const url::Component host2 = gurl2.parsed_for_possibly_invalid_spec().host; - if ((host1.len <= 0) || (host1.len != host2.len)) + // Quickly reject cases where either host is empty. + if (!gurl1.has_host() || !gurl2.has_host()) return false; - return !strncmp(gurl1.possibly_invalid_spec().data() + host1.begin, - gurl2.possibly_invalid_spec().data() + host2.begin, - host1.len); + + // Check for exact host matches, which is faster than looking up the domain + // and registry. + if (gurl1.host_piece() == gurl2.host_piece()) + return true; + + // Check for a domain and registry match. + const base::StringPiece& domain1 = + GetDomainAndRegistryAsStringPiece(gurl1, filter); + return !domain1.empty() && + (domain1 == GetDomainAndRegistryAsStringPiece(gurl2, filter)); } bool SameDomainOrHost(const url::Origin& origin1,
diff --git a/net/base/registry_controlled_domains/registry_controlled_domain.h b/net/base/registry_controlled_domains/registry_controlled_domain.h index 9e631f6f1..429a577 100644 --- a/net/base/registry_controlled_domains/registry_controlled_domain.h +++ b/net/base/registry_controlled_domains/registry_controlled_domain.h
@@ -190,9 +190,9 @@ // These convenience functions return true if the two GURLs or Origins both have // hosts and one of the following is true: +// * The hosts are identical. // * They each have a known domain and registry, and it is the same for both // URLs. Note that this means the trailing dot, if any, must match too. -// * They don't have known domains/registries, but the hosts are identical. // Effectively, callers can use this function to check whether the input URLs // represent hosts "on the same site". NET_EXPORT bool SameDomainOrHost(const GURL& gurl1, const GURL& gurl2,
diff --git a/net/disk_cache/simple/simple_version_upgrade.cc b/net/disk_cache/simple/simple_version_upgrade.cc index 85a9ad96..1c4a7ba2 100644 --- a/net/disk_cache/simple/simple_version_upgrade.cc +++ b/net/disk_cache/simple/simple_version_upgrade.cc
@@ -149,7 +149,7 @@ if (!fake_index_file.IsValid()) { if (fake_index_file.error_details() == base::File::FILE_ERROR_NOT_FOUND) { - return WriteFakeIndexFile(fake_index, SimpleExperiment()); + return WriteFakeIndexFile(fake_index, experiment); } return false; }
diff --git a/net/disk_cache/simple/simple_version_upgrade_unittest.cc b/net/disk_cache/simple/simple_version_upgrade_unittest.cc index ec0ffb6..7fd85a3 100644 --- a/net/disk_cache/simple/simple_version_upgrade_unittest.cc +++ b/net/disk_cache/simple/simple_version_upgrade_unittest.cc
@@ -124,6 +124,33 @@ cache_dir.GetPath(), disk_cache::SimpleExperiment())); } +TEST(SimpleVersionUpgradeTest, ExperimentStoredInNewFakeIndex) { + base::ScopedTempDir cache_dir; + ASSERT_TRUE(cache_dir.CreateUniqueTempDir()); + const base::FilePath cache_path = cache_dir.GetPath(); + const base::FilePath file_name = cache_path.AppendASCII(kFakeIndexFileName); + + disk_cache::SimpleExperiment experiment; + experiment.type = disk_cache::SimpleExperimentType::SIZE; + experiment.param = 100u; + + // There is no index on disk, so the upgrade should write a new one and return + // true. + EXPECT_TRUE( + disk_cache::UpgradeSimpleCacheOnDisk(cache_dir.GetPath(), experiment)); + + std::string new_fake_index_contents; + ASSERT_TRUE(base::ReadFileToString(cache_path.AppendASCII(kFakeIndexFileName), + &new_fake_index_contents)); + const disk_cache::FakeIndexData* fake_index_header; + fake_index_header = reinterpret_cast<const disk_cache::FakeIndexData*>( + new_fake_index_contents.data()); + + EXPECT_EQ(disk_cache::SimpleExperimentType::SIZE, + fake_index_header->experiment_type); + EXPECT_EQ(100u, fake_index_header->experiment_param); +} + TEST(SimpleVersionUpgradeTest, FakeIndexVersionGetsUpdated) { base::ScopedTempDir cache_dir; ASSERT_TRUE(cache_dir.CreateUniqueTempDir());
diff --git a/net/http/http_stream_factory_impl_job_controller.cc b/net/http/http_stream_factory_impl_job_controller.cc index daff299..3fdc072 100644 --- a/net/http/http_stream_factory_impl_job_controller.cc +++ b/net/http/http_stream_factory_impl_job_controller.cc
@@ -852,13 +852,13 @@ if (alternative_service.protocol == UNINITIALIZED_ALTERNATE_PROTOCOL) { type = NO_ALTERNATIVE_SERVICE; } else if (alternative_service.protocol == QUIC) { - if (request_info.url.host() == alternative_service.host) { + if (request_info.url.host_piece() == alternative_service.host) { type = QUIC_SAME_DESTINATION; } else { type = QUIC_DIFFERENT_DESTINATION; } } else { - if (request_info.url.host() == alternative_service.host) { + if (request_info.url.host_piece() == alternative_service.host) { type = NOT_QUIC_SAME_DESTINATION; } else { type = NOT_QUIC_DIFFERENT_DESTINATION;
diff --git a/net/http/transport_security_state.cc b/net/http/transport_security_state.cc index afc5b93a..9b42feb 100644 --- a/net/http/transport_security_state.cc +++ b/net/http/transport_security_state.cc
@@ -815,7 +815,9 @@ return; } report_sender_->Send(expect_staple_state.report_uri, - "application/json; charset=utf-8", serialized_report); + "application/json; charset=utf-8", serialized_report, + base::Closure(), + base::Bind(RecordUMAForHPKPReportFailure)); } bool TransportSecurityState::HasPublicKeyPins(const std::string& host) { @@ -920,8 +922,6 @@ TransportSecurityState::ReportSenderInterface* report_sender) { DCHECK(CalledOnValidThread()); report_sender_ = report_sender; - if (report_sender_) - report_sender_->SetErrorCallback(base::Bind(RecordUMAForHPKPReportFailure)); } void TransportSecurityState::SetExpectCTReporter( @@ -1074,7 +1074,8 @@ base::TimeDelta::FromMinutes(kTimeToRememberHPKPReportsMins)); report_sender_->Send(pkp_state.report_uri, "application/json; charset=utf-8", - serialized_report); + serialized_report, base::Closure(), + base::Bind(RecordUMAForHPKPReportFailure)); return PKPStatus::VIOLATED; }
diff --git a/net/http/transport_security_state.h b/net/http/transport_security_state.h index d5116c7..fc40b7d 100644 --- a/net/http/transport_security_state.h +++ b/net/http/transport_security_state.h
@@ -256,12 +256,13 @@ // Sends the given serialized |report| to |report_uri| with // Content-Type header as specified in // |content_type|. |content_type| should be non-empty. - virtual void Send(const GURL& report_uri, - base::StringPiece content_type, - base::StringPiece report) = 0; - - // Sets a callback to be called when report sending fails. - virtual void SetErrorCallback( + // |report_id| could be any non-negative integer. It's passed back to the + // error or success callbacks. + virtual void Send( + const GURL& report_uri, + base::StringPiece content_type, + base::StringPiece report, + const base::Callback<void()>& success_callback, const base::Callback<void(const GURL&, int)>& error_callback) = 0; protected:
diff --git a/net/http/transport_security_state_unittest.cc b/net/http/transport_security_state_unittest.cc index 93b75f3..fcd2a16 100644 --- a/net/http/transport_security_state_unittest.cc +++ b/net/http/transport_security_state_unittest.cc
@@ -89,17 +89,17 @@ MockCertificateReportSender() {} ~MockCertificateReportSender() override {} - void Send(const GURL& report_uri, - base::StringPiece content_type, - base::StringPiece report) override { + void Send( + const GURL& report_uri, + base::StringPiece content_type, + base::StringPiece report, + const base::Callback<void()>& success_callback, + const base::Callback<void(const GURL&, int)>& error_callback) override { latest_report_uri_ = report_uri; report.CopyToString(&latest_report_); content_type.CopyToString(&latest_content_type_); } - void SetErrorCallback( - const base::Callback<void(const GURL&, int)>& error_callback) override {} - void Clear() { latest_report_uri_ = GURL(); latest_report_ = std::string(); @@ -126,21 +126,18 @@ int net_error() { return net_error_; } // TransportSecurityState::ReportSenderInterface: - void Send(const GURL& report_uri, - base::StringPiece content_type, - base::StringPiece report) override { - ASSERT_FALSE(error_callback_.is_null()); - error_callback_.Run(report_uri, net_error_); - } - - void SetErrorCallback( + void Send( + const GURL& report_uri, + base::StringPiece content_type, + base::StringPiece report, + const base::Callback<void()>& success_callback, const base::Callback<void(const GURL&, int)>& error_callback) override { - error_callback_ = error_callback; + ASSERT_FALSE(error_callback.is_null()); + error_callback.Run(report_uri, net_error_); } private: const int net_error_; - base::Callback<void(const GURL&, int)> error_callback_; }; // A mock ExpectCTReporter that remembers the latest violation that was
diff --git a/net/net.gypi b/net/net.gypi index f34bff2..80dd53f 100644 --- a/net/net.gypi +++ b/net/net.gypi
@@ -886,6 +886,8 @@ 'quic/chromium/quic_chromium_packet_reader.h', 'quic/chromium/quic_chromium_packet_writer.cc', 'quic/chromium/quic_chromium_packet_writer.h', + 'quic/chromium/quic_clock_skew_detector.h', + 'quic/chromium/quic_clock_skew_detector.cc', 'quic/chromium/quic_connection_logger.cc', 'quic/chromium/quic_connection_logger.h', 'quic/chromium/quic_utils_chromium.h', @@ -1219,6 +1221,8 @@ 'spdy/spdy_framer_decoder_adapter.h', 'spdy/spdy_header_block.cc', 'spdy/spdy_header_block.h', + 'spdy/spdy_header_indexing.cc', + 'spdy/spdy_header_indexing.h', 'spdy/spdy_headers_block_parser.cc', 'spdy/spdy_headers_block_parser.h', 'spdy/spdy_headers_handler_interface.h', @@ -1662,6 +1666,7 @@ 'quic/chromium/quic_chromium_client_session_test.cc', 'quic/chromium/quic_chromium_client_stream_test.cc', 'quic/chromium/quic_chromium_connection_helper_test.cc', + 'quic/chromium/quic_clock_skew_detector_test.cc', 'quic/chromium/quic_end_to_end_unittest.cc', 'quic/chromium/quic_http_stream_test.cc', 'quic/chromium/quic_network_transaction_unittest.cc', @@ -1900,6 +1905,7 @@ 'spdy/spdy_frame_reader_test.cc', 'spdy/spdy_framer_test.cc', 'spdy/spdy_header_block_test.cc', + 'spdy/spdy_header_indexing_test.cc', 'spdy/spdy_headers_block_parser_test.cc', 'spdy/spdy_http_stream_unittest.cc', 'spdy/spdy_http_utils_unittest.cc',
diff --git a/net/quic/chromium/quic_clock_skew_detector.cc b/net/quic/chromium/quic_clock_skew_detector.cc new file mode 100644 index 0000000..efd372e --- /dev/null +++ b/net/quic/chromium/quic_clock_skew_detector.cc
@@ -0,0 +1,33 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/chromium/quic_clock_skew_detector.h" + +#include "base/metrics/histogram_macros.h" + +namespace net { + +QuicClockSkewDetector::QuicClockSkewDetector(base::TimeTicks ticks_time, + base::Time wall_time) + : last_ticks_time_(ticks_time), last_wall_time_(wall_time) {} + +bool QuicClockSkewDetector::ClockSkewDetected(base::TimeTicks ticks_now, + base::Time wall_now) { + base::TimeDelta ticks_delta = ticks_now - last_ticks_time_; + base::TimeDelta wall_delta = wall_now - last_wall_time_; + base::TimeDelta offset = wall_delta - ticks_delta; + last_wall_time_ = wall_now; + last_ticks_time_ = ticks_now; + + UMA_HISTOGRAM_TIMES( + "Net.QuicClock.SkewOffset", + base::TimeDelta::FromMicroseconds(offset.InMicroseconds())); + + if (offset < base::TimeDelta::FromSeconds(1)) + return false; + + return true; +} + +} // namespace net
diff --git a/net/quic/chromium/quic_clock_skew_detector.h b/net/quic/chromium/quic_clock_skew_detector.h new file mode 100644 index 0000000..1cc26f8 --- /dev/null +++ b/net/quic/chromium/quic_clock_skew_detector.h
@@ -0,0 +1,30 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_CHROMIUM_QUIC_CLOCK_SKEW_DETECTOR_H_ +#define NET_QUIC_CHROMIUM_QUIC_CLOCK_SKEW_DETECTOR_H_ + +#include "base/time/time.h" +#include "net/base/net_export.h" + +namespace net { + +class NET_EXPORT_PRIVATE QuicClockSkewDetector { + public: + QuicClockSkewDetector(base::TimeTicks ticks_time, base::Time wall_time); + + // Returns true if the delta between |wall_now| and |last_wall_time_| is + // more than one second larger than the delta between |ticks_now| and + // |last_ticks_time_|. Updates |last_ticks_time_| and |last_wall_time_|. + bool ClockSkewDetected(base::TimeTicks ticks_now, base::Time wall_now); + + private: + // Clock skew detection members + base::TimeTicks last_ticks_time_; + base::Time last_wall_time_; +}; + +} // namespace net + +#endif // NET_QUIC_CHROMIUM_QUIC_CLOCK_SKEW_DETECTOR_H_
diff --git a/net/quic/chromium/quic_clock_skew_detector_test.cc b/net/quic/chromium/quic_clock_skew_detector_test.cc new file mode 100644 index 0000000..1aca24e6 --- /dev/null +++ b/net/quic/chromium/quic_clock_skew_detector_test.cc
@@ -0,0 +1,69 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/chromium/quic_clock_skew_detector.h" + +#include "net/quic/test_tools/mock_clock.h" +#include "net/quic/test_tools/mock_random.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { +namespace test { +namespace { + +class QuicClockSkewDetectorTest : public ::testing::Test { + protected: + QuicClockSkewDetectorTest() + : start_ticks_time_(base::TimeTicks::Now()), + start_wall_time_(base::Time::Now()), + detector_(start_ticks_time_, start_wall_time_) {} + + base::TimeTicks start_ticks_time_; + base::Time start_wall_time_; + QuicClockSkewDetector detector_; +}; + +TEST_F(QuicClockSkewDetectorTest, NoChange) { + EXPECT_FALSE( + detector_.ClockSkewDetected(start_ticks_time_, start_wall_time_)); +} + +TEST_F(QuicClockSkewDetectorTest, NoOffset) { + base::TimeDelta delta = base::TimeDelta::FromSeconds(57); + EXPECT_FALSE(detector_.ClockSkewDetected(start_ticks_time_ + delta, + start_wall_time_ + delta)); +} + +TEST_F(QuicClockSkewDetectorTest, SmallOffset) { + base::TimeDelta delta = base::TimeDelta::FromMilliseconds(57); + EXPECT_FALSE( + detector_.ClockSkewDetected(start_ticks_time_, start_wall_time_ + delta)); +} + +TEST_F(QuicClockSkewDetectorTest, ManySmallOffset) { + for (int i = 0; i < 10; ++i) { + base::TimeDelta delta = base::TimeDelta::FromMilliseconds(500); + EXPECT_FALSE(detector_.ClockSkewDetected(start_ticks_time_, + start_wall_time_ + i * delta)); + } +} + +TEST_F(QuicClockSkewDetectorTest, LargeOffset) { + base::TimeDelta delta = base::TimeDelta::FromMilliseconds(1001); + EXPECT_TRUE( + detector_.ClockSkewDetected(start_ticks_time_, start_wall_time_ + delta)); +} + +TEST_F(QuicClockSkewDetectorTest, LargeOffsetThenSmallOffset) { + base::TimeDelta delta = base::TimeDelta::FromMilliseconds(1001); + EXPECT_TRUE( + detector_.ClockSkewDetected(start_ticks_time_, start_wall_time_ + delta)); + base::TimeDelta small_delta = base::TimeDelta::FromMilliseconds(571001); + EXPECT_FALSE(detector_.ClockSkewDetected( + start_ticks_time_ + small_delta, start_wall_time_ + delta + small_delta)); +} + +} // namespace +} // namespace test +} // namespace net
diff --git a/net/quic/chromium/quic_stream_factory.cc b/net/quic/chromium/quic_stream_factory.cc index 339ea7e..1e283f52 100644 --- a/net/quic/chromium/quic_stream_factory.cc +++ b/net/quic/chromium/quic_stream_factory.cc
@@ -753,6 +753,7 @@ random_generator_(random_generator), clock_(clock), max_packet_length_(max_packet_length), + clock_skew_detector_(base::TimeTicks::Now(), base::Time::Now()), socket_performance_watcher_factory_(socket_performance_watcher_factory), config_(InitializeQuicConfig(connection_options, idle_connection_timeout_seconds)), @@ -925,6 +926,14 @@ base::StringPiece method, const NetLogWithSource& net_log, QuicStreamRequest* request) { + if (clock_skew_detector_.ClockSkewDetected(base::TimeTicks::Now(), + base::Time::Now())) { + while (!active_sessions_.empty()) { + QuicChromiumClientSession* session = active_sessions_.begin()->second; + OnSessionGoingAway(session); + // TODO(rch): actually close the session? + } + } DCHECK(server_id.host_port_pair().Equals(HostPortPair::FromURL(url))); // Enforce session affinity for promised streams. QuicClientPromisedInfo* promised =
diff --git a/net/quic/chromium/quic_stream_factory.h b/net/quic/chromium/quic_stream_factory.h index 6daaeb85..afe0836 100644 --- a/net/quic/chromium/quic_stream_factory.h +++ b/net/quic/chromium/quic_stream_factory.h
@@ -32,6 +32,7 @@ #include "net/proxy/proxy_server.h" #include "net/quic/chromium/network_connection.h" #include "net/quic/chromium/quic_chromium_client_session.h" +#include "net/quic/chromium/quic_clock_skew_detector.h" #include "net/quic/chromium/quic_http_stream.h" #include "net/quic/core/quic_client_push_promise_index.h" #include "net/quic/core/quic_config.h" @@ -509,6 +510,7 @@ QuicRandom* random_generator_; std::unique_ptr<QuicClock> clock_; const size_t max_packet_length_; + QuicClockSkewDetector clock_skew_detector_; // Factory which is used to create socket performance watcher. A new watcher // is created for every QUIC connection.
diff --git a/net/quic/core/quic_client_session_base.h b/net/quic/core/quic_client_session_base.h index f4024e2..32d1ba8 100644 --- a/net/quic/core/quic_client_session_base.h +++ b/net/quic/core/quic_client_session_base.h
@@ -122,7 +122,7 @@ std::unordered_map<QuicStreamId, std::unique_ptr<QuicClientPromisedInfo>>; // As per rfc7540, section 10.5: track promise streams in "reserved - // (remote)". The primary key is URL from he promise request + // (remote)". The primary key is URL from the promise request // headers. The promised stream id is a secondary key used to get // promise info when the response headers of the promised stream // arrive.
diff --git a/net/quic/core/quic_server_id.cc b/net/quic/core/quic_server_id.cc index 9bcf84c..ecc8d0e40 100644 --- a/net/quic/core/quic_server_id.cc +++ b/net/quic/core/quic_server_id.cc
@@ -46,7 +46,7 @@ GURL url(str); if (!url.is_valid()) return QuicServerId(); - return QuicServerId(HostPortPair::FromURL(url), url.path() == "/private" + return QuicServerId(HostPortPair::FromURL(url), url.path_piece() == "/private" ? PRIVACY_MODE_ENABLED : PRIVACY_MODE_DISABLED); }
diff --git a/net/quic/core/quic_session.cc b/net/quic/core/quic_session.cc index bcd29c8..c3c6688 100644 --- a/net/quic/core/quic_session.cc +++ b/net/quic/core/quic_session.cc
@@ -13,7 +13,6 @@ #include "net/quic/core/quic_connection.h" #include "net/quic/core/quic_flags.h" #include "net/quic/core/quic_flow_controller.h" -#include "net/ssl/ssl_info.h" using base::IntToString; using base::StringPiece;
diff --git a/net/spdy/spdy_alt_svc_wire_format.cc b/net/spdy/spdy_alt_svc_wire_format.cc index 38c8fdd..e94b4fa7 100644 --- a/net/spdy/spdy_alt_svc_wire_format.cc +++ b/net/spdy/spdy_alt_svc_wire_format.cc
@@ -303,20 +303,39 @@ std::string* host, uint16_t* port) { host->clear(); - for (; c != end && *c != ':'; ++c) { - if (*c == '"') { - // Port is mandatory. - return false; - } - if (*c == '\\') { - ++c; - if (c == end) { + if (c == end) { + return false; + } + if (*c == '[') { + for (; c != end && *c != ']'; ++c) { + if (*c == '"') { + // Port is mandatory. return false; } + host->push_back(*c); } + if (c == end) { + return false; + } + DCHECK_EQ(']', *c); host->push_back(*c); + ++c; + } else { + for (; c != end && *c != ':'; ++c) { + if (*c == '"') { + // Port is mandatory. + return false; + } + if (*c == '\\') { + ++c; + if (c == end) { + return false; + } + } + host->push_back(*c); + } } - if (c == end) { + if (c == end || *c != ':') { return false; } DCHECK_EQ(':', *c);
diff --git a/net/spdy/spdy_alt_svc_wire_format_test.cc b/net/spdy/spdy_alt_svc_wire_format_test.cc index e07c622..9b559b5 100644 --- a/net/spdy/spdy_alt_svc_wire_format_test.cc +++ b/net/spdy/spdy_alt_svc_wire_format_test.cc
@@ -429,14 +429,33 @@ input.begin(), input.end(), &host, &port)); EXPECT_EQ("foo", host); EXPECT_EQ(137, port); + + input = StringPiece("[2003:8:0:16::509d:9615]:443"); + ASSERT_TRUE(test::SpdyAltSvcWireFormatPeer::ParseAltAuthority( + input.begin(), input.end(), &host, &port)); + EXPECT_EQ("[2003:8:0:16::509d:9615]", host); + EXPECT_EQ(443, port); } // Test ParseAltAuthority() on invalid input: empty string, no port, zero port, // non-digit characters following port. TEST(SpdyAltSvcWireFormatTest, ParseAltAuthorityInvalid) { - const char* invalid_input_array[] = {"", ":", "foo:", ":bar", - ":0", "foo:0", ":12bar", "foo:23bar", - " ", ":12 ", "foo:12 "}; + const char* invalid_input_array[] = {"", + ":", + "foo:", + ":bar", + ":0", + "foo:0", + ":12bar", + "foo:23bar", + " ", + ":12 ", + "foo:12 ", + "[2003:8:0:16::509d:9615]", + "[2003:8:0:16::509d:9615]:", + "[2003:8:0:16::509d:9615]foo:443", + "[2003:8:0:16::509d:9615:443", + "2003:8:0:16::509d:9615]:443"}; for (const char* invalid_input : invalid_input_array) { StringPiece input(invalid_input); std::string host; @@ -514,6 +533,22 @@ input.begin(), input.end(), &value32)); } +// Test parsing an Alt-Svc entry with IP literal hostname. +// Regression test for https://crbug.com/664173. +TEST(SpdyAltSvcWireFormatTest, ParseIPLiteral) { + const char* input = + "quic=\"[2003:8:0:16::509d:9615]:443\"; v=\"36,35\"; ma=60"; + SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; + ASSERT_TRUE( + SpdyAltSvcWireFormat::ParseHeaderFieldValue(input, &altsvc_vector)); + EXPECT_EQ(1u, altsvc_vector.size()); + EXPECT_EQ("quic", altsvc_vector[0].protocol_id); + EXPECT_EQ("[2003:8:0:16::509d:9615]", altsvc_vector[0].host); + EXPECT_EQ(443u, altsvc_vector[0].port); + EXPECT_EQ(60u, altsvc_vector[0].max_age); + EXPECT_THAT(altsvc_vector[0].version, ::testing::ElementsAre(36, 35)); +} + } // namespace } // namespace net
diff --git a/net/spdy/spdy_header_indexing.cc b/net/spdy/spdy_header_indexing.cc new file mode 100644 index 0000000..8b4a64de --- /dev/null +++ b/net/spdy/spdy_header_indexing.cc
@@ -0,0 +1,174 @@ +// Copyright (c) 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/spdy/spdy_header_indexing.h" + +#include "net/spdy/spdy_bug_tracker.h" + +using base::StringPiece; + +namespace net { + +int32_t FLAGS_gfe_spdy_indexing_set_bound = 300; +int32_t FLAGS_gfe_spdy_tracking_set_bound = 2000; + +HeaderIndexing::HeaderIndexing() + : indexing_set_bound_(FLAGS_gfe_spdy_indexing_set_bound), + tracking_set_bound_(FLAGS_gfe_spdy_tracking_set_bound) { + SPDY_BUG_IF(indexing_set_bound_ >= tracking_set_bound_) + << "Tracking set should be larger than indexing set"; +} + +HeaderIndexing::~HeaderIndexing() {} + +void HeaderIndexing::CreateInitIndexingHeaders() { + const std::string initial_fields[] = { + // Estimated top 100 fields. + "alt-svc", + "date", + "cache-control", + "content-type", + "expires", + "location", + "x-xss-protection", + "p3p", + "set-cookie", + "alternate-protocol", + "last-modified", + "server", + "x-snapchat-request-id", + "content-disposition", + "strict-transport-security", + "x-content-type-options", + "content-security-policy", + "x-frame-options", + "x-snapchat-notice", + "pragma", + ":status", + "content-length", + "etag", + "x-cloud-trace-context", + "vary", + "access-control-expose-headers", + "content-encoding", + "access-control-allow-origin", + "age", + ":protocol", + "via", + "x-robots-tag", + "link", + "access-control-allow-headers", + "x-google-session-info", + "x-google-backends", + "x-google-gfe-request-trace", + "warning", + "x-guploader-uploadid", + "x-cup-server-proof", + "timing-allow-origin", + "x-google-trace", + "access-control-allow-credentials", + "google-delayed-impression", + "google-creative-id", + "access-control-allow-methods", + "x-ua-compatible", + "x-google-gfe-response-code-details-trace", + "google-lineitem-id", + "version", + "x-google-dos-service-trace", + "x-google-service", + "x-google-gfe-service-trace", + "sane-time-millis", + "x-google-netmon-label", + "x-google-apiary-auth-scopes", + "x-seed-signature", + "content-security-policy-report-only", + "x-auto-login", + "x-original-content-length", + "accept-ranges", + "x-goog-hash", + "x-google-gfe-response-body-transformations", + "cf-ray", + "x-content-security-policy-report-only", + "x-google-shellfish-status", + "x-amz-id-2", + "get-dictionary", + "grpc-message", + "x-hw", + "x-google-gfe-backend-request-info", + "x-goog-upload-header-x-google-session-info", + "x-amz-cf-id", + "x-powered-by", + "www-authenticate", + "access-control-max-age", + "x-spf-response-type", + "x-goog-meta-encoded_request", + "x-goog-generation", + "x-google-gslb-service", + "x-google-servertype", + "x-cache", + "x-chromium-appcache-fallback-override", + "x-goog-upload-url", + "x-goog-upload-control-url", + "content-range", + "x-seen-by", + "x-google-apps-framework-action", + "content-location", + "x-daystart", + "x-varnish", + "fastly-debug-digest", + "x-daynum", + "x-goog-stored-content-encoding", + "x-goog-storage-class", + "x-google-cookies-blocked", + "x-range-md5", + "x-served-by", + "x-client-wire-protocol", + "content-language", + }; + + indexing_set_.clear(); + indexing_set_ = + HeaderSet(initial_fields, initial_fields + arraysize(initial_fields)); + tracking_set_ = + HeaderSet(initial_fields, initial_fields + arraysize(initial_fields)); +} + +bool HeaderIndexing::ShouldIndex(StringPiece header, StringPiece /* value */) { + if (header.empty()) { + return false; + } + // header is in indexing set. + std::string header_str(header.data(), header.size()); + if (indexing_set_.find(header_str) != indexing_set_.end()) { + return true; + } + // header not in indexing set. Check tracking set. + if (tracking_set_.find(header_str) != tracking_set_.end()) { + // Seen this header before. Add it to indexing set. + TryInsertHeader(std::move(header_str), &indexing_set_, indexing_set_bound_); + } else { + // Add header to tracking set. + TryInsertHeader(std::move(header_str), &tracking_set_, tracking_set_bound_); + } + return false; +} + +void HeaderIndexing::TryInsertHeader(std::string&& header, + HeaderSet* set, + size_t bound) { + std::pair<HeaderSet::iterator, bool> result = set->insert(std::move(header)); + if (set->size() > bound) { + // Reach the size limit. Remove the header next to the newly added header. + // If the new header is at the end, look for the "next" element at the + // beginning. + HeaderSet::iterator it = std::next(result.first); + if (it != set->end()) { + set->erase(it); + } else { + set->erase(set->begin()); + } + } +} + +} // namespace net
diff --git a/net/spdy/spdy_header_indexing.h b/net/spdy/spdy_header_indexing.h new file mode 100644 index 0000000..09507b9 --- /dev/null +++ b/net/spdy/spdy_header_indexing.h
@@ -0,0 +1,63 @@ +// Copyright (c) 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_SPDY_SPDY_HEADER_INDEXING_H_ +#define NET_SPDY_SPDY_HEADER_INDEXING_H_ + +#include <memory> +#include <string> +#include <unordered_set> +#include <utility> + +#include "base/strings/string_piece.h" +#include "net/base/net_export.h" + +namespace net { + +namespace test { +class HeaderIndexingPeer; +} + +NET_EXPORT_PRIVATE extern int32_t FLAGS_gfe_spdy_indexing_set_bound; +NET_EXPORT_PRIVATE extern int32_t FLAGS_gfe_spdy_tracking_set_bound; + +// Maintain two headers sets: Indexing set and tracking +// set. Call ShouldIndex() for each header to decide if to index it. If for some +// connections, we decide to index all headers, we may still want to call +// UpdateSets to log the headers into both sets. +class NET_EXPORT HeaderIndexing { + public: + using HeaderSet = std::unordered_set<std::string>; + + HeaderIndexing(); + ~HeaderIndexing(); + + void CreateInitIndexingHeaders(); + + // Decide if a header should be indexed. We only use |header|. Add |value| to + // be consistent with HPACK indexing policy interface. + bool ShouldIndex(base::StringPiece header, base::StringPiece value); + + // Not to make the indexing decision but to update sets. + void UpdateSets(base::StringPiece header, base::StringPiece value) { + ShouldIndex(header, value); + } + + // TODO(yasong): Add function to log statistic info. For example, cache hit + // and miss rate. + + private: + friend class test::HeaderIndexingPeer; + void TryInsertHeader(std::string&& header, HeaderSet* set, size_t bound); + // Headers to index. + HeaderSet indexing_set_; + // Headers seen so far. + HeaderSet tracking_set_; + const size_t indexing_set_bound_; + const size_t tracking_set_bound_; +}; + +} // namespace net + +#endif // NET_SPDY_SPDY_HEADER_INDEXING_H_
diff --git a/net/spdy/spdy_header_indexing_test.cc b/net/spdy/spdy_header_indexing_test.cc new file mode 100644 index 0000000..1efcd24 --- /dev/null +++ b/net/spdy/spdy_header_indexing_test.cc
@@ -0,0 +1,125 @@ +// Copyright (c) 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/spdy/spdy_header_indexing.h" + +#include "base/memory/ptr_util.h" +#include "base/strings/string_piece.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/platform_test.h" + +using base::StringPiece; + +namespace net { + +namespace test { + +class HeaderIndexingPeer { + public: + HeaderIndexingPeer() : hi_() {} + + void CreateTestInit() { + std::string input[] = {"key1", "key2", "key3"}; + hi_.indexing_set_ = + HeaderIndexing::HeaderSet(input, input + arraysize(input)); + hi_.tracking_set_ = + HeaderIndexing::HeaderSet(input, input + arraysize(input)); + } + + bool ShouldIndex(StringPiece header) { return hi_.ShouldIndex(header, ""); } + + void CreateInitIndexingHeaders() { hi_.CreateInitIndexingHeaders(); } + + void TryInsert(std::string&& header) { + hi_.TryInsertHeader(std::move(header), &(hi_.indexing_set_), + hi_.indexing_set_bound_); + } + + bool InTrackingSet(std::string str) { + return hi_.tracking_set_.find(str) != hi_.tracking_set_.end(); + } + + size_t indexing_set_size() const { return hi_.indexing_set_.size(); } + + size_t tracking_set_size() const { return hi_.tracking_set_.size(); } + + HeaderIndexing::HeaderSet* indexing_set() { return &(hi_.indexing_set_); } + + HeaderIndexing::HeaderSet* tracking_set() { return &(hi_.tracking_set_); } + + private: + HeaderIndexing hi_; +}; + +class SpdyHeaderIndexingTest : public ::testing::Test { + protected: + SpdyHeaderIndexingTest() { + FLAGS_gfe_spdy_indexing_set_bound = 3; + FLAGS_gfe_spdy_tracking_set_bound = 4; + hi_ = base::MakeUnique<HeaderIndexingPeer>(); + hi_->CreateTestInit(); + } + void SetUp() override { + EXPECT_EQ(3u, hi_->indexing_set_size()); + EXPECT_EQ(3u, hi_->tracking_set_size()); + } + std::unique_ptr<HeaderIndexingPeer> hi_; +}; + +TEST_F(SpdyHeaderIndexingTest, TestTryInsertHeader) { + std::string key("key4"); + hi_->TryInsert(std::move(key)); + EXPECT_EQ(3u, hi_->indexing_set_size()); + EXPECT_TRUE(hi_->ShouldIndex("key4")); +} + +TEST_F(SpdyHeaderIndexingTest, TestShouldIndex) { + std::string key3 = "key3"; + std::string key4 = "key4"; + std::string key5 = "key5"; + // Cache hit. + EXPECT_TRUE(hi_->ShouldIndex(key3)); + EXPECT_EQ(3u, hi_->indexing_set_size()); + EXPECT_EQ(3u, hi_->tracking_set_size()); + + // Cache miss. Add to tracking set. + EXPECT_FALSE(hi_->ShouldIndex(key4)); + EXPECT_EQ(3u, hi_->indexing_set_size()); + EXPECT_EQ(4u, hi_->tracking_set_size()); + EXPECT_TRUE(hi_->InTrackingSet(key4)); + // Cache miss. Add to indexing set by kicking one entry out. + EXPECT_FALSE(hi_->ShouldIndex(key4)); + EXPECT_EQ(3u, hi_->indexing_set_size()); + EXPECT_EQ(4u, hi_->tracking_set_size()); + EXPECT_TRUE(hi_->InTrackingSet(key4)); + // Cache hit. + EXPECT_TRUE(hi_->ShouldIndex(key4)); + + // Cache miss. Add to tracking set by kicking one entry out. + EXPECT_FALSE(hi_->ShouldIndex(key5)); + EXPECT_EQ(3u, hi_->indexing_set_size()); + EXPECT_EQ(4u, hi_->tracking_set_size()); + EXPECT_TRUE(hi_->ShouldIndex(key4)); + EXPECT_TRUE(hi_->InTrackingSet(key5)); + // Cache miss. Add to indexing set by kicking one entry out. + EXPECT_FALSE(hi_->ShouldIndex(key5)); + EXPECT_EQ(3u, hi_->indexing_set_size()); + EXPECT_EQ(4u, hi_->tracking_set_size()); + EXPECT_TRUE(hi_->ShouldIndex(key5)); + EXPECT_TRUE(hi_->InTrackingSet(key5)); +} + +TEST_F(SpdyHeaderIndexingTest, TestSetInit) { + hi_->CreateInitIndexingHeaders(); + EXPECT_EQ(100u, hi_->indexing_set_size()); + EXPECT_EQ(100u, hi_->tracking_set_size()); + EXPECT_TRUE(hi_->ShouldIndex(":status")); + EXPECT_TRUE(hi_->InTrackingSet(":status")); + EXPECT_FALSE(hi_->InTrackingSet("NotValid")); + EXPECT_FALSE(hi_->ShouldIndex("NotValid")); +} + +} // namespace test + +} // namespace net
diff --git a/net/test/python_utils.cc b/net/test/python_utils.cc index 6e19ea5..868abbb 100644 --- a/net/test/python_utils.cc +++ b/net/test/python_utils.cc
@@ -24,6 +24,11 @@ const char kPythonPathEnv[] = "PYTHONPATH"; +void ClearPythonPath() { + std::unique_ptr<base::Environment> env(base::Environment::Create()); + env->UnSetVar(kPythonPathEnv); +} + void AppendToPythonPath(const base::FilePath& dir) { std::unique_ptr<base::Environment> env(base::Environment::Create()); std::string old_path;
diff --git a/net/test/python_utils.h b/net/test/python_utils.h index ca06021..c72c9445 100644 --- a/net/test/python_utils.h +++ b/net/test/python_utils.h
@@ -15,6 +15,9 @@ // This is the python path variable name. extern const char kPythonPathEnv[]; +// Clears the python path, this is useful for test hermeticity. +void ClearPythonPath(); + // Appends the dir to python path environment variable. void AppendToPythonPath(const base::FilePath& dir);
diff --git a/net/test/python_utils_unittest.cc b/net/test/python_utils_unittest.cc index 48eb97376..91f742a 100644 --- a/net/test/python_utils_unittest.cc +++ b/net/test/python_utils_unittest.cc
@@ -15,6 +15,15 @@ #include "base/strings/stringprintf.h" #include "testing/gtest/include/gtest/gtest.h" +TEST(PythonUtils, Clear) { + std::unique_ptr<base::Environment> env(base::Environment::Create()); + env->SetVar(kPythonPathEnv, "foo"); + EXPECT_TRUE(env->HasVar(kPythonPathEnv)); + + ClearPythonPath(); + EXPECT_FALSE(env->HasVar(kPythonPathEnv)); +} + TEST(PythonUtils, Append) { const base::FilePath::CharType kAppendDir1[] = FILE_PATH_LITERAL("test/path_append1");
diff --git a/net/test/spawned_test_server/local_test_server.cc b/net/test/spawned_test_server/local_test_server.cc index 6829a85..30211667 100644 --- a/net/test/spawned_test_server/local_test_server.cc +++ b/net/test/spawned_test_server/local_test_server.cc
@@ -162,6 +162,8 @@ } bool LocalTestServer::SetPythonPath() const { + ClearPythonPath(); + base::FilePath third_party_dir; if (!PathService::Get(base::DIR_SOURCE_ROOT, &third_party_dir)) { LOG(ERROR) << "Failed to get DIR_SOURCE_ROOT";
diff --git a/net/url_request/report_sender.cc b/net/url_request/report_sender.cc index b99ef69..96263d7 100644 --- a/net/url_request/report_sender.cc +++ b/net/url_request/report_sender.cc
@@ -13,28 +13,50 @@ #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_status.h" +namespace { +const void* const kUserDataKey = &kUserDataKey; + +class CallbackInfo : public base::SupportsUserData::Data { + public: + CallbackInfo(const net::ReportSender::SuccessCallback& success_callback, + const net::ReportSender::ErrorCallback& error_callback) + : success_callback_(success_callback), error_callback_(error_callback) {} + + ~CallbackInfo() override {} + + const net::ReportSender::SuccessCallback& success_callback() const { + return success_callback_; + } + const net::ReportSender::ErrorCallback& error_callback() const { + return error_callback_; + } + + private: + net::ReportSender::SuccessCallback success_callback_; + net::ReportSender::ErrorCallback error_callback_; +}; +} // namespace + namespace net { ReportSender::ReportSender(URLRequestContext* request_context, CookiesPreference cookies_preference) - : ReportSender(request_context, cookies_preference, ErrorCallback()) {} - -ReportSender::ReportSender(URLRequestContext* request_context, - CookiesPreference cookies_preference, - const ErrorCallback& error_callback) : request_context_(request_context), - cookies_preference_(cookies_preference), - error_callback_(error_callback) {} + cookies_preference_(cookies_preference) {} ReportSender::~ReportSender() { } void ReportSender::Send(const GURL& report_uri, base::StringPiece content_type, - base::StringPiece report) { + base::StringPiece report, + const SuccessCallback& success_callback, + const ErrorCallback& error_callback) { DCHECK(!content_type.empty()); std::unique_ptr<URLRequest> url_request = request_context_->CreateRequest(report_uri, DEFAULT_PRIORITY, this); + url_request->SetUserData(&kUserDataKey, + new CallbackInfo(success_callback, error_callback)); int load_flags = LOAD_BYPASS_CACHE | LOAD_DISABLE_CACHE | LOAD_DO_NOT_SEND_AUTH_DATA; @@ -60,17 +82,18 @@ raw_url_request->Start(); } -void ReportSender::SetErrorCallback(const ErrorCallback& error_callback) { - error_callback_ = error_callback; -} - void ReportSender::OnResponseStarted(URLRequest* request, int net_error) { DCHECK_NE(ERR_IO_PENDING, net_error); + CallbackInfo* callback_info = + static_cast<CallbackInfo*>(request->GetUserData(&kUserDataKey)); + DCHECK(callback_info); if (net_error != OK) { DVLOG(1) << "Failed to send report for " << request->url().host(); - if (!error_callback_.is_null()) - error_callback_.Run(request->url(), net_error); + if (!callback_info->error_callback().is_null()) + callback_info->error_callback().Run(request->url(), net_error); + } else if (!callback_info->success_callback().is_null()) { + callback_info->success_callback().Run(); } CHECK_GT(inflight_requests_.erase(request), 0u);
diff --git a/net/url_request/report_sender.h b/net/url_request/report_sender.h index 8fa46ca..a230f06 100644 --- a/net/url_request/report_sender.h +++ b/net/url_request/report_sender.h
@@ -30,6 +30,7 @@ : public URLRequest::Delegate, public TransportSecurityState::ReportSenderInterface { public: + using SuccessCallback = base::Callback<void()>; using ErrorCallback = base::Callback<void(const GURL&, int)>; // Represents whether or not to send cookies along with reports. @@ -42,23 +43,14 @@ ReportSender(URLRequestContext* request_context, CookiesPreference cookies_preference); - // Constructs a ReportSender that sends reports with the - // given |request_context| and includes or excludes cookies based on - // |cookies_preference|. |request_context| must outlive the - // ReportSender. When sending a report results in an error, - // |error_callback| is called with the report URI and net error as - // arguments. - ReportSender(URLRequestContext* request_context, - CookiesPreference cookies_preference, - const ErrorCallback& error_callback); - ~ReportSender() override; // TransportSecurityState::ReportSenderInterface implementation. void Send(const GURL& report_uri, base::StringPiece content_type, - base::StringPiece report) override; - void SetErrorCallback(const ErrorCallback& error_callback) override; + base::StringPiece report, + const SuccessCallback& success_callback, + const ErrorCallback& error_callback) override; // net::URLRequest::Delegate implementation. void OnResponseStarted(URLRequest* request, int net_error) override; @@ -71,9 +63,6 @@ std::map<URLRequest*, std::unique_ptr<URLRequest>> inflight_requests_; - // Called when a sent report results in an error. - ErrorCallback error_callback_; - DISALLOW_COPY_AND_ASSIGN(ReportSender); };
diff --git a/net/url_request/report_sender_unittest.cc b/net/url_request/report_sender_unittest.cc index 4d1096dd..3865730e 100644 --- a/net/url_request/report_sender_unittest.cc +++ b/net/url_request/report_sender_unittest.cc
@@ -54,6 +54,10 @@ *called = true; } +void SuccessCallback(bool* called) { + *called = true; +} + // A network delegate that lets tests check that a report // was sent. It counts the number of requests and lets tests register a // callback to run when the request is destroyed. It also checks that @@ -155,10 +159,13 @@ TestURLRequestContext* context() { return &context_; } protected: - void SendReport(ReportSender* reporter, - const std::string& report, - const GURL& url, - size_t request_sequence_number) { + void SendReport( + ReportSender* reporter, + const std::string& report, + const GURL& url, + size_t request_sequence_number, + const base::Callback<void()>& success_callback, + const base::Callback<void(const GURL&, int)>& error_callback) { base::RunLoop run_loop; network_delegate_.set_url_request_destroyed_callback( run_loop.QuitClosure()); @@ -169,7 +176,8 @@ EXPECT_EQ(request_sequence_number, network_delegate_.num_requests()); - reporter->Send(url, "application/foobar", report); + reporter->Send(url, "application/foobar", report, success_callback, + error_callback); // The report is sent asynchronously, so wait for the report's // URLRequest to be destroyed before checking that the report was @@ -179,6 +187,14 @@ EXPECT_EQ(request_sequence_number + 1, network_delegate_.num_requests()); } + void SendReport(ReportSender* reporter, + const std::string& report, + const GURL& url, + size_t request_sequence_number) { + SendReport(reporter, report, url, request_sequence_number, base::Closure(), + base::Callback<void(const GURL&, int)>()); + } + TestReportSenderNetworkDelegate network_delegate_; private: @@ -215,8 +231,10 @@ EXPECT_EQ(0u, network_delegate_.num_requests()); - reporter.Send(url, "application/foobar", kDummyReport); - reporter.Send(url, "application/foobar", kSecondDummyReport); + reporter.Send(url, "application/foobar", kDummyReport, base::Closure(), + base::Callback<void(const GURL&, int)>()); + reporter.Send(url, "application/foobar", kSecondDummyReport, base::Closure(), + base::Callback<void(const GURL&, int)>()); run_loop.Run(); @@ -240,7 +258,8 @@ std::unique_ptr<ReportSender> reporter( new ReportSender(context(), ReportSender::DO_NOT_SEND_COOKIES)); - reporter->Send(url, "application/foobar", kDummyReport); + reporter->Send(url, "application/foobar", kDummyReport, base::Closure(), + base::Callback<void(const GURL&, int)>()); reporter.reset(); EXPECT_EQ(1u, network_delegate_.num_requests()); @@ -256,26 +275,32 @@ } // Test that the error callback, if provided, gets called when a request -// returns an error. -TEST_F(ReportSenderTest, ErroredRequestCallsCallback) { +// returns an error and the success callback doesn't get called. +TEST_F(ReportSenderTest, ErroredRequestCallsErrorCallback) { bool error_callback_called = false; + bool success_callback_called = false; GURL url = URLRequestFailedJob::GetMockHttpsUrl(ERR_FAILED); - ReportSender reporter(context(), ReportSender::DO_NOT_SEND_COOKIES, - base::Bind(ErrorCallback, &error_callback_called)); + ReportSender reporter(context(), ReportSender::DO_NOT_SEND_COOKIES); // SendReport will block until the URLRequest is destroyed. - SendReport(&reporter, kDummyReport, url, 0); + SendReport(&reporter, kDummyReport, url, 0, + base::Bind(SuccessCallback, &success_callback_called), + base::Bind(ErrorCallback, &error_callback_called)); EXPECT_TRUE(error_callback_called); + EXPECT_FALSE(success_callback_called); } -// Test that the error callback does not get called when a request -// does not return an error. -TEST_F(ReportSenderTest, SuccessfulRequestDoesNotCallErrorCallback) { +// Test that the error callback does not get called and the success callback +/// gets called when a request does not return an error. +TEST_F(ReportSenderTest, SuccessfulRequestCallsSuccessCallback) { bool error_callback_called = false; + bool success_callback_called = false; GURL url = URLRequestMockDataJob::GetMockHttpsUrl("dummy data", 1); - ReportSender reporter(context(), ReportSender::DO_NOT_SEND_COOKIES, - base::Bind(ErrorCallback, &error_callback_called)); - SendReport(&reporter, kDummyReport, url, 0); + ReportSender reporter(context(), ReportSender::DO_NOT_SEND_COOKIES); + SendReport(&reporter, kDummyReport, url, 0, + base::Bind(SuccessCallback, &success_callback_called), + base::Bind(ErrorCallback, &error_callback_called)); EXPECT_FALSE(error_callback_called); + EXPECT_TRUE(success_callback_called); } // Test that cookies are sent or not sent according to the error
diff --git a/net/url_request/url_request_unittest.cc b/net/url_request/url_request_unittest.cc index d369453..a91224a5 100644 --- a/net/url_request/url_request_unittest.cc +++ b/net/url_request/url_request_unittest.cc
@@ -677,17 +677,16 @@ MockCertificateReportSender() {} ~MockCertificateReportSender() override {} - void Send(const GURL& report_uri, - base::StringPiece content_type, - base::StringPiece report) override { + void Send( + const GURL& report_uri, + base::StringPiece content_type, + base::StringPiece report, + const base::Callback<void()>& success_callback, + const base::Callback<void(const GURL&, int)>& error_callback) override { latest_report_uri_ = report_uri; report.CopyToString(&latest_report_); content_type.CopyToString(&latest_content_type_); } - - void SetErrorCallback( - const base::Callback<void(const GURL&, int)>& error_callback) override {} - const GURL& latest_report_uri() { return latest_report_uri_; } const std::string& latest_report() { return latest_report_; } const std::string& latest_content_type() { return latest_content_type_; }
diff --git a/ppapi/proxy/nacl_message_scanner.cc b/ppapi/proxy/nacl_message_scanner.cc index e31ee38..19edce26 100644 --- a/ppapi/proxy/nacl_message_scanner.cc +++ b/ppapi/proxy/nacl_message_scanner.cc
@@ -63,7 +63,6 @@ // Now write the handle itself in POSIX style. // See ParamTraits<FileDescriptor>::Read for where these values are read. msg->WriteBool(true); // valid == true - msg->WriteBool(false); // brokerable == false msg->WriteInt(handle_index); } }
diff --git a/remoting/client/ios/BUILD.gn b/remoting/client/ios/BUILD.gn new file mode 100644 index 0000000..92c8a24 --- /dev/null +++ b/remoting/client/ios/BUILD.gn
@@ -0,0 +1,43 @@ +# Copyright 2016 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +group("all") { + testonly = true + + deps = [ + "./bridge:all", + ] +} + +group("all_test") { + testonly = true + + deps = [ + "./bridge:bridge_unit_tests", + ] +} + +source_set("ios_core") { + sources = [ + "utility.h", + "utility.mm", + ] + + public_deps = [ + "//third_party/webrtc/base:rtc_base", + "//third_party/webrtc/modules/desktop_capture:primitives", + ] + + deps = [ + "//base", + ] + + libs = [ + "CoreGraphics.framework", + "GLKit.framework", + "OpenGLES.framework", + ] + + configs += [ "//build/config/compiler:enable_arc" ] +}
diff --git a/remoting/client/ios/DEPS b/remoting/client/ios/DEPS new file mode 100644 index 0000000..50529ba --- /dev/null +++ b/remoting/client/ios/DEPS
@@ -0,0 +1,10 @@ +include_rules = [ + "+google/protobuf", + "+remoting/codec", + "+remoting/client/ios", + "+remoting/client/ios/bridge", + "+remoting/signaling", + "+third_party/libjingle", + "+third_party/webrtc", + "+third_party/protobuf/src", +]
diff --git a/remoting/client/ios/bridge/BUILD.gn b/remoting/client/ios/bridge/BUILD.gn new file mode 100644 index 0000000..bc4c658 --- /dev/null +++ b/remoting/client/ios/bridge/BUILD.gn
@@ -0,0 +1,93 @@ +# Copyright 2016 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//build/config/ios/rules.gni") + +group("all") { + testonly = true + + deps = [ + ":bridge", + ":bridge_unit_tests", + ] +} + +source_set("bridge") { + include_dirs = [ + "$root_gen_dir", + "//third_party/protobuf/src", + ] + + sources = [ + "client_instance.cc", + "client_instance.h", + "client_proxy.h", + "client_proxy.mm", + "client_proxy_delegate.h", + "client_proxy_delegate_wrapper.h", + "client_proxy_delegate_wrapper.mm", + "frame_consumer_bridge.cc", + "frame_consumer_bridge.h", + "host_proxy.h", + "host_proxy.mm", + ] + + public_deps = [ + "//remoting/protocol", + "//third_party/webrtc/base:rtc_base", + "//third_party/webrtc/modules/desktop_capture:primitives", + ] + + deps = [ + "//base", + "//net", + "//remoting/client/ios:ios_core", + "//remoting/resources:strings", + "//ui/base", + "//ui/gfx", + "//ui/resources", + "//ui/strings:ui_strings", + ] + + libs = [ + "Accelerate.framework", + "AudioToolbox.framework", + "CoreAudio.framework", + "CoreData.framework", + "CoreMIDI.framework", + "CoreVideo.framework", + "CoreGraphics.framework", + "GLKit.framework", + "OpenGLES.framework", + "Webkit.framework", + ] + + configs += [ "//build/config/compiler:enable_arc" ] +} + +source_set("bridge_unit_tests") { + testonly = true + + include_dirs = [ + "$root_gen_dir", + "//third_party/protobuf/src", + ] + + sources = [ + "client_instance_unittest.mm", + "client_proxy_unittest.mm", + + # "frame_consumer_bridge_unittest.cc", + "host_proxy_unittest.mm", + ] + + deps = [ + ":bridge", + "//testing/gtest", + ] + + configs += [ "//build/config/compiler:enable_arc" ] + + data = [] +}
diff --git a/remoting/client/ios/bridge/DEPS b/remoting/client/ios/bridge/DEPS new file mode 100644 index 0000000..0c7839b --- /dev/null +++ b/remoting/client/ios/bridge/DEPS
@@ -0,0 +1,9 @@ +include_rules = [ + "+google/protobuf", + "+remoting/codec", + "+remoting/client/ios", + "+remoting/signaling", + "+third_party/libjingle", + "+third_party/webrtc", + "+third_party/protobuf/src", +]
diff --git a/remoting/client/ios/bridge/client_instance.cc b/remoting/client/ios/bridge/client_instance.cc new file mode 100644 index 0000000..25e9852 --- /dev/null +++ b/remoting/client/ios/bridge/client_instance.cc
@@ -0,0 +1,363 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "remoting/client/ios/bridge/client_instance.h" + +#include "base/bind.h" +#include "base/bind_helpers.h" +#include "base/logging.h" +#include "base/memory/ptr_util.h" +#include "base/synchronization/waitable_event.h" +#include "jingle/glue/thread_wrapper.h" +#include "net/socket/client_socket_factory.h" +#include "remoting/base/chromium_url_request.h" +#include "remoting/base/url_request_context_getter.h" +#include "remoting/client/audio_player.h" +#include "remoting/client/client_status_logger.h" +#include "remoting/client/ios/bridge/client_proxy.h" +#include "remoting/proto/event.pb.h" +#include "remoting/protocol/chromium_port_allocator_factory.h" +#include "remoting/protocol/client_authentication_config.h" +#include "remoting/protocol/host_stub.h" +#include "remoting/protocol/negotiating_client_authenticator.h" +#include "remoting/protocol/transport_context.h" +#include "remoting/signaling/delegating_signal_strategy.h" + + +//#include "remoting/client/ios/audio_player_buffer.h" // TODO(nicholss): need +// to also pull in the player and attach to buffer. + +// TODO(nicholss): There is another client instance used by android. Need to +// merge the two. + +namespace { +const char* const kXmppServer = "talk.google.com"; +const char kDirectoryBotJid[] = "remoting@bot.talk.google.com"; +} // namespace + +namespace remoting { + +ClientInstance::ClientInstance(const base::WeakPtr<ClientProxy>& proxy, + const std::string& username, + const std::string& auth_token, + const std::string& host_jid, + const std::string& host_id, + const std::string& host_pubkey) + : proxyToClient_(proxy), host_jid_(host_jid), device_id_() { + if (!base::MessageLoop::current()) { + ui_loop_ = new base::MessageLoop(base::MessageLoop::TYPE_UI); + base::MessageLoopForUI::current()->Attach(); + } else { + ui_loop_ = base::MessageLoopForUI::current(); + } + + // |ui_loop_| runs on the main thread, so |ui_task_runner_| will run on the + // main thread. We can not kill the main thread when the message loop becomes + // idle so the callback function does nothing (as opposed to the typical + // base::MessageLoop::QuitClosure()) + ui_task_runner_ = new AutoThreadTaskRunner(ui_loop_->task_runner(), + base::Bind(&base::DoNothing)); + + network_task_runner_ = AutoThread::CreateWithType( + "native_net", ui_task_runner_, base::MessageLoop::TYPE_IO); + file_task_runner_ = AutoThread::CreateWithType("native_file", ui_task_runner_, + base::MessageLoop::TYPE_IO); + audio_task_runner_ = AutoThread::CreateWithType( + "native_audio", ui_task_runner_, base::MessageLoop::TYPE_IO); + + url_requester_ = + new URLRequestContextGetter(network_task_runner_, file_task_runner_); + + DCHECK(ui_task_runner_->BelongsToCurrentThread()); + + // Initialize XMPP config. + xmpp_config_.host = kXmppServer; + xmpp_config_.username = username; + xmpp_config_.auth_token = auth_token; + + client_auth_config_.host_id = host_id; + client_auth_config_.fetch_secret_callback = + base::Bind(&ClientInstance::FetchSecret, this); + // client_auth_config_.fetch_third_party_token_callback = + // std::unique_ptr<protocol::ThirdPartyClientAuthenticator::TokenFetcher>(); +} + +ClientInstance::~ClientInstance() {} + +void ClientInstance::Start(const std::string& pairing_id, + const std::string& pairing_secret) { + DCHECK(ui_task_runner_->BelongsToCurrentThread()); + + client_auth_config_.pairing_client_id = pairing_id; + client_auth_config_.pairing_secret = pairing_secret; + + view_.reset(new FrameConsumerBridge( + this, base::Bind(&ClientProxy::RedrawCanvas, proxyToClient_))); + + network_task_runner_->PostTask( + FROM_HERE, + base::Bind(&ClientInstance::ConnectToHostOnNetworkThread, this)); +} + +void ClientInstance::Cleanup() { + DCHECK(ui_task_runner_->BelongsToCurrentThread()); + + // |view_| must be destroyed on the UI thread before the producer is gone. + view_.reset(); + + network_task_runner_->PostTask( + FROM_HERE, + base::Bind(&ClientInstance::DisconnectFromHostOnNetworkThread, this)); +} + +// HOST attempts to continue automatically with previously supplied credentials, +// if it can't it requests the user's PIN. +void ClientInstance::FetchSecret( + bool pairable, + const protocol::SecretFetchedCallback& callback) { + if (!ui_task_runner_->BelongsToCurrentThread()) { + ui_task_runner_->PostTask( + FROM_HERE, + base::Bind(&ClientInstance::FetchSecret, this, pairable, callback)); + return; + } + + pin_callback_ = callback; + + if (proxyToClient_) { + // We attempted to connect using an existing pairing that was rejected. + // Unless we forget about the stale credentials, we'll continue trying + // them. + proxyToClient_->CommitPairingCredentials(client_auth_config_.host_id, "", + ""); + + proxyToClient_->DisplayAuthenticationPrompt(pairable); + } +} + +void ClientInstance::ProvideSecret(const std::string& pin, + bool create_pairing, + const std::string& device_id) { + DCHECK(ui_task_runner_->BelongsToCurrentThread()); + create_pairing_ = create_pairing; + device_id_ = device_id; + + // Before this function can be called, FetchSecret must have been called, + // which creates |pin_callback_| + DCHECK(!pin_callback_.is_null()); + network_task_runner_->PostTask(FROM_HERE, base::Bind(pin_callback_, pin)); +} + +void ClientInstance::PerformMouseAction( + const webrtc::DesktopVector& position, + const webrtc::DesktopVector& wheel_delta, + protocol::MouseEvent_MouseButton button, + bool button_down) { + if (!network_task_runner_->BelongsToCurrentThread()) { + network_task_runner_->PostTask( + FROM_HERE, base::Bind(&ClientInstance::PerformMouseAction, this, + position, wheel_delta, button, button_down)); + return; + } + + protocol::MouseEvent action; + action.set_x(position.x()); + action.set_y(position.y()); + action.set_wheel_delta_x(wheel_delta.x()); + action.set_wheel_delta_y(wheel_delta.y()); + action.set_button(button); + + // TODO(nicholss) this throws a npe when there is a delay on connecting to a + // host + touch. + client_->input_stub()->InjectMouseEvent(action); +} + +void ClientInstance::PerformKeyboardAction(int key_code, bool key_down) { + if (!network_task_runner_->BelongsToCurrentThread()) { + network_task_runner_->PostTask( + FROM_HERE, base::Bind(&ClientInstance::PerformKeyboardAction, this, + key_code, key_down)); + return; + } + + protocol::KeyEvent action; + action.set_usb_keycode(key_code); + action.set_pressed(key_down); + client_->input_stub()->InjectKeyEvent(action); +} + +void ClientInstance::OnConnectionState(protocol::ConnectionToHost::State state, + protocol::ErrorCode error) { + DCHECK(network_task_runner_->BelongsToCurrentThread()); + + client_status_logger_->LogSessionStateChange(state, error); + + ui_task_runner_->PostTask( + FROM_HERE, base::Bind(&ClientInstance::HandleConnectionStateOnUIThread, + this, state, error)); +} + +void ClientInstance::OnConnectionReady(bool ready) { + // We ignore this message, since OnConnectionState tells us the same thing. +} + +void ClientInstance::OnRouteChanged(const std::string& channel_name, + const protocol::TransportRoute& route) { + VLOG(1) << "Using " << protocol::TransportRoute::GetTypeString(route.type) + << " connection for " << channel_name << " channel"; +} + +void ClientInstance::SetCapabilities(const std::string& capabilities) {} + +void ClientInstance::SetPairingResponse( + const protocol::PairingResponse& response) { + if (!ui_task_runner_->BelongsToCurrentThread()) { + ui_task_runner_->PostTask( + FROM_HERE, + base::Bind(&ClientInstance::SetPairingResponse, this, response)); + return; + } + + VLOG(1) << "Successfully established pairing with host"; + + if (proxyToClient_) + proxyToClient_->CommitPairingCredentials(client_auth_config_.host_id, + response.client_id(), + response.shared_secret()); +} + +void ClientInstance::DeliverHostMessage( + const protocol::ExtensionMessage& message) { + NOTIMPLEMENTED(); +} + +void ClientInstance::SetDesktopSize(const webrtc::DesktopSize& size, + const webrtc::DesktopVector& dpi) { + // ClientInstance get size from the frames and it doesn't use DPI, so this + // call can be ignored. +} + +// Returning interface of protocol::ClipboardStub. +protocol::ClipboardStub* ClientInstance::GetClipboardStub() { + return this; +} + +// Returning interface of protocol::CursorShapeStub. +protocol::CursorShapeStub* ClientInstance::GetCursorShapeStub() { + return this; +} + +void ClientInstance::InjectClipboardEvent( + const protocol::ClipboardEvent& event) { + NOTIMPLEMENTED(); +} + +void ClientInstance::SetCursorShape(const protocol::CursorShapeInfo& shape) { + if (!ui_task_runner_->BelongsToCurrentThread()) { + ui_task_runner_->PostTask( + FROM_HERE, base::Bind(&ClientInstance::SetCursorShape, this, shape)); + return; + } + if (proxyToClient_) + proxyToClient_->UpdateCursorShape(shape); +} + +void ClientInstance::ConnectToHostOnNetworkThread() { + DCHECK(network_task_runner_->BelongsToCurrentThread()); + + jingle_glue::JingleThreadWrapper::EnsureForCurrentMessageLoop(); + + client_context_.reset(new ClientContext(network_task_runner_)); + client_context_->Start(); + + perf_tracker_.reset(new protocol::PerformanceTracker()); + + video_renderer_.reset(new SoftwareVideoRenderer(view_.get())); + // TODO(nicholss): SoftwareVideoRenderer was changed to now have Initialize, + // but it is unclear how to integrate into existing code. + // video_renderer_->Initialize(client_context_, perf_tracker_.get())); + + client_.reset(new ChromotingClient( + client_context_.get(), this, video_renderer_.get(), + nullptr // TODO(nicholss): GetAudioConsumer().get() + )); + + signaling_.reset( + new XmppSignalStrategy(net::ClientSocketFactory::GetDefaultFactory(), + url_requester_, xmpp_config_)); + + client_status_logger_.reset(new ClientStatusLogger( + ServerLogEntry::ME2ME, signaling_.get(), kDirectoryBotJid)); + + protocol::NetworkSettings network_settings( + protocol::NetworkSettings::NAT_TRAVERSAL_FULL); + + // Use Chrome's network stack to allocate ports for peer-to-peer channels. + + scoped_refptr<protocol::TransportContext> transport_context = + new protocol::TransportContext( + signaling_.get(), + base::WrapUnique(new protocol::ChromiumPortAllocatorFactory()), + base::WrapUnique(new ChromiumUrlRequestFactory(url_requester_)), + protocol::NetworkSettings( + protocol::NetworkSettings::NAT_TRAVERSAL_FULL), + protocol::TransportRole::CLIENT); + + client_->Start(signaling_.get(), client_auth_config_, transport_context, + host_jid_, std::string()); +} + +// TODO(nicholss): Port audio impl for iOS. +// base::WeakPtr<protocol::AudioStub> ClientInstance::GetAudioConsumer() { +// if (!audio_player_) { +// audio_player_ = AudioPlayerIos::CreateAudioPlayer( +// network_task_runner_, +// audio_task_runner_); +// } +// +// return audio_player_->GetAudioConsumer(); +// } + +void ClientInstance::DisconnectFromHostOnNetworkThread() { + DCHECK(network_task_runner_->BelongsToCurrentThread()); + + // |client_| must be torn down before |signaling_|. + client_.reset(); + client_status_logger_.reset(); + signaling_.reset(); + perf_tracker_.reset(); + // audio_consumer_->reset(); // TODO(nicholss): Or should this be a call to + // Stop? + // audio_player_->reset(); // TODO(nicholss): Or should this be a call to + // Stop? + video_renderer_.reset(); + client_context_->Stop(); +} + +void ClientInstance::HandleConnectionStateOnUIThread( + protocol::ConnectionToHost::State state, + protocol::ErrorCode error) { + if (create_pairing_ && device_id_.length() > 0 && + state == protocol::ConnectionToHost::CONNECTED) { + DoPairing(); + } + + if (proxyToClient_) + proxyToClient_->ReportConnectionStatus(state, error); +} + +void ClientInstance::DoPairing() { + if (!network_task_runner_->BelongsToCurrentThread()) { + network_task_runner_->PostTask( + FROM_HERE, base::Bind(&ClientInstance::DoPairing, this)); + return; + } + + VLOG(1) << "Attempting to pair with host"; + protocol::PairingRequest request; + request.set_client_name(device_id_); + client_->host_stub()->RequestPairing(request); +} + +} // namespace remoting
diff --git a/remoting/client/ios/bridge/client_instance.h b/remoting/client/ios/bridge/client_instance.h new file mode 100644 index 0000000..7b2b4d6 --- /dev/null +++ b/remoting/client/ios/bridge/client_instance.h
@@ -0,0 +1,204 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef REMOTING_CLIENT_IOS_BRIDGE_CLIENT_INSTANCE_H_ +#define REMOTING_CLIENT_IOS_BRIDGE_CLIENT_INSTANCE_H_ + +#include <memory> +#include <string> + +#include "base/bind.h" +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/memory/weak_ptr.h" +#include "base/message_loop/message_loop.h" +#include "net/url_request/url_request_context_getter.h" +#include "remoting/base/auto_thread.h" +#include "remoting/client/chromoting_client.h" +#include "remoting/client/client_context.h" +#include "remoting/client/client_user_interface.h" +#include "remoting/client/ios/bridge/frame_consumer_bridge.h" +#include "remoting/client/software_video_renderer.h" +#include "remoting/proto/control.pb.h" +#include "remoting/proto/event.pb.h" +#include "remoting/protocol/audio_stub.h" +#include "remoting/protocol/clipboard_stub.h" +#include "remoting/protocol/cursor_shape_stub.h" +#include "remoting/protocol/network_settings.h" +#include "remoting/protocol/performance_tracker.h" +#include "remoting/protocol/transport_context.h" +#include "remoting/signaling/xmpp_signal_strategy.h" + + +//#include "remoting/client/ios/audio_player_ios.h" + +namespace remoting { + +// class AudioPlayerIos; +class AudioConsumer; +class ClientProxy; +class ClientStatusLogger; +class FrameConsumerBridge; + +// ClientUserInterface that indirectly makes and receives OBJ_C calls from the +// UI application. +class ClientInstance : public ClientUserInterface, + public protocol::ClipboardStub, + public protocol::CursorShapeStub, + public base::RefCountedThreadSafe<ClientInstance> { + public: + // Initiates a connection with the specified host. Call from the UI thread. To + // connect with an unpaired host, pass in |pairing_id| and |pairing_secret| as + // empty strings. + ClientInstance(const base::WeakPtr<ClientProxy>& proxy, + const std::string& username, + const std::string& auth_token, + const std::string& host_jid, + const std::string& host_id, + const std::string& host_pubkey); + + // Begins the connection process. Should not be called again until after + // |CleanUp|. + void Start(const std::string& pairing_id, const std::string& pairing_secret); + + // Terminates the current connection (if it hasn't already failed) and cleans + // up. Must be called before destruction can occur or a memory leak may occur. + void Cleanup(); + + // Notifies the user interface that the user needs to enter a PIN. The + // current authentication attempt is put on hold until |callback| is invoked. + // May be called on any thread. + void FetchSecret(bool pairable, + const protocol::SecretFetchedCallback& callback); + + // Provides the user's PIN and resumes the host authentication attempt. Call + // on the UI thread once the user has finished entering this PIN into the UI, + // but only after the UI has been asked to provide a PIN (via FetchSecret()). + void ProvideSecret(const std::string& pin, + bool create_pair, + const std::string& device_id); + + // Moves the host's cursor to the specified coordinates, optionally with some + // mouse button depressed. If |button| is BUTTON_UNDEFINED, no click is made. + void PerformMouseAction( + const webrtc::DesktopVector& position, + const webrtc::DesktopVector& wheel_delta, + protocol::MouseEvent_MouseButton button, + bool button_down); + + // Sends the provided keyboard scan code to the host. + void PerformKeyboardAction(int key_code, bool key_down); + + // ClientUserInterface implementation. + void OnConnectionState(protocol::ConnectionToHost::State state, + protocol::ErrorCode error) override; + void OnConnectionReady(bool ready) override; + void OnRouteChanged(const std::string& channel_name, + const protocol::TransportRoute& route) override; + void SetCapabilities(const std::string& capabilities) override; + void SetPairingResponse(const protocol::PairingResponse& response) override; + void DeliverHostMessage(const protocol::ExtensionMessage& message) override; + protocol::ClipboardStub* GetClipboardStub() override; + protocol::CursorShapeStub* GetCursorShapeStub() override; + + // CursorShapeStub implementation. + void InjectClipboardEvent(const protocol::ClipboardEvent& event) override; + + // ClipboardStub implementation. + void SetCursorShape(const protocol::CursorShapeInfo& shape) override; + + void SetDesktopSize(const webrtc::DesktopSize& size, + const webrtc::DesktopVector& dpi) override; + + scoped_refptr<AutoThreadTaskRunner> display_task_runner() { + return ui_task_runner_; + } + + scoped_refptr<AutoThreadTaskRunner> network_task_runner() { + return network_task_runner_; + } + + scoped_refptr<AutoThreadTaskRunner> file_task_runner() { + return file_task_runner_; + } + + scoped_refptr<AutoThreadTaskRunner> audio_task_runner() { + return audio_task_runner_; + } + + private: + // This object is ref-counted, so it cleans itself up. + ~ClientInstance() override; + + void ConnectToHostOnNetworkThread(); + void DisconnectFromHostOnNetworkThread(); + + void HandleConnectionStateOnUIThread(protocol::ConnectionToHost::State state, + protocol::ErrorCode error); + + // Request pairing from the host. + void DoPairing(); + + // base::WeakPtr<protocol::AudioStub> GetAudioConsumer(); + + // Proxy to exchange messages between the + // common Chromoting protocol and UI Application. + base::WeakPtr<ClientProxy> proxyToClient_; + + // ID of the host we are connecting to. + std::string host_jid_; + + protocol::ClientAuthenticationConfig client_auth_config_; + + // This group of variables is to be used on the display thread. + std::unique_ptr<SoftwareVideoRenderer> video_renderer_; + std::unique_ptr<FrameConsumerBridge> view_; + + // This group of variables is to be used on the network thread. + std::unique_ptr<ClientContext> client_context_; + std::unique_ptr<protocol::PerformanceTracker> perf_tracker_; + std::unique_ptr<ChromotingClient> client_; + XmppSignalStrategy::XmppServerConfig xmpp_config_; + std::unique_ptr<XmppSignalStrategy> signaling_; // Must outlive client_ + std::unique_ptr<ClientStatusLogger> client_status_logger_; + + // This group of variables is to be used on the audio thread. + // std::unique_ptr<AudioPlayerIos> audio_player_; + + // Pass this the user's PIN once we have it. To be assigned and accessed on + // the UI thread, but must be posted to the network thread to call it. + protocol::SecretFetchedCallback pin_callback_; + + // Indicates whether to establish a new pairing with this host. This is + // modified in ProvideSecret(), but thereafter to be used only from the + // network thread. (This is safe because ProvideSecret() is invoked at most + // once per run, and always before any reference to this flag.) + bool create_pairing_ = false; + + // A unique identifier for the user's device. + // Only to be used when a pairing is created. + std::string device_id_; + + // Chromium code's connection to the OBJ_C message loop. Once created the + // MessageLoop will live for the life of the program. An attempt was made to + // create the primary message loop earlier in the programs life, but a + // MessageLoop requires ARC to be disabled. + base::MessageLoop* ui_loop_; + + // References to native threads. + scoped_refptr<AutoThreadTaskRunner> ui_task_runner_; + scoped_refptr<AutoThreadTaskRunner> network_task_runner_; + scoped_refptr<AutoThreadTaskRunner> file_task_runner_; + scoped_refptr<AutoThreadTaskRunner> audio_task_runner_; + + scoped_refptr<net::URLRequestContextGetter> url_requester_; + + friend class base::RefCountedThreadSafe<ClientInstance>; + + DISALLOW_COPY_AND_ASSIGN(ClientInstance); +}; + +} // namespace remoting + +#endif // REMOTING_CLIENT_IOS_BRIDGE_CLIENT_INSTANCE_H_
diff --git a/remoting/client/ios/bridge/client_instance_unittest.mm b/remoting/client/ios/bridge/client_instance_unittest.mm new file mode 100644 index 0000000..7307eda --- /dev/null +++ b/remoting/client/ios/bridge/client_instance_unittest.mm
@@ -0,0 +1,329 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "remoting/client/ios/bridge/client_instance.h" + +#import "remoting/client/ios/host_preferences.h" +#import "testing/gtest_mac.h" + +#include "base/compiler_specific.h" +#include "base/mac/scoped_nsobject.h" +#include "base/run_loop.h" +#include "base/strings/sys_string_conversions.h" +#include "base/synchronization/waitable_event.h" +#include "remoting/base/constants.h" +#include "remoting/client/ios/bridge/client_proxy.h" +#include "remoting/client/ios/bridge/client_proxy_delegate_wrapper.h" +#include "remoting/proto/event.pb.h" +#include "remoting/protocol/clipboard_stub.h" + + +@interface ClientProxyDelegateForClientInstanceTester + : NSObject<ClientProxyDelegate> + +- (void)resetDidReceiveSomething; + +// Validating what was received is outside of the scope for this test unit. See +// ClientProxyUnittest for those tests. +@property(nonatomic, assign) BOOL didReceiveSomething; + +@end + +@implementation ClientProxyDelegateForClientInstanceTester + +@synthesize didReceiveSomething = _didReceiveSomething; + +- (void)resetDidReceiveSomething { + _didReceiveSomething = false; +} + +- (void)requestHostPin:(BOOL)pairingSupported { + _didReceiveSomething = true; +} + +- (void)connected { + _didReceiveSomething = true; +} + +- (void)connectionStatus:(NSString*)statusMessage { + _didReceiveSomething = true; +} + +- (void)connectionFailed:(NSString*)errorMessage { + _didReceiveSomething = true; +} + +- (void)applyFrame:(const webrtc::DesktopSize&)size + stride:(NSInteger)stride + data:(uint8_t*)data + rects:(const std::vector<webrtc::DesktopRect>&)rects { + _didReceiveSomething = true; +} + +- (void)applyCursor:(const webrtc::DesktopSize&)size + hotspot:(const webrtc::DesktopVector&)hotspot + cursorData:(uint8_t*)data { + _didReceiveSomething = true; +} + +@end + +namespace remoting { + +namespace { + +NSString* const kHostId = @"HostIdTest"; +NSString* const kPairingId = @"PairingIdTest"; +NSString* const kPairingSecret = @"PairingSecretTest"; +NSString* const kSecretPin = @"SecretPinTest"; +NSString* const kDeviceId = @"TestingDevice"; + +// TODO(aboone) should be able to call RunLoop().RunUntilIdle() instead but +// MessagePumpUIApplication::DoRun is marked NOTREACHED() +void RunCFMessageLoop() { + int result; + do { // Repeat until no messages remain + result = CFRunLoopRunInMode( + kCFRunLoopDefaultMode, + 0, // Execute queued messages, do not wait for additional messages + YES); // Do only one message at a time + } while (result != kCFRunLoopRunStopped && result != kCFRunLoopRunFinished && + result != kCFRunLoopRunTimedOut); +} + +void SecretPinCallBack(const std::string& secret) { + ASSERT_STREQ(base::SysNSStringToUTF8(kSecretPin).c_str(), secret.c_str()); +} + +} // namespace + +class ClientInstanceTest : public ::testing::Test { + protected: + void SetUp() override { + testDelegate_.reset( + [[ClientProxyDelegateForClientInstanceTester alloc] init]); + proxy_.reset(new ClientProxy( + [ClientProxyDelegateWrapper wrapDelegate:testDelegate_])); + instance_ = new ClientInstance(proxy_->AsWeakPtr(), "", "", "", "", ""); + } + + void TearDown() override { + // Ensure memory is not leaking + // Notice Cleanup is safe to call, regardless of if Start() was ever called. + instance_->Cleanup(); + RunCFMessageLoop(); + // An object on the network thread which owns a reference to |instance_| may + // be cleaned up 'soon', but not immediately. Lets wait it out, up to 1 + // second. + for (int i = 0; i < 100; i++) { + if (!instance_->HasOneRef()) { + [NSThread sleepForTimeInterval:.01]; + } else { + break; + } + } + + // Remove the last reference from |instance_|, and destructor is called. + ASSERT_TRUE(instance_->HasOneRef()); + instance_ = NULL; + } + + void AssertAcknowledged(BOOL wasAcknowledged) { + ASSERT_EQ(wasAcknowledged, [testDelegate_ didReceiveSomething]); + // Reset for the next test + [testDelegate_ resetDidReceiveSomething]; + } + + void TestStatusAndError(protocol::ConnectionToHost::State state, + protocol::ErrorCode error) { + instance_->OnConnectionState(state, error); + AssertAcknowledged(true); + } + + void TestConnectionStatus(protocol::ConnectionToHost::State state) { + TestStatusAndError(state, protocol::ErrorCode::OK); + TestStatusAndError(state, protocol::ErrorCode::PEER_IS_OFFLINE); + TestStatusAndError(state, protocol::ErrorCode::SESSION_REJECTED); + TestStatusAndError(state, protocol::ErrorCode::INCOMPATIBLE_PROTOCOL); + TestStatusAndError(state, protocol::ErrorCode::AUTHENTICATION_FAILED); + TestStatusAndError(state, protocol::ErrorCode::CHANNEL_CONNECTION_ERROR); + TestStatusAndError(state, protocol::ErrorCode::SIGNALING_ERROR); + TestStatusAndError(state, protocol::ErrorCode::SIGNALING_TIMEOUT); + TestStatusAndError(state, protocol::ErrorCode::HOST_OVERLOAD); + TestStatusAndError(state, protocol::ErrorCode::UNKNOWN_ERROR); + } + + base::scoped_nsobject<ClientProxyDelegateForClientInstanceTester> + testDelegate_; + std::unique_ptr<ClientProxy> proxy_; + scoped_refptr<ClientInstance> instance_; +}; + +TEST_F(ClientInstanceTest, Create) { + // This is a test for memory leaking. Ensure a completely unused instance of + // ClientInstance is destructed. + + ASSERT_TRUE(instance_.get() != NULL); + ASSERT_TRUE(instance_->HasOneRef()); +} + +TEST_F(ClientInstanceTest, CreateAndStart) { + // This is a test for memory leaking. Ensure a properly used instance of + // ClientInstance is destructed. + + ASSERT_TRUE(instance_.get() != NULL); + ASSERT_TRUE(instance_->HasOneRef()); + + instance_->Start("", ""); + RunCFMessageLoop(); + ASSERT_TRUE(!instance_->HasOneRef()); // more than one +} + +TEST_F(ClientInstanceTest, SecretPin) { + NSString* hostId = kHostId; + NSString* pairingId = kPairingId; + NSString* pairingSecret = kPairingSecret; + + HostPreferences* newHost = [HostPreferences hostForId:hostId]; + newHost.pairId = pairingId; + newHost.pairSecret = pairingSecret; + [newHost saveToSSOKeychain]; + + // Suggesting that our pairing Id is known, but since it is not the correct + // credentials expect the stored value to be discarded before requesting the + // PIN. + instance_ = new ClientInstance(proxy_->AsWeakPtr(), "", "", "", + base::SysNSStringToUTF8(kHostId), ""); + + instance_->Start(base::SysNSStringToUTF8(kPairingId), + base::SysNSStringToUTF8(kPairingSecret)); + RunCFMessageLoop(); + + instance_->FetchSecret(false, base::Bind(&SecretPinCallBack)); + RunCFMessageLoop(); + AssertAcknowledged(true); + + HostPreferences* host = [HostPreferences hostForId:hostId]; + + // The pairing information was discarded. + ASSERT_TRUE([host.pairId isEqualToString:@""]); + ASSERT_TRUE([host.pairSecret isEqualToString:@""]); + + instance_->ProvideSecret(base::SysNSStringToUTF8(kSecretPin), false, + base::SysNSStringToUTF8(kDeviceId)); + RunCFMessageLoop(); +} + +TEST_F(ClientInstanceTest, NoProxy) { + // After the proxy is released, we still expect quite a few functions to be + // able to run, but not produce any output. Some of these are just being + // executed for code coverage, the outputs are not pertinent to this test + // unit. + proxy_.reset(); + + instance_->Start("", ""); + RunCFMessageLoop(); + + instance_->FetchSecret(false, base::Bind(&SecretPinCallBack)); + AssertAcknowledged(false); + + instance_->ProvideSecret(base::SysNSStringToUTF8(kSecretPin), false, + base::SysNSStringToUTF8(kDeviceId)); + AssertAcknowledged(false); + + instance_->PerformMouseAction(webrtc::DesktopVector(0, 0), + webrtc::DesktopVector(0, 0), + (protocol::MouseEvent_MouseButton)0, false); + AssertAcknowledged(false); + + instance_->PerformKeyboardAction(0, false); + AssertAcknowledged(false); + + instance_->OnConnectionState(protocol::ConnectionToHost::State::CONNECTED, + protocol::ErrorCode::OK); + AssertAcknowledged(false); + + instance_->OnConnectionReady(false); + AssertAcknowledged(false); + + instance_->OnRouteChanged("", protocol::TransportRoute()); + AssertAcknowledged(false); + + // SetCapabilities requires a host connection to be established + // instance_->SetCapabilities(""); + // AssertAcknowledged(false); + + instance_->SetPairingResponse(protocol::PairingResponse()); + AssertAcknowledged(false); + + instance_->DeliverHostMessage(protocol::ExtensionMessage()); + AssertAcknowledged(false); + + ASSERT_TRUE(instance_->GetClipboardStub() != NULL); + ASSERT_TRUE(instance_->GetCursorShapeStub() != NULL); + + protocol::ClipboardEvent event; + event.set_mime_type(kMimeTypeTextUtf8); + event.set_data("Test data."); + instance_->InjectClipboardEvent(event); + AssertAcknowledged(false); + + instance_->SetCursorShape(protocol::CursorShapeInfo()); + AssertAcknowledged(false); +} + +TEST_F(ClientInstanceTest, OnConnectionStateINITIALIZING) { + TestConnectionStatus(protocol::ConnectionToHost::State::INITIALIZING); +} + +TEST_F(ClientInstanceTest, OnConnectionStateCONNECTING) { + TestConnectionStatus(protocol::ConnectionToHost::State::CONNECTING); +} + +TEST_F(ClientInstanceTest, OnConnectionStateAUTHENTICATED) { + TestConnectionStatus(protocol::ConnectionToHost::State::AUTHENTICATED); +} + +TEST_F(ClientInstanceTest, OnConnectionStateCONNECTED) { + TestConnectionStatus(protocol::ConnectionToHost::State::CONNECTED); +} + +TEST_F(ClientInstanceTest, OnConnectionStateFAILED) { + TestConnectionStatus(protocol::ConnectionToHost::State::FAILED); +} + +TEST_F(ClientInstanceTest, OnConnectionStateCLOSED) { + TestConnectionStatus(protocol::ConnectionToHost::State::CLOSED); +} + +TEST_F(ClientInstanceTest, OnConnectionReady) { + instance_->OnConnectionReady(true); + AssertAcknowledged(false); + instance_->OnConnectionReady(false); + AssertAcknowledged(false); +} + +TEST_F(ClientInstanceTest, OnRouteChanged) { + // Not expecting anything to happen + protocol::TransportRoute route; + + route.type = protocol::TransportRoute::DIRECT; + instance_->OnRouteChanged("", route); + AssertAcknowledged(false); + + route.type = protocol::TransportRoute::STUN; + instance_->OnRouteChanged("", route); + AssertAcknowledged(false); + + route.type = protocol::TransportRoute::RELAY; + instance_->OnRouteChanged("", route); + AssertAcknowledged(false); +} + +TEST_F(ClientInstanceTest, SetCursorShape) { + instance_->SetCursorShape(protocol::CursorShapeInfo()); + AssertAcknowledged(true); +} + +} // namespace remoting
diff --git a/remoting/client/ios/bridge/client_proxy.h b/remoting/client/ios/bridge/client_proxy.h new file mode 100644 index 0000000..c31e87921 --- /dev/null +++ b/remoting/client/ios/bridge/client_proxy.h
@@ -0,0 +1,68 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef REMOTING_CLIENT_IOS_BRIDGE_HOST_PROXY_H_ +#define REMOTING_CLIENT_IOS_BRIDGE_HOST_PROXY_H_ + +#include <memory> +#include <string> +#include <objc/objc.h> + +#include "base/memory/weak_ptr.h" +#include "remoting/protocol/connection_to_host.h" +#include "third_party/webrtc/modules/desktop_capture/desktop_frame.h" + +#if defined(__OBJC__) +@class ClientProxyDelegateWrapper; +#else // __OBJC__ +class ClientProxyDelegateWrapper; +#endif // __OBJC__ + +namespace remoting { + +// class AudioConsumer; + +namespace protocol { +class CursorShapeInfo; +} // namespace protocol + +// Proxies incoming common Chromoting protocol (HOST) to the UI Application +// (CLIENT). The HOST will have a Weak reference to call member functions on +// the UI Thread. +class ClientProxy : public base::SupportsWeakPtr<ClientProxy> { + public: + ClientProxy(ClientProxyDelegateWrapper* wrapper); + + // Notifies the user of the current connection status. + void ReportConnectionStatus(protocol::ConnectionToHost::State state, + protocol::ErrorCode error); + + // Display a dialog box asking the user to enter a PIN. + void DisplayAuthenticationPrompt(bool pairing_supported); + + // Saves new pairing credentials to permanent storage. An empty string + // represents the unknown value, do not use the NULL value. + void CommitPairingCredentials(const std::string& host_id, + const std::string& pair_id, + const std::string& pair_secret); + + // Delivers the latest image buffer for the canvas. + void RedrawCanvas(webrtc::DesktopFrame* buffer); + + // Updates cursor. + void UpdateCursorShape(const protocol::CursorShapeInfo& cursor_shape); + + private: + // Pointer to the UI application which implements the ClientProxyDelegate. + // (id) is similar to a (void*) |delegate_| is set from accepting a + // strongly typed @interface which wraps the @protocol ClientProxyDelegate. + // see comments for host_proxy_delegate_wrapper.h + id delegate_; + + DISALLOW_COPY_AND_ASSIGN(ClientProxy); +}; + +} // namespace remoting + +#endif // REMOTING_CLIENT_IOS_BRIDGE_HOST_PROXY_H_
diff --git a/remoting/client/ios/bridge/client_proxy.mm b/remoting/client/ios/bridge/client_proxy.mm new file mode 100644 index 0000000..2be7bd36 --- /dev/null +++ b/remoting/client/ios/bridge/client_proxy.mm
@@ -0,0 +1,155 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +#include "remoting/client/ios/bridge/client_proxy.h" + +#import "remoting/base/string_resources.h" +#import "remoting/client/ios/bridge/client_proxy_delegate_wrapper.h" +#import "remoting/client/ios/host_preferences.h" +#import "remoting/client/ios/utility.h" +#import "remoting/proto/control.pb.h" + +#include "base/logging.h" +#include "base/strings/string_util.h" +#include "base/strings/sys_string_conversions.h" + +namespace { +// The value indicating a successful connection has been established via a call +// to ReportConnectionStatus. +const static int kSuccessfulConnection = 3; + +NSString* GetStatusMsg(remoting::protocol::ConnectionToHost::State code) { + switch (code) { + case remoting::protocol::ConnectionToHost::INITIALIZING: + return CRD_LOCALIZED_STRING(IDS_FOOTER_WAITING); + case remoting::protocol::ConnectionToHost::CONNECTING: + return CRD_LOCALIZED_STRING(IDS_FOOTER_CONNECTING); + case remoting::protocol::ConnectionToHost::AUTHENTICATED: + // TODO(nicholss): This says "Working..." + return CRD_LOCALIZED_STRING(IDS_WORKING); + case remoting::protocol::ConnectionToHost::CONNECTED: + // TODO(nicholss): This says "Connected:" + return CRD_LOCALIZED_STRING(IDS_LABEL_CONNECTED); + case remoting::protocol::ConnectionToHost::FAILED: + // TODO(nicholss): This says "Authentication failed. Please sign in to + // Chrome again." + return CRD_LOCALIZED_STRING(IDS_ERROR_AUTHENTICATION_FAILED ); + case remoting::protocol::ConnectionToHost::CLOSED: + return CRD_LOCALIZED_STRING(IDS_MESSAGE_SESSION_FINISHED); + } + return CRD_LOCALIZED_STRING(IDS_ERROR_UNEXPECTED); +} + +// Translate a connection error code integer to a NSString description. +NSString* GetErrorMsg(remoting::protocol::ErrorCode code) { + switch (code) { + case remoting::protocol::ErrorCode::OK: + return CRD_LOCALIZED_STRING(IDS_OK); + case remoting::protocol::ErrorCode::INVALID_ACCOUNT: + return CRD_LOCALIZED_STRING(IDS_ERROR_INVALID_ACCOUNT); + case remoting::protocol::ErrorCode::MAX_SESSION_LENGTH: + return CRD_LOCALIZED_STRING(IDS_ERROR_MAX_SESSION_LENGTH); + case remoting::protocol::ErrorCode::PEER_IS_OFFLINE: + return CRD_LOCALIZED_STRING(IDS_ERROR_HOST_IS_OFFLINE); + case remoting::protocol::ErrorCode::HOST_CONFIGURATION_ERROR: + return CRD_LOCALIZED_STRING(IDS_ERROR_HOST_CONFIGURATION_ERROR); + case remoting::protocol::ErrorCode::SESSION_REJECTED: + return CRD_LOCALIZED_STRING(IDS_ERROR_INVALID_ACCESS_CODE); + case remoting::protocol::ErrorCode::INCOMPATIBLE_PROTOCOL: + return CRD_LOCALIZED_STRING(IDS_ERROR_INCOMPATIBLE_PROTOCOL); + case remoting::protocol::ErrorCode::AUTHENTICATION_FAILED: + return CRD_LOCALIZED_STRING(IDS_ERROR_INVALID_ACCESS_CODE); + case remoting::protocol::ErrorCode::CHANNEL_CONNECTION_ERROR: + return CRD_LOCALIZED_STRING(IDS_ERROR_P2P_FAILURE); + case remoting::protocol::ErrorCode::SIGNALING_ERROR: + return CRD_LOCALIZED_STRING(IDS_ERROR_P2P_FAILURE); + case remoting::protocol::ErrorCode::SIGNALING_TIMEOUT: + return CRD_LOCALIZED_STRING(IDS_ERROR_P2P_FAILURE); + case remoting::protocol::ErrorCode::HOST_OVERLOAD: + return CRD_LOCALIZED_STRING(IDS_ERROR_HOST_OVERLOAD); + case remoting::protocol::ErrorCode::UNKNOWN_ERROR: + return CRD_LOCALIZED_STRING(IDS_ERROR_UNEXPECTED); + } + return CRD_LOCALIZED_STRING(IDS_ERROR_UNEXPECTED); +} + +} // namespace + +namespace remoting { + +ClientProxy::ClientProxy(ClientProxyDelegateWrapper* wrapper) { + delegate_ = [wrapper delegate]; +} + +void ClientProxy::ReportConnectionStatus( + protocol::ConnectionToHost::State state, + protocol::ErrorCode error) { + DCHECK(delegate_); + if (state <= kSuccessfulConnection && error == protocol::ErrorCode::OK) { + // Report Progress + [delegate_ connectionStatus:GetStatusMsg(state)]; + + if (state == kSuccessfulConnection) { + [delegate_ connected]; + } + } else { + [delegate_ connectionStatus:GetStatusMsg(state)]; + if (error != protocol::ErrorCode::OK) { + [delegate_ connectionFailed:GetErrorMsg(error)]; + } + } +} + +void ClientProxy::DisplayAuthenticationPrompt(bool pairing_supported) { + DCHECK(delegate_); + [delegate_ requestHostPin:pairing_supported]; +} + +void ClientProxy::CommitPairingCredentials(const std::string& host_id, + const std::string& pair_id, + const std::string& pair_secret) { + DCHECK(delegate_); + NSString* nsHostId = base::SysUTF8ToNSString(host_id); + NSString* nsPairId = base::SysUTF8ToNSString(pair_id); + NSString* nsPairSecret = base::SysUTF8ToNSString(pair_secret); + + HostPreferences* host = [HostPreferences hostForId:nsHostId]; + host.pairId = nsPairId; + host.pairSecret = nsPairSecret; + + [host saveToSSOKeychain]; +} + +void ClientProxy::RedrawCanvas(webrtc::DesktopFrame* buffer) { + DCHECK(delegate_); + std::vector<webrtc::DesktopRect> rects; + + for (webrtc::DesktopRegion::Iterator i(buffer->updated_region()); + !i.IsAtEnd(); i.Advance()) { + rects.push_back(i.rect()); + } + + [delegate_ applyFrame:buffer->size() + stride:buffer->stride() + data:buffer->data() + rects:rects]; +} + +void ClientProxy::UpdateCursorShape( + const protocol::CursorShapeInfo& cursor_shape) { + DCHECK(delegate_); + const uint8_t* cursor_data = reinterpret_cast<const uint8_t*>( + cursor_shape.data().data()); + [delegate_ applyCursor:webrtc::DesktopSize(cursor_shape.width(), + cursor_shape.height()) + hotspot:webrtc::DesktopVector(cursor_shape.hotspot_x(), + cursor_shape.hotspot_y()) + cursorData:const_cast<uint8_t*>(cursor_data)]; +} + +} // namespace remoting
diff --git a/remoting/client/ios/bridge/client_proxy_delegate.h b/remoting/client/ios/bridge/client_proxy_delegate.h new file mode 100644 index 0000000..5e90f52 --- /dev/null +++ b/remoting/client/ios/bridge/client_proxy_delegate.h
@@ -0,0 +1,43 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef REMOTING_CLIENT_IOS_BRIDGE_HOST_PROXY_DELEGATE_H_ +#define REMOTING_CLIENT_IOS_BRIDGE_HOST_PROXY_DELEGATE_H_ + +#import <Foundation/Foundation.h> +#import <UIKit/UIKit.h> + +#include <vector> + +#include "third_party/webrtc/modules/desktop_capture/desktop_geometry.h" + +// Contract to provide for callbacks from the common Chromoting protocol to the +// UI Application. +@protocol ClientProxyDelegate<NSObject> + +// HOST request for client to input their PIN. +- (void)requestHostPin:(BOOL)pairingSupported; + +// HOST notification that a connection has been successfully opened. +- (void)connected; + +// HOST notification for a change in connections status. +- (void)connectionStatus:(NSString*)statusMessage; + +// HOST notification that a connection has failed. +- (void)connectionFailed:(NSString*)errorMessage; + +// A new Canvas (desktop) update has arrived. +- (void)applyFrame:(const webrtc::DesktopSize&)size + stride:(NSInteger)stride + data:(uint8_t*)data + rects:(const std::vector<webrtc::DesktopRect>&)regions; + +// A new Cursor (mouse) update has arrived. +- (void)applyCursor:(const webrtc::DesktopSize&)size + hotspot:(const webrtc::DesktopVector&)hotspot + cursorData:(uint8_t*)data; +@end + +#endif // REMOTING_CLIENT_IOS_BRIDGE_HOST_PROXY_DELEGATE_H_
diff --git a/remoting/client/ios/bridge/client_proxy_delegate_wrapper.h b/remoting/client/ios/bridge/client_proxy_delegate_wrapper.h new file mode 100644 index 0000000..9d5de4e --- /dev/null +++ b/remoting/client/ios/bridge/client_proxy_delegate_wrapper.h
@@ -0,0 +1,33 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef REMOTING_CLIENT_IOS_BRIDGE_HOST_PROXY_DELEGATE_WRAPPER_H_ +#define REMOTING_CLIENT_IOS_BRIDGE_HOST_PROXY_DELEGATE_WRAPPER_H_ + +#import <Foundation/Foundation.h> +#import <UIKit/UIKit.h> + +#include <vector> + +#include "third_party/webrtc/modules/desktop_capture/desktop_geometry.h" + +#import "remoting/client/ios/bridge/client_proxy_delegate.h" + +// Wraps ClientProxyDelegate in a class so C++ can accept a strongly typed +// pointer. C++ does not understand the id<> convention of passing around a +// OBJ_C @protocol pointer. So the @protocol is wrapped and the class is passed +// around. After accepting an instance of ClientProxyDelegateWrapper, the +// @protocol can be referenced as type (id), which is similar to a (void*). + +@interface ClientProxyDelegateWrapper : NSObject + +@property(nonatomic, retain, readonly) id<ClientProxyDelegate> delegate; + +- (id)init __unavailable; + ++ (id)wrapDelegate:(id<ClientProxyDelegate>)delegate; + +@end + +#endif // REMOTING_CLIENT_IOS_BRIDGE_HOST_PROXY_DELEGATE_WRAPPER_H_
diff --git a/remoting/client/ios/bridge/client_proxy_delegate_wrapper.mm b/remoting/client/ios/bridge/client_proxy_delegate_wrapper.mm new file mode 100644 index 0000000..0297b9b --- /dev/null +++ b/remoting/client/ios/bridge/client_proxy_delegate_wrapper.mm
@@ -0,0 +1,31 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +#import "remoting/client/ios/bridge/client_proxy_delegate_wrapper.h" + +@interface ClientProxyDelegateWrapper (Private) +- (id)initWithDelegate:(id<ClientProxyDelegate>)delegate; +@end + +@implementation ClientProxyDelegateWrapper + +@synthesize delegate = _delegate; + +- (id)initWithDelegate:(id<ClientProxyDelegate>)delegate { + self = [super init]; + if (self) { + _delegate = delegate; + } + return self; +} + ++ (id)wrapDelegate:(id<ClientProxyDelegate>)delegate { + return [[ClientProxyDelegateWrapper alloc] initWithDelegate:delegate]; +} + +@end
diff --git a/remoting/client/ios/bridge/client_proxy_unittest.mm b/remoting/client/ios/bridge/client_proxy_unittest.mm new file mode 100644 index 0000000..a0aebd8 --- /dev/null +++ b/remoting/client/ios/bridge/client_proxy_unittest.mm
@@ -0,0 +1,371 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +#import "remoting/client/ios/bridge/client_proxy.h" + +#import "base/compiler_specific.h" +#import "testing/gtest_mac.h" + +#import "remoting/client/ios/host_preferences.h" +#import "remoting/client/ios/bridge/client_proxy_delegate_wrapper.h" + +#include "base/strings/sys_string_conversions.h" +#include "remoting/proto/control.pb.h" +#include "remoting/proto/event.pb.h" + +@interface ClientProxyDelegateTester : NSObject<ClientProxyDelegate> +@property(nonatomic, assign) BOOL isConnected; +@property(nonatomic, copy) NSString* statusMessage; +@property(nonatomic, copy) NSString* errorMessage; +@property(nonatomic, assign) BOOL isPairingSupported; +@property(nonatomic, assign) webrtc::DesktopSize size; +@property(nonatomic, assign) NSInteger stride; +@property(nonatomic, assign) uint8_t* data; +@property(nonatomic, assign) std::vector<webrtc::DesktopRect> rects; +@property(nonatomic, assign) webrtc::DesktopVector hotspot; +@end + +@implementation ClientProxyDelegateTester + +@synthesize isConnected = _isConnected; +@synthesize statusMessage = _statusMessage; +@synthesize errorMessage = _errorMessage; +@synthesize isPairingSupported = _isPairingSupported; +@synthesize size = _size; +@synthesize stride = _stride; +@synthesize data = _data; +@synthesize rects = _rects; +@synthesize hotspot = _hotspot; + +- (void)connected { + _isConnected = true; +} + +- (void)connectionStatus:(NSString*)statusMessage { + _statusMessage = statusMessage; +} + +- (void)connectionFailed:(NSString*)errorMessage { + _errorMessage = errorMessage; +} + +- (void)requestHostPin:(BOOL)pairingSupported { + _isPairingSupported = pairingSupported; +} + +- (void)applyFrame:(const webrtc::DesktopSize&)size + stride:(NSInteger)stride + data:(uint8_t*)data + rects:(const std::vector<webrtc::DesktopRect>&)rects { + _size = size; + _stride = stride; + _data = data; + _rects.assign(rects.begin(), rects.end()); +} + +- (void)applyCursor:(const webrtc::DesktopSize&)size + hotspot:(const webrtc::DesktopVector&)hotspot + cursorData:(uint8_t*)data { + _size = size; + _hotspot = hotspot; + _data = data; +} + +@end + +namespace remoting { + +namespace { + +NSString* kStatusINITIALIZING = @"Initializing connection"; +NSString* kStatusCONNECTING = @"Connecting"; +NSString* kStatusAUTHENTICATED = @"Authenticated"; +NSString* kStatusCONNECTED = @"Connected"; +NSString* kStatusFAILED = @"Connection Failed"; +NSString* kStatusCLOSED = @"Connection closed"; +NSString* kStatusDEFAULT = @"Unknown connection state"; + +NSString* kErrorPEER_IS_OFFLINE = @"Requested host is offline."; +NSString* kErrorSESSION_REJECTED = @"Session was rejected by the host."; +NSString* kErrorINCOMPATIBLE_PROTOCOL = @"Incompatible Protocol."; +NSString* kErrorAUTHENTICATION_FAILED = @"Authentication Failed."; +NSString* kErrorCHANNEL_CONNECTION_ERROR = @"Channel Connection Error"; +NSString* kErrorSIGNALING_ERROR = @"Signaling Error"; +NSString* kErrorSIGNALING_TIMEOUT = @"Signaling Timeout"; +NSString* kErrorHOST_OVERLOAD = @"Host Overload"; +NSString* kErrorUNKNOWN_ERROR = + @"An unknown error has occurred, preventing the session from opening."; +NSString* kErrorDEFAULT = @"An unknown error code has occurred."; + +const webrtc::DesktopSize kFrameSize(100, 100); + +// Note these are disjoint regions. Testing intersecting regions is beyond the +// scope of this test class. +const webrtc::DesktopRect kFrameSubRect1 = + webrtc::DesktopRect::MakeXYWH(0, 0, 10, 10); +const webrtc::DesktopRect kFrameSubRect2 = + webrtc::DesktopRect::MakeXYWH(11, 11, 10, 10); +const webrtc::DesktopRect kFrameSubRect3 = + webrtc::DesktopRect::MakeXYWH(22, 22, 10, 10); + +const int kCursorHeight = 10; +const int kCursorWidth = 20; +const int kCursorHotSpotX = 4; +const int kCursorHotSpotY = 8; +// |kCursorDataLength| is assumed to be evenly divisible by 4 +const int kCursorDataLength = kCursorHeight * kCursorWidth; +const uint32_t kCursorDataPattern = 0xF0E1D2C3; + +NSString* const kHostName = @"ClientProxyHostNameTest"; +NSString* const kPairingId = @"ClientProxyPairingIdTest"; +NSString* const kPairingSecret = @"ClientProxyPairingSecretTest"; + +} // namespace + +class ClientProxyTest : public ::testing::Test { + protected: + void SetUp() override { + delegateTester_ = [[ClientProxyDelegateTester alloc] init]; + clientProxy_.reset(new ClientProxy( + [ClientProxyDelegateWrapper wrapDelegate:delegateTester_])); + } + + void ResetIsConnected() { delegateTester_.isConnected = false; } + + void TestConnnectionStatus(protocol::ConnectionToHost::State state, + NSString* expectedStatusMsg) { + ResetIsConnected(); + clientProxy_->ReportConnectionStatus(state, protocol::ErrorCode::OK); + EXPECT_NSEQ(expectedStatusMsg, delegateTester_.statusMessage); + + if (state == protocol::ConnectionToHost::State::CONNECTED) { + EXPECT_TRUE(delegateTester_.isConnected); + } else { + EXPECT_FALSE(delegateTester_.isConnected); + } + + TestErrorMessages(state, expectedStatusMsg); + } + + void TestForError(protocol::ConnectionToHost::State state, + protocol::ErrorCode errorCode, + NSString* expectedStatusMsg, + NSString* expectedErrorMsg) { + ResetIsConnected(); + clientProxy_->ReportConnectionStatus(state, errorCode); + EXPECT_FALSE(delegateTester_.isConnected); + EXPECT_NSEQ(expectedStatusMsg, delegateTester_.statusMessage); + EXPECT_NSEQ(expectedErrorMsg, delegateTester_.errorMessage); + } + + void TestErrorMessages(protocol::ConnectionToHost::State state, + NSString* expectedStatusMsg) { + TestForError(state, protocol::ErrorCode::AUTHENTICATION_FAILED, + expectedStatusMsg, kErrorAUTHENTICATION_FAILED); + TestForError(state, protocol::ErrorCode::CHANNEL_CONNECTION_ERROR, + expectedStatusMsg, kErrorCHANNEL_CONNECTION_ERROR); + TestForError(state, protocol::ErrorCode::HOST_OVERLOAD, expectedStatusMsg, + kErrorHOST_OVERLOAD); + TestForError(state, protocol::ErrorCode::INCOMPATIBLE_PROTOCOL, + expectedStatusMsg, kErrorINCOMPATIBLE_PROTOCOL); + TestForError(state, protocol::ErrorCode::PEER_IS_OFFLINE, + expectedStatusMsg, kErrorPEER_IS_OFFLINE); + TestForError(state, protocol::ErrorCode::SESSION_REJECTED, + expectedStatusMsg, kErrorSESSION_REJECTED); + TestForError(state, protocol::ErrorCode::SIGNALING_ERROR, + expectedStatusMsg, kErrorSIGNALING_ERROR); + TestForError(state, protocol::ErrorCode::SIGNALING_TIMEOUT, + expectedStatusMsg, kErrorSIGNALING_TIMEOUT); + TestForError(state, protocol::ErrorCode::UNKNOWN_ERROR, expectedStatusMsg, + kErrorUNKNOWN_ERROR); + TestForError(state, static_cast<protocol::ErrorCode>(999), + expectedStatusMsg, kErrorDEFAULT); + } + + void ValidateHost(const std::string& hostName, + const std::string& pairingId, + const std::string& pairingSecret) { + NSString* hostNameAsNSString = base::SysUTF8ToNSString(hostName); + + // Check if credentials are currently stored, and if so, delete them. + HostPreferences* existingHost = + [HostPreferences hostForId:hostNameAsNSString]; + if (existingHost != nil) { + existingHost.pairId = @""; + existingHost.pairSecret = @""; + [existingHost saveToSSOKeychain]; + } + + clientProxy_->CommitPairingCredentials(hostName, pairingId, pairingSecret); + + // Fetch new credentials from keychain. + HostPreferences* host = [HostPreferences hostForId:hostNameAsNSString]; + + ASSERT_TRUE(host != nil); + ASSERT_TRUE([base::SysUTF8ToNSString(hostName) + isEqualToString:host.hostId]); + + if (pairingId.length() > 0) { + ASSERT_TRUE([base::SysUTF8ToNSString(pairingId) + isEqualToString:host.pairId]); + } else { + ASSERT_TRUE([host.pairId isEqualToString:@""]); + } + + if (pairingSecret.length() > 0) { + ASSERT_TRUE([base::SysUTF8ToNSString(pairingSecret) + isEqualToString:host.pairSecret]); + } else { + ASSERT_TRUE([host.pairSecret isEqualToString:@""]); + } + } + + std::unique_ptr<ClientProxy> clientProxy_; + ClientProxyDelegateTester* delegateTester_; + ClientProxyDelegateWrapper* delegateWrapper_; +}; + +// TODO(nicholss): Removing these tests for now until we settle on a +// what the final strings will be. +// TEST_F(ClientProxyTest, ReportConnectionStatusINITIALIZING) { +// TestConnnectionStatus(protocol::ConnectionToHost::State::INITIALIZING, +// kStatusINITIALIZING); +// } +// +// TEST_F(ClientProxyTest, ReportConnectionStatusCONNECTING) { +// TestConnnectionStatus(protocol::ConnectionToHost::State::CONNECTING, +// kStatusCONNECTING); +// } +// +// TEST_F(ClientProxyTest, ReportConnectionStatusAUTHENTICATED) { +// TestConnnectionStatus(protocol::ConnectionToHost::State::AUTHENTICATED, +// kStatusAUTHENTICATED); +// } +// +// TEST_F(ClientProxyTest, ReportConnectionStatusCONNECTED) { +// TestConnnectionStatus(protocol::ConnectionToHost::State::CONNECTED, +// kStatusCONNECTED); +// } +// +// TEST_F(ClientProxyTest, ReportConnectionStatusFAILED) { +// TestConnnectionStatus(protocol::ConnectionToHost::State::FAILED, +// kStatusFAILED); +// } +// +// TEST_F(ClientProxyTest, ReportConnectionStatusCLOSED) { +// TestConnnectionStatus(protocol::ConnectionToHost::State::CLOSED, +// kStatusCLOSED); +// } +// +// TEST_F(ClientProxyTest, ReportConnectionStatusDEFAULT) { +// TestConnnectionStatus(static_cast<protocol::ConnectionToHost::State>(999), +// kStatusDEFAULT); +// } + +TEST_F(ClientProxyTest, DisplayAuthenticationPrompt) { + clientProxy_->DisplayAuthenticationPrompt(true); + ASSERT_TRUE(delegateTester_.isPairingSupported); + clientProxy_->DisplayAuthenticationPrompt(false); + ASSERT_FALSE(delegateTester_.isPairingSupported); +} + +TEST_F(ClientProxyTest, CommitPairingCredentialsBasic) { + ValidateHost("", "", ""); +} + +TEST_F(ClientProxyTest, CommitPairingCredentialsExtended) { + ValidateHost(base::SysNSStringToUTF8(kHostName), + base::SysNSStringToUTF8(kPairingId), + base::SysNSStringToUTF8(kPairingSecret)); +} + +// TODO(nicholss): Re-enable these tests. +// TEST_F(ClientProxyTest, RedrawCanvasBasic) { +// webrtc::BasicDesktopFrame frame(webrtc::DesktopSize(1, 1)); +// webrtc::DesktopRegion regions; +// regions.AddRect(webrtc::DesktopRect::MakeLTRB(0, 0, 1, 1)); +// +// clientProxy_->RedrawCanvas(webrtc::DesktopSize(1, 1), &frame, regions); +// +// ASSERT_TRUE(webrtc::DesktopSize(1, 1).equals(delegateTester_.size)); +// ASSERT_EQ(4, delegateTester_.stride); +// ASSERT_TRUE(delegateTester_.data != NULL); +// ASSERT_EQ(1, delegateTester_.regions.size()); +// ASSERT_TRUE(delegateTester_.regions[0].equals( +// webrtc::DesktopRect::MakeLTRB(0, 0, 1, 1))); +// } +// +// TEST_F(ClientProxyTest, RedrawCanvasExtended) { +// webrtc::BasicDesktopFrame frame(kFrameSize); +// webrtc::DesktopRegion regions; +// regions.AddRect(kFrameSubRect1); +// regions.AddRect(kFrameSubRect2); +// regions.AddRect(kFrameSubRect3); +// +// clientProxy_->RedrawCanvas(kFrameSize, &frame, regions); +// +// ASSERT_TRUE(kFrameSize.equals(delegateTester_.size)); +// ASSERT_EQ(kFrameSize.width() * webrtc::DesktopFrame::kBytesPerPixel, +// delegateTester_.stride); +// ASSERT_TRUE(delegateTester_.data != NULL); +// ASSERT_EQ(3, delegateTester_.regions.size()); +// ASSERT_TRUE(delegateTester_.regions[0].equals(kFrameSubRect1)); +// ASSERT_TRUE(delegateTester_.regions[1].equals(kFrameSubRect2)); +// ASSERT_TRUE(delegateTester_.regions[2].equals(kFrameSubRect3)); +// } + +TEST_F(ClientProxyTest, UpdateCursorBasic) { + protocol::CursorShapeInfo cursor_proto; + cursor_proto.set_width(1); + cursor_proto.set_height(1); + cursor_proto.set_hotspot_x(0); + cursor_proto.set_hotspot_y(0); + + char data[4]; + memset(data, 0xFF, 4); + + cursor_proto.set_data(data); + + clientProxy_->UpdateCursorShape(cursor_proto); + + ASSERT_EQ(1, delegateTester_.size.width()); + ASSERT_EQ(1, delegateTester_.size.height()); + ASSERT_EQ(0, delegateTester_.hotspot.x()); + ASSERT_EQ(0, delegateTester_.hotspot.y()); + ASSERT_TRUE(delegateTester_.data != NULL); + for (int i = 0; i < 4; i++) { + ASSERT_EQ(0xFF, delegateTester_.data[i]); + } +} + +TEST_F(ClientProxyTest, UpdateCursorExtended) { + protocol::CursorShapeInfo cursor_proto; + cursor_proto.set_width(kCursorWidth); + cursor_proto.set_height(kCursorHeight); + cursor_proto.set_hotspot_x(kCursorHotSpotX); + cursor_proto.set_hotspot_y(kCursorHotSpotY); + + char data[kCursorDataLength]; + memset_pattern4(data, &kCursorDataPattern, kCursorDataLength); + + cursor_proto.set_data(data); + + clientProxy_->UpdateCursorShape(cursor_proto); + + ASSERT_EQ(kCursorWidth, delegateTester_.size.width()); + ASSERT_EQ(kCursorHeight, delegateTester_.size.height()); + ASSERT_EQ(kCursorHotSpotX, delegateTester_.hotspot.x()); + ASSERT_EQ(kCursorHotSpotY, delegateTester_.hotspot.y()); + ASSERT_TRUE(delegateTester_.data != NULL); + for (int i = 0; i < kCursorDataLength / 4; i++) { + ASSERT_TRUE(memcmp(&delegateTester_.data[i * 4], &kCursorDataPattern, 4) == + 0); + } +} + +} // namespace remoting
diff --git a/remoting/client/ios/bridge/frame_consumer_bridge.cc b/remoting/client/ios/bridge/frame_consumer_bridge.cc new file mode 100644 index 0000000..f129235 --- /dev/null +++ b/remoting/client/ios/bridge/frame_consumer_bridge.cc
@@ -0,0 +1,56 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "remoting/client/ios/bridge/frame_consumer_bridge.h" + +#include "base/bind.h" +#include "base/logging.h" +#include "base/memory/ptr_util.h" +#include "base/synchronization/waitable_event.h" +#include "remoting/base/util.h" +#include "third_party/webrtc/modules/desktop_capture/desktop_frame.h" + +namespace remoting { + +FrameConsumerBridge::FrameConsumerBridge(ClientInstance* client_instance, + const OnFrameCallback callback) + : callback_(callback), runtime_(client_instance), weak_factory_(this) {} + +FrameConsumerBridge::~FrameConsumerBridge() {} + +std::unique_ptr<webrtc::DesktopFrame> FrameConsumerBridge::AllocateFrame( + const webrtc::DesktopSize& size) { + return base::WrapUnique(new webrtc::BasicDesktopFrame(size)); +} + +void FrameConsumerBridge::RenderFrame( + std::unique_ptr<webrtc::DesktopFrame> frame) { + DCHECK(runtime_->display_task_runner()->BelongsToCurrentThread()); + // Draw the frame + callback_.Run(frame.get()); +} + +void FrameConsumerBridge::DrawFrame(std::unique_ptr<webrtc::DesktopFrame> frame, + const base::Closure& done) { + DCHECK(runtime_->network_task_runner()->BelongsToCurrentThread()); + + runtime_->display_task_runner()->PostTaskAndReply( + FROM_HERE, base::Bind(&FrameConsumerBridge::RenderFrame, + weak_factory_.GetWeakPtr(), base::Passed(&frame)), + base::Bind(&FrameConsumerBridge::OnFrameRendered, + weak_factory_.GetWeakPtr(), done)); +} + +void FrameConsumerBridge::OnFrameRendered(const base::Closure& done) { + DCHECK(runtime_->network_task_runner()->BelongsToCurrentThread()); + + if (!done.is_null()) + done.Run(); +} + +FrameConsumerBridge::PixelFormat FrameConsumerBridge::GetPixelFormat() { + return FORMAT_RGBA; +} + +} // namespace remoting
diff --git a/remoting/client/ios/bridge/frame_consumer_bridge.h b/remoting/client/ios/bridge/frame_consumer_bridge.h new file mode 100644 index 0000000..ca51821 --- /dev/null +++ b/remoting/client/ios/bridge/frame_consumer_bridge.h
@@ -0,0 +1,62 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef REMOTING_CLIENT_IOS_BRIDGE_FRAME_CONSUMER_BRIDGE_H_ +#define REMOTING_CLIENT_IOS_BRIDGE_FRAME_CONSUMER_BRIDGE_H_ + +#include <list> +#include <memory> + +#include "base/callback.h" +#include "base/compiler_specific.h" +#include "base/memory/scoped_vector.h" +#include "base/memory/weak_ptr.h" +#include "remoting/client/ios/bridge/client_instance.h" +#include "remoting/protocol/frame_consumer.h" +#include "third_party/webrtc/modules/desktop_capture/desktop_frame.h" +#include "third_party/webrtc/modules/desktop_capture/desktop_geometry.h" + +namespace remoting { + +class ClientInstance; + +// TODO(nicholss): It should be possible to use remoting/client/ +// dual_buffer_frame_consumer.h instead of this class. +class FrameConsumerBridge : public protocol::FrameConsumer { + public: + typedef base::Callback<void(webrtc::DesktopFrame* buffer)> OnFrameCallback; + + // A callback is provided to return frame updates asynchronously. + explicit FrameConsumerBridge(ClientInstance* client_instance, + const OnFrameCallback callback); + + ~FrameConsumerBridge() override; + + std::unique_ptr<webrtc::DesktopFrame> AllocateFrame( + const webrtc::DesktopSize& size) override; + + void DrawFrame(std::unique_ptr<webrtc::DesktopFrame> frame, + const base::Closure& done) override; + + PixelFormat GetPixelFormat() override; + + private: + void RenderFrame(std::unique_ptr<webrtc::DesktopFrame> frame); + + void OnFrameRendered(const base::Closure& done); + + OnFrameCallback callback_; + + ClientInstance* runtime_; + + webrtc::DesktopSize view_size_; + + base::WeakPtrFactory<FrameConsumerBridge> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(FrameConsumerBridge); +}; + +} // namespace remoting + +#endif // REMOTING_CLIENT_IOS_BRIDGE_FRAME_CONSUMER_BRIDGE_H_
diff --git a/remoting/client/ios/bridge/frame_consumer_bridge_unittest.cc b/remoting/client/ios/bridge/frame_consumer_bridge_unittest.cc new file mode 100644 index 0000000..61e2ec9 --- /dev/null +++ b/remoting/client/ios/bridge/frame_consumer_bridge_unittest.cc
@@ -0,0 +1,140 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "remoting/client/ios/bridge/frame_consumer_bridge.h" + +#include <gtest/gtest.h> +#include <memory> +#include <queue> + +#include "base/bind.h" +#include "third_party/webrtc/modules/desktop_capture/desktop_frame.h" +#include "third_party/webrtc/modules/desktop_capture/desktop_region.h" + +namespace { +const webrtc::DesktopSize kFrameSize(100, 100); +const webrtc::DesktopVector kDpi(100, 100); + +const webrtc::DesktopRect FrameRect() { + return webrtc::DesktopRect::MakeSize(kFrameSize); +} + +webrtc::DesktopRegion FrameRegion() { + return webrtc::DesktopRegion(FrameRect()); +} + +void FrameDelivery(webrtc::DesktopFrame* buffer, + const webrtc::DesktopRegion& region) { + ASSERT_TRUE(buffer->size().equals(kFrameSize)); + ASSERT_TRUE(region.Equals(FrameRegion())); +}; + +} // namespace + +namespace remoting { + +class FrameProducerTester : public FrameProducer { + public: + virtual ~FrameProducerTester(){}; + + void DrawBuffer(webrtc::DesktopFrame* buffer) override { + frames.push(buffer); + }; + + void InvalidateRegion(const webrtc::DesktopRegion& region) override { + NOTIMPLEMENTED(); + }; + + void RequestReturnBuffers(const base::Closure& done) override { + // Don't have to actually return the buffers. This function is really + // saying don't use the references anymore, they are now invalid. + while (!frames.empty()) { + frames.pop(); + } + done.Run(); + }; + + void SetOutputSizeAndClip(const webrtc::DesktopSize& view_size, + const webrtc::DesktopRect& clip_area) override { + viewSize = view_size; + clipArea = clip_area; + }; + + std::queue<webrtc::DesktopFrame*> frames; + webrtc::DesktopSize viewSize; + webrtc::DesktopRect clipArea; +}; + +class FrameConsumerBridgeTest : public ::testing::Test { + protected: + void SetUp() override { + frameProducer_.reset(new FrameProducerTester()); + frameConsumer_.reset(new FrameConsumerBridge(base::Bind(&FrameDelivery))); + frameConsumer_->Initialize(frameProducer_.get()); + } + void TearDown() override {} + + std::unique_ptr<FrameProducerTester> frameProducer_; + std::unique_ptr<FrameConsumerBridge> frameConsumer_; +}; + +TEST(FrameConsumerBridgeTest_NotInitialized, CreateAndRelease) { + std::unique_ptr<FrameConsumerBridge> frameConsumer_( + new FrameConsumerBridge(base::Bind(&FrameDelivery))); + ASSERT_TRUE(frameConsumer_.get() != NULL); + frameConsumer_.reset(); + ASSERT_TRUE(frameConsumer_.get() == NULL); +} + +// TODO(nicholss): FrameConsumer has changed since last integration. +// Need to update the tests. +// TEST_F(FrameConsumerBridgeTest, ApplyBuffer) { +// webrtc::DesktopFrame* frame = NULL; +// ASSERT_EQ(0, frameProducer_->frames.size()); +// frameConsumer_->SetSourceSize(kFrameSize, kDpi); +// ASSERT_EQ(1, frameProducer_->frames.size()); +// +// // Return the frame, and ensure we get it back +// frame = frameProducer_->frames.front(); +// frameProducer_->frames.pop(); +// ASSERT_EQ(0, frameProducer_->frames.size()); +// frameConsumer_->ApplyBuffer( +// kFrameSize, FrameRect(), frame, FrameRegion(), FrameRegion()); +// ASSERT_EQ(1, frameProducer_->frames.size()); +// ASSERT_TRUE(frame == frameProducer_->frames.front()); +// ASSERT_TRUE(frame->data() == frameProducer_->frames.front()->data()); +// +// // Change the SourceSize, we should get a new frame, but when the old frame +// is +// // submitted we will not get it back. +// frameConsumer_->SetSourceSize(webrtc::DesktopSize(1, 1), kDpi); +// ASSERT_EQ(2, frameProducer_->frames.size()); +// frame = frameProducer_->frames.front(); +// frameProducer_->frames.pop(); +// ASSERT_EQ(1, frameProducer_->frames.size()); +// frameConsumer_->ApplyBuffer( +// kFrameSize, FrameRect(), frame, FrameRegion(), FrameRegion()); +// ASSERT_EQ(1, frameProducer_->frames.size()); +// } +// +// TEST_F(FrameConsumerBridgeTest, SetSourceSize) { +// frameConsumer_->SetSourceSize(webrtc::DesktopSize(0, 0), +// webrtc::DesktopVector(0, 0)); +// ASSERT_TRUE(frameProducer_->viewSize.equals(webrtc::DesktopSize(0, 0))); +// ASSERT_TRUE(frameProducer_->clipArea.equals( +// webrtc::DesktopRect::MakeLTRB(0, 0, 0, 0))); +// ASSERT_EQ(1, frameProducer_->frames.size()); +// ASSERT_TRUE( +// frameProducer_->frames.front()->size().equals(webrtc::DesktopSize(0, +// 0))); +// +// frameConsumer_->SetSourceSize(kFrameSize, kDpi); +// ASSERT_TRUE(frameProducer_->viewSize.equals(kFrameSize)); +// ASSERT_TRUE(frameProducer_->clipArea.equals(FrameRect())); +// ASSERT_EQ(2, frameProducer_->frames.size()); +// frameProducer_->frames.pop(); +// ASSERT_TRUE(frameProducer_->frames.front()->size().equals(kFrameSize)); +// } + +} // namespace remoting
diff --git a/remoting/client/ios/bridge/host_proxy.h b/remoting/client/ios/bridge/host_proxy.h new file mode 100644 index 0000000..b0ec6bf --- /dev/null +++ b/remoting/client/ios/bridge/host_proxy.h
@@ -0,0 +1,68 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef REMOTING_CLIENT_IOS_BRIDGE_CLIENT_PROXY_H_ +#define REMOTING_CLIENT_IOS_BRIDGE_CLIENT_PROXY_H_ + +#import <Foundation/Foundation.h> +#import <UIKit/UIKit.h> + +#include <memory> + +#import "remoting/client/ios/bridge/client_proxy_delegate_wrapper.h" + +#include "base/memory/ref_counted.h" +#include "third_party/webrtc/modules/desktop_capture/desktop_geometry.h" + +namespace remoting { +class ClientInstance; +class ClientProxy; +} // namespace remoting + +// HostProxy is one channel of a bridge from the UI Application (CLIENT) and the +// common Chromoting protocol (HOST). HostProxy proxies message from the UI +// application to the host. The reverse channel, ClientProxy, is owned by the +// HostProxy to control deconstruction order, but is shared with the +// ClientInstance to perform work. + +@interface HostProxy : NSObject { + @private + // Host to Client channel. + std::unique_ptr<remoting::ClientProxy> _hostToClientChannel; + // Client to Host channel, must be released before |_hostToClientChannel|. + scoped_refptr<remoting::ClientInstance> _clientToHostChannel; + // Connection state. + BOOL _isConnected; +} + +// TRUE when a connection has been established successfully. +- (BOOL)isConnected; + +// Forwards credentials from CLIENT and to HOST and begins establishing a +// connection. +- (void)connectToHost:(NSString*)username + authToken:(NSString*)token + jabberId:(NSString*)jid + hostId:(NSString*)hostId + publicKey:(NSString*)hostPublicKey + delegate:(id<ClientProxyDelegate>)delegate; + +// Report from CLIENT with the user's PIN. +- (void)authenticationResponse:(NSString*)pin createPairing:(BOOL)createPairing; + +// CLIENT initiated disconnection. +- (void)disconnectFromHost; + +// Report from CLIENT of mouse input. +- (void)mouseAction:(const webrtc::DesktopVector&)position + wheelDelta:(const webrtc::DesktopVector&)wheelDelta + whichButton:(NSInteger)buttonPressed + buttonDown:(BOOL)buttonIsDown; + +// Report from CLIENT of keyboard input. +- (void)keyboardAction:(NSInteger)keyCode keyDown:(BOOL)keyIsDown; + +@end + +#endif // REMOTING_CLIENT_IOS_BRIDGE_CLIENT_PROXY_H_
diff --git a/remoting/client/ios/bridge/host_proxy.mm b/remoting/client/ios/bridge/host_proxy.mm new file mode 100644 index 0000000..30f4f44e --- /dev/null +++ b/remoting/client/ios/bridge/host_proxy.mm
@@ -0,0 +1,116 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "remoting/client/ios/bridge/host_proxy.h" + +#import "remoting/client/ios/host_preferences.h" +#import "remoting/client/ios/bridge/client_instance.h" +#import "remoting/client/ios/bridge/client_proxy.h" + +#include "base/strings/sys_string_conversions.h" + +@implementation HostProxy + +// Override default constructor and initialize internals. +- (id)init { + self = [super init]; + if (self) { + _isConnected = false; + } + return self; +} + +// Override default destructor. +- (void)dealloc { + if (_isConnected) { + [self disconnectFromHost]; + } + + //[super dealloc]; // TODO(nicholss): ARC forbids explicit message send of + //'dealloc' +} + +- (BOOL)isConnected { + return _isConnected; +} + +- (void)connectToHost:(NSString*)username + authToken:(NSString*)token + jabberId:(NSString*)jid + hostId:(NSString*)hostId + publicKey:(NSString*)hostPublicKey + delegate:(id<ClientProxyDelegate>)delegate { + // Implicitly, if currently connected, discard the connection and begin a new + // connection. + [self disconnectFromHost]; + + _hostToClientChannel.reset(new remoting::ClientProxy( + [ClientProxyDelegateWrapper wrapDelegate:delegate])); + + DCHECK(!_clientToHostChannel.get()); + _clientToHostChannel = new remoting::ClientInstance( + _hostToClientChannel->AsWeakPtr(), base::SysNSStringToUTF8(username), + base::SysNSStringToUTF8(token), base::SysNSStringToUTF8(jid), + base::SysNSStringToUTF8(hostId), base::SysNSStringToUTF8(hostPublicKey)); + + HostPreferences* host = [HostPreferences hostForId:hostId]; + _clientToHostChannel->Start(base::SysNSStringToUTF8(host.pairId), + base::SysNSStringToUTF8(host.pairSecret)); + _isConnected = YES; +} + +- (void)authenticationResponse:(NSString*)pin + createPairing:(BOOL)createPairing { + if (_isConnected) { + // Where |deviceId| is first created doesn't matter, but it does have to be + // from an Obj-C file. Creating |deviceId| now, just before passing a copy + // into a C++ interface. + NSString* deviceId = + [[[UIDevice currentDevice] identifierForVendor] UUIDString]; + + _clientToHostChannel->ProvideSecret(base::SysNSStringToUTF8(pin), + createPairing, + base::SysNSStringToUTF8(deviceId)); + } +} + +- (void)disconnectFromHost { + if (_isConnected) { + VLOG(1) << "Disconnecting from Host"; + + // |_clientToHostChannel| must be closed before releasing + // |_hostToClientChannel|. + + // |_clientToHostChannel| owns several objects that have references to + // itself. These objects need to be cleaned up before we can release + // |_clientToHostChannel|. + _clientToHostChannel->Cleanup(); + // All other references to |_clientToHostChannel| should now be free. When + // the next statement is executed the destructor is called automatically. + _clientToHostChannel = NULL; + + _hostToClientChannel.reset(); + + _isConnected = NO; + } +} + +- (void)mouseAction:(const webrtc::DesktopVector&)position + wheelDelta:(const webrtc::DesktopVector&)wheelDelta + whichButton:(NSInteger)buttonPressed + buttonDown:(BOOL)buttonIsDown { + if (_isConnected) { + _clientToHostChannel->PerformMouseAction(position, wheelDelta, + (remoting::protocol::MouseEvent_MouseButton) buttonPressed, + buttonIsDown); + } +} + +- (void)keyboardAction:(NSInteger)keyCode keyDown:(BOOL)keyIsDown { + if (_isConnected) { + _clientToHostChannel->PerformKeyboardAction(keyCode, keyIsDown); + } +} + +@end
diff --git a/remoting/client/ios/bridge/host_proxy_unittest.mm b/remoting/client/ios/bridge/host_proxy_unittest.mm new file mode 100644 index 0000000..79f37ccd --- /dev/null +++ b/remoting/client/ios/bridge/host_proxy_unittest.mm
@@ -0,0 +1,51 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +#import "remoting/client/ios/bridge/host_proxy.h" + +#import "base/compiler_specific.h" +#import "testing/gtest_mac.h" + +namespace remoting { + +class HostProxyTest : public ::testing::Test { + protected: + void SetUp() override { hostProxy_ = [[HostProxy alloc] init]; } + + void CallPassThroughFunctions() { + [hostProxy_ mouseAction:webrtc::DesktopVector(0, 0) + wheelDelta:webrtc::DesktopVector(0, 0) + whichButton:0 + buttonDown:NO]; + [hostProxy_ keyboardAction:0 keyDown:NO]; + } + + HostProxy* hostProxy_; +}; + +TEST_F(HostProxyTest, ConnectDisconnect) { + CallPassThroughFunctions(); + + ASSERT_FALSE([hostProxy_ isConnected]); + [hostProxy_ connectToHost:@"" + authToken:@"" + jabberId:@"" + hostId:@"" + publicKey:@"" + delegate:nil]; + ASSERT_TRUE([hostProxy_ isConnected]); + + CallPassThroughFunctions(); + + [hostProxy_ disconnectFromHost]; + ASSERT_FALSE([hostProxy_ isConnected]); + + CallPassThroughFunctions(); +} + +} // namespace remoting
diff --git a/remoting/client/ios/host_preferences.h b/remoting/client/ios/host_preferences.h new file mode 100644 index 0000000..72dc7ed --- /dev/null +++ b/remoting/client/ios/host_preferences.h
@@ -0,0 +1,31 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef REMOTING_IOS_HOST_PREFERENCES_H_ +#define REMOTING_IOS_HOST_PREFERENCES_H_ + +#import <CoreData/CoreData.h> + +// A HostPreferences contains details to negotiate and maintain a connection +// to a remote Chromoting host. This is an entity in a backing store. + +@interface HostPreferences : NSObject<NSCoding> + +// Properties supplied by the host server. +@property(nonatomic, copy) NSString* hostId; +@property(nonatomic, copy) NSString* pairId; +@property(nonatomic, copy) NSString* pairSecret; + +// Commit this record using the SSOKeychain +// for SSOSigninManager's current identity. +- (void)saveToSSOKeychain; + +// Load a record from the SSOKeychain +// for SSOSigninManager's current identity. +// If a record does not exist, return a new record with a blank secret. ++ (HostPreferences*)hostForId:(NSString*)hostId; + +@end + +#endif // REMOTING_IOS_HOST_PREFERENCES_H_
diff --git a/remoting/client/ios/utility.h b/remoting/client/ios/utility.h new file mode 100644 index 0000000..3fe2370 --- /dev/null +++ b/remoting/client/ios/utility.h
@@ -0,0 +1,105 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef REMOTING_IOS_UTILITY_H_ +#define REMOTING_IOS_UTILITY_H_ + +#import <Foundation/Foundation.h> +#import <GLKit/GLKit.h> +#import <OpenGLES/ES2/gl.h> +#include <memory> + +#include "third_party/webrtc/modules/desktop_capture/desktop_frame.h" +#include "third_party/webrtc/modules/desktop_capture/desktop_geometry.h" + +#import "remoting/client/ios/bridge/host_proxy.h" + +#define CRD_LOCALIZED_STRING(stringId) \ + [Utility localizedStringForKey:@ #stringId dummyId:stringId] + +typedef struct { + GLKVector2 geometryVertex; + GLKVector2 textureVertex; +} TexturedVertex; + +typedef struct { + TexturedVertex bl; + TexturedVertex br; + TexturedVertex tl; + TexturedVertex tr; +} TexturedQuad; + +typedef struct { + GLuint name; + webrtc::DesktopRect rect; + // The draw surface is a triangle strip (triangles defined by the intersecting + // vertexes) to create a rectangle surface. + // 1****3 + // | / | + // | / | + // 2****4 + // This also determines the resolution of our surface, being a unit (NxN) grid + // with finite divisions. For our surface N = 1, and the number of divisions + // respects the CLIENT's desktop resolution. + TexturedQuad quad; +} TextureContainer; + +typedef struct { + std::unique_ptr<webrtc::BasicDesktopFrame> image; + std::unique_ptr<webrtc::DesktopVector> offset; +} GLRegion; + +@interface Utility : NSObject + ++ (BOOL)isPad; + ++ (BOOL)isInLandscapeMode; + +// Return the resolution in respect to orientation. ++ (CGSize)getOrientatedSize:(CGSize)size + shouldWidthBeLongestSide:(BOOL)shouldWidthBeLongestSide; + ++ (void)showAlert:(NSString*)title message:(NSString*)message; + ++ (NSString*)appVersionNumberDisplayString; + +// GL Binding Context requires some specific flags for the type of textures +// being drawn. ++ (void)bindTextureForIOS:(GLuint)glName; + +// Sometimes it is necessary to read gl errors. This is called in various +// places while working in the GL Context. ++ (void)logGLErrorCode:(NSString*)funcName; + ++ (void)drawSubRectToGLFromRectOfSize:(const webrtc::DesktopSize&)rectSize + subRect:(const webrtc::DesktopRect&)subRect + data:(const uint8_t*)data; + ++ (void)moveMouse:(HostProxy*)controller at:(const webrtc::DesktopVector&)point; + ++ (void)leftClickOn:(HostProxy*)controller + at:(const webrtc::DesktopVector&)point; + ++ (void)middleClickOn:(HostProxy*)controller + at:(const webrtc::DesktopVector&)point; + ++ (void)rightClickOn:(HostProxy*)controller + at:(const webrtc::DesktopVector&)point; + ++ (void)mouseScroll:(HostProxy*)controller + at:(const webrtc::DesktopVector&)point + delta:(const webrtc::DesktopVector&)delta; + +// Wrapper around NSLocalizedString. Don't call this directly. Use +// CRD_LOCALIZED_STRING instead. |dummyId| is ignored. It's used by +// CRD_LOCALIZED_STRING to force the compiler to resolve the constant name. ++ (NSString*)localizedStringForKey:(NSString*)key dummyId:(int)dummyId; + +// Objective-C friendly wrapper around ReplaceStringPlaceholders. ++ (NSString*)stringWithL10nFormat:(NSString*)format + withReplacements:(NSArray*)replacements; + +@end + +#endif // REMOTING_IOS_UTILITY_H_
diff --git a/remoting/client/ios/utility.mm b/remoting/client/ios/utility.mm new file mode 100644 index 0000000..23a4faf --- /dev/null +++ b/remoting/client/ios/utility.mm
@@ -0,0 +1,173 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +#import "remoting/client/ios/utility.h" + +#include "base/logging.h" +#include "base/strings/string_util.h" +#include "base/strings/sys_string_conversions.h" + +@implementation Utility + ++ (BOOL)isPad { + return (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad); +} + ++ (BOOL)isInLandscapeMode { + UIInterfaceOrientation orientation = + [UIApplication sharedApplication].statusBarOrientation; + + if ((orientation == UIInterfaceOrientationLandscapeLeft) || + (orientation == UIInterfaceOrientationLandscapeRight)) { + return YES; + } + return NO; +} + ++ (CGSize)getOrientatedSize:(CGSize)size + shouldWidthBeLongestSide:(BOOL)shouldWidthBeLongestSide { + if (shouldWidthBeLongestSide && (size.height > size.width)) { + return CGSizeMake(size.height, size.width); + } + return size; +} + ++ (void)showAlert:(NSString*)title message:(NSString*)message { + UIAlertController* alert; + alert = + [UIAlertController alertControllerWithTitle:title + message:message + preferredStyle:UIAlertControllerStyleAlert]; + + UIAlertAction* defaultAction = + [UIAlertAction actionWithTitle:@"OK" + style:UIAlertActionStyleDefault + handler:^(UIAlertAction* action){ + }]; + + [alert addAction:defaultAction]; + [[UIApplication sharedApplication].delegate.window.rootViewController + presentViewController:alert + animated:YES + completion:nil]; +} + ++ (NSString*)appVersionNumberDisplayString { + NSDictionary* infoDictionary = [[NSBundle mainBundle] infoDictionary]; + + NSString* version = + [infoDictionary objectForKey:@"CFBundleShortVersionString"]; + + return [NSString stringWithFormat:@"Version %@", version]; +} + ++ (void)bindTextureForIOS:(GLuint)glName { + glBindTexture(GL_TEXTURE_2D, glName); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); +} + ++ (void)logGLErrorCode:(NSString*)funcName { + GLenum errorCode = 1; + + while (errorCode != 0) { + errorCode = glGetError(); // I don't know why this is returning an error + // on the first call to this function, but if I + // don't read it, then stuff doesn't work... + VLOG_IF(0, errorCode) << "GLerror in " << + [funcName cStringUsingEncoding:NSUTF8StringEncoding] << ": " + << std::hex << errorCode << std::dec; + } +} + ++ (void)drawSubRectToGLFromRectOfSize:(const webrtc::DesktopSize&)rectSize + subRect:(const webrtc::DesktopRect&)subRect + data:(const uint8_t*)data { + DCHECK(rectSize.width() >= subRect.width()); + DCHECK(rectSize.height() >= subRect.height()); + DCHECK(subRect.left() >= 0); + DCHECK(subRect.top() >= 0); + DCHECK(data); + + glTexSubImage2D(GL_TEXTURE_2D, 0, subRect.left(), subRect.top(), + subRect.width(), subRect.height(), GL_RGBA, GL_UNSIGNED_BYTE, + data); +} + ++ (void)moveMouse:(HostProxy*)controller + at:(const webrtc::DesktopVector&)point { + [controller mouseAction:point + wheelDelta:webrtc::DesktopVector(0, 0) + whichButton:0 + buttonDown:NO]; +} + ++ (void)leftClickOn:(HostProxy*)controller + at:(const webrtc::DesktopVector&)point { + [controller mouseAction:point + wheelDelta:webrtc::DesktopVector(0, 0) + whichButton:1 + buttonDown:YES]; + [controller mouseAction:point + wheelDelta:webrtc::DesktopVector(0, 0) + whichButton:1 + buttonDown:NO]; +} + ++ (void)middleClickOn:(HostProxy*)controller + at:(const webrtc::DesktopVector&)point { + [controller mouseAction:point + wheelDelta:webrtc::DesktopVector(0, 0) + whichButton:2 + buttonDown:YES]; + [controller mouseAction:point + wheelDelta:webrtc::DesktopVector(0, 0) + whichButton:2 + buttonDown:NO]; +} + ++ (void)rightClickOn:(HostProxy*)controller + at:(const webrtc::DesktopVector&)point { + [controller mouseAction:point + wheelDelta:webrtc::DesktopVector(0, 0) + whichButton:3 + buttonDown:YES]; + [controller mouseAction:point + wheelDelta:webrtc::DesktopVector(0, 0) + whichButton:3 + buttonDown:NO]; +} + ++ (void)mouseScroll:(HostProxy*)controller + at:(const webrtc::DesktopVector&)point + delta:(const webrtc::DesktopVector&)delta { + [controller mouseAction:point wheelDelta:delta whichButton:0 buttonDown:NO]; +} + ++ (NSString*)localizedStringForKey:(NSString*)key dummyId:(int)dummyId { + return NSLocalizedString(key, nil); +} + ++ (NSString*)stringWithL10nFormat:(NSString*)format + withReplacements:(NSArray*)replacements { + std::string format_str(base::SysNSStringToUTF8(format)); + std::vector<std::string> replacements_str; + + for (NSString* replacement in replacements) { + DCHECK([replacement isKindOfClass:[NSString class]]); + replacements_str.push_back(base::SysNSStringToUTF8(replacement)); + } + + std::string formatted_str( + base::ReplaceStringPlaceholders(format_str, replacements_str, nullptr)); + return base::SysUTF8ToNSString(formatted_str); +} + +@end
diff --git a/services/catalog/public/cpp/resource_loader.cc b/services/catalog/public/cpp/resource_loader.cc index e8c7475..4eb8c63 100644 --- a/services/catalog/public/cpp/resource_loader.cc +++ b/services/catalog/public/cpp/resource_loader.cc
@@ -33,8 +33,7 @@ bool ResourceLoader::OpenFiles(filesystem::mojom::DirectoryPtr directory, const std::set<std::string>& paths) { - mojo::Array<filesystem::mojom::FileOpenDetailsPtr> details( - mojo::Array<filesystem::mojom::FileOpenDetailsPtr>::New(paths.size())); + std::vector<filesystem::mojom::FileOpenDetailsPtr> details(paths.size()); size_t i = 0; for (const auto& path : paths) { filesystem::mojom::FileOpenDetailsPtr open_details( @@ -45,8 +44,7 @@ details[i++] = std::move(open_details); } - mojo::Array<filesystem::mojom::FileOpenResultPtr> results( - mojo::Array<filesystem::mojom::FileOpenResultPtr>::New(paths.size())); + std::vector<filesystem::mojom::FileOpenResultPtr> results; if (!directory->OpenFileHandles(std::move(details), &results)) return false;
diff --git a/services/ui/surfaces/direct_output_surface_ozone.cc b/services/ui/surfaces/direct_output_surface_ozone.cc index 99262d1..0cbf4bc 100644 --- a/services/ui/surfaces/direct_output_surface_ozone.cc +++ b/services/ui/surfaces/direct_output_surface_ozone.cc
@@ -111,13 +111,6 @@ context_provider_->ContextSupport()->PartialSwapBuffers( frame.sub_buffer_rect); } - - gpu::gles2::GLES2Interface* gl = context_provider_->ContextGL(); - const GLuint64 fence_sync = gl->InsertFenceSyncCHROMIUM(); - gl->ShallowFlushCHROMIUM(); - - gpu::SyncToken sync_token; - gl->GenUnverifiedSyncTokenCHROMIUM(fence_sync, sync_token.GetData()); } uint32_t DirectOutputSurfaceOzone::GetFramebufferCopyTextureFormat() {
diff --git a/services/ui/ws/gpu_service_proxy.cc b/services/ui/ws/gpu_service_proxy.cc index 6d3b126..0f851cc 100644 --- a/services/ui/ws/gpu_service_proxy.cc +++ b/services/ui/ws/gpu_service_proxy.cc
@@ -110,41 +110,8 @@ callback.Run(gfx::GpuMemoryBufferHandle()); return; } - - size_t bytes = 0; - if (!gfx::BufferSizeForBufferFormatChecked(size, format, &bytes)) { - callback.Run(gfx::GpuMemoryBufferHandle()); - return; - } - - mojo::ScopedSharedBufferHandle mojo_handle = - mojo::SharedBufferHandle::Create(bytes); - if (!mojo_handle.is_valid()) { - callback.Run(gfx::GpuMemoryBufferHandle()); - return; - } - - base::SharedMemoryHandle shm_handle; - size_t shm_size; - bool readonly; - MojoResult result = mojo::UnwrapSharedMemoryHandle( - std::move(mojo_handle), &shm_handle, &shm_size, &readonly); - if (result != MOJO_RESULT_OK) { - callback.Run(gfx::GpuMemoryBufferHandle()); - return; - } - DCHECK_EQ(shm_size, bytes); - DCHECK(!readonly); - const int stride = base::checked_cast<int>( - gfx::RowSizeForBufferFormat(size.width(), format, 0)); - - gfx::GpuMemoryBufferHandle gmb_handle; - gmb_handle.type = gfx::SHARED_MEMORY_BUFFER; - gmb_handle.id = id; - gmb_handle.handle = shm_handle; - gmb_handle.offset = 0; - gmb_handle.stride = stride; - callback.Run(gmb_handle); + callback.Run(gpu::GpuMemoryBufferImplSharedMemory::AllocateForChildProcess( + id, size, format)); } void GpuServiceProxy::DestroyGpuMemoryBuffer(gfx::GpuMemoryBufferId id,
diff --git a/services/video_capture/device_factory_media_to_mojo_adapter.cc b/services/video_capture/device_factory_media_to_mojo_adapter.cc index 719df9d..87766dff 100644 --- a/services/video_capture/device_factory_media_to_mojo_adapter.cc +++ b/services/video_capture/device_factory_media_to_mojo_adapter.cc
@@ -41,15 +41,17 @@ const EnumerateDeviceDescriptorsCallback& callback) { media::VideoCaptureDeviceDescriptors descriptors; device_factory_->GetDeviceDescriptors(&descriptors); - callback.Run(descriptors); + callback.Run(std::move(descriptors)); } void DeviceFactoryMediaToMojoAdapter::GetSupportedFormats( - const media::VideoCaptureDeviceDescriptor& device_descriptor, + const std::string& device_id, const GetSupportedFormatsCallback& callback) { + media::VideoCaptureDeviceDescriptor descriptor; + media::VideoCaptureFormats media_formats; + if (LookupDescriptorFromId(device_id, &descriptor)) + device_factory_->GetSupportedFormats(descriptor, &media_formats); std::vector<VideoCaptureFormat> result; - std::vector<media::VideoCaptureFormat> media_formats; - device_factory_->GetSupportedFormats(device_descriptor, &media_formats); for (const auto& media_format : media_formats) { // The Video Capture Service requires devices to deliver frames either in // I420 or MJPEG formats. @@ -69,31 +71,38 @@ } void DeviceFactoryMediaToMojoAdapter::CreateDeviceProxy( - const media::VideoCaptureDeviceDescriptor& device_descriptor, + const std::string& device_id, mojom::VideoCaptureDeviceProxyRequest proxy_request, const CreateDeviceProxyCallback& callback) { - if (active_devices_.find(device_descriptor) != active_devices_.end()) { + auto active_device_iter = active_devices_by_id_.find(device_id); + if (active_device_iter != active_devices_by_id_.end()) { // The requested device is already in use. // Revoke the access and close the device, then bind to the new request. - ActiveDeviceEntry& device_entry = active_devices_[device_descriptor]; + ActiveDeviceEntry& device_entry = active_device_iter->second; device_entry.binding->Unbind(); device_entry.device_proxy->Stop(); device_entry.binding->Bind(std::move(proxy_request)); device_entry.binding->set_connection_error_handler(base::Bind( &DeviceFactoryMediaToMojoAdapter::OnClientConnectionErrorOrClose, - base::Unretained(this), device_descriptor)); + base::Unretained(this), device_id)); callback.Run(mojom::DeviceAccessResultCode::SUCCESS); return; } + // Create device + media::VideoCaptureDeviceDescriptor descriptor; + if (LookupDescriptorFromId(device_id, &descriptor) == false) { + callback.Run(mojom::DeviceAccessResultCode::ERROR_DEVICE_NOT_FOUND); + return; + } std::unique_ptr<media::VideoCaptureDevice> media_device = - device_factory_->CreateDevice(device_descriptor); + device_factory_->CreateDevice(descriptor); if (media_device == nullptr) { callback.Run(mojom::DeviceAccessResultCode::ERROR_DEVICE_NOT_FOUND); return; } - // Add entry to |active_devices| to keep track of it + // Add entry to active_devices to keep track of it ActiveDeviceEntry device_entry; device_entry.device_proxy = base::MakeUnique<VideoCaptureDeviceProxyImpl>( std::move(media_device), jpeg_decoder_factory_callback_); @@ -102,16 +111,32 @@ device_entry.device_proxy.get(), std::move(proxy_request)); device_entry.binding->set_connection_error_handler(base::Bind( &DeviceFactoryMediaToMojoAdapter::OnClientConnectionErrorOrClose, - base::Unretained(this), device_descriptor)); - active_devices_[device_descriptor] = std::move(device_entry); + base::Unretained(this), device_id)); + active_devices_by_id_[device_id] = std::move(device_entry); callback.Run(mojom::DeviceAccessResultCode::SUCCESS); } void DeviceFactoryMediaToMojoAdapter::OnClientConnectionErrorOrClose( - const media::VideoCaptureDeviceDescriptor& descriptor) { - active_devices_[descriptor].device_proxy->Stop(); - active_devices_.erase(descriptor); + const std::string& device_id) { + active_devices_by_id_[device_id].device_proxy->Stop(); + active_devices_by_id_.erase(device_id); +} + +bool DeviceFactoryMediaToMojoAdapter::LookupDescriptorFromId( + const std::string& device_id, + media::VideoCaptureDeviceDescriptor* descriptor) { + media::VideoCaptureDeviceDescriptors descriptors; + device_factory_->GetDeviceDescriptors(&descriptors); + auto descriptor_iter = std::find_if( + descriptors.begin(), descriptors.end(), + [&device_id](const media::VideoCaptureDeviceDescriptor& descriptor) { + return descriptor.device_id == device_id; + }); + if (descriptor_iter == descriptors.end()) + return false; + *descriptor = *descriptor_iter; + return true; } } // namespace video_capture
diff --git a/services/video_capture/device_factory_media_to_mojo_adapter.h b/services/video_capture/device_factory_media_to_mojo_adapter.h index f4fc0da..bea683a 100644 --- a/services/video_capture/device_factory_media_to_mojo_adapter.h +++ b/services/video_capture/device_factory_media_to_mojo_adapter.h
@@ -34,12 +34,11 @@ void EnumerateDeviceDescriptors( const EnumerateDeviceDescriptorsCallback& callback) override; void GetSupportedFormats( - const media::VideoCaptureDeviceDescriptor& device_descriptor, + const std::string& device_id, const GetSupportedFormatsCallback& callback) override; - void CreateDeviceProxy( - const media::VideoCaptureDeviceDescriptor& device_descriptor, - mojom::VideoCaptureDeviceProxyRequest proxy_request, - const CreateDeviceProxyCallback& callback) override; + void CreateDeviceProxy(const std::string& device_id, + mojom::VideoCaptureDeviceProxyRequest proxy_request, + const CreateDeviceProxyCallback& callback) override; private: struct ActiveDeviceEntry { @@ -55,13 +54,15 @@ std::unique_ptr<mojo::Binding<mojom::VideoCaptureDeviceProxy>> binding; }; - void OnClientConnectionErrorOrClose( - const media::VideoCaptureDeviceDescriptor& descriptor); + void OnClientConnectionErrorOrClose(const std::string& device_id); + + // Returns false if no descriptor found. + bool LookupDescriptorFromId(const std::string& device_id, + media::VideoCaptureDeviceDescriptor* descriptor); const std::unique_ptr<media::VideoCaptureDeviceFactory> device_factory_; const media::VideoCaptureJpegDecoderFactoryCB jpeg_decoder_factory_callback_; - std::map<media::VideoCaptureDeviceDescriptor, ActiveDeviceEntry> - active_devices_; + std::map<std::string, ActiveDeviceEntry> active_devices_by_id_; }; } // namespace video_capture
diff --git a/services/video_capture/fake_device_descriptor_unittest.cc b/services/video_capture/fake_device_descriptor_unittest.cc index 810dbfb..08af99f 100644 --- a/services/video_capture/fake_device_descriptor_unittest.cc +++ b/services/video_capture/fake_device_descriptor_unittest.cc
@@ -27,7 +27,7 @@ Run(mojom::DeviceAccessResultCode::SUCCESS)) .Times(1); factory_->CreateDeviceProxy( - fake_device_descriptor_, mojo::GetProxy(&device_proxy_1), + fake_device_descriptor_.device_id, mojo::GetProxy(&device_proxy_1), base::Bind(&MockCreateDeviceProxyCallback::Run, base::Unretained(&create_device_proxy_callback_1))); device_proxy_1.set_connection_error_handler( @@ -43,7 +43,7 @@ .Times(1) .WillOnce(InvokeWithoutArgs([&wait_loop]() { wait_loop.Quit(); })); factory_->CreateDeviceProxy( - fake_device_descriptor_, mojo::GetProxy(&device_proxy_2), + fake_device_descriptor_.device_id, mojo::GetProxy(&device_proxy_2), base::Bind(&MockCreateDeviceProxyCallback::Run, base::Unretained(&create_device_proxy_callback_2))); device_proxy_2.set_connection_error_handler( @@ -58,13 +58,13 @@ TEST_F(FakeDeviceDescriptorTest, CanUseSecondRequestedProxy) { mojom::VideoCaptureDeviceProxyPtr device_proxy_1; factory_->CreateDeviceProxy( - fake_device_descriptor_, mojo::GetProxy(&device_proxy_1), + fake_device_descriptor_.device_id, mojo::GetProxy(&device_proxy_1), base::Bind([](mojom::DeviceAccessResultCode result_code) {})); base::RunLoop wait_loop; mojom::VideoCaptureDeviceProxyPtr device_proxy_2; factory_->CreateDeviceProxy( - fake_device_descriptor_, mojo::GetProxy(&device_proxy_2), + fake_device_descriptor_.device_id, mojo::GetProxy(&device_proxy_2), base::Bind( [](base::RunLoop* wait_loop, mojom::DeviceAccessResultCode result_code) { wait_loop->Quit(); },
diff --git a/services/video_capture/fake_device_test.cc b/services/video_capture/fake_device_test.cc index 793d3e4..7021173 100644 --- a/services/video_capture/fake_device_test.cc +++ b/services/video_capture/fake_device_test.cc
@@ -33,7 +33,7 @@ wait_loop.Quit(); })); factory_->GetSupportedFormats( - fake_device_descriptor_, + fake_device_descriptor_.device_id, base::Bind(&MockSupportedFormatsReceiver::OnGetSupportedFormatsCallback, base::Unretained(&supported_formats_receiver_))); wait_loop.Run(); @@ -45,7 +45,8 @@ media::PowerLineFrequency::FREQUENCY_DEFAULT; factory_->CreateDeviceProxy( - std::move(fake_device_descriptor_), mojo::GetProxy(&fake_device_proxy_), + std::move(fake_device_descriptor_.device_id), + mojo::GetProxy(&fake_device_proxy_), base::Bind([](mojom::DeviceAccessResultCode result_code) { ASSERT_EQ(mojom::DeviceAccessResultCode::SUCCESS, result_code); }));
diff --git a/services/video_capture/fake_device_unittest.cc b/services/video_capture/fake_device_unittest.cc index ceff3b8..93afe7c 100644 --- a/services/video_capture/fake_device_unittest.cc +++ b/services/video_capture/fake_device_unittest.cc
@@ -31,14 +31,6 @@ namespace video_capture { TEST_F(FakeDeviceTest, FrameCallbacksArrive) { - VideoCaptureSettings arbitrary_requested_settings; - arbitrary_requested_settings.format.frame_size.SetSize(640, 480); - arbitrary_requested_settings.format.frame_rate = 15; - arbitrary_requested_settings.resolution_change_policy = - media::RESOLUTION_POLICY_FIXED_RESOLUTION; - arbitrary_requested_settings.power_line_frequency = - media::PowerLineFrequency::FREQUENCY_DEFAULT; - base::RunLoop wait_loop; const int kNumFramesToWaitFor = 3; int num_frames_arrived = 0; @@ -53,7 +45,7 @@ } })); - fake_device_proxy_->Start(arbitrary_requested_settings, + fake_device_proxy_->Start(requestable_settings_, std::move(receiver_proxy)); wait_loop.Run(); }
diff --git a/services/video_capture/mock_device_descriptor_receiver.h b/services/video_capture/mock_device_descriptor_receiver.h index b75534b..5781183 100644 --- a/services/video_capture/mock_device_descriptor_receiver.h +++ b/services/video_capture/mock_device_descriptor_receiver.h
@@ -5,7 +5,7 @@ #ifndef SERVICES_VIDEO_CAPTURE_MOCK_DEVICE_DESCRIPTOR_RECEIVER_H_ #define SERVICES_VIDEO_CAPTURE_MOCK_DEVICE_DESCRIPTOR_RECEIVER_H_ -#include "services/video_capture/public/interfaces/video_capture_device_factory.mojom.h" +#include "media/capture/video/video_capture_device_descriptor.h" #include "testing/gmock/include/gmock/gmock.h" namespace video_capture {
diff --git a/services/video_capture/mock_device_test.cc b/services/video_capture/mock_device_test.cc index 419d9cf..cf9b440 100644 --- a/services/video_capture/mock_device_test.cc +++ b/services/video_capture/mock_device_test.cc
@@ -9,8 +9,7 @@ MockDeviceTest::MockDeviceTest() : service_manager::test::ServiceTest("service:video_capture_unittests") {} -MockDeviceTest::~MockDeviceTest() = - default; +MockDeviceTest::~MockDeviceTest() = default; void MockDeviceTest::SetUp() { ServiceTest::SetUp(); @@ -27,7 +26,7 @@ // Obtain the mock device from the factory factory_->CreateDeviceProxy( - mock_descriptor, mojo::GetProxy(&device_proxy_), + mock_descriptor.device_id, mojo::GetProxy(&device_proxy_), base::Bind([](mojom::DeviceAccessResultCode result_code) {})); requested_settings_.format.frame_size = gfx::Size(800, 600);
diff --git a/services/video_capture/public/interfaces/video_capture_device_factory.mojom b/services/video_capture/public/interfaces/video_capture_device_factory.mojom index 0175201..bf0aa378 100644 --- a/services/video_capture/public/interfaces/video_capture_device_factory.mojom +++ b/services/video_capture/public/interfaces/video_capture_device_factory.mojom
@@ -17,21 +17,20 @@ // Enables access to a set of video capture devices. // Typical operation is to first call EnumerateDeviceDescriptors() to obtain -// information about available devices. The obtained descriptors can then be -// used to either obtain the supported formats for a device using -// GetSupportedFormats(), or to create an instance of VideoCaptureDevice for -// the device using CreateDevice(). -// TODO(chfremer): Consider using a simple string identifier instead of a -// VideoCaptureDeviceDescriptor. -// https://crbug.com/637439 +// information about available devices. The |device_id| of the descriptors can +// subsequently be used to either obtain the supported formats for a device +// using GetSupportedFormats(), or to create an instance of +// VideoCaptureDeviceProxy using CreateDeviceProxy(). +// The factory guarantees that no two device descriptors it returns use the +// same |device_id|. interface VideoCaptureDeviceFactory { EnumerateDeviceDescriptors() => (array<VideoCaptureDeviceDescriptor> descriptors); - GetSupportedFormats(VideoCaptureDeviceDescriptor device_descriptor) + GetSupportedFormats(string device_id) => (array<VideoCaptureFormat> supported_formats); - // Provides exclusive access to the device identified by |device_descriptor|. + // Provides exclusive access to the device identified by |device_id|. // The access is valid until either the message pipe associated with // |proxy_request| is closed by the client, or a subsequent call to // CreateDeviceProxy() is made. When a subsequent call is made while the @@ -42,7 +41,7 @@ // |proxy_request| has been (asynchronously) discarded a subsequent call to // CreateDeviceProxy() would succeed if it were to deny access while still // in use. - CreateDeviceProxy(VideoCaptureDeviceDescriptor device_descriptor, + CreateDeviceProxy(string device_id, VideoCaptureDeviceProxy& proxy_request) => (DeviceAccessResultCode result_code); };
diff --git a/services/video_capture/receiver_mojo_to_media_adapter.h b/services/video_capture/receiver_mojo_to_media_adapter.h index 1640613..0a83074 100644 --- a/services/video_capture/receiver_mojo_to_media_adapter.h +++ b/services/video_capture/receiver_mojo_to_media_adapter.h
@@ -8,10 +8,6 @@ #include "media/capture/video/video_frame_receiver.h" #include "services/video_capture/public/interfaces/video_frame_receiver.mojom.h" -namespace media { -class MojoSharedBufferVideoFrame; -} - namespace video_capture { // Adapter that allows a mojom::VideoFrameReceiver to be used in place of @@ -31,7 +27,6 @@ private: mojom::VideoFrameReceiverPtr receiver_; - scoped_refptr<media::MojoSharedBufferVideoFrame> shared_buffer_frame_; }; } // namespace video_capture
diff --git a/services/video_capture/video_capture_service.cc b/services/video_capture/video_capture_service.cc index 0a3b18a7..d369416a 100644 --- a/services/video_capture/video_capture_service.cc +++ b/services/video_capture/video_capture_service.cc
@@ -14,6 +14,7 @@ #include "services/video_capture/mock_device_factory.h" namespace { + // TODO(chfremer): Replace with an actual decoder factory. // https://crbug.com/584797 std::unique_ptr<media::VideoCaptureJpegDecoder> CreateJpegDecoder() {
diff --git a/services/video_capture/video_capture_service_unittest.cc b/services/video_capture/video_capture_service_unittest.cc index d7ada51..4b1c702 100644 --- a/services/video_capture/video_capture_service_unittest.cc +++ b/services/video_capture/video_capture_service_unittest.cc
@@ -54,9 +54,7 @@ // Tests that VideoCaptureDeviceFactory::CreateDeviceProxy() returns an error // code when trying to create a device for an invalid descriptor. TEST_F(VideoCaptureServiceTest, ErrorCodeOnCreateDeviceForInvalidDescriptor) { - media::VideoCaptureDeviceDescriptor invalid_descriptor; - invalid_descriptor.device_id = "invalid"; - invalid_descriptor.model_id = "invalid"; + const std::string invalid_device_id = "invalid"; base::RunLoop wait_loop; mojom::VideoCaptureDeviceProxyPtr fake_device_proxy; MockCreateDeviceProxyCallback create_device_proxy_callback; @@ -65,7 +63,7 @@ .Times(1) .WillOnce(InvokeWithoutArgs([&wait_loop]() { wait_loop.Quit(); })); factory_->CreateDeviceProxy( - std::move(invalid_descriptor), mojo::GetProxy(&fake_device_proxy), + invalid_device_id, mojo::GetProxy(&fake_device_proxy), base::Bind(&MockCreateDeviceProxyCallback::Run, base::Unretained(&create_device_proxy_callback))); wait_loop.Run();
diff --git a/testing/buildbot/chromium.android.json b/testing/buildbot/chromium.android.json index b535937b..a2ed50f2 100644 --- a/testing/buildbot/chromium.android.json +++ b/testing/buildbot/chromium.android.json
@@ -1233,7 +1233,7 @@ "device_type": "bullhead" } ], - "hard_timeout": 960, + "hard_timeout": 1200, "shards": 1 } }
diff --git a/testing/buildbot/chromium.chromiumos.json b/testing/buildbot/chromium.chromiumos.json index fa25d91..346f6d6 100644 --- a/testing/buildbot/chromium.chromiumos.json +++ b/testing/buildbot/chromium.chromiumos.json
@@ -180,6 +180,12 @@ "swarming": { "can_use_on_swarming_builders": true }, + "test": "gl_unittests_ozonex" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, "test": "google_apis_unittests" }, {
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index 977ef4ab..994e02c 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -896,6 +896,243 @@ } ] }, + "Android x64 Tests": { + "gtest_tests": [ + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "angle_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "base_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "blink_heap_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "cacheinvalidation_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "capture_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "cast_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "cc_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "components_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "content_browsertests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "content_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "crypto_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "display_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "gcm_unit_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "gfx_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "google_apis_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "gpu_ipc_service_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "gpu_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "ipc_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "jingle_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "media_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "midi_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "mojo_common_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "mojo_public_bindings_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "mojo_public_system_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "mojo_system_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "net_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "remoting_unittests" + }, + { + "override_compile_targets": [ + "sandbox_linux_unittests_deps" + ], + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "sandbox_linux_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "skia_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "sql_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "ui_base_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "unit_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "url_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "webkit_unit_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": false + }, + "test": "wtf_unittests" + } + ], + "instrumentation_tests": [ + { + "test": "android_webview_test_apk" + }, + { + "test": "blimp_test_apk" + }, + { + "test": "chrome_public_test_apk" + }, + { + "test": "chrome_sync_shell_test_apk" + }, + { + "test": "content_shell_test_apk" + }, + { + "test": "mojo_test_apk" + } + ] + }, "Blimp Android Client": { "gtest_tests": [ {
diff --git a/testing/buildbot/chromium.perf.fyi.json b/testing/buildbot/chromium.perf.fyi.json index 80a911f..77162dd 100644 --- a/testing/buildbot/chromium.perf.fyi.json +++ b/testing/buildbot/chromium.perf.fyi.json
@@ -54,14 +54,99 @@ }, { "args": [], + "isolate_name": "gpu_perftests", + "name": "gpu_perftests", + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "gpu": "8086:22b1", + "id": "build47b4", + "os": "Windows-10-10586", + "pool": "Chrome-perf" + } + ], + "expiration": 14400 + } + }, + { + "args": [], + "isolate_name": "load_library_perf_tests", + "name": "load_library_perf_tests", + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "gpu": "8086:22b1", + "id": "build47-b4", + "os": "Windows-10-10586", + "pool": "Chrome-perf" + } + ], + "expiration": 14400 + } + }, + { + "args": [], + "isolate_name": "performance_browser_tests", + "name": "performance_browser_tests", + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "gpu": "8086:22b1", + "id": "build48-b4", + "os": "Windows-10-10586", + "pool": "Chrome-perf" + } + ], + "expiration": 14400 + } + }, + { + "args": [], "isolate_name": "cc_perftests", "name": "cc_perftests", "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [ { - "gpu": "1002:9874", - "id": "build171-b4", + "gpu": "8086:22b1", + "id": "build48-b4", + "os": "Windows-10-10586", + "pool": "Chrome-perf" + } + ], + "expiration": 14400 + } + }, + { + "args": [], + "isolate_name": "angle_perftests", + "name": "angle_perftests", + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "gpu": "8086:22b1", + "id": "build48-b4", + "os": "Windows-10-10586", + "pool": "Chrome-perf" + } + ], + "expiration": 14400 + } + }, + { + "args": [], + "isolate_name": "tracing_perftests", + "name": "tracing_perftests", + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "gpu": "8086:22b1", + "id": "build48-b4", "os": "Windows-10-10586", "pool": "Chrome-perf" }
diff --git a/testing/buildbot/filters/browser-side-navigation.linux.browser_tests.filter b/testing/buildbot/filters/browser-side-navigation.linux.browser_tests.filter index fe0df62..62be23d 100644 --- a/testing/buildbot/filters/browser-side-navigation.linux.browser_tests.filter +++ b/testing/buildbot/filters/browser-side-navigation.linux.browser_tests.filter
@@ -7,15 +7,10 @@ -PrerenderBrowserTest.PrerenderCrossProcessServerRedirectNoHang # TabManagerTest.TabManagerBasics crashes sometimes -TabManagerTest.TabManagerBasics --TemplateURLScraperTest.ScrapeWithOnSubmit -ThreatDOMDetailsTest.Everything -WebNavigationApiTest.RequestOpenTab -WebNavigationApiTest.UserAction -# Errors related to forms submission. --PhishingDOMFeatureExtractorTest.SubFrames --PhishingDOMFeatureExtractorTest.SubframeRemoval - # https://crbug.com/652767: NavigationHandle::GetResponseHeaders sometimes # returns null for browser-side navigations -PageLoadMetricsBrowserTest.Ignore204Pages
diff --git a/testing/buildbot/filters/browser-side-navigation.linux.content_browsertests.filter b/testing/buildbot/filters/browser-side-navigation.linux.content_browsertests.filter index 7b4ec2a..228212a 100644 --- a/testing/buildbot/filters/browser-side-navigation.linux.content_browsertests.filter +++ b/testing/buildbot/filters/browser-side-navigation.linux.content_browsertests.filter
@@ -1,3 +1,4 @@ +-NavigationControllerBrowserTest.EnsureSamePageNavigationUpdatesFrameNavigationEntry -NavigationControllerBrowserTest.FrameNavigationEntry_RecreatedInjectedSrcdocSubframe -RenderFrameHostManagerTest.RestoreSubframeFileAccessForHistoryNavigation -RequestDataResourceDispatcherHostBrowserTest.*
diff --git a/testing/buildbot/gn_isolate_map.pyl b/testing/buildbot/gn_isolate_map.pyl index d99345d..700329d 100644 --- a/testing/buildbot/gn_isolate_map.pyl +++ b/testing/buildbot/gn_isolate_map.pyl
@@ -20,7 +20,8 @@ # "windowed_test_launcher" # : the test is a gtest-based test that uses the "brave-new-test-launcher" # from //base/test:test_support and needs to run under Xvfb if run on -# an X11-based platform (use_x11=true). +# an X11-based platform (use_x11=true or use_ozone=true && +# --ozone_platform=x11). # "console_test_launcher" # : the test is a gtest-based test that uses the "brave-new-test-launcher" # from //base/test:test_support but does not need Xvfb. @@ -431,6 +432,13 @@ "type": "raw", "args": [], }, + "gl_unittests_ozonex": { + "label": "//ui/gl:gl_unittests_ozonex", + "label_type": "group", + "type": "windowed_test_launcher", + "executable": "gl_unittests", + "args": ["--ozone-platform=x11"], + }, "gn_all": { "label": "//:gn_all", "type": "additional_compile_target", @@ -804,6 +812,56 @@ "cc_perftests", ], }, + "load_library_perf_tests": { + "label": "//chrome/test:load_library_perf_tests", + "type": "script", + "script": "//testing/scripts/run_gtest_perf_test.py", + "args": [ + "load_library_perf_tests", + "--test-launcher-print-test-stdio=always" + ], + }, + "tracing_perftests": { + "label": "//components/tracing:tracing_perftests", + "type": "script", + "script": "//testing/scripts/run_gtest_perf_test.py", + "args": [ + "tracing_perftests", + "--test-launcher-print-test-stdio=always" + ], + }, + "gpu_perftests": { + "label": "//gpu:gpu_perftests", + "type": "script", + "script": "//testing/scripts/run_gtest_perf_test.py", + "args": [ + "gpu_perftests", + "--adb-path", + "src/third_party/catapult/devil/bin/deps/linux2/x86_64/bin/adb" + ], + }, + "angle_perftests": { + "label": "//chrom/test:angle_perftests", + "type": "script", + "script": "//testing/scripts/run_gtest_perf_test.py", + "args": [ + "angle_perftests", + "--test-launcher-print-test-stdio=always", + "--test-launcher-jobs=1" + ], + }, + "performance_browser_tests": { + "label": "//chrom/test:performance_browser_tests", + "type": "script", + "script": "//testing/scripts/run_gtest_perf_test.py", + "args": [ + "performance_browser_tests", + "--test-launcher-print-test-stdio=always", + "--gtest_filter=TabCapturePerformanceTest.*:CastV2PerformanceTest.*", + "--test-launcher-jobs=1", + "--enable-gpu" + ], + }, "mus_ime_unittests": { "label": "//services/ui/ime:mus_ime_unittests", "type": "windowed_test_launcher", @@ -873,6 +931,18 @@ "label": "//chrome/android/webapk/shell_apk:webapk_shell_apk_junit_tests", "type": "junit_test", }, + "webkit_layout_tests": { + "label": "//:webkit_layout_tests", + "type": "script", + "script": "//testing/scripts/run_telemetry_as_googletest.py", + "args": [ + "--xvfb", + "../../third_party/WebKit/Tools/Scripts/run-webkit-tests", + "--clobber-old-results", + "--no-show-results", + "--results-directory", "${ISOLATED_OUTDIR}/layout-test-results", + ], + }, "webkit_unit_tests": { "label": "//third_party/WebKit/Source/web:webkit_unit_tests", "type": "console_test_launcher",
diff --git a/testing/buildbot/manage.py b/testing/buildbot/manage.py index 111888c..9ab1d91f 100755 --- a/testing/buildbot/manage.py +++ b/testing/buildbot/manage.py
@@ -195,6 +195,10 @@ 'voice_engine_unittests', 'webrtc_nonparallel_tests', 'xmllite_xmpp_unittests', + + # isolate is currently too slow for this target. + # http://crbug.com/524758 + 'webkit_layout_tests', }
diff --git a/testing/buildbot/timeouts.py b/testing/buildbot/timeouts.py new file mode 100755 index 0000000..f3204b1a --- /dev/null +++ b/testing/buildbot/timeouts.py
@@ -0,0 +1,199 @@ +#!/usr/bin/env python +# Copyright 2016 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Calculate reasonable timeout for each step as analysed by the actual runtimes +on the Swarming server. +""" + +import Queue +import argparse +import json +import os +import subprocess +import sys +import threading +import time +import urllib + + +THIS_DIR = os.path.dirname(os.path.abspath(__file__)) + + +def human_int(s): + """Returns human readable time rounded to the second.""" + s = int(round(s)) + if s <= 60: + return '%ds' % s + m = s/60 + if m <= 60: + return '%dm%02ds' % (m, s%60) + return '%dh%02dm%02ds' % (m/60, m%60, s%60) + + +def human(s): + """Returns human readable time rounded to the tenth of second.""" + if s <= 60: + return '%.1fs' % s + m = int(round(s/60)) + if m <= 60: + return '%dm%04.1fs' % (m, s%60) + return '%dh%02dm%04.1fs' % (m/60, m%60, s%60) + + +class Stats(object): + """Holds runtimes statistics for a step run on a builder.""" + def __init__(self, builder, step, durations): + self.builder = builder + self.step = step + self.durations = durations + self.avg = sum(durations) / float(len(durations)) + self.len = len(durations) + self.max = max(durations) + self.timeout = max(120, int(round(self.max / 60.)) * 120) + + def __str__(self): + return 'avg: %4ds max: %4ds timeout: %4ds' % ( + round(self.avg), round(self.max), self.timeout) + + +class Pool(object): + def __init__(self, size): + self._durations = [] + self._inputs = Queue.Queue() + self._lock = threading.Lock() + self._outputs = [] + self._start = time.time() + self._total = 0 + self._threads = [ + threading.Thread(name=str(i), target=self._run) for i in xrange(size) + ] + for t in self._threads: + t.start() + + def put(self, f): + self._inputs.put(f) + with self._lock: + self._total += 1 + + def join(self): + for _ in xrange(len(self._threads)): + self._inputs.put(None) + try: + for t in self._threads: + while t.isAlive(): + t.join(0.1) + self._print_eta() + except KeyboardInterrupt: + sys.stderr.write('\nInterrupted!\n') + with self._lock: + return self._outputs[:] + + def _print_eta(self): + elapsed = human(time.time() - self._start) + with self._lock: + out = '\r%d/%d Elapsed: %s' % (len(self._outputs), self._total, elapsed) + if self._durations: + avg = sum(self._durations) / float(len(self._durations)) + rem = self._total - len(self._outputs) + eta = avg * rem / float(len(self._threads)) + out += ' ETA: %s ' % human_int(eta) + sys.stderr.write(out) + sys.stderr.flush() + + def _run(self): + while True: + f = self._inputs.get() + if not f: + return + s = time.time() + o = f() + e = time.time() - s + with self._lock: + self._durations.append(e) + self._outputs.append(o) + + +def query(server, number, builder, step): + q = 'tasks/list?%s' % urllib.urlencode([ + ('tags', 'buildername:%s' % builder), + ('tags', 'name:%s' % step), + ]) + cmd = [ + sys.executable, '../../tools/swarming_client/swarming.py', 'query', + '-S', server, '--limit', str(number), q, + ] + out = subprocess.check_output(cmd, stderr=subprocess.PIPE) + try: + data = json.loads(out) + except ValueError: + sys.stderr.write(out) + return None + if not 'items' in data: + # No task with this pattern. + return None + durations = [i['duration'] for i in data['items'] if i.get('duration')] + if not durations: + # There was tasks but none completed correctly, i.e. internal_failure. + return None + return Stats(builder, step, durations) + + +def extract_tags(data, test_name): + """Returns all the tags that should be queried from a json file.""" + out = [] + for b, d in sorted(data.iteritems()): + if not 'gtest_tests' in d: + continue + for t in d['gtest_tests']: + if not t.get('swarming', {}).get('can_use_on_swarming_builders'): + continue + if test_name and t['test'] != test_name: + continue + out.append((b, t['test'])) + return out + + +def query_server(server, number, data): + """Query the Swarming server to steps durations.""" + def _get_func(builder, step): + return lambda: query(server, number, builder, step) + # Limit to 256 threads, otherwise some OSes have trouble with it. + p = Pool(min(len(data), 256)) + for builder, step in data: + p.put(_get_func(builder, step)) + return p.join() + + +def main(): + os.chdir(THIS_DIR) + parser = argparse.ArgumentParser(description=sys.modules[__name__].__doc__) + parser.add_argument( + '-f', metavar='chromium.foo.json', help='file to open', required=True) + parser.add_argument('-s', metavar='foo_unittest', help='step to process') + parser.add_argument( + '-N', metavar='200', default=200, type=int, + help='number of executions to look at') + parser.add_argument( + '-S', metavar='chromium-swarm.appspot.com', + default='chromium-swarm.appspot.com', help='server to use') + args = parser.parse_args() + + with open(args.f) as f: + d = json.load(f) + tags = extract_tags(d, args.s) + if not tags: + print('No step to process found') + return 1 + out = [i for i in query_server(args.S, args.N, tags) if i] + print('') + maxbuilder = max(len(i.builder) for i in out) + maxstep = max(len(i.step) for i in out) + for i in sorted(out, key=lambda i: (i.builder, i.step)): + print('%-*s / %-*s %s' % (maxbuilder, i.builder, maxstep, i.step, i)) + return 0 + + +if __name__ == "__main__": + sys.exit(main())
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 31ee255..42e9e02 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -519,6 +519,7 @@ { "name": "DocumentWriteScriptBlockGroup", "params": { + "disallowFetchForDocWrittenScriptsInMainFrame": "false", "disallowFetchForDocWrittenScriptsInMainFrameOnSlowConnections": "true" }, "disable_features": [
diff --git a/third_party/WebKit/LayoutTests/FlagExpectations/enable-slimming-paint-v2 b/third_party/WebKit/LayoutTests/FlagExpectations/enable-slimming-paint-v2 index e0ec009..304c8b51 100644 --- a/third_party/WebKit/LayoutTests/FlagExpectations/enable-slimming-paint-v2 +++ b/third_party/WebKit/LayoutTests/FlagExpectations/enable-slimming-paint-v2
@@ -160,8 +160,8 @@ Bug(none) compositing/gestures/gesture-tapHighlight-1-overflow-div-composited.html [ Failure ] Bug(none) compositing/gestures/gesture-tapHighlight-1-overflow-div-layout-change-2.html [ Failure ] Bug(none) compositing/gestures/gesture-tapHighlight-1-overflow-div-layout-change.html [ Failure ] -Bug(none) compositing/gestures/gesture-tapHighlight-1-overflow-div-scrolled-late-noncomposite.html [ Failure ] Bug(none) compositing/gestures/gesture-tapHighlight-1-overflow-div-scrolled-late-composite.html [ Failure ] +Bug(none) compositing/gestures/gesture-tapHighlight-1-overflow-div-scrolled-late-noncomposite.html [ Failure ] Bug(none) compositing/gestures/gesture-tapHighlight-1-overflow-div-scrolled.html [ Failure ] Bug(none) compositing/gestures/gesture-tapHighlight-1-overflow-div.html [ Failure ] Bug(none) compositing/gestures/gesture-tapHighlight-2-iframe-composited-inner.html [ Failure ] @@ -926,6 +926,8 @@ Bug(none) fast/multicol/nested-auto-height-short-first-row.html [ Failure ] Bug(none) fast/multicol/nested-auto-height.html [ Failure ] Bug(none) fast/multicol/nested-balanced-inner-column-count-1-with-forced-break.html [ Failure ] +Bug(none) fast/multicol/nested-balanced-inner-with-many-breaks-2.html [ Failure ] +Bug(none) fast/multicol/nested-balanced-inner-with-many-breaks.html [ Failure ] Bug(none) fast/multicol/nested-balanced-with-strut-before-first-line.html [ Failure ] Bug(none) fast/multicol/nested-columns.html [ Failure ] Bug(none) fast/multicol/nested-fixed-height-with-struts.html [ Failure ] @@ -1080,8 +1082,8 @@ Bug(none) fast/replaced/width100percent-textarea.html [ Failure ] Bug(none) fast/scroll-behavior/ [ Skip ] Bug(none) fast/scrolling/overflow-clip-with-page-scale.html [ Crash Timeout ] -Bug(none) fast/scrolling/scrollbar-tickmarks-styled.html [ Failure ] Bug(none) fast/scrolling/scrollbar-tickmarks-styled-after-onload.html [ Failure ] +Bug(none) fast/scrolling/scrollbar-tickmarks-styled.html [ Failure ] Bug(none) fast/selectors/166.html [ Failure ] Bug(none) fast/selectors/input-with-selection-pseudo-element.html [ Failure ] Bug(none) fast/shapes/shape-outside-floats/shape-outside-boxes-001.html [ Failure ] @@ -1169,7 +1171,6 @@ Bug(none) fast/transforms/transforms-with-opacity.html [ Failure ] Bug(none) fast/writing-mode/border-radius-clipping-vertical-lr.html [ Failure ] Bug(none) fast/writing-mode/fieldsets.html [ Failure ] -Bug(none) fast/writing-mode/Kusa-Makura-background-canvas.html [ Failure Crash ] Bug(none) svg/animations/animateMotion-accumulate-1a.svg [ Failure ] Bug(none) svg/animations/animateMotion-accumulate-1b.svg [ Failure ] Bug(none) svg/animations/animateMotion-accumulate-1c.svg [ Failure ] @@ -1911,7 +1912,6 @@ Bug(none) fast/events/middleClickAutoscroll-event-fired.html [ Timeout ] Bug(none) fast/events/mouse-wheel-main-frame-scroll.html [ Timeout ] Bug(none) fast/scrolling/hover-during-scroll.html [ Timeout ] -Bug(none) fast/scrolling/scrollbar-tickmarks-hittest.html [ Timeout ] crbug.com/651292 svg/dynamic-updates/SVGImageElement-dom-x-attr.html [ Pass Failure ] crbug.com/651292 svg/dynamic-updates/SVGImageElement-svgdom-height-prop.html [ Pass Failure ]
diff --git a/third_party/WebKit/LayoutTests/FlagExpectations/site-per-process b/third_party/WebKit/LayoutTests/FlagExpectations/site-per-process index 7da7dbd..71a56eeb 100644 --- a/third_party/WebKit/LayoutTests/FlagExpectations/site-per-process +++ b/third_party/WebKit/LayoutTests/FlagExpectations/site-per-process
@@ -61,7 +61,8 @@ crbug.com/615156 http/tests/intersection-observer/iframe-cross-origin.html [ Timeout ] # https://crbug.com/616626 - allow_universal_access_from_file_urls doesn't work with --site-per-process. -crbug.com/616626 http/tests/local/drag-over-remote-content.html [ Timeout ] +# https://crbug.com/665058 - EventSender drag-and-drop simulation doesn't support OOPIFs. +crbug.com/665058 http/tests/local/drag-over-remote-content.html [ Crash ] # https://crbug.com/619662 - Expected console output differences. crbug.com/619662 http/tests/navigation/cross-origin-fragment-navigation-is-async.html [ Failure ]
diff --git a/third_party/WebKit/LayoutTests/RandomOrderExpectations b/third_party/WebKit/LayoutTests/RandomOrderExpectations index 48f81c6..c6f0fa0 100644 --- a/third_party/WebKit/LayoutTests/RandomOrderExpectations +++ b/third_party/WebKit/LayoutTests/RandomOrderExpectations
@@ -1,129 +1,129 @@ -compositing/reflections/nested-reflection-anchor-point.html [ Pass Failure ] -compositing/reflections/nested-reflection-animated.html [ Pass Failure ] -compositing/reflections/nested-reflection-transition.html [ Pass Failure ] -css3/filters/effect-all-on-background-hw.html [ Pass Failure ] -css3/filters/effect-contrast-hw.html [ Pass Failure ] -editing/pasteboard/data-transfer-items-image-png.html [ Pass Failure ] -fast/canvas/canvas-drawImage-live-video.html [ Pass Failure ] -fast/events/click-anchor-blur-refocus-window.html [ Pass Failure ] -fast/events/click-anchor-refocus-window.html [ Pass Failure ] -fast/events/click-checkbox-refocus-window.html [ Pass Failure ] -fast/events/click-focus-anchor-has-ring.html [ Pass Failure ] -fast/events/click-focus-keydown-no-ring.html [ Pass Failure ] -fast/events/click-focus-svganchor-has-ring.html [ Pass Failure ] -fast/events/click-focus-svganchor-no-ring.html [ Pass Failure ] -fast/events/click-svganchor-blur-refocus-window.html [ Pass Failure ] -fast/events/click-svganchor-refocus-window.html [ Pass Failure ] -fast/events/context-no-deselect.html [ Pass Failure ] -fast/events/middleClickAutoscroll-panIcon.html [ Pass Failure ] -fast/events/mouse-cursor-change-after-image-load.html [ Pass Failure ] -fast/events/mouse-cursor.html [ Pass Failure ] -fast/events/onload-re-entry.html [ Pass Failure ] -fast/filesystem/cross-filesystem-op.html [ Pass Failure ] -fast/scroll-behavior/main-frame-interrupted-scroll.html [ Pass Failure ] -fast/text/ellipsis-ltr-text-in-rtl-flow-underline-composition.html [ Pass Failure ] -fast/text/ellipsis-rtl-text-in-ltr-flow.html [ Pass Failure ] -fast/text/ellipsis-rtl-text-in-rtl-flow.html [ Pass Failure ] -fast/text/ellipsis-rtl-text-in-rtl-flow-underline.html [ Pass Failure ] -fast/text/ellipsis-rtl-text-in-ltr-flow-underline.html [ Pass Failure ] -fast/text/ellipsis-rtl-text-in-ltr-flow-underline-composition.html [ Pass Failure ] -fast/text/ellipsis-rtl-text-in-rtl-flow-underline-composition.html [ Pass Failure ] -fast/text/emphasis.html [ Pass Failure ] -fast/text/emphasis-vertical.html [ Pass Failure ] -http/tests/appcache/main-resource-redirect.html [ Pass Failure ] -http/tests/appcache/obsolete-error-events.html [ Pass Failure ] -http/tests/appcache/non-html.xhtml [ Pass Failure ] -http/tests/appcache/remove-cache.html [ Pass Failure ] -http/tests/cache/post-redirect-get.php [ Pass Failure ] -http/tests/cache/post-with-cached-subresources.php [ Pass Failure ] -http/tests/cachestorage/window/cache-add.html [ Pass Failure ] -http/tests/cachestorage/window/cache-storage.html [ Pass Failure ] -http/tests/cachestorage/worker/cache-storage.html [ Pass Failure ] -http/tests/fetch/serviceworker-proxied/thorough/cookie-nocors.html [ Pass Failure ] -http/tests/fetch/serviceworker-proxied/thorough/cors-preflight-other-https.html [ Pass Failure ] -http/tests/fetch/serviceworker-proxied/thorough/redirect-base-https-other-https.html [ Pass Failure ] -http/tests/fetch/serviceworker-proxied/thorough/redirect-credentials-base-https-other-https.html [ Pass Failure ] -http/tests/fetch/window/thorough/access-control-base-https-other-https.html [ Pass Failure ] -http/tests/fetch/window/thorough/access-control.html [ Pass Failure ] -http/tests/fetch/window/thorough/auth-base-https-other-https.html [ Pass Failure ] -http/tests/fetch/window/thorough/auth.html [ Pass Failure ] -http/tests/fetch/window/thorough/auth-other-https.html [ Pass Failure ] -http/tests/fetch/window/thorough/cookie-base-https-other-https.html [ Pass Failure ] -http/tests/fetch/window/thorough/cookie-nocors-other-https.html [ Pass Failure ] -http/tests/fetch/window/thorough/cors-preflight2-base-https-other-https.html [ Pass Failure ] -http/tests/fetch/window/thorough/cors-preflight2-other-https.html [ Pass Failure ] -http/tests/fetch/window/thorough/cors-preflight-base-https-other-https.html [ Pass Failure ] -http/tests/fetch/window/thorough/redirect-base-https-other-https.html [ Pass Failure ] -http/tests/fetch/window/thorough/redirect-password-other-https.html [ Pass Failure ] -http/tests/fetch/window/thorough/scheme-blob.html [ Pass Failure ] -http/tests/fetch/window/thorough/scheme-data-other-https.html [ Pass Failure ] -http/tests/inspector/network/har-content.html [ Pass Failure ] -http/tests/loading/doc-write-sync-third-party-script-block-effectively-2g.html [ Pass Failure ] -http/tests/media/video-load-suspend.html [ Pass Failure ] -http/tests/misc/script-no-store.html [ Pass Failure ] -http/tests/security/contentSecurityPolicy/require-sri-for/require-sri-for-script-reportonly-blocked.php [ Pass Failure ] -http/tests/security/contentTypeOptions/block-image-as-script.html [ Pass Failure ] -http/tests/security/cors-rfc1918/internal-to-internal-xhr.html [ Pass Failure ] -http/tests/security/document-origin-domain.html [ Pass Failure ] -http/tests/security/isolatedWorld/bypass-main-world-csp-for-inline-style.html [ Pass Failure ] -http/tests/security/isolatedWorld/bypass-main-world-csp-for-xhr.html [ Pass Failure ] -http/tests/security/isolatedWorld/bypass-main-world-csp-iframes.html [ Pass Failure ] -http/tests/security/isolatedWorld/events.html [ Pass Failure ] -http/tests/security/link-crossorigin-preload-no-cors.html [ Pass Failure ] -http/tests/security/same-origin-css.html [ Pass Failure ] -http/tests/security/same-origin-css-in-quirks.html [ Pass Failure ] -http/tests/security/webgl-remote-read-remote-image-allowed.html [ Pass Failure ] -http/tests/security/webgl-remote-read-remote-image-allowed-with-credentials.html [ Pass Failure ] -http/tests/w3c/webperf/submission/Google/resource-timing/html/test_resource_script_types.html [ Pass Failure ] -http/tests/workers/worker-document-domain-security.html [ Pass Failure ] -http/tests/workers/worker-performance-timeline.html [ Pass Failure ] -inspector/elements/styles-4/styles-update-from-js.html [ Pass Failure ] -inspector-protocol/heap-profiler/heap-snapshot-with-active-dom-object.html [ Pass Failure ] -media/autoplay-clears-autoplaying-flag.html [ Pass Failure ] -media/track/track-cue-rendering-tree-is-removed-properly.html [ Pass Failure ] -media/track/track-default-attribute.html [ Pass Failure ] -media/track/track-kind-user-preference.html [ Pass Failure ] -paint/invalidation/background-resize-height.html [ Pass Failure ] -storage/domstorage/events/basic.html [ Pass Failure ] -storage/domstorage/events/case-sensitive.html [ Pass Failure ] -svg/dom/transform-parser.html [ Pass Failure ] -virtual/display_list_2d_canvas/fast/canvas/canvas-createImageBitmap-webgl.html [ Pass Failure ] -virtual/display_list_2d_canvas/fast/canvas/canvas-drawImage-live-video.html [ Pass Failure ] -virtual/display_list_2d_canvas/fast/canvas/OffscreenCanvas-2d-drawImage.html [ Pass Failure ] -virtual/display_list_2d_canvas/fast/canvas/OffscreenCanvas-commit-invalid-call.html [ Pass Failure ] -virtual/gpu/fast/canvas/canvas-createImageBitmap-webgl.html [ Pass Failure ] -virtual/gpu/fast/canvas/canvas-drawImage-live-video.html [ Pass Failure ] -virtual/gpu/fast/canvas/canvas-lose-restore-googol-size.html [ Pass Failure ] -virtual/gpu/fast/canvas/canvas-lost-gpu-context.html [ Pass Failure ] -virtual/gpu/fast/canvas/OffscreenCanvas-2d-drawImage.html [ Pass Failure ] -virtual/mojo-loading/webexposed/css-properties-as-js-properties.html [ Pass Failure ] -virtual/mojo-loading/webexposed/web-animations-api.html [ Pass Failure ] -virtual/mojo-service-worker/http/tests/serviceworker/extendable-event-waituntil.html [ Pass Failure ] -virtual/mojo-service-worker/http/tests/serviceworker/fetch-canvas-tainting.html [ Pass Failure ] -virtual/mojo-service-worker/http/tests/serviceworker/fetch-cors-xhr.html [ Pass Failure ] -virtual/mojo-service-worker/http/tests/serviceworker/fetch-event.html [ Pass Failure ] -virtual/mojo-service-worker/http/tests/serviceworker/fetch-frame-resource.html [ Pass Failure ] -virtual/mojo-service-worker/http/tests/serviceworker/fetch-response-taint.html [ Pass Failure ] -virtual/mojo-service-worker/http/tests/serviceworker/foreign-fetch-basics.html [ Pass Failure ] -virtual/mojo-service-worker/http/tests/serviceworker/foreign-fetch-workers.html [ Pass Failure ] -virtual/scroll_customization/fast/scroll-behavior/main-frame-interrupted-scroll.html [ Pass Failure ] -virtual/sharedarraybuffer/fast/workers/worker-gc.html [ Pass Failure ] -virtual/threaded/animations/3d/transform-origin-vs-functions.html [ Pass Failure ] -virtual/threaded/animations/animation-transition-collision-crash.html [ Pass Failure ] -virtual/threaded/animations/composited-animations-simple.html [ Pass Failure ] -virtual/threaded/animations/transform-responsive-neutral-keyframe.html [ Pass Failure ] -virtual/threaded/fast/scroll-behavior/overflow-scroll-animates.html [ Pass Failure ] -virtual/threaded/fast/scroll-behavior/smooth-scroll/horizontal-smooth-scroll-in-rtl.html [ Pass Failure ] -virtual/threaded/fast/scroll-behavior/smooth-scroll/main-thread-scrolling-reason-added.html [ Pass Failure ] -virtual/threaded/fast/scroll-behavior/smooth-scroll/ongoing-smooth-scroll-anchors.html [ Pass Failure ] -virtual/threaded/fast/scroll-behavior/smooth-scroll/ongoing-smooth-scroll-vertical-rl-anchors.html [ Pass Failure ] -virtual/threaded/fast/scroll-behavior/smooth-scroll/scroll-during-selection.html [ Pass Failure ] -virtual/threaded/transitions/opacity-transform-transitions-inside-iframe.html [ Pass Failure ] -virtual/threaded/transitions/opacity-transition-zindex.html [ Pass Failure ] -virtual/threaded/transitions/position-background-transition.html [ Pass Failure ] -virtual/threaded/transitions/transition-end-event-container.html [ Pass Failure ] -virtual/threaded/transitions/transition-end-event-multiple-02.html [ Pass Failure ] -virtual/threaded/transitions/transition-end-event-transform.html [ Pass Failure ] -virtual/threaded/transitions/transition-end-event-unprefixed-02.html [ Pass Failure ] -virtual/threaded/transitions/transition-end-event-window.html [ Pass Failure ] -virtual/threaded/transitions/unprefixed-transform.html [ Pass Failure ] +crbug.com/653722 compositing/reflections/nested-reflection-anchor-point.html [ Pass Failure ] +crbug.com/653722 compositing/reflections/nested-reflection-animated.html [ Pass Failure ] +crbug.com/653722 compositing/reflections/nested-reflection-transition.html [ Pass Failure ] +crbug.com/663581 css3/filters/effect-all-on-background-hw.html [ Pass Failure ] +crbug.com/663581 css3/filters/effect-contrast-hw.html [ Pass Failure ] +crbug.com/663585 editing/pasteboard/data-transfer-items-image-png.html [ Pass Failure ] +crbug.com/663838 fast/canvas/canvas-drawImage-live-video.html [ Pass Failure ] +crbug.com/663840 fast/events/click-anchor-blur-refocus-window.html [ Pass Failure ] +crbug.com/663840 fast/events/click-anchor-refocus-window.html [ Pass Failure ] +crbug.com/663840 fast/events/click-checkbox-refocus-window.html [ Pass Failure ] +crbug.com/663840 fast/events/click-focus-anchor-has-ring.html [ Pass Failure ] +crbug.com/663840 fast/events/click-focus-keydown-no-ring.html [ Pass Failure ] +crbug.com/663840 fast/events/click-focus-svganchor-has-ring.html [ Pass Failure ] +crbug.com/663840 fast/events/click-focus-svganchor-no-ring.html [ Pass Failure ] +crbug.com/663840 fast/events/click-svganchor-blur-refocus-window.html [ Pass Failure ] +crbug.com/663840 fast/events/click-svganchor-refocus-window.html [ Pass Failure ] +crbug.com/663847 fast/events/context-no-deselect.html [ Pass Failure ] +crbug.com/663848 fast/events/middleClickAutoscroll-panIcon.html [ Pass Failure ] +crbug.com/663849 fast/events/mouse-cursor-change-after-image-load.html [ Pass Failure ] +crbug.com/663849 fast/events/mouse-cursor.html [ Pass Failure ] +crbug.com/663851 fast/events/onload-re-entry.html [ Pass Failure ] +crbug.com/663852 fast/filesystem/cross-filesystem-op.html [ Pass Failure ] +crbug.com/663853 fast/scroll-behavior/main-frame-interrupted-scroll.html [ Pass Failure ] +crbug.com/663855 fast/text/ellipsis-ltr-text-in-rtl-flow-underline-composition.html [ Pass Failure ] +crbug.com/663855 fast/text/ellipsis-rtl-text-in-ltr-flow.html [ Pass Failure ] +crbug.com/663855 fast/text/ellipsis-rtl-text-in-rtl-flow.html [ Pass Failure ] +crbug.com/663855 fast/text/ellipsis-rtl-text-in-rtl-flow-underline.html [ Pass Failure ] +crbug.com/663855 fast/text/ellipsis-rtl-text-in-ltr-flow-underline.html [ Pass Failure ] +crbug.com/663855 fast/text/ellipsis-rtl-text-in-ltr-flow-underline-composition.html [ Pass Failure ] +crbug.com/663855 fast/text/ellipsis-rtl-text-in-rtl-flow-underline-composition.html [ Pass Failure ] +crbug.com/663858 fast/text/emphasis.html [ Pass Failure ] +crbug.com/663858 fast/text/emphasis-vertical.html [ Pass Failure ] +crbug.com/663860 http/tests/appcache/main-resource-redirect.html [ Pass Failure ] +crbug.com/663860 http/tests/appcache/obsolete-error-events.html [ Pass Failure ] +crbug.com/663860 http/tests/appcache/non-html.xhtml [ Pass Failure ] +crbug.com/663860 http/tests/appcache/remove-cache.html [ Pass Failure ] +crbug.com/663865 http/tests/cache/post-redirect-get.php [ Pass Failure ] +crbug.com/663865 http/tests/cache/post-with-cached-subresources.php [ Pass Failure ] +crbug.com/663871 http/tests/cachestorage/window/cache-add.html [ Pass Failure ] +crbug.com/663871 http/tests/cachestorage/window/cache-storage.html [ Pass Failure ] +crbug.com/663871 http/tests/cachestorage/worker/cache-storage.html [ Pass Failure ] +crbug.com/663872 http/tests/fetch/serviceworker-proxied/thorough/cookie-nocors.html [ Pass Failure ] +crbug.com/663872 http/tests/fetch/serviceworker-proxied/thorough/cors-preflight-other-https.html [ Pass Failure ] +crbug.com/663872 http/tests/fetch/serviceworker-proxied/thorough/redirect-base-https-other-https.html [ Pass Failure ] +crbug.com/663872 http/tests/fetch/serviceworker-proxied/thorough/redirect-credentials-base-https-other-https.html [ Pass Failure ] +crbug.com/663874 http/tests/fetch/window/thorough/access-control-base-https-other-https.html [ Pass Failure ] +crbug.com/663874 http/tests/fetch/window/thorough/access-control.html [ Pass Failure ] +crbug.com/663874 http/tests/fetch/window/thorough/auth-base-https-other-https.html [ Pass Failure ] +crbug.com/663874 http/tests/fetch/window/thorough/auth.html [ Pass Failure ] +crbug.com/663874 http/tests/fetch/window/thorough/auth-other-https.html [ Pass Failure ] +crbug.com/663874 http/tests/fetch/window/thorough/cookie-base-https-other-https.html [ Pass Failure ] +crbug.com/663874 http/tests/fetch/window/thorough/cookie-nocors-other-https.html [ Pass Failure ] +crbug.com/663874 http/tests/fetch/window/thorough/cors-preflight2-base-https-other-https.html [ Pass Failure ] +crbug.com/663874 http/tests/fetch/window/thorough/cors-preflight2-other-https.html [ Pass Failure ] +crbug.com/663874 http/tests/fetch/window/thorough/cors-preflight-base-https-other-https.html [ Pass Failure ] +crbug.com/663874 http/tests/fetch/window/thorough/redirect-base-https-other-https.html [ Pass Failure ] +crbug.com/663874 http/tests/fetch/window/thorough/redirect-password-other-https.html [ Pass Failure ] +crbug.com/663874 http/tests/fetch/window/thorough/scheme-blob.html [ Pass Failure ] +crbug.com/663874 http/tests/fetch/window/thorough/scheme-data-other-https.html [ Pass Failure ] +crbug.com/663875 http/tests/inspector/network/har-content.html [ Pass Failure ] +crbug.com/663876 http/tests/loading/doc-write-sync-third-party-script-block-effectively-2g.html [ Pass Failure ] +crbug.com/663877 http/tests/media/video-load-suspend.html [ Pass Failure ] +crbug.com/663879 http/tests/misc/script-no-store.html [ Pass Failure ] +crbug.com/664816 http/tests/security/contentSecurityPolicy/require-sri-for/require-sri-for-script-reportonly-blocked.php [ Pass Failure ] +crbug.com/664817 http/tests/security/contentTypeOptions/block-image-as-script.html [ Pass Failure ] +crbug.com/664839 http/tests/security/cors-rfc1918/internal-to-internal-xhr.html [ Pass Failure ] +crbug.com/664839 http/tests/security/document-origin-domain.html [ Pass Failure ] +crbug.com/664819 http/tests/security/isolatedWorld/bypass-main-world-csp-for-inline-style.html [ Pass Failure ] +crbug.com/664819 http/tests/security/isolatedWorld/bypass-main-world-csp-for-xhr.html [ Pass Failure ] +crbug.com/664819 http/tests/security/isolatedWorld/bypass-main-world-csp-iframes.html [ Pass Failure ] +crbug.com/664819 http/tests/security/isolatedWorld/events.html [ Pass Failure ] +crbug.com/664839 http/tests/security/link-crossorigin-preload-no-cors.html [ Pass Failure ] +crbug.com/664839 http/tests/security/same-origin-css.html [ Pass Failure ] +crbug.com/664839 http/tests/security/same-origin-css-in-quirks.html [ Pass Failure ] +crbug.com/664839 http/tests/security/webgl-remote-read-remote-image-allowed.html [ Pass Failure ] +crbug.com/664839 http/tests/security/webgl-remote-read-remote-image-allowed-with-credentials.html [ Pass Failure ] +crbug.com/664840 http/tests/w3c/webperf/submission/Google/resource-timing/html/test_resource_script_types.html [ Pass Failure ] +crbug.com/664841 http/tests/workers/worker-document-domain-security.html [ Pass Failure ] +crbug.com/664841 http/tests/workers/worker-performance-timeline.html [ Pass Failure ] +crbug.com/664843 inspector/elements/styles-4/styles-update-from-js.html [ Pass Failure ] +crbug.com/664842 inspector-protocol/heap-profiler/heap-snapshot-with-active-dom-object.html [ Pass Failure ] +crbug.com/664845 media/autoplay-clears-autoplaying-flag.html [ Pass Failure ] +crbug.com/664844 media/track/track-cue-rendering-tree-is-removed-properly.html [ Pass Failure ] +crbug.com/664844 media/track/track-default-attribute.html [ Pass Failure ] +crbug.com/664844 media/track/track-kind-user-preference.html [ Pass Failure ] +crbug.com/664846 paint/invalidation/background-resize-height.html [ Pass Failure ] +crbug.com/664848 storage/domstorage/events/basic.html [ Pass Failure ] +crbug.com/664848 storage/domstorage/events/case-sensitive.html [ Pass Failure ] +crbug.com/664849 svg/dom/transform-parser.html [ Pass Failure ] +crbug.com/664850 virtual/display_list_2d_canvas/fast/canvas/canvas-createImageBitmap-webgl.html [ Pass Failure ] +crbug.com/664850 virtual/display_list_2d_canvas/fast/canvas/canvas-drawImage-live-video.html [ Pass Failure ] +crbug.com/664850 virtual/display_list_2d_canvas/fast/canvas/OffscreenCanvas-2d-drawImage.html [ Pass Failure ] +crbug.com/664850 virtual/display_list_2d_canvas/fast/canvas/OffscreenCanvas-commit-invalid-call.html [ Pass Failure ] +crbug.com/664852 virtual/gpu/fast/canvas/canvas-createImageBitmap-webgl.html [ Pass Failure ] +crbug.com/664852 virtual/gpu/fast/canvas/canvas-drawImage-live-video.html [ Pass Failure ] +crbug.com/664852 virtual/gpu/fast/canvas/canvas-lose-restore-googol-size.html [ Pass Failure ] +crbug.com/664852 virtual/gpu/fast/canvas/canvas-lost-gpu-context.html [ Pass Failure ] +crbug.com/664852 virtual/gpu/fast/canvas/OffscreenCanvas-2d-drawImage.html [ Pass Failure ] +crbug.com/664853 virtual/mojo-loading/webexposed/css-properties-as-js-properties.html [ Pass Failure ] +crbug.com/664853 virtual/mojo-loading/webexposed/web-animations-api.html [ Pass Failure ] +crbug.com/664854 virtual/mojo-service-worker/http/tests/serviceworker/extendable-event-waituntil.html [ Pass Failure ] +crbug.com/664854 virtual/mojo-service-worker/http/tests/serviceworker/fetch-canvas-tainting.html [ Pass Failure ] +crbug.com/664854 virtual/mojo-service-worker/http/tests/serviceworker/fetch-cors-xhr.html [ Pass Failure ] +crbug.com/664854 virtual/mojo-service-worker/http/tests/serviceworker/fetch-event.html [ Pass Failure ] +crbug.com/664854 virtual/mojo-service-worker/http/tests/serviceworker/fetch-frame-resource.html [ Pass Failure ] +crbug.com/664854 virtual/mojo-service-worker/http/tests/serviceworker/fetch-response-taint.html [ Pass Failure ] +crbug.com/664854 virtual/mojo-service-worker/http/tests/serviceworker/foreign-fetch-basics.html [ Pass Failure ] +crbug.com/664854 virtual/mojo-service-worker/http/tests/serviceworker/foreign-fetch-workers.html [ Pass Failure ] +crbug.com/664855 virtual/scroll_customization/fast/scroll-behavior/main-frame-interrupted-scroll.html [ Pass Failure ] +crbug.com/664856 virtual/sharedarraybuffer/fast/workers/worker-gc.html [ Pass Failure ] +crbug.com/664857 virtual/threaded/animations/3d/transform-origin-vs-functions.html [ Pass Failure ] +crbug.com/664857 virtual/threaded/animations/animation-transition-collision-crash.html [ Pass Failure ] +crbug.com/664857 virtual/threaded/animations/composited-animations-simple.html [ Pass Failure ] +crbug.com/664857 virtual/threaded/animations/transform-responsive-neutral-keyframe.html [ Pass Failure ] +crbug.com/664858 virtual/threaded/fast/scroll-behavior/overflow-scroll-animates.html [ Pass Failure ] +crbug.com/664858 virtual/threaded/fast/scroll-behavior/smooth-scroll/horizontal-smooth-scroll-in-rtl.html [ Pass Failure ] +crbug.com/664858 virtual/threaded/fast/scroll-behavior/smooth-scroll/main-thread-scrolling-reason-added.html [ Pass Failure ] +crbug.com/664858 virtual/threaded/fast/scroll-behavior/smooth-scroll/ongoing-smooth-scroll-anchors.html [ Pass Failure ] +crbug.com/664858 virtual/threaded/fast/scroll-behavior/smooth-scroll/ongoing-smooth-scroll-vertical-rl-anchors.html [ Pass Failure ] +crbug.com/664858 virtual/threaded/fast/scroll-behavior/smooth-scroll/scroll-during-selection.html [ Pass Failure ] +crbug.com/664859 virtual/threaded/transitions/opacity-transform-transitions-inside-iframe.html [ Pass Failure ] +crbug.com/664859 virtual/threaded/transitions/opacity-transition-zindex.html [ Pass Failure ] +crbug.com/664859 virtual/threaded/transitions/position-background-transition.html [ Pass Failure ] +crbug.com/664859 virtual/threaded/transitions/transition-end-event-container.html [ Pass Failure ] +crbug.com/664859 virtual/threaded/transitions/transition-end-event-multiple-02.html [ Pass Failure ] +crbug.com/664859 virtual/threaded/transitions/transition-end-event-transform.html [ Pass Failure ] +crbug.com/664859 virtual/threaded/transitions/transition-end-event-unprefixed-02.html [ Pass Failure ] +crbug.com/664859 virtual/threaded/transitions/transition-end-event-window.html [ Pass Failure ] +crbug.com/664859 virtual/threaded/transitions/unprefixed-transform.html [ Pass Failure ]
diff --git a/third_party/WebKit/LayoutTests/TestExpectations b/third_party/WebKit/LayoutTests/TestExpectations index 360c72c..0293b32 100644 --- a/third_party/WebKit/LayoutTests/TestExpectations +++ b/third_party/WebKit/LayoutTests/TestExpectations
@@ -410,6 +410,7 @@ crbug.com/520611 [ Debug ] fast/filesystem/workers/file-writer-events-shared-worker.html [ Failure Pass ] crbug.com/520613 http/tests/cache/freshness-header.html [ Failure Pass ] crbug.com/520194 http/tests/xmlhttprequest/timeout/xmlhttprequest-timeout-worker-overridesexpires.html [ Failure Pass ] +crbug.com/520194 virtual/mojo-loading/http/tests/xmlhttprequest/timeout/xmlhttprequest-timeout-worker-overridesexpires.html [ Failure Pass ] crbug.com/410974 fast/scroll-behavior/scroll-customization/scrollstate-basic.html [ Pass Failure ] crbug.com/410974 fast/scroll-behavior/scroll-customization/scrollstate-consume-deltas.html [ Pass Failure ] @@ -430,6 +431,7 @@ crbug.com/518883 crbug.com/390452 http/tests/security/isolatedWorld/media-query-wrapper-leaks.html [ Failure Pass Timeout ] crbug.com/518987 http/tests/xmlhttprequest/navigation-abort-detaches-frame.html [ Pass Timeout ] +crbug.com/518987 virtual/mojo-loading/http/tests/xmlhttprequest/navigation-abort-detaches-frame.html [ Pass Timeout ] crbug.com/518988 [ Win7 ] http/tests/xmlhttprequest/xmlhttprequest-50ms-download-dispatch.html [ Failure Pass ] crbug.com/518989 [ Mac ] imported/csswg-test/css-writing-modes-3/writing-mode-vertical-rl-002.xht [ Failure Pass Timeout ] crbug.com/518998 media/video-poster-after-loadedmetadata.html [ Failure Pass ] @@ -464,7 +466,9 @@ crbug.com/248938 virtual/threaded/animations/animation-iteration-event-destroy-renderer.html [ Pass Timeout ] crbug.com/248938 virtual/threaded/animations/transition-and-animation-3.html [ Pass Timeout ] crbug.com/446385 [ Linux Mac ] http/tests/xmlhttprequest/xmlhttprequest-json-response-overflow.html [ Pass Timeout ] +crbug.com/446385 [ Linux Mac ] virtual/mojo-loading/http/tests/xmlhttprequest/xmlhttprequest-json-response-overflow.html [ Pass Timeout ] crbug.com/446385 [ Win7 Debug ] http/tests/xmlhttprequest/xmlhttprequest-json-response-overflow.html [ Crash Pass Timeout ] +crbug.com/446385 [ Win7 Debug ] virtual/mojo-loading/http/tests/xmlhttprequest/xmlhttprequest-json-response-overflow.html [ Crash Pass Timeout ] crbug.com/248938 virtual/threaded/transitions/interrupt-transform-transition.html [ Pass Failure ] crbug.com/248938 virtual/threaded/animations/dynamic-stylesheet-loading.html [ Pass Failure Timeout ] crbug.com/248938 virtual/threaded/transitions/change-duration-during-transition.html [ Pass Failure ] @@ -480,6 +484,7 @@ crbug.com/248938 [ Linux ] virtual/threaded/transitions/unprefixed-perspective-origin.html [ Pass Timeout ] crbug.com/248938 [ Linux ] virtual/threaded/transitions/transition-not-interpolable.html [ Pass Timeout ] crbug.com/248938 [ Mac ] virtual/threaded/transitions/interrupted-all-transition.html [ Pass Failure ] +crbug.com/248938 virtual/threaded/animations/fill-mode-multiple-keyframes.html [ Pass Failure ] crbug.com/659123 [ Mac ] fast/css/text-overflow-ellipsis-button.html [ Pass Failure ] @@ -1163,6 +1168,7 @@ crbug.com/509025 [ Mac10.10 ] virtual/rootlayerscrolls/scrollbars/short-scrollbar.html [ Failure ] crbug.com/464736 http/tests/xmlhttprequest/ontimeout-event-override-after-failure.html [ Pass Failure ] +crbug.com/464736 virtual/mojo-loading/http/tests/xmlhttprequest/ontimeout-event-override-after-failure.html [ Pass Failure ] crbug.com/621772 fast/forms/color/color-suggestion-picker-with-scrollbar-appearance.html [ Pass Failure ] crbug.com/652995 fast/forms/text/input-text-scroll-left-on-blur.html [ Pass Failure ] @@ -1414,13 +1420,12 @@ crbug.com/660580 [ Precise ] virtual/scalefactor200withzoom/fast/hidpi/static/drag-image.html [ Skip ] crbug.com/660580 [ Precise ] virtual/threaded/printing/fixed-positioned-headers-and-footers.html [ Skip ] -# Tests added from W3C auto import bot +# ====== New tests from w3c-test-autoroller added here ====== crbug.com/626703 imported/csswg-test/vendor-imports/mozilla/mozilla-central-reftests/flexbox/flexbox-align-self-baseline-horiz-001a.xhtml [ Failure ] crbug.com/626703 imported/csswg-test/vendor-imports/mozilla/mozilla-central-reftests/flexbox/flexbox-align-self-baseline-horiz-001b.xhtml [ Failure ] crbug.com/626703 imported/csswg-test/vendor-imports/mozilla/mozilla-central-reftests/flexbox/flexbox-align-self-baseline-horiz-006.xhtml [ Failure ] crbug.com/626703 imported/csswg-test/vendor-imports/mozilla/mozilla-central-reftests/flexbox/flexbox-align-self-baseline-horiz-007.xhtml [ Failure ] crbug.com/626703 imported/csswg-test/vendor-imports/mozilla/mozilla-central-reftests/writing-modes-3/logical-physical-mapping-001.html [ Failure ] -crbug.com/626703 imported/wpt/imagebitmap-renderingcontext/bitmaprenderer-as-imagesource.html [ Crash Timeout ] crbug.com/626703 imported/wpt/dom/events/EventTarget-dispatchEvent.html [ Failure ] crbug.com/626703 imported/wpt/html/browsers/history/the-history-interface/non-automated/traverse_the_history_unload_prompt_1-manual.html [ Failure ] crbug.com/626703 imported/wpt/html/browsers/history/the-history-interface/non-automated/traverse_the_history_unload_prompt_2-manual.html [ Failure ] @@ -1554,7 +1559,10 @@ crbug.com/659917 virtual/mojo-loading/http/tests/xmlhttprequest/upload-onloadend-event-after-abort.html [ Timeout ] crbug.com/659917 virtual/mojo-loading/http/tests/xmlhttprequest/redirect-cross-origin-post.html [ Timeout ] crbug.com/659917 virtual/mojo-loading/http/tests/xmlhttprequest/access-control-and-redirects.html [ Timeout ] -crbug.com/659917 virtual/mojo-loading/http/tests/xmlhttprequest/xmlhttprequest-json-response-overflow.html [ Failure Pass Timeout ] + +# TODO(yhirano): There is an entry for the base test, but this test is flakier +# than that. Fix this test so that we can move the entry to the base test +# section. crbug.com/659917 virtual/mojo-loading/http/tests/xmlhttprequest/xmlhttprequest-50ms-download-dispatch.html [ Failure Pass ] crbug.com/664873 http/tests/xmlhttprequest/small-chunks-response-text.html [ Failure Pass ]
diff --git a/third_party/WebKit/LayoutTests/W3CImportExpectations b/third_party/WebKit/LayoutTests/W3CImportExpectations index 1baa790..90086b0d 100644 --- a/third_party/WebKit/LayoutTests/W3CImportExpectations +++ b/third_party/WebKit/LayoutTests/W3CImportExpectations
@@ -248,6 +248,7 @@ imported/wpt/http [ Skip ] ## Owners: none; No tests in the directory. # imported/wpt/images [ Pass ] +imported/wpt/imagebitmap-renderingcontext [ Skip ] imported/wpt/infrastructure [ Skip ] imported/wpt/innerText [ Skip ] imported/wpt/js [ Skip ]
diff --git a/third_party/WebKit/LayoutTests/accessibility/content-changed-notification-causes-crash-expected.txt b/third_party/WebKit/LayoutTests/accessibility/content-changed-notification-causes-crash-expected.txt index 25a62d2..75eb5f5c 100644 --- a/third_party/WebKit/LayoutTests/accessibility/content-changed-notification-causes-crash-expected.txt +++ b/third_party/WebKit/LayoutTests/accessibility/content-changed-notification-causes-crash-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. >> Ensures that this snippet does not lead to a crash. Bug 86029.
diff --git a/third_party/WebKit/LayoutTests/accessibility/contenteditable-table-check-causes-crash-expected.txt b/third_party/WebKit/LayoutTests/accessibility/contenteditable-table-check-causes-crash-expected.txt index ef56c18..d8d1606 100644 --- a/third_party/WebKit/LayoutTests/accessibility/contenteditable-table-check-causes-crash-expected.txt +++ b/third_party/WebKit/LayoutTests/accessibility/contenteditable-table-check-causes-crash-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 16: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 16: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Ensures that this snippet does not lead to a crash in the code that detects if a table is contenteditable. Bug 87409. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/accessibility/duplicate-axlayoutobject-crash-expected.txt b/third_party/WebKit/LayoutTests/accessibility/duplicate-axlayoutobject-crash-expected.txt index a36f884a..760e0efe 100644 --- a/third_party/WebKit/LayoutTests/accessibility/duplicate-axlayoutobject-crash-expected.txt +++ b/third_party/WebKit/LayoutTests/accessibility/duplicate-axlayoutobject-crash-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. PASS successfullyParsed is true TEST COMPLETE
diff --git a/third_party/WebKit/LayoutTests/compositing/overflow/composited-sticky-element-expected.html b/third_party/WebKit/LayoutTests/compositing/overflow/composited-sticky-element-expected.html new file mode 100644 index 0000000..356061f --- /dev/null +++ b/third_party/WebKit/LayoutTests/compositing/overflow/composited-sticky-element-expected.html
@@ -0,0 +1,26 @@ +<script> +onload = function() { + scroller.scrollTop = 100; +} +</script> +<style> +#scroller { + background: white; + height: 200px; + overflow: auto; + width: 200px; +} +.sticky { + position: relative; + top: 100px; + height: 50px; + background: green; +} +.spacer { + height: 2000px; +} +</style> +<div id="scroller"> + <div class="sticky"></div> + <div class="spacer"></div> +</div>
diff --git a/third_party/WebKit/LayoutTests/compositing/overflow/composited-sticky-element.html b/third_party/WebKit/LayoutTests/compositing/overflow/composited-sticky-element.html new file mode 100644 index 0000000..f52efcd --- /dev/null +++ b/third_party/WebKit/LayoutTests/compositing/overflow/composited-sticky-element.html
@@ -0,0 +1,28 @@ +<script> +onload = function() { + scroller.scrollTop = 100; +} +</script> +<style> +#scroller { + /* Opaque background means scroller is composited. */ + background: white; + height: 200px; + overflow: auto; + width: 200px; +} +.sticky { + position: sticky; + top: 0; + height: 50px; + /* Opaque background means sticky element is composited. */ + background: green; +} +.spacer { + height: 2000px; +} +</style> +<div id="scroller"> + <div class="sticky"></div> + <div class="spacer"></div> +</div>
diff --git a/third_party/WebKit/LayoutTests/editing/deleting/delete-across-editable-content-boundaries-3-expected.txt b/third_party/WebKit/LayoutTests/editing/deleting/delete-across-editable-content-boundaries-3-expected.txt deleted file mode 100644 index 2689f47..0000000 --- a/third_party/WebKit/LayoutTests/editing/deleting/delete-across-editable-content-boundaries-3-expected.txt +++ /dev/null
@@ -1,34 +0,0 @@ -This tests to see that selected editable nodes that are not in both the start and end editable roots are cleared. You should see one non-editable piece and an editable one and then two empty table cells. The table cells are editable but are preserved and not removed because they are in a non-editable region. They should be completely cleared out, even the second one that contains a non-editable piece. <radr://problem/5026848> -| " -" -| <table> -| border="1" -| contenteditable="false" -| " - " -| <tbody> -| <tr> -| " - " -| <td> -| "Non-editable" -| " - " -| <td> -| contenteditable="true" -| "Editable <#selection-caret>content" -| " - " -| <!-- The following cell should be removed, even though it contains non-editable pieces. --> -| " - " -| <td> -| contenteditable="true" -| " - " -| <td> -| contenteditable="true" -| " - " -| " -"
diff --git a/third_party/WebKit/LayoutTests/editing/deleting/delete-across-editable-content-boundaries-3.html b/third_party/WebKit/LayoutTests/editing/deleting/delete-across-editable-content-boundaries-3.html index 6b4a3f395..a68b0125 100644 --- a/third_party/WebKit/LayoutTests/editing/deleting/delete-across-editable-content-boundaries-3.html +++ b/third_party/WebKit/LayoutTests/editing/deleting/delete-across-editable-content-boundaries-3.html
@@ -1,30 +1,26 @@ -<!DOCTYPE html> -<html> -<body> -<p id="description">This tests to see that selected editable nodes that are not in both the start and end editable roots are cleared. You should see one non-editable piece and an editable one and then two empty table cells. The table cells are editable but are preserved and not removed because they are in a non-editable region. They should be completely cleared out, even the second one that contains a non-editable piece. <radr://problem/5026848></p> -<div id="div" contenteditable="true"> -<table border="1" contenteditable="false"> - <tr> - <td>Non-editable</td> - <td contenteditable="true">Editable <span id="start">content</span></td> - <!-- The following cell should be removed, even though it contains non-editable pieces. --> - <td contenteditable="true">Editable</td> - <td contenteditable="true">Edit<span contenteditable="false">(non-editable content that should be removed because its in an editable region)</span>able</td> - </tr> -</table> -Editable <span id="end">content</span> -</div> - -<script src="../../resources/dump-as-markup.js"></script> +<!doctype html> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script src="../assert_selection.js"></script> <script> -var sel = window.getSelection(); -var start = document.getElementById("start"); -var end = document.getElementById("end"); -sel.setBaseAndExtent(start, 0, end, 0); -document.execCommand("Delete"); -Markup.description(description.textContent); -Markup.dump("div"); +test(() => assert_selection( + [ + '<div contenteditable>', + '<table contenteditable="false"><tbody><tr>', + '<td contenteditable>foo|bar</td>', + '<td contenteditable>baz<span contenteditable="false">abc</span>def</td>', + '</tr></tbody></table>', + 'ghi^jk', + '</div>' + ].join(''), + 'delete', + [ + '<div contenteditable>', + '<table contenteditable="false"><tbody><tr>', + '<td contenteditable>foo|jk</td>', + '<td contenteditable></td>', + '</tr></tbody></table>', + '</div>' + ].join('')), + 'Delete selected editable nodes that are not in both the start and end editable roots'); </script> - -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/editing/deleting/forward-delete.html b/third_party/WebKit/LayoutTests/editing/deleting/forward-delete.html index c401473e7..54cd7e1 100644 --- a/third_party/WebKit/LayoutTests/editing/deleting/forward-delete.html +++ b/third_party/WebKit/LayoutTests/editing/deleting/forward-delete.html
@@ -1,43 +1,16 @@ -<html> -<head> - -<style> -.editing { - border: 2px solid red; - padding: 12px; - font-size: 24px; -} -.explanation { - border: 2px solid blue; - padding: 12px; - font-size: 24px; - margin-bottom: 24px; -} -</style> -<script src=../editing.js language="JavaScript" type="text/JavaScript" ></script> - +<!doctype html> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script src="../assert_selection.js"></script> <script> - -function editingTest() { - for (i = 0; i < 4; i++) - forwardDeleteCommand(); -} - +test(() => assert_selection( + '<div contenteditable>|foo bar</div>', + selection => { + selection.document.execCommand('ForwardDelete'); + selection.document.execCommand('ForwardDelete'); + selection.document.execCommand('ForwardDelete'); + selection.document.execCommand('ForwardDelete'); + }, + '<div contenteditable>|bar</div>'), + 'Delete selected editable nodes that are not in both the start and end editable roots'); </script> - -<title>Editing Test</title> -</head> -<body contenteditable="true"> -<div class="explanation"> -Should see "bar" in the red box. Insertion point should be at the start of the document. -</div> - -<div id="root" style="word-wrap: break-word; -khtml-nbsp-mode: space; -khtml-line-break: after-white-space;"> -<div id="test" class="editing">foo bar</div></div> - -<script> -runEditingTest(); -</script> - -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/editing/execCommand/remove-format-elements-expected.txt b/third_party/WebKit/LayoutTests/editing/execCommand/remove-format-elements-expected.txt index 125a665..18f01d8 100644 --- a/third_party/WebKit/LayoutTests/editing/execCommand/remove-format-elements-expected.txt +++ b/third_party/WebKit/LayoutTests/editing/execCommand/remove-format-elements-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 58: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 58: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Removed acronym, b, bdo, big, cite, code, dfn, em, font, i, ins, kbd, nobr, q, s, samp, small, strike, strong, sub, sup, tt, u, var Preserved
diff --git a/third_party/WebKit/LayoutTests/editing/spelling/spellcheck-marker.html b/third_party/WebKit/LayoutTests/editing/spelling/spellcheck-marker.html new file mode 100644 index 0000000..45ac953 --- /dev/null +++ b/third_party/WebKit/LayoutTests/editing/spelling/spellcheck-marker.html
@@ -0,0 +1,24 @@ +<!DOCTYPE html> + +<script src='../../resources/testharness.js'></script> +<script src='../../resources/testharnessreport.js'></script> +<script src='../../editing/assert_selection.js'></script> +<script> +test(function () { + assert_not_equals(window.internals, undefined, + 'This test requires internals.'); + assert_selection( + '<div contenteditable>^appla| </div>', + selection => { + const document = selection.document; + const start = selection.anchorOffset; + const end = selection.focusOffset; + assert_false(internals.hasSpellingMarker(document, start, end)); + internals.setMarker(document, selection.getRangeAt(0), 'Spelling'); + assert_true(internals.hasSpellingMarker(document, start, end)); + internals.replaceMisspelled(document, 'apple'); + }, + '<div contenteditable>apple| </div>' + ); +}, 'test setMarker and replaceMisspelled in internals'); +</script>
diff --git a/third_party/WebKit/LayoutTests/fast/block/child-not-removed-from-parent-lineboxes-crash-expected.txt b/third_party/WebKit/LayoutTests/fast/block/child-not-removed-from-parent-lineboxes-crash-expected.txt index 08cd1fd2..ee2bc98 100644 --- a/third_party/WebKit/LayoutTests/fast/block/child-not-removed-from-parent-lineboxes-crash-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/block/child-not-removed-from-parent-lineboxes-crash-expected.txt
@@ -1,2 +1,2 @@ -CONSOLE WARNING: line 12: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 12: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. PASS: does not crash
diff --git a/third_party/WebKit/LayoutTests/fast/block/float/float-not-removed-from-first-letter-expected.txt b/third_party/WebKit/LayoutTests/fast/block/float/float-not-removed-from-first-letter-expected.txt index a8f71aa..9f5b4548 100644 --- a/third_party/WebKit/LayoutTests/fast/block/float/float-not-removed-from-first-letter-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/block/float/float-not-removed-from-first-letter-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 16: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 16: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Webkit Bug 86019 - Crash due to floats not removed from first-letter element. PASS. WebKit didn't crash.
diff --git a/third_party/WebKit/LayoutTests/fast/block/float/split-inline-sibling-of-float-crash-expected.txt b/third_party/WebKit/LayoutTests/fast/block/float/split-inline-sibling-of-float-crash-expected.txt index d723b94..7798ab2 100644 --- a/third_party/WebKit/LayoutTests/fast/block/float/split-inline-sibling-of-float-crash-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/block/float/split-inline-sibling-of-float-crash-expected.txt
@@ -1,2 +1,2 @@ -CONSOLE WARNING: line 12: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 12: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. PASS if no crash or assert under ASAN
diff --git a/third_party/WebKit/LayoutTests/fast/canvas/OffscreenCanvas-placeholder-image-source-with-worker.html b/third_party/WebKit/LayoutTests/fast/canvas/OffscreenCanvas-placeholder-image-source-with-worker.html new file mode 100644 index 0000000..642b0a4 --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/canvas/OffscreenCanvas-placeholder-image-source-with-worker.html
@@ -0,0 +1,55 @@ +<!DOCTYPE html> +<title>Test using a placeholder canvas as an image source.</title> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> + +<script id='myWorker' type='text/worker'> +var ctx; +self.onmessage = function(msg) { + ctx = msg.data.getContext('2d'); + ctx.fillStyle = '#0f0'; + ctx.fillRect(0, 0, 100, 100); + ctx.commit(); + + self.postMessage("done"); +}; +</script> + +<script> +var t = async_test("Test that using a placeholder canvas as a source image accesses the image that was committed to the associated OffscreenCanvas in a worker."); +var canvas = document.createElement('canvas'); +canvas.width = 100; +canvas.height = 100; +var offscreen = canvas.transferControlToOffscreen(); + +var blob = new Blob([document.getElementById('myWorker').textContent]); +var worker = new Worker(URL.createObjectURL(blob)); +worker.postMessage(offscreen, [offscreen]); +worker.addEventListener('message', msg => { + // the message is a synchronization barrier that guarantees + // that the offscreen commit has been processed on the worker thread. + verifyImage(canvas, "verify that drawImage works with placeholder canvas as a source."); + var testImage = new Image(); + testImage.src = canvas.toDataURL(); + testImage.onload = function() { + verifyImage(canvas, "verify that toDataURL works on placeholder canvas."); + canvas.toBlob(blob => { + createImageBitmap(blob).then(image => { + verifyImage(image, "verify that toBlob works on placeholder canvas."); + t.done(); + }) + }); + } +}); + +function verifyImage(image, description) { + var testCanvas = document.createElement('canvas'); + var testCtx = testCanvas.getContext('2d'); + testCtx.drawImage(image, 0, 0); + + t.step(function() { + var pixel = testCtx.getImageData(50, 50, 1, 1).data; + assert_array_equals(pixel, [0, 255, 0, 255], description); + }); +} +</script> \ No newline at end of file
diff --git a/third_party/WebKit/LayoutTests/fast/canvas/OffscreenCanvas-placeholder-image-source.html b/third_party/WebKit/LayoutTests/fast/canvas/OffscreenCanvas-placeholder-image-source.html new file mode 100644 index 0000000..fa2b295 --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/canvas/OffscreenCanvas-placeholder-image-source.html
@@ -0,0 +1,48 @@ +<!DOCTYPE html> +<title>Test using a placeholder canvas as an image source.</title> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> + +<script> +var t = async_test("Test that using a placeholder canvas as a source image accesses the image that was committed to the associated OffscreenCanvas."); +var canvas = document.createElement('canvas'); +canvas.width = 100; +canvas.height = 100; +var offscreen = canvas.transferControlToOffscreen(); + +var ctx = offscreen.getContext('2d'); +ctx.fillStyle = '#0f0'; +ctx.fillRect(0, 0, 100, 100); +ctx.commit(); +verifyImage(canvas, [0, 0, 0, 0], "Verify that OffscreenCanvas.commit() does not propagate the image synchronously to the placeholder canvas."); + +setTimeout(function() { + // setTimeout is a synchronization barrier that guarantees + // that the offscreen commit has been processed by the event loop, + // as long as the timeout event is queued after the call to commit(). + var green = [0, 255, 0, 255]; + verifyImage(canvas, green, "verify that drawImage works with placeholder canvas as a source."); + var testImage = new Image(); + testImage.src = canvas.toDataURL(); + testImage.onload = function() { + verifyImage(canvas, green, "verify that toDataURL works on placeholder canvas."); + canvas.toBlob(blob => { + createImageBitmap(blob).then(image => { + verifyImage(image, green, "verify that toBlob works on placeholder canvas."); + t.done(); + }) + }); + } +}, 0); + +function verifyImage(image, expectedColor, description) { + var testCanvas = document.createElement('canvas'); + var testCtx = testCanvas.getContext('2d'); + testCtx.drawImage(image, 0, 0); + + t.step(function() { + var pixel = testCtx.getImageData(50, 50, 1, 1).data; + assert_array_equals(pixel, expectedColor, description); + }); +} +</script> \ No newline at end of file
diff --git a/third_party/WebKit/LayoutTests/fast/canvas/OffscreenCanvas-transferControlToOffscreen.html b/third_party/WebKit/LayoutTests/fast/canvas/OffscreenCanvas-transferControlToOffscreen.html index e961996..8d61b355 100644 --- a/third_party/WebKit/LayoutTests/fast/canvas/OffscreenCanvas-transferControlToOffscreen.html +++ b/third_party/WebKit/LayoutTests/fast/canvas/OffscreenCanvas-transferControlToOffscreen.html
@@ -64,12 +64,6 @@ assert_throws("InvalidStateError", function() { canvas4.width = 20; }, "canvas resizing width is not allowed after transferring control to offscreen."); - assert_throws("InvalidStateError", function() { - canvas4.toBlob(function() {}); - }, "canvas.toBlob is not allowed after transferring control to offscreen."); - assert_throws("InvalidStateError", function() { - canvas4.toDataURL(); - }, "canvas.toDataURL is not allowed after transferring control to offscreen."); }, "Test if modifying canvas after it transfers controls to offscreen throw exceptions"); </script>
diff --git a/third_party/WebKit/LayoutTests/fast/canvas/canvas-createImageBitmap-invalid-args-expected.txt b/third_party/WebKit/LayoutTests/fast/canvas/canvas-createImageBitmap-invalid-args-expected.txt index cb02558..b8c0e7c 100644 --- a/third_party/WebKit/LayoutTests/fast/canvas/canvas-createImageBitmap-invalid-args-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/canvas/canvas-createImageBitmap-invalid-args-expected.txt
@@ -55,7 +55,8 @@ PASS reason instanceof Error is true InvalidStateError: The source image cannot be decoded. PASS Rejected as expected: invalid canvas -FAIL reason instanceof Error should be true. Was false. +null +PASS Rejected as expected: cropRect too big null PASS successfullyParsed is true
diff --git a/third_party/WebKit/LayoutTests/fast/canvas/canvas-createImageBitmap-invalid-args.html b/third_party/WebKit/LayoutTests/fast/canvas/canvas-createImageBitmap-invalid-args.html index af1488cf..f920b73 100644 --- a/third_party/WebKit/LayoutTests/fast/canvas/canvas-createImageBitmap-invalid-args.html +++ b/third_party/WebKit/LayoutTests/fast/canvas/canvas-createImageBitmap-invalid-args.html
@@ -10,22 +10,23 @@ var reason; -function shouldBeRejected(promise, message) { +function shouldBeRejected(promise, message, isReasonError) { return promise.then(function() { testFailed('Resolved unexpectedly: ' + message); }, function(e) { reason = e; testPassed('Rejected as expected: ' + message); - shouldBeTrue('reason instanceof Error'); + if (isReasonError) + shouldBeTrue('reason instanceof Error'); debug(e); }); } function checkInvalidRange(source, message) { return Promise.resolve().then(function() { - return shouldBeRejected(createImageBitmap(source, 0, 0, 10, 0), message + ' / invalid range'); + return shouldBeRejected(createImageBitmap(source, 0, 0, 10, 0), message + ' / invalid range', true); }).then(function() { - return shouldBeRejected(createImageBitmap(source, 0, 0, 0, 10), message + ' / invalid range'); + return shouldBeRejected(createImageBitmap(source, 0, 0, 0, 10), message + ' / invalid range', true); }); } @@ -82,13 +83,13 @@ } Promise.resolve().then(function() { - return shouldBeRejected(createImageBitmap(undefined), 'undefined'); + return shouldBeRejected(createImageBitmap(undefined), 'undefined', true); }).then(function() { - return shouldBeRejected(createImageBitmap(null), 'null'); + return shouldBeRejected(createImageBitmap(null), 'null', true); }).then(function() { - return shouldBeRejected(createImageBitmap(new Image), 'empty image'); + return shouldBeRejected(createImageBitmap(new Image), 'empty image', true); }).then(function() { - return shouldBeRejected(createImageBitmap(document.createElement('video')), 'empty video'); + return shouldBeRejected(createImageBitmap(document.createElement('video')), 'empty video', true); }).then(function() { return createImage().then(function(image) { return checkInvalidRange(image, 'image'); @@ -118,12 +119,15 @@ }); }).then(function() { return createBlob('resources/shadow-offset.js').then(function(blob) { - return shouldBeRejected(createImageBitmap(blob), 'invalid blob'); + return shouldBeRejected(createImageBitmap(blob), 'invalid blob', true); }); }).then(function() { return createInvalidCanvas().then(function(invalidCanvas) { - return shouldBeRejected(createImageBitmap(invalidCanvas), 'invalid canvas'); + return shouldBeRejected(createImageBitmap(invalidCanvas), 'invalid canvas', false); }); +}).then(function() { + var imageData = new ImageData(10, 10); + return shouldBeRejected(createImageBitmap(imageData, 0, 0, 0x10004, 0x10004, {premultiplyAlpha:"none"}), 'cropRect too big', false); }).catch(function(e) { testFailed('Unexpected rejection: ' + e); }).then(finishJSTest, finishJSTest);
diff --git a/third_party/WebKit/LayoutTests/imported/wpt/imagebitmap-renderingcontext/bitmaprenderer-as-imagesource.html b/third_party/WebKit/LayoutTests/fast/canvas/imagebitmap/bitmaprenderer-as-imagesource.html similarity index 69% rename from third_party/WebKit/LayoutTests/imported/wpt/imagebitmap-renderingcontext/bitmaprenderer-as-imagesource.html rename to third_party/WebKit/LayoutTests/fast/canvas/imagebitmap/bitmaprenderer-as-imagesource.html index 1dbfa2b..4a22799 100644 --- a/third_party/WebKit/LayoutTests/imported/wpt/imagebitmap-renderingcontext/bitmaprenderer-as-imagesource.html +++ b/third_party/WebKit/LayoutTests/fast/canvas/imagebitmap/bitmaprenderer-as-imagesource.html
@@ -1,9 +1,6 @@ <!DOCTYPE html> -<meta charset="utf-8"> -<title>Canvas's ImageBitmapRenderingContext test</title> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<link rel="help" href="https://html.spec.whatwg.org/multipage/scripting.html#the-imagebitmap-rendering-context"> +<script src="../../../resources/testharness.js"></script> +<script src="../../../resources/testharnessreport.js"></script> <script> var width = 10; var height = 10; @@ -14,6 +11,7 @@ assert_array_equals(color, [r, g, b, a]); } + function consumeImageBitmap(image, t) { var myCanvas = document.createElement('canvas'); @@ -21,18 +19,32 @@ var myCtx = myCanvas.getContext('bitmaprenderer'); myCtx.transferFromImageBitmap(image); + var dstCanvas = document.createElement('canvas'); + dstCanvas.width = dstCanvas.height = 20; + var dstCtx = dstCanvas.getContext('2d'); + dstCtx.clearRect(0, 0, 20, 20); + dstCtx.drawImage(myCanvas, 0, 0); + testCanvas(dstCtx, 5, 5, 0, 255, 0, 255); + testCanvas(dstCtx, 15, 15, 0, 0, 0, 0); + t.done(); +} + +function consumeImageBitmapByCreateImageBitmap(image, t) +{ + var myCanvas = document.createElement('canvas'); + myCanvas.width = myCanvas.height = 20; + var myCtx = myCanvas.getContext('bitmaprenderer'); + myCtx.transferFromImageBitmap(image); + createImageBitmap(myCanvas).then(t.step_func_done(function(imageBitmap) { - // Per spec, when transferFromImageBitmap happens, the transferred - // ImageBitmap (|image| here) should be the intrinsic size of - // myCanvas, and hence myCanvas.width/height is ignored. Therefore, - // this created |imageBitmap| should have the same size as the |image|. assert_equals(imageBitmap.width, width); assert_equals(imageBitmap.height, height); var dstCanvas = document.createElement('canvas'); dstCanvas.width = dstCanvas.height = 20; var dstCtx = dstCanvas.getContext('2d'); - dstCtx.drawImage(myCanvas, 0, 0); + dstCtx.clearRect(0, 0, 20, 20); + dstCtx.drawImage(imageBitmap, 0, 0); testCanvas(dstCtx, 5, 5, 0, 255, 0, 255); testCanvas(dstCtx, 15, 15, 0, 0, 0, 0); })); @@ -48,6 +60,18 @@ createImageBitmap(canvas).then(t.step_func(function(image) { consumeImageBitmap(image, t); })); +}, 'Test that drawImage from a bitmaprenderer canvas produces correct result'); + +async_test(function(t) { + var canvas = document.createElement("canvas"); + canvas.width = width; + canvas.height = height; + var ctx = canvas.getContext('2d'); + ctx.fillStyle = '#0f0'; + ctx.fillRect(0, 0, width, height); + createImageBitmap(canvas).then(t.step_func(function(image) { + consumeImageBitmapByCreateImageBitmap(image, t); + })); }, 'Test that createImageBitmap from a bitmaprenderer canvas produces correct result'); async_test(function(t) {
diff --git a/third_party/WebKit/LayoutTests/fast/css-grid-layout/stale-grid-layout-expected.txt b/third_party/WebKit/LayoutTests/fast/css-grid-layout/stale-grid-layout-expected.txt index 30301db..f294c90 100644 --- a/third_party/WebKit/LayoutTests/fast/css-grid-layout/stale-grid-layout-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/css-grid-layout/stale-grid-layout-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. The test checks that we don't add non-children of the grid into the grid representation This test has passed if it didn't crash under ASAN.
diff --git a/third_party/WebKit/LayoutTests/fast/css/pseudo-required-optional-unapplied-expected.txt b/third_party/WebKit/LayoutTests/fast/css/pseudo-required-optional-unapplied-expected.txt index 0a4d250..300b204 100644 --- a/third_party/WebKit/LayoutTests/fast/css/pseudo-required-optional-unapplied-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/css/pseudo-required-optional-unapplied-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Check cases that :required/:optional classes are not applied On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/deprecated-flexbox/crash-button-keygen-expected.txt b/third_party/WebKit/LayoutTests/fast/deprecated-flexbox/crash-button-keygen-expected.txt index 4c7a98d..e293659 100644 --- a/third_party/WebKit/LayoutTests/fast/deprecated-flexbox/crash-button-keygen-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/deprecated-flexbox/crash-button-keygen-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Test for bug 63776: Partial layout when a flex-box has visibility: collapse This test PASSES if it does not CRASH.
diff --git a/third_party/WebKit/LayoutTests/fast/dom/Attr/update-attribute-node-no-crash-expected.txt b/third_party/WebKit/LayoutTests/fast/dom/Attr/update-attribute-node-no-crash-expected.txt index cde05ee..1140631 100644 --- a/third_party/WebKit/LayoutTests/fast/dom/Attr/update-attribute-node-no-crash-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/dom/Attr/update-attribute-node-no-crash-expected.txt
@@ -3,9 +3,9 @@ On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". -PASS replaced = element.setAttributeNode(attr); replaced.name is "STYLE" +PASS replaced = element.setAttributeNode(attr); replaced.name is "style" PASS replaced.value is "background-color: red" -PASS attr.name is "STYLE" +PASS attr.name is "style" PASS attr.value is "" PASS element.getAttribute('style') is "" PASS element.getAttribute('StyLE') is ""
diff --git a/third_party/WebKit/LayoutTests/fast/dom/Attr/update-attribute-node-no-crash.html b/third_party/WebKit/LayoutTests/fast/dom/Attr/update-attribute-node-no-crash.html index db9b7167..996ff3bb 100644 --- a/third_party/WebKit/LayoutTests/fast/dom/Attr/update-attribute-node-no-crash.html +++ b/third_party/WebKit/LayoutTests/fast/dom/Attr/update-attribute-node-no-crash.html
@@ -11,9 +11,9 @@ var element = document.getElementById("test"); var attr = document.createAttribute("STYLE"); // This aligns with Trident rather than Gecko. -shouldBeEqualToString("replaced = element.setAttributeNode(attr); replaced.name", "STYLE"); +shouldBeEqualToString("replaced = element.setAttributeNode(attr); replaced.name", "style"); shouldBeEqualToString("replaced.value", "background-color: red"); -shouldBeEqualToString("attr.name", "STYLE"); +shouldBeEqualToString("attr.name", "style"); shouldBeEqualToString("attr.value", ""); shouldBeEqualToString("element.getAttribute('style')", ""); shouldBeEqualToString("element.getAttribute('StyLE')", "");
diff --git a/third_party/WebKit/LayoutTests/fast/dom/Element/getAttribute-check-case-sensitivity-expected.txt b/third_party/WebKit/LayoutTests/fast/dom/Element/getAttribute-check-case-sensitivity-expected.txt index 8cde726..ad58bcd 100644 --- a/third_party/WebKit/LayoutTests/fast/dom/Element/getAttribute-check-case-sensitivity-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/dom/Element/getAttribute-check-case-sensitivity-expected.txt
@@ -9,14 +9,14 @@ PASS testGetAttributeNodeMixedCase() is "x" PASS testGetAttributeNodeLowerCase() is "x" PASS testSetAttributeNodeKeepsRef() is "1" -PASS testAttribNodeNamePreservesCase() is "A,A" -PASS testAttribNodeNamePreservesCaseGetNode() is "A,A" -PASS testAttribNodeNamePreservesCaseGetNode2() is "B,B" +PASS testAttribNodeNamePreservesCase() is "a,a" +PASS testAttribNodeNamePreservesCaseGetNode() is "a,a" +PASS testAttribNodeNamePreservesCaseGetNode2() is "b,b" PASS testAttribNodeNameGetMutate() is "1" -PASS (new XMLSerializer).serializeToString(node) is "<div xmlns=\"http://www.w3.org/1999/xhtml\" myAttrib=\"XXX\"></div>" -PASS node.getAttributeNode('myAttrib').name is "myAttrib" -PASS node.getAttributeNode('myattrib').name is "myAttrib" -PASS attrib.name is "myAttrib" +PASS (new XMLSerializer).serializeToString(node) is "<div xmlns=\"http://www.w3.org/1999/xhtml\" myattrib=\"XXX\"></div>" +PASS node.getAttributeNode('myAttrib').name is "myattrib" +PASS node.getAttributeNode('myattrib').name is "myattrib" +PASS attrib.name is "myattrib" PASS successfullyParsed is true TEST COMPLETE
diff --git a/third_party/WebKit/LayoutTests/fast/dom/Element/script-tests/getAttribute-check-case-sensitivity.js b/third_party/WebKit/LayoutTests/fast/dom/Element/script-tests/getAttribute-check-case-sensitivity.js index ee2bffa..3b73ac2 100644 --- a/third_party/WebKit/LayoutTests/fast/dom/Element/script-tests/getAttribute-check-case-sensitivity.js +++ b/third_party/WebKit/LayoutTests/fast/dom/Element/script-tests/getAttribute-check-case-sensitivity.js
@@ -61,7 +61,7 @@ return result.join(","); } -shouldBe("testAttribNodeNamePreservesCase()", '"A,A"'); +shouldBe("testAttribNodeNamePreservesCase()", '"a,a"'); function testAttribNodeNamePreservesCaseGetNode() @@ -82,7 +82,7 @@ return result.join(","); } -shouldBe("testAttribNodeNamePreservesCaseGetNode()", '"A,A"'); +shouldBe("testAttribNodeNamePreservesCaseGetNode()", '"a,a"'); function testAttribNodeNamePreservesCaseGetNode2() { @@ -109,7 +109,7 @@ return result.join(","); } -shouldBe("testAttribNodeNamePreservesCaseGetNode2()", '"B,B"'); +shouldBe("testAttribNodeNamePreservesCaseGetNode2()", '"b,b"'); function testAttribNodeNameGetMutate() { @@ -135,7 +135,7 @@ attrib.value = "XXX"; node.setAttributeNode(attrib); -shouldBe("(new XMLSerializer).serializeToString(node)", '"<div xmlns=\\"http://www.w3.org/1999/xhtml\\" myAttrib=\\"XXX\\"></div>"'); -shouldBe("node.getAttributeNode('myAttrib').name", '"myAttrib"'); -shouldBe("node.getAttributeNode('myattrib').name", '"myAttrib"'); -shouldBe("attrib.name", '"myAttrib"'); +shouldBe("(new XMLSerializer).serializeToString(node)", '"<div xmlns=\\"http://www.w3.org/1999/xhtml\\" myattrib=\\"XXX\\"></div>"'); +shouldBe("node.getAttributeNode('myAttrib').name", '"myattrib"'); +shouldBe("node.getAttributeNode('myattrib').name", '"myattrib"'); +shouldBe("attrib.name", '"myattrib"');
diff --git a/third_party/WebKit/LayoutTests/fast/dom/HTMLFormElement/associated-elements-after-index-assertion-fail1-expected.txt b/third_party/WebKit/LayoutTests/fast/dom/HTMLFormElement/associated-elements-after-index-assertion-fail1-expected.txt index 0303108..ee8e0b18 100644 --- a/third_party/WebKit/LayoutTests/fast/dom/HTMLFormElement/associated-elements-after-index-assertion-fail1-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/dom/HTMLFormElement/associated-elements-after-index-assertion-fail1-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. This page verifies fix for bug 58247. WebKit should not crash when this page is rendered.
diff --git a/third_party/WebKit/LayoutTests/fast/dom/HTMLKeygenElement/keygen-expected.txt b/third_party/WebKit/LayoutTests/fast/dom/HTMLKeygenElement/keygen-expected.txt index c60e736..e518029 100644 --- a/third_party/WebKit/LayoutTests/fast/dom/HTMLKeygenElement/keygen-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/dom/HTMLKeygenElement/keygen-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. This tests the keygen element On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/dom/NodeList/nodelist-reachable-expected.txt b/third_party/WebKit/LayoutTests/fast/dom/NodeList/nodelist-reachable-expected.txt index 871653e..50943e4 100644 --- a/third_party/WebKit/LayoutTests/fast/dom/NodeList/nodelist-reachable-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/dom/NodeList/nodelist-reachable-expected.txt
@@ -2,7 +2,7 @@ PASS document.getElementsByClassName("class").customProperty is 2 PASS document.getElementsByName("name").customProperty is 3 PASS document.getElementsByTagName("body").customProperty is 4 -FAIL document.querySelector("form").elements["radios"].customProperty should be 5 (of type number). Was undefined (of type undefined). +PASS document.querySelector("form").elements["radios"].customProperty is 5 PASS document.querySelector("input").labels.customProperty is 6 PASS successfullyParsed is true
diff --git a/third_party/WebKit/LayoutTests/fast/dom/click-method-on-html-element-expected.txt b/third_party/WebKit/LayoutTests/fast/dom/click-method-on-html-element-expected.txt index ed12f55..b88475f 100644 --- a/third_party/WebKit/LayoutTests/fast/dom/click-method-on-html-element-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/dom/click-method-on-html-element-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 16: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 16: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. The support of click() method on HTMLElement. Pass: Click event handler called for: a
diff --git a/third_party/WebKit/LayoutTests/fast/dom/domstring-attribute-reflection-expected.txt b/third_party/WebKit/LayoutTests/fast/dom/domstring-attribute-reflection-expected.txt index c5c3d9b7..9dd5883 100644 --- a/third_party/WebKit/LayoutTests/fast/dom/domstring-attribute-reflection-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/dom/domstring-attribute-reflection-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 10: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 10: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Reflected DOMString attribute test for button/@name Initial value: PASS element.name is "" @@ -239,36 +239,6 @@ PASS element.getAttribute("label") is "456" -Reflected DOMString attribute test for menuitem/@type -Initial value: -PASS element.type is "" -PASS element.getAttribute("type") is null -Setting a value via the IDL attribute: -PASS element.type = "foo"; element.type is "foo" -PASS element.getAttribute("type") is "foo" -Setting a value via the content attribute: -PASS element.setAttribute("type", " bar\n"); element.type is " bar\n" -PASS element.getAttribute("type") is " bar\n" -Setting null via the IDL attribute: -PASS element.type = null; element.type is "null" -PASS element.getAttribute("type") is "null" -Setting null via the content attribute: -PASS element.setAttribute("type", null); element.type is "null" -PASS element.getAttribute("type") is "null" -Setting undefined via the IDL attribute: -PASS element.type = undefined; element.type is "undefined" -PASS element.getAttribute("type") is "undefined" -Setting undefined via the content attribute: -PASS element.setAttribute("type", undefined); element.type is "undefined" -PASS element.getAttribute("type") is "undefined" -Setting non-string via the IDL attribute: -PASS element.type = 123; element.type is "123" -PASS element.getAttribute("type") is "123" -Setting non-string via the content attribute: -PASS element.setAttribute("type", 456); element.type is "456" -PASS element.getAttribute("type") is "456" - - Reflected DOMString attribute test for menuitem/@label Initial value: PASS element.label is ""
diff --git a/third_party/WebKit/LayoutTests/fast/dom/domstring-attribute-reflection.html b/third_party/WebKit/LayoutTests/fast/dom/domstring-attribute-reflection.html index 5a9ed357..f633fed 100644 --- a/third_party/WebKit/LayoutTests/fast/dom/domstring-attribute-reflection.html +++ b/third_party/WebKit/LayoutTests/fast/dom/domstring-attribute-reflection.html
@@ -61,7 +61,6 @@ testDOMStringReflection('keygen', 'name'); testDOMStringReflection('menu', 'type'); testDOMStringReflection('menu', 'label'); -testDOMStringReflection('menuitem', 'type'); testDOMStringReflection('menuitem', 'label'); testDOMStringReflection('object', 'name'); testDOMStringReflection('output', 'name');
diff --git a/third_party/WebKit/LayoutTests/fast/dom/element-attribute-js-null-expected.txt b/third_party/WebKit/LayoutTests/fast/dom/element-attribute-js-null-expected.txt index e11458e9..81aa283 100644 --- a/third_party/WebKit/LayoutTests/fast/dom/element-attribute-js-null-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/dom/element-attribute-js-null-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 362: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 362: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. This test setting various attributes of a elements to JavaScript null. TEST SUCCEEDED: The value was null. [tested Node.nodeValue]
diff --git a/third_party/WebKit/LayoutTests/fast/dom/shadow/layout-tests-can-access-shadow-expected.txt b/third_party/WebKit/LayoutTests/fast/dom/shadow/layout-tests-can-access-shadow-expected.txt index f5bdd26f..7ac42240 100644 --- a/third_party/WebKit/LayoutTests/fast/dom/shadow/layout-tests-can-access-shadow-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/dom/shadow/layout-tests-can-access-shadow-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. This tests that layout tests can access shadow DOM.
diff --git a/third_party/WebKit/LayoutTests/fast/dom/shadow/no-renderers-for-light-children-expected.txt b/third_party/WebKit/LayoutTests/fast/dom/shadow/no-renderers-for-light-children-expected.txt index 73ada819..f57033b9 100644 --- a/third_party/WebKit/LayoutTests/fast/dom/shadow/no-renderers-for-light-children-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/dom/shadow/no-renderers-for-light-children-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Children of an element are never rendered is it has a shadow DOM subtree. Should not see the word FAIL below.
diff --git a/third_party/WebKit/LayoutTests/fast/dom/shadow/nodetype-expected.txt b/third_party/WebKit/LayoutTests/fast/dom/shadow/nodetype-expected.txt index d4221ea..9659ad6 100644 --- a/third_party/WebKit/LayoutTests/fast/dom/shadow/nodetype-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/dom/shadow/nodetype-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. This tests the shadow host's and shadow root's nodeType. PASS keygen.nodeType is Node.ELEMENT_NODE
diff --git a/third_party/WebKit/LayoutTests/fast/dom/shadow/shadow-disable-expected.txt b/third_party/WebKit/LayoutTests/fast/dom/shadow/shadow-disable-expected.txt index b651510..b0a5a340 100644 --- a/third_party/WebKit/LayoutTests/fast/dom/shadow/shadow-disable-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/dom/shadow/shadow-disable-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 50: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 50: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Tests to ensure that shadow element cannot be created in elements having dynamically created shadow root. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/dom/wrapper-classes-expected.txt b/third_party/WebKit/LayoutTests/fast/dom/wrapper-classes-expected.txt index e507ddf..c8e9981 100644 --- a/third_party/WebKit/LayoutTests/fast/dom/wrapper-classes-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/dom/wrapper-classes-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 26: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 26: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. This tests wrapper class names for JavaScript. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/dynamic/insertAdjacentHTML-allowed-parents-expected.txt b/third_party/WebKit/LayoutTests/fast/dynamic/insertAdjacentHTML-allowed-parents-expected.txt index 239006d..25c5bb3 100644 --- a/third_party/WebKit/LayoutTests/fast/dynamic/insertAdjacentHTML-allowed-parents-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/dynamic/insertAdjacentHTML-allowed-parents-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 14: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 14: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. PASS: insertAdjacentHTML did not throw an exception when using the a tag. PASS: insertAdjacentHTML did not throw an exception when using the abbr tag. PASS: insertAdjacentHTML did not throw an exception when using the acronym tag.
diff --git a/third_party/WebKit/LayoutTests/fast/forms/access-key-for-all-elements-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/access-key-for-all-elements-expected.txt index 6f5bf1e..9616ab6b 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/access-key-for-all-elements-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/access-key-for-all-elements-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 28: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 28: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. This test checks to see if accesskey attributes works on all elements. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/autofocus-keygen-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/autofocus-keygen-expected.txt index 1ca15f5..39c880ec 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/autofocus-keygen-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/autofocus-keygen-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. This tests whether the keygen element supports the autofocus attribute.
diff --git a/third_party/WebKit/LayoutTests/fast/forms/fieldset/fieldset-elements-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/fieldset/fieldset-elements-expected.txt index 1f3dd12..0393cc9 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/fieldset/fieldset-elements-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/fieldset/fieldset-elements-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 14: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 14: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. This test the elements attibute of HTMLFieldSet element. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/fieldset/fieldset-form-collection-radionode-list-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/fieldset/fieldset-form-collection-radionode-list-expected.txt index b6c9669e..b361421 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/fieldset/fieldset-form-collection-radionode-list-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/fieldset/fieldset-form-collection-radionode-list-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. CONSOLE WARNING: line 1: The specified value "inputRadioValue" does not conform to the required format, "yyyy-MM-dd". This test is for RadioNodeList specified at http://www.whatwg.org/specs/web-apps/current-work/multipage/common-dom-interfaces.html#radionodelist
diff --git a/third_party/WebKit/LayoutTests/fast/forms/form-associated-element-crash3-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/form-associated-element-crash3-expected.txt index 8e7a8cb..2fd8964 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/form-associated-element-crash3-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/form-associated-element-crash3-expected.txt
@@ -1,2 +1,2 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. This test passes if it doesn't crash. Note: You might need to reload this test many times (or run the test under valgrind / ASAN) to see a crash.
diff --git a/third_party/WebKit/LayoutTests/fast/forms/form-associated-element-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/form-associated-element-expected.txt index e00099f..2d3f9cf 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/form-associated-element-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/form-associated-element-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Verify that only elements that are 'form associatable' get a form owner. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/form-attribute-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/form-attribute-expected.txt index cb3f5c8..ad823f8 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/form-attribute-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/form-attribute-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 16: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 16: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. This test checks the form attribute of the form-associated elements. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/form-collection-elements-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/form-collection-elements-expected.txt index 6bfbd2e..7b9b29f 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/form-collection-elements-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/form-collection-elements-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 16: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 16: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. This test lists all the elements of a form per http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#category-listed. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/form-collection-elements-order-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/form-collection-elements-order-expected.txt index a7bd9f8..4c86ced 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/form-collection-elements-order-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/form-collection-elements-order-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 27: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 27: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. This test examines the order of form associated elements which are classified as 'listed'. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/form-collection-radio-node-list-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/form-collection-radio-node-list-expected.txt index 6202b51..56a8b47 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/form-collection-radio-node-list-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/form-collection-radio-node-list-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. CONSOLE WARNING: line 1: The specified value "inputRadioValue" does not conform to the required format, "yyyy-MM-dd". This test is for RadioNodeList specified at http://www.whatwg.org/specs/web-apps/current-work/multipage/common-dom-interfaces.html#radionodelist
diff --git a/third_party/WebKit/LayoutTests/fast/forms/form-radio-img-node-list-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/form-radio-img-node-list-expected.txt index dde0da9a..baf968c 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/form-radio-img-node-list-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/form-radio-img-node-list-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Test RadioNodeLists returned by the HTMLFormElement named-getter. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/form-radio-node-list-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/form-radio-node-list-expected.txt index e10647f..b30038c 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/form-radio-node-list-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/form-radio-node-list-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Test RadioNodeLists returned by the HTMLFormElement named-getter. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/label/label-contains-other-interactive-content-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/label/label-contains-other-interactive-content-expected.txt index 5423950..20feb9b 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/label/label-contains-other-interactive-content-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/label/label-contains-other-interactive-content-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 22: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 22: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. button PASS document.activeElement.id is not "control" details
diff --git a/third_party/WebKit/LayoutTests/fast/forms/label/labelable-elements-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/label/labelable-elements-expected.txt index f4ea61f..dde24003 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/label/labelable-elements-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/label/labelable-elements-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 28: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 28: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Test labelable elements have labels attribute and others do not. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/label/labels-add-htmlFor-label-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/label/labels-add-htmlFor-label-expected.txt index 7c795133..0ed3185f 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/label/labels-add-htmlFor-label-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/label/labels-add-htmlFor-label-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 28: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 28: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Test that the labels list of a form control is dynamically updated when adding a label whose htmlFor points to that control. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/label/labels-add-parent-label-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/label/labels-add-parent-label-expected.txt index 05755c1..00f1980 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/label/labels-add-parent-label-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/label/labels-add-parent-label-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 28: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 28: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Test that the labels list of a form control is dynamically updated when adding a label as parent for that form control. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/label/labels-change-htmlFor-attribute-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/label/labels-change-htmlFor-attribute-expected.txt index e054767d..f680a1b0 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/label/labels-change-htmlFor-attribute-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/label/labels-change-htmlFor-attribute-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 28: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 28: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Test that the labels list of a form control is dynamically updated when the htmlFor attribute of a label changes to point to that control. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/label/labels-multiple-sibling-labels-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/label/labels-multiple-sibling-labels-expected.txt index c42be898..42fc584 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/label/labels-multiple-sibling-labels-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/label/labels-multiple-sibling-labels-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 28: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 28: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Test that the labels list of a form control contains multiple sibling labels. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/label/labels-parent-and-sibling-labels-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/label/labels-parent-and-sibling-labels-expected.txt index 6a7b3b1..d1d9d91 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/label/labels-parent-and-sibling-labels-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/label/labels-parent-and-sibling-labels-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 28: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 28: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Test that the labels list of a form control contains both parent label and sibling label. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/label/labels-remove-htmlFor-attribute-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/label/labels-remove-htmlFor-attribute-expected.txt index 2ccf3902..ba0542f 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/label/labels-remove-htmlFor-attribute-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/label/labels-remove-htmlFor-attribute-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 28: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 28: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Test that the labels list of a form control is dynamically updated when the htmlFor attribute of a label is removed. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/label/labels-remove-htmlFor-label-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/label/labels-remove-htmlFor-label-expected.txt index fee5778..69af53e 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/label/labels-remove-htmlFor-label-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/label/labels-remove-htmlFor-label-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 28: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 28: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Test that the labels list of a form control is dynamically updated when removing the htmlFor attribute that pointed to that form control. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/label/labels-remove-parent-label-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/label/labels-remove-parent-label-expected.txt index 57ebcde..f17d896 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/label/labels-remove-parent-label-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/label/labels-remove-parent-label-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 28: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 28: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Test that the labels list of a form control is dynamically updated when removing a label as parent for that form control. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/label/labels-set-htmlFor-attribute-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/label/labels-set-htmlFor-attribute-expected.txt index e054767d..f680a1b0 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/label/labels-set-htmlFor-attribute-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/label/labels-set-htmlFor-attribute-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 28: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 28: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Test that the labels list of a form control is dynamically updated when the htmlFor attribute of a label changes to point to that control. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/large-parts-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/large-parts-expected.txt index 80859cd5..4efc6aab 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/large-parts-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/large-parts-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Test for Bug 41737. PASS unless crash.
diff --git a/third_party/WebKit/LayoutTests/fast/forms/reportValidity-valid-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/reportValidity-valid-expected.txt index 9b99fddd..f18e0d8 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/reportValidity-valid-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/reportValidity-valid-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. This test checks if reportValidity() returns correctly a true (meaning no error) result. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/setCustomValidity-arguments-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/setCustomValidity-arguments-expected.txt index f7ce3a7..935883b4 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/setCustomValidity-arguments-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/setCustomValidity-arguments-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 17: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 17: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Test how setCustomValidity reacts to too few arguments. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/setCustomValidity-existence-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/setCustomValidity-existence-expected.txt index b869614..bbd3ebc 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/setCustomValidity-existence-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/setCustomValidity-existence-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 16: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 16: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Existence tests for .setCustomValidity property On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/state-restore-skip-stateless-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/state-restore-skip-stateless-expected.txt index be692a9f..5cb67d5a 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/state-restore-skip-stateless-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/state-restore-skip-stateless-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. CONSOLE MESSAGE: line 44: Test if state of stateless form control types are not saved. PASS There is a state for hidden PASS There is a state for text
diff --git a/third_party/WebKit/LayoutTests/fast/forms/validationMessage-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/validationMessage-expected.txt index 4cffc329..17077b0 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/validationMessage-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/validationMessage-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 198: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 198: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Test for validationMessage DOM property. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/validity-property-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/validity-property-expected.txt index 75f4a435..ba12433d 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/validity-property-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/validity-property-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Each form control in this document exposes a validity attribute that returns a live instance of ValidityState. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/willvalidate-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/willvalidate-expected.txt index 8bf5c31..d5a2d5e 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/willvalidate-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/willvalidate-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 16: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 16: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Various tests for .willValidate property On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/html/clone-keygen-expected.txt b/third_party/WebKit/LayoutTests/fast/html/clone-keygen-expected.txt index e7022de4..4a0fe71 100644 --- a/third_party/WebKit/LayoutTests/fast/html/clone-keygen-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/html/clone-keygen-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Tests that a cloned keygen has the right shadow pseudo ID. You should see two big keygens with purple text (they should look the same.)
diff --git a/third_party/WebKit/LayoutTests/fast/lists/li-minimum-long-value-expected.html b/third_party/WebKit/LayoutTests/fast/lists/li-minimum-long-value-expected.html new file mode 100644 index 0000000..00d5b83 --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/lists/li-minimum-long-value-expected.html
@@ -0,0 +1 @@ +<li>
diff --git a/third_party/WebKit/LayoutTests/fast/lists/li-minimum-long-value.html b/third_party/WebKit/LayoutTests/fast/lists/li-minimum-long-value.html new file mode 100644 index 0000000..3f8fcbd --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/lists/li-minimum-long-value.html
@@ -0,0 +1 @@ +<li value="-2147483648">
diff --git a/third_party/WebKit/LayoutTests/fast/multicol/span/positioned-child-not-removed-crash-expected.txt b/third_party/WebKit/LayoutTests/fast/multicol/span/positioned-child-not-removed-crash-expected.txt index 1d65dc3..66a82f57 100644 --- a/third_party/WebKit/LayoutTests/fast/multicol/span/positioned-child-not-removed-crash-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/multicol/span/positioned-child-not-removed-crash-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 22: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 22: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Test passes if it does not crash.
diff --git a/third_party/WebKit/LayoutTests/fast/replaced/keygen-as-table-column-group-crash-expected.txt b/third_party/WebKit/LayoutTests/fast/replaced/keygen-as-table-column-group-crash-expected.txt index 976d3d0f..6e405e4d 100644 --- a/third_party/WebKit/LayoutTests/fast/replaced/keygen-as-table-column-group-crash-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/replaced/keygen-as-table-column-group-crash-expected.txt
@@ -1,2 +1,2 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. PASS if no crash or assert.
diff --git a/third_party/WebKit/LayoutTests/fast/ruby/float-object-doesnt-crash-expected.txt b/third_party/WebKit/LayoutTests/fast/ruby/float-object-doesnt-crash-expected.txt index 7877c5d..2bcc288 100644 --- a/third_party/WebKit/LayoutTests/fast/ruby/float-object-doesnt-crash-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/ruby/float-object-doesnt-crash-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Test passes if it does not crash when run with memory checking for use-after-free. | >
diff --git a/third_party/WebKit/LayoutTests/fast/table/crash-splitColumn-2-expected.txt b/third_party/WebKit/LayoutTests/fast/table/crash-splitColumn-2-expected.txt index e8926a0..2947528 100644 --- a/third_party/WebKit/LayoutTests/fast/table/crash-splitColumn-2-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/table/crash-splitColumn-2-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 26: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 26: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Bug 70171: Crash in LayoutTableSection::splitColumn This test PASSES if it does not CRASH or ASSERT.
diff --git a/third_party/WebKit/LayoutTests/fast/xmlhttprequest/xmlhttprequest-responsetype-arraybuffer-expected.txt b/third_party/WebKit/LayoutTests/fast/xmlhttprequest/xmlhttprequest-responsetype-arraybuffer-expected.txt index 866cc57..1971f8d 100644 --- a/third_party/WebKit/LayoutTests/fast/xmlhttprequest/xmlhttprequest-responsetype-arraybuffer-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/xmlhttprequest/xmlhttprequest-responsetype-arraybuffer-expected.txt
@@ -23,7 +23,7 @@ checksum : 84637740 PASS exception correctly thrown when xhr.responseText is accessed but responseType is 'arraybuffer' : InvalidStateError: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'arraybuffer').. PASS exception correctly thrown when xhr.responseXML is accessed but responseType is 'arraybuffer' : InvalidStateError: Failed to read the 'responseXML' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'document' (was 'arraybuffer').. -FAIL xhr.response.foo should be bar (of type string). Was undefined (of type undefined). +PASS xhr.response.foo is 'bar' PASS successfullyParsed is true TEST COMPLETE
diff --git a/third_party/WebKit/LayoutTests/html5lib/generated/run-tests19-data-expected.txt b/third_party/WebKit/LayoutTests/html5lib/generated/run-tests19-data-expected.txt index c15b9fd..6fee9d3b 100644 --- a/third_party/WebKit/LayoutTests/html5lib/generated/run-tests19-data-expected.txt +++ b/third_party/WebKit/LayoutTests/html5lib/generated/run-tests19-data-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. ../resources/tests19.dat: 8 9
diff --git a/third_party/WebKit/LayoutTests/html5lib/generated/run-tests19-write-expected.txt b/third_party/WebKit/LayoutTests/html5lib/generated/run-tests19-write-expected.txt index 851edc5..9c2680f 100644 --- a/third_party/WebKit/LayoutTests/html5lib/generated/run-tests19-write-expected.txt +++ b/third_party/WebKit/LayoutTests/html5lib/generated/run-tests19-write-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 165: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 165: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. ../resources/tests19.dat: 8 9
diff --git a/third_party/WebKit/LayoutTests/html5lib/generated/run-tests25-data-expected.txt b/third_party/WebKit/LayoutTests/html5lib/generated/run-tests25-data-expected.txt index 140eede..4218f00 100644 --- a/third_party/WebKit/LayoutTests/html5lib/generated/run-tests25-data-expected.txt +++ b/third_party/WebKit/LayoutTests/html5lib/generated/run-tests25-data-expected.txt
@@ -1,2 +1,2 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. ../resources/tests25.dat: PASS
diff --git a/third_party/WebKit/LayoutTests/html5lib/generated/run-tests25-write-expected.txt b/third_party/WebKit/LayoutTests/html5lib/generated/run-tests25-write-expected.txt index 46d736e..2651115 100644 --- a/third_party/WebKit/LayoutTests/html5lib/generated/run-tests25-write-expected.txt +++ b/third_party/WebKit/LayoutTests/html5lib/generated/run-tests25-write-expected.txt
@@ -1,2 +1,2 @@ -CONSOLE WARNING: line 165: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 165: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. ../resources/tests25.dat: PASS
diff --git a/third_party/WebKit/LayoutTests/html5lib/generated/run-tests7-data-expected.txt b/third_party/WebKit/LayoutTests/html5lib/generated/run-tests7-data-expected.txt index 455b9600..85c25f56 100644 --- a/third_party/WebKit/LayoutTests/html5lib/generated/run-tests7-data-expected.txt +++ b/third_party/WebKit/LayoutTests/html5lib/generated/run-tests7-data-expected.txt
@@ -1,3 +1,3 @@ CONSOLE ERROR: line 1: Uncaught SyntaxError: Unexpected token < -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. ../resources/tests7.dat: PASS
diff --git a/third_party/WebKit/LayoutTests/html5lib/generated/run-tests7-write-expected.txt b/third_party/WebKit/LayoutTests/html5lib/generated/run-tests7-write-expected.txt index 065adda..dad9584 100644 --- a/third_party/WebKit/LayoutTests/html5lib/generated/run-tests7-write-expected.txt +++ b/third_party/WebKit/LayoutTests/html5lib/generated/run-tests7-write-expected.txt
@@ -1,3 +1,3 @@ CONSOLE ERROR: line 1: Uncaught SyntaxError: Unexpected token < -CONSOLE WARNING: line 165: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 165: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. ../resources/tests7.dat: PASS
diff --git a/third_party/WebKit/LayoutTests/html5lib/resources/tests11.dat b/third_party/WebKit/LayoutTests/html5lib/resources/tests11.dat index 6fef8f2..faaf97b 100644 --- a/third_party/WebKit/LayoutTests/html5lib/resources/tests11.dat +++ b/third_party/WebKit/LayoutTests/html5lib/resources/tests11.dat
@@ -1,5 +1,5 @@ #data -<!DOCTYPE html><body><svg attributeName='' attributeType='' baseFrequency='' baseProfile='' calcMode='' clipPathUnits='' diffuseConstant='' edgeMode='' filterUnits='' glyphRef='' gradientTransform='' gradientUnits='' kernelMatrix='' kernelUnitLength='' keyPoints='' keySplines='' keyTimes='' lengthAdjust='' limitingConeAngle='' markerHeight='' markerUnits='' markerWidth='' maskContentUnits='' maskUnits='' numOctaves='' pathLength='' patternContentUnits='' patternTransform='' patternUnits='' pointsAtX='' pointsAtY='' pointsAtZ='' preserveAlpha='' preserveAspectRatio='' primitiveUnits='' refX='' refY='' repeatCount='' repeatDur='' requiredExtensions='' requiredFeatures='' specularConstant='' specularExponent='' spreadMethod='' startOffset='' stdDeviation='' stitchTiles='' surfaceScale='' systemLanguage='' tableValues='' targetX='' targetY='' textLength='' viewBox='' viewTarget='' xChannelSelector='' yChannelSelector='' zoomAndPan=''></svg> +<!DOCTYPE html><body><svg attributeName='' attributeType='' baseFrequency='' baseProfile='' calcMode='' clipPathUnits='' diffuseConstant='' edgeMode='' filterUnits='' glyphRef='' gradientTransform='' gradientUnits='' kernelMatrix='' kernelUnitLength='' keyPoints='' keySplines='' keyTimes='' lengthAdjust='' limitingConeAngle='' markerHeight='' markerUnits='' markerWidth='' maskContentUnits='' maskUnits='' numOctaves='' pathLength='' patternContentUnits='' patternTransform='' patternUnits='' pointsAtX='' pointsAtY='' pointsAtZ='' preserveAlpha='' preserveAspectRatio='' primitiveUnits='' refX='' refY='' repeatCount='' repeatDur='' requiredExtensions='' requiredFeatures='' specularConstant='' specularExponent='' spreadMethod='' startOffset='' stdDeviation='' stitchTiles='' surfaceScale='' systemLanguage='' tableValues='' targetX='' targetY='' textLength='' viewBox='' xChannelSelector='' yChannelSelector='' zoomAndPan=''></svg> #errors #document | <!DOCTYPE html> @@ -61,13 +61,12 @@ | targetY="" | textLength="" | viewBox="" -| viewTarget="" | xChannelSelector="" | yChannelSelector="" | zoomAndPan="" #data -<!DOCTYPE html><BODY><SVG ATTRIBUTENAME='' ATTRIBUTETYPE='' BASEFREQUENCY='' BASEPROFILE='' CALCMODE='' CLIPPATHUNITS='' DIFFUSECONSTANT='' EDGEMODE='' FILTERUNITS='' GLYPHREF='' GRADIENTTRANSFORM='' GRADIENTUNITS='' KERNELMATRIX='' KERNELUNITLENGTH='' KEYPOINTS='' KEYSPLINES='' KEYTIMES='' LENGTHADJUST='' LIMITINGCONEANGLE='' MARKERHEIGHT='' MARKERUNITS='' MARKERWIDTH='' MASKCONTENTUNITS='' MASKUNITS='' NUMOCTAVES='' PATHLENGTH='' PATTERNCONTENTUNITS='' PATTERNTRANSFORM='' PATTERNUNITS='' POINTSATX='' POINTSATY='' POINTSATZ='' PRESERVEALPHA='' PRESERVEASPECTRATIO='' PRIMITIVEUNITS='' REFX='' REFY='' REPEATCOUNT='' REPEATDUR='' REQUIREDEXTENSIONS='' REQUIREDFEATURES='' SPECULARCONSTANT='' SPECULAREXPONENT='' SPREADMETHOD='' STARTOFFSET='' STDDEVIATION='' STITCHTILES='' SURFACESCALE='' SYSTEMLANGUAGE='' TABLEVALUES='' TARGETX='' TARGETY='' TEXTLENGTH='' VIEWBOX='' VIEWTARGET='' XCHANNELSELECTOR='' YCHANNELSELECTOR='' ZOOMANDPAN=''></SVG> +<!DOCTYPE html><BODY><SVG ATTRIBUTENAME='' ATTRIBUTETYPE='' BASEFREQUENCY='' BASEPROFILE='' CALCMODE='' CLIPPATHUNITS='' DIFFUSECONSTANT='' EDGEMODE='' FILTERUNITS='' GLYPHREF='' GRADIENTTRANSFORM='' GRADIENTUNITS='' KERNELMATRIX='' KERNELUNITLENGTH='' KEYPOINTS='' KEYSPLINES='' KEYTIMES='' LENGTHADJUST='' LIMITINGCONEANGLE='' MARKERHEIGHT='' MARKERUNITS='' MARKERWIDTH='' MASKCONTENTUNITS='' MASKUNITS='' NUMOCTAVES='' PATHLENGTH='' PATTERNCONTENTUNITS='' PATTERNTRANSFORM='' PATTERNUNITS='' POINTSATX='' POINTSATY='' POINTSATZ='' PRESERVEALPHA='' PRESERVEASPECTRATIO='' PRIMITIVEUNITS='' REFX='' REFY='' REPEATCOUNT='' REPEATDUR='' REQUIREDEXTENSIONS='' REQUIREDFEATURES='' SPECULARCONSTANT='' SPECULAREXPONENT='' SPREADMETHOD='' STARTOFFSET='' STDDEVIATION='' STITCHTILES='' SURFACESCALE='' SYSTEMLANGUAGE='' TABLEVALUES='' TARGETX='' TARGETY='' TEXTLENGTH='' VIEWBOX='' XCHANNELSELECTOR='' YCHANNELSELECTOR='' ZOOMANDPAN=''></SVG> #errors #document | <!DOCTYPE html> @@ -129,13 +128,12 @@ | targetY="" | textLength="" | viewBox="" -| viewTarget="" | xChannelSelector="" | yChannelSelector="" | zoomAndPan="" #data -<!DOCTYPE html><body><svg attributename='' attributetype='' basefrequency='' baseprofile='' calcmode='' clippathunits='' diffuseconstant='' edgemode='' filterunits='' glyphref='' gradienttransform='' gradientunits='' kernelmatrix='' kernelunitlength='' keypoints='' keysplines='' keytimes='' lengthadjust='' limitingconeangle='' markerheight='' markerunits='' markerwidth='' maskcontentunits='' maskunits='' numoctaves='' pathlength='' patterncontentunits='' patterntransform='' patternunits='' pointsatx='' pointsaty='' pointsatz='' preservealpha='' preserveaspectratio='' primitiveunits='' refx='' refy='' repeatcount='' repeatdur='' requiredextensions='' requiredfeatures='' specularconstant='' specularexponent='' spreadmethod='' startoffset='' stddeviation='' stitchtiles='' surfacescale='' systemlanguage='' tablevalues='' targetx='' targety='' textlength='' viewbox='' viewtarget='' xchannelselector='' ychannelselector='' zoomandpan=''></svg> +<!DOCTYPE html><body><svg attributename='' attributetype='' basefrequency='' baseprofile='' calcmode='' clippathunits='' diffuseconstant='' edgemode='' filterunits='' glyphref='' gradienttransform='' gradientunits='' kernelmatrix='' kernelunitlength='' keypoints='' keysplines='' keytimes='' lengthadjust='' limitingconeangle='' markerheight='' markerunits='' markerwidth='' maskcontentunits='' maskunits='' numoctaves='' pathlength='' patterncontentunits='' patterntransform='' patternunits='' pointsatx='' pointsaty='' pointsatz='' preservealpha='' preserveaspectratio='' primitiveunits='' refx='' refy='' repeatcount='' repeatdur='' requiredextensions='' requiredfeatures='' specularconstant='' specularexponent='' spreadmethod='' startoffset='' stddeviation='' stitchtiles='' surfacescale='' systemlanguage='' tablevalues='' targetx='' targety='' textlength='' viewbox='' xchannelselector='' ychannelselector='' zoomandpan=''></svg> #errors #document | <!DOCTYPE html> @@ -197,13 +195,12 @@ | targetY="" | textLength="" | viewBox="" -| viewTarget="" | xChannelSelector="" | yChannelSelector="" | zoomAndPan="" #data -<!DOCTYPE html><body><math attributeName='' attributeType='' baseFrequency='' baseProfile='' calcMode='' clipPathUnits='' diffuseConstant='' edgeMode='' filterUnits='' glyphRef='' gradientTransform='' gradientUnits='' kernelMatrix='' kernelUnitLength='' keyPoints='' keySplines='' keyTimes='' lengthAdjust='' limitingConeAngle='' markerHeight='' markerUnits='' markerWidth='' maskContentUnits='' maskUnits='' numOctaves='' pathLength='' patternContentUnits='' patternTransform='' patternUnits='' pointsAtX='' pointsAtY='' pointsAtZ='' preserveAlpha='' preserveAspectRatio='' primitiveUnits='' refX='' refY='' repeatCount='' repeatDur='' requiredExtensions='' requiredFeatures='' specularConstant='' specularExponent='' spreadMethod='' startOffset='' stdDeviation='' stitchTiles='' surfaceScale='' systemLanguage='' tableValues='' targetX='' targetY='' textLength='' viewBox='' viewTarget='' xChannelSelector='' yChannelSelector='' zoomAndPan=''></math> +<!DOCTYPE html><body><math attributeName='' attributeType='' baseFrequency='' baseProfile='' calcMode='' clipPathUnits='' diffuseConstant='' edgeMode='' filterUnits='' glyphRef='' gradientTransform='' gradientUnits='' kernelMatrix='' kernelUnitLength='' keyPoints='' keySplines='' keyTimes='' lengthAdjust='' limitingConeAngle='' markerHeight='' markerUnits='' markerWidth='' maskContentUnits='' maskUnits='' numOctaves='' pathLength='' patternContentUnits='' patternTransform='' patternUnits='' pointsAtX='' pointsAtY='' pointsAtZ='' preserveAlpha='' preserveAspectRatio='' primitiveUnits='' refX='' refY='' repeatCount='' repeatDur='' requiredExtensions='' requiredFeatures='' specularConstant='' specularExponent='' spreadMethod='' startOffset='' stdDeviation='' stitchTiles='' surfaceScale='' systemLanguage='' tableValues='' targetX='' targetY='' textLength='' viewBox='' xChannelSelector='' yChannelSelector='' zoomAndPan=''></math> #errors #document | <!DOCTYPE html> @@ -265,7 +262,6 @@ | targety="" | textlength="" | viewbox="" -| viewtarget="" | xchannelselector="" | ychannelselector="" | zoomandpan=""
diff --git a/third_party/WebKit/LayoutTests/http/tests/inspector/debugger-test.js b/third_party/WebKit/LayoutTests/http/tests/inspector/debugger-test.js index 405a79ff..fa304f7 100644 --- a/third_party/WebKit/LayoutTests/http/tests/inspector/debugger-test.js +++ b/third_party/WebKit/LayoutTests/http/tests/inspector/debugger-test.js
@@ -425,11 +425,25 @@ sourceFrame._breakpointManager.findBreakpoints(sourceFrame._uiSourceCode, lineNumber)[0].remove(); }; +InspectorTest.waitBreakpointSidebarPane = function() +{ + return new Promise(resolve => InspectorTest.addSniffer(Sources.JavaScriptBreakpointsSidebarPane.prototype, "_didUpdateForTest", resolve)); +} + +InspectorTest.breakpointsSidebarPaneContent = function() +{ + var paneElement = self.runtime.sharedInstance(Sources.JavaScriptBreakpointsSidebarPane).contentElement; + var empty = paneElement.querySelector('.gray-info-message'); + if (empty) + return InspectorTest.textContentWithLineBreaks(empty); + var entries = Array.from(paneElement.querySelectorAll('.breakpoint-entry')); + return entries.map(InspectorTest.textContentWithLineBreaks).join('\n'); +} + InspectorTest.dumpBreakpointSidebarPane = function(title) { - var paneElement = self.runtime.sharedInstance(Sources.JavaScriptBreakpointsSidebarPane).element; InspectorTest.addResult("Breakpoint sidebar pane " + (title || "")); - InspectorTest.addResult(InspectorTest.textContentWithLineBreaks(paneElement)); + InspectorTest.addResult(InspectorTest.breakpointsSidebarPaneContent()); }; InspectorTest.dumpScopeVariablesSidebarPane = function()
diff --git a/third_party/WebKit/LayoutTests/http/tests/inspector/network/har-content.html b/third_party/WebKit/LayoutTests/http/tests/inspector/network/har-content.html index 97bd774..67154859 100644 --- a/third_party/WebKit/LayoutTests/http/tests/inspector/network/har-content.html +++ b/third_party/WebKit/LayoutTests/http/tests/inspector/network/har-content.html
@@ -7,12 +7,19 @@ <script> var test = function() { - function step1() + InspectorTest.NetworkAgent.setCacheDisabled(true, sendCSSRequest); + + function sendCSSRequest() { - InspectorTest.makeSimpleXHR("GET", "resources/binary.data", false, step2); + InspectorTest.makeSimpleXHR("GET", "resources/initiator.css", false, sendBinaryRequest); } - function step2() + function sendBinaryRequest() + { + InspectorTest.makeSimpleXHR("GET", "resources/binary.data", false, makeHAR); + } + + function makeHAR() { var writer = new Network.HARWriter(); var stream = new InspectorTest.StringOutputStream(onSaved); @@ -59,8 +66,6 @@ InspectorTest.addResult("FAIL: can't find resource for " + regexp); return null; } - - InspectorTest.makeSimpleXHR("GET", "resources/initiator.css", false, step1); } </script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/inspector/persistence/persistence-move-breakpoints-expected.txt b/third_party/WebKit/LayoutTests/http/tests/inspector/persistence/persistence-move-breakpoints-expected.txt index 42cd8e0..c2aea508 100644 --- a/third_party/WebKit/LayoutTests/http/tests/inspector/persistence/persistence-move-breakpoints-expected.txt +++ b/third_party/WebKit/LayoutTests/http/tests/inspector/persistence/persistence-move-breakpoints-expected.txt
@@ -4,12 +4,14 @@ Running: addFileSystem Running: setBreakpointInFileSystemUISourceCode - file:///var/www/inspector/persistence/resources/foo.js:0 +Breakpoint sidebar pane +foo.js:1 Running: addFileMapping - http://127.0.0.1:8000/inspector/persistence/resources/foo.js:0 +Breakpoint sidebar pane +foo.js:1 Running: removeFileMapping - http://127.0.0.1:8000/inspector/persistence/resources/foo.js:0 file:///var/www/inspector/persistence/resources/foo.js:0 + http://127.0.0.1:8000/inspector/persistence/resources/foo.js:0
diff --git a/third_party/WebKit/LayoutTests/http/tests/inspector/persistence/persistence-move-breakpoints.html b/third_party/WebKit/LayoutTests/http/tests/inspector/persistence/persistence-move-breakpoints.html index 131578944..56b63e8b 100644 --- a/third_party/WebKit/LayoutTests/http/tests/inspector/persistence/persistence-move-breakpoints.html +++ b/third_party/WebKit/LayoutTests/http/tests/inspector/persistence/persistence-move-breakpoints.html
@@ -28,8 +28,7 @@ function onSourceFrame(sourceFrame) { InspectorTest.setBreakpoint(sourceFrame, 0, "", true); - dumpBreakpointSidebarPane(); - next(); + InspectorTest.waitBreakpointSidebarPane().then(InspectorTest.dumpBreakpointSidebarPane).then(next); } }, @@ -40,8 +39,7 @@ function onBindingCreated(binding) { - dumpBreakpointSidebarPane(); - next(); + InspectorTest.waitBreakpointSidebarPane().then(InspectorTest.dumpBreakpointSidebarPane).then(next); } }, @@ -56,18 +54,22 @@ if (binding.network.name() !== "foo.js") return Persistence.persistence.removeEventListener(Persistence.Persistence.Events.BindingRemoved, onBindingRemoved); - dumpBreakpointSidebarPane(); - next(); + InspectorTest.waitBreakpointSidebarPane().then(dumpBreakpointSidebarPane).then(next); } }, ]); function dumpBreakpointSidebarPane() { - var sidebarPane = self.runtime.sharedInstance(Sources.JavaScriptBreakpointsSidebarPane) - var breakpoints = sidebarPane._items.keysArray(); - for (var breakpoint of breakpoints) - InspectorTest.addResult(" " + breakpoint.uiSourceCode().url() +":" + breakpoint.lineNumber()); + var paneElement = self.runtime.sharedInstance(Sources.JavaScriptBreakpointsSidebarPane).contentElement; + var empty = paneElement.querySelector('.gray-info-message'); + if (empty) + return InspectorTest.textContentWithLineBreaks(empty); + var entries = Array.from(paneElement.querySelectorAll('.breakpoint-entry')); + for (var entry of entries) { + var uiLocation = entry[Sources.JavaScriptBreakpointsSidebarPane._locationSymbol]; + InspectorTest.addResult(" " + uiLocation.uiSourceCode.url() +":" + uiLocation.lineNumber); + } } }; </script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/inspector/search/sources-search-scope-in-files-expected.txt b/third_party/WebKit/LayoutTests/http/tests/inspector/search/sources-search-scope-in-files-expected.txt index 53d19b8..60833ba 100644 --- a/third_party/WebKit/LayoutTests/http/tests/inspector/search/sources-search-scope-in-files-expected.txt +++ b/third_party/WebKit/LayoutTests/http/tests/inspector/search/sources-search-scope-in-files-expected.txt
@@ -1,7 +1,7 @@ Tests that ScriptSearchScope performs search across all sources correctly. See bug 41350. -Total uiSourceCodes: 15 +Total uiSourceCodes: 16 Running: testIgnoreCase Search result #1: uiSourceCode.url = file:///var/www/search.css
diff --git a/third_party/WebKit/LayoutTests/http/tests/misc/submit-post-keygen-expected.txt b/third_party/WebKit/LayoutTests/http/tests/misc/submit-post-keygen-expected.txt index aeffdb4..2223fd1c 100644 --- a/third_party/WebKit/LayoutTests/http/tests/misc/submit-post-keygen-expected.txt +++ b/third_party/WebKit/LayoutTests/http/tests/misc/submit-post-keygen-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. This is a regression test for keygen tag POST processing: https://bugs.webkit.org/show_bug.cgi?id=70617. SUCCESS: keygen was parsed correctly
diff --git a/third_party/WebKit/LayoutTests/http/tests/xmlhttprequest/onloadstart-send.html b/third_party/WebKit/LayoutTests/http/tests/xmlhttprequest/onloadstart-send.html new file mode 100644 index 0000000..c9c203a --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/xmlhttprequest/onloadstart-send.html
@@ -0,0 +1,27 @@ +<!doctype html> +<html> +<head> +<title>XMLHttpRequest: send() during onloadstart</title> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> +</head> +<body> +<script> +var testAsync = async_test("Attempting a send() during onloadstart"); +testAsync.step(() => { + var xhr = new XMLHttpRequest(); + xhr.open("POST", "resources/delay.php?iteration=1&delay=1000"); + xhr.onloadstart = testAsync.step_func(() => { + assert_equals(xhr.readyState, XMLHttpRequest.OPENED); + // Step 2 of send(): "If the send() flag is set, throw an InvalidStateError exception." + assert_throws('InvalidStateError', () => { xhr.send(); }); + }); + xhr.onloadend = testAsync.step_func(() => { + assert_equals(xhr.readyState, XMLHttpRequest.DONE); + testAsync.done(); + }); + xhr.send(); +}); +</script> +</body> +</html>
diff --git a/third_party/WebKit/LayoutTests/http/tests/xmlhttprequest/withCredentials-after-send.html b/third_party/WebKit/LayoutTests/http/tests/xmlhttprequest/withCredentials-after-send.html new file mode 100644 index 0000000..df731120b --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/xmlhttprequest/withCredentials-after-send.html
@@ -0,0 +1,40 @@ +<!doctype html> +<html> +<head> +<title>XMLHttpRequest: setting withCredentials while sending data</title> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> +</head> +<body> +<script> +var testAsync = async_test("Setting withCredentials, post-send() (async)"); +testAsync.step(() => { + var xhr = new XMLHttpRequest(); + xhr.open("POST", "resources/delay.php?iteration=1&delay=1000"); + xhr.onloadstart = testAsync.step_func(() => { + assert_equals(xhr.readyState, XMLHttpRequest.OPENED); + assert_throws('InvalidStateError', () => { xhr.withCredentials = true; }); + }); + xhr.onloadend = testAsync.step_func(() => { + assert_equals(xhr.readyState, XMLHttpRequest.DONE); + testAsync.done(); + }); + xhr.send(); +}); + +var testSync = async_test("Setting withCredentials, post-send() (sync)"); +testSync.step(() => { + var xhr = new XMLHttpRequest(); + xhr.open("POST", "resources/delay.php?iteration=1&delay=1000", false); + xhr.onprogress = testSync.step_func(() => { + assert_throws('InvalidStateError', () => { xhr.withCredentials = true }); + }); + xhr.onloadend = testSync.step_func(() => { + assert_equals(xhr.readyState, XMLHttpRequest.DONE); + testSync.done(); + }); + xhr.send(); +}); +</script> +</body> +</html>
diff --git a/third_party/WebKit/LayoutTests/imported/csswg-test/vendor-imports/mozilla/mozilla-central-reftests/writing-modes-3/logical-physical-mapping-001-expected.html b/third_party/WebKit/LayoutTests/imported/csswg-test/vendor-imports/mozilla/mozilla-central-reftests/writing-modes-3/logical-physical-mapping-001-expected.html index bf744bf..c64050c 100644 --- a/third_party/WebKit/LayoutTests/imported/csswg-test/vendor-imports/mozilla/mozilla-central-reftests/writing-modes-3/logical-physical-mapping-001-expected.html +++ b/third_party/WebKit/LayoutTests/imported/csswg-test/vendor-imports/mozilla/mozilla-central-reftests/writing-modes-3/logical-physical-mapping-001-expected.html
@@ -2,6 +2,7 @@ <html> <head> <meta charset="UTF-8"> +<title>CSS Reference: border-block and border-inline logical properties in different writing modes</title> <link rel="author" title="Manish Goregaokar" href="mailto:manishearth@gmail.com"> <style> #body tr td:nth-child(2) div {
diff --git a/third_party/WebKit/LayoutTests/imported/csswg-test/vendor-imports/mozilla/mozilla-central-reftests/writing-modes-3/logical-physical-mapping-001.html b/third_party/WebKit/LayoutTests/imported/csswg-test/vendor-imports/mozilla/mozilla-central-reftests/writing-modes-3/logical-physical-mapping-001.html index 157e1f3..25140f1 100644 --- a/third_party/WebKit/LayoutTests/imported/csswg-test/vendor-imports/mozilla/mozilla-central-reftests/writing-modes-3/logical-physical-mapping-001.html +++ b/third_party/WebKit/LayoutTests/imported/csswg-test/vendor-imports/mozilla/mozilla-central-reftests/writing-modes-3/logical-physical-mapping-001.html
@@ -2,8 +2,9 @@ <html> <head> <meta charset="UTF-8"> +<title>CSS Test: border-block and border-inline logical properties in different writing modes</title> <link rel="author" title="Manish Goregaokar" href="mailto:manishearth@gmail.com"> -<link rel="help" href="https://drafts.csswg.org/css-writing-modes/#logical-to-physical"> +<link rel="help" href="https://drafts.csswg.org/css-writing-modes-3/#logical-to-physical"> <link rel="match" href="logical-physical-mapping-001-ref.html"> <style> #block-start div.outer div {
diff --git a/third_party/WebKit/LayoutTests/imported/wpt/dom/nodes/Document-createAttribute-expected.txt b/third_party/WebKit/LayoutTests/imported/wpt/dom/nodes/Document-createAttribute-expected.txt deleted file mode 100644 index 91aeeece..0000000 --- a/third_party/WebKit/LayoutTests/imported/wpt/dom/nodes/Document-createAttribute-expected.txt +++ /dev/null
@@ -1,25 +0,0 @@ -This is a testharness.js-based test. -PASS HTML document.createAttribute("") -PASS XML document.createAttribute("") -PASS HTML document.createAttribute("invalid^Name") -PASS XML document.createAttribute("invalid^Name") -PASS HTML document.createAttribute("\\") -PASS XML document.createAttribute("\\") -PASS HTML document.createAttribute("'") -PASS XML document.createAttribute("'") -PASS HTML document.createAttribute("\"") -PASS XML document.createAttribute("\"") -PASS HTML document.createAttribute("0") -PASS XML document.createAttribute("0") -PASS HTML document.createAttribute("0:a") -PASS XML document.createAttribute("0:a") -PASS HTML document.createAttribute("title") -PASS XML document.createAttribute("title") -FAIL HTML document.createAttribute("TITLE") assert_equals: expected "title" but got "TITLE" -PASS XML document.createAttribute("TITLE") -PASS HTML document.createAttribute(null) -PASS XML document.createAttribute(null) -PASS HTML document.createAttribute(undefined) -PASS XML document.createAttribute(undefined) -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/imported/wpt/html/dom/reflection-forms-expected.txt b/third_party/WebKit/LayoutTests/imported/wpt/html/dom/reflection-forms-expected.txt index fd476f2..0a4d0a3 100644 --- a/third_party/WebKit/LayoutTests/imported/wpt/html/dom/reflection-forms-expected.txt +++ b/third_party/WebKit/LayoutTests/imported/wpt/html/dom/reflection-forms-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 559: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 559: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. This is a testharness.js-based test. PASS form.title: 32 tests PASS form.lang: 32 tests
diff --git a/third_party/WebKit/LayoutTests/imported/wpt/html/dom/reflection-misc-expected.txt b/third_party/WebKit/LayoutTests/imported/wpt/html/dom/reflection-misc-expected.txt index b9b5076..671d7cff 100644 --- a/third_party/WebKit/LayoutTests/imported/wpt/html/dom/reflection-misc-expected.txt +++ b/third_party/WebKit/LayoutTests/imported/wpt/html/dom/reflection-misc-expected.txt
@@ -150,68 +150,7 @@ PASS menuitem.hidden: 33 tests PASS menuitem.accessKey: 32 tests PASS menuitem.tabIndex: 24 tests -PASS menuitem.type: typeof IDL attribute -FAIL menuitem.type: IDL get with DOM attribute unset assert_equals: expected "command" but got "" -FAIL menuitem.type: setAttribute() to "" assert_equals: IDL get expected "command" but got "" -FAIL menuitem.type: setAttribute() to " \0\x01\x02\x03\x04\x05\x06\x07 \b\t\n\v\f\r\x0e\x0f \x10\x11\x12\x13\x14\x15\x16\x17 \x18\x19\x1a\x1b\x1c\x1d\x1e\x1f foo " assert_equals: IDL get expected "command" but got " \0\x01\x02\x03\x04\x05\x06\x07 \b\t\n\v\f\r\x0e\x0f \x10\x11\x12\x13\x14\x15\x16\x17 \x18\x19\x1a\x1b\x1c\x1d\x1e\x1f foo " -FAIL menuitem.type: setAttribute() to undefined assert_equals: IDL get expected "command" but got "undefined" -FAIL menuitem.type: setAttribute() to 7 assert_equals: IDL get expected "command" but got "7" -FAIL menuitem.type: setAttribute() to 1.5 assert_equals: IDL get expected "command" but got "1.5" -FAIL menuitem.type: setAttribute() to true assert_equals: IDL get expected "command" but got "true" -FAIL menuitem.type: setAttribute() to false assert_equals: IDL get expected "command" but got "false" -FAIL menuitem.type: setAttribute() to object "[object Object]" assert_equals: IDL get expected "command" but got "[object Object]" -FAIL menuitem.type: setAttribute() to NaN assert_equals: IDL get expected "command" but got "NaN" -FAIL menuitem.type: setAttribute() to Infinity assert_equals: IDL get expected "command" but got "Infinity" -FAIL menuitem.type: setAttribute() to -Infinity assert_equals: IDL get expected "command" but got "-Infinity" -FAIL menuitem.type: setAttribute() to "\0" assert_equals: IDL get expected "command" but got "\0" -FAIL menuitem.type: setAttribute() to null assert_equals: IDL get expected "command" but got "null" -FAIL menuitem.type: setAttribute() to object "test-toString" assert_equals: IDL get expected "command" but got "test-toString" -FAIL menuitem.type: setAttribute() to object "test-valueOf" assert_equals: IDL get expected "command" but got "test-valueOf" -PASS menuitem.type: setAttribute() to "command" -FAIL menuitem.type: setAttribute() to "xcommand" assert_equals: IDL get expected "command" but got "xcommand" -FAIL menuitem.type: setAttribute() to "command\0" assert_equals: IDL get expected "command" but got "command\0" -FAIL menuitem.type: setAttribute() to "ommand" assert_equals: IDL get expected "command" but got "ommand" -FAIL menuitem.type: setAttribute() to "COMMAND" assert_equals: IDL get expected "command" but got "COMMAND" -PASS menuitem.type: setAttribute() to "checkbox" -FAIL menuitem.type: setAttribute() to "xcheckbox" assert_equals: IDL get expected "command" but got "xcheckbox" -FAIL menuitem.type: setAttribute() to "checkbox\0" assert_equals: IDL get expected "command" but got "checkbox\0" -FAIL menuitem.type: setAttribute() to "heckbox" assert_equals: IDL get expected "command" but got "heckbox" -FAIL menuitem.type: setAttribute() to "CHECKBOX" assert_equals: IDL get expected "checkbox" but got "CHECKBOX" -PASS menuitem.type: setAttribute() to "radio" -FAIL menuitem.type: setAttribute() to "xradio" assert_equals: IDL get expected "command" but got "xradio" -FAIL menuitem.type: setAttribute() to "radio\0" assert_equals: IDL get expected "command" but got "radio\0" -FAIL menuitem.type: setAttribute() to "adio" assert_equals: IDL get expected "command" but got "adio" -FAIL menuitem.type: setAttribute() to "RADIO" assert_equals: IDL get expected "radio" but got "RADIO" -FAIL menuitem.type: IDL set to "" assert_equals: IDL get expected "command" but got "" -FAIL menuitem.type: IDL set to " \0\x01\x02\x03\x04\x05\x06\x07 \b\t\n\v\f\r\x0e\x0f \x10\x11\x12\x13\x14\x15\x16\x17 \x18\x19\x1a\x1b\x1c\x1d\x1e\x1f foo " assert_equals: IDL get expected "command" but got " \0\x01\x02\x03\x04\x05\x06\x07 \b\t\n\v\f\r\x0e\x0f \x10\x11\x12\x13\x14\x15\x16\x17 \x18\x19\x1a\x1b\x1c\x1d\x1e\x1f foo " -FAIL menuitem.type: IDL set to undefined assert_equals: IDL get expected "command" but got "undefined" -FAIL menuitem.type: IDL set to 7 assert_equals: IDL get expected "command" but got "7" -FAIL menuitem.type: IDL set to 1.5 assert_equals: IDL get expected "command" but got "1.5" -FAIL menuitem.type: IDL set to true assert_equals: IDL get expected "command" but got "true" -FAIL menuitem.type: IDL set to false assert_equals: IDL get expected "command" but got "false" -FAIL menuitem.type: IDL set to object "[object Object]" assert_equals: IDL get expected "command" but got "[object Object]" -FAIL menuitem.type: IDL set to NaN assert_equals: IDL get expected "command" but got "NaN" -FAIL menuitem.type: IDL set to Infinity assert_equals: IDL get expected "command" but got "Infinity" -FAIL menuitem.type: IDL set to -Infinity assert_equals: IDL get expected "command" but got "-Infinity" -FAIL menuitem.type: IDL set to "\0" assert_equals: IDL get expected "command" but got "\0" -FAIL menuitem.type: IDL set to null assert_equals: IDL get expected "command" but got "null" -FAIL menuitem.type: IDL set to object "test-toString" assert_equals: IDL get expected "command" but got "test-toString" -FAIL menuitem.type: IDL set to object "test-valueOf" assert_equals: IDL get expected "command" but got "test-valueOf" -PASS menuitem.type: IDL set to "command" -FAIL menuitem.type: IDL set to "xcommand" assert_equals: IDL get expected "command" but got "xcommand" -FAIL menuitem.type: IDL set to "command\0" assert_equals: IDL get expected "command" but got "command\0" -FAIL menuitem.type: IDL set to "ommand" assert_equals: IDL get expected "command" but got "ommand" -FAIL menuitem.type: IDL set to "COMMAND" assert_equals: IDL get expected "command" but got "COMMAND" -PASS menuitem.type: IDL set to "checkbox" -FAIL menuitem.type: IDL set to "xcheckbox" assert_equals: IDL get expected "command" but got "xcheckbox" -FAIL menuitem.type: IDL set to "checkbox\0" assert_equals: IDL get expected "command" but got "checkbox\0" -FAIL menuitem.type: IDL set to "heckbox" assert_equals: IDL get expected "command" but got "heckbox" -FAIL menuitem.type: IDL set to "CHECKBOX" assert_equals: IDL get expected "checkbox" but got "CHECKBOX" -PASS menuitem.type: IDL set to "radio" -FAIL menuitem.type: IDL set to "xradio" assert_equals: IDL get expected "command" but got "xradio" -FAIL menuitem.type: IDL set to "radio\0" assert_equals: IDL get expected "command" but got "radio\0" -FAIL menuitem.type: IDL set to "adio" assert_equals: IDL get expected "command" but got "adio" -FAIL menuitem.type: IDL set to "RADIO" assert_equals: IDL get expected "radio" but got "RADIO" +PASS menuitem.type: 62 tests PASS menuitem.label: 32 tests PASS menuitem.icon: 38 tests PASS menuitem.disabled: 33 tests
diff --git a/third_party/WebKit/LayoutTests/imported/wpt/html/semantics/forms/constraints/form-validation-willValidate-expected.txt b/third_party/WebKit/LayoutTests/imported/wpt/html/semantics/forms/constraints/form-validation-willValidate-expected.txt index 542042ac..249cf1a 100644 --- a/third_party/WebKit/LayoutTests/imported/wpt/html/semantics/forms/constraints/form-validation-willValidate-expected.txt +++ b/third_party/WebKit/LayoutTests/imported/wpt/html/semantics/forms/constraints/form-validation-willValidate-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 361: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 361: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. This is a testharness.js-based test. PASS [INPUT in HIDDEN status] Must be barred from the constraint validation PASS [INPUT in BUTTON status] Must be barred from the constraint validation
diff --git a/third_party/WebKit/LayoutTests/imported/wpt/html/semantics/forms/form-control-infrastructure/form-expected.txt b/third_party/WebKit/LayoutTests/imported/wpt/html/semantics/forms/form-control-infrastructure/form-expected.txt index 7f80b64..c997ddd 100644 --- a/third_party/WebKit/LayoutTests/imported/wpt/html/semantics/forms/form-control-infrastructure/form-expected.txt +++ b/third_party/WebKit/LayoutTests/imported/wpt/html/semantics/forms/form-control-infrastructure/form-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. This is a testharness.js-based test. PASS button.form PASS fieldset.form
diff --git a/third_party/WebKit/LayoutTests/imported/wpt/html/semantics/forms/the-label-element/labelable-elements-expected.txt b/third_party/WebKit/LayoutTests/imported/wpt/html/semantics/forms/the-label-element/labelable-elements-expected.txt index 3d15f7ba..37b09d2 100644 --- a/third_party/WebKit/LayoutTests/imported/wpt/html/semantics/forms/the-label-element/labelable-elements-expected.txt +++ b/third_party/WebKit/LayoutTests/imported/wpt/html/semantics/forms/the-label-element/labelable-elements-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. This is a testharness.js-based test. PASS Check if the output element is a labelable element PASS Check if the output element can access 'labels'
diff --git a/third_party/WebKit/LayoutTests/imported/wpt/html/semantics/grouping-content/the-ol-element/grouping-ol-expected.txt b/third_party/WebKit/LayoutTests/imported/wpt/html/semantics/grouping-content/the-ol-element/grouping-ol-expected.txt index ee3dabf8..c0df0600 100644 --- a/third_party/WebKit/LayoutTests/imported/wpt/html/semantics/grouping-content/the-ol-element/grouping-ol-expected.txt +++ b/third_party/WebKit/LayoutTests/imported/wpt/html/semantics/grouping-content/the-ol-element/grouping-ol-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. This is a testharness.js-based test. PASS The prototype for OL is HTMLOListElement.prototype PASS 'reversed' property should be defined on OL.
diff --git a/third_party/WebKit/LayoutTests/imported/wpt/html/semantics/interfaces-expected.txt b/third_party/WebKit/LayoutTests/imported/wpt/html/semantics/interfaces-expected.txt index 091485f1..a81a9f7c 100644 --- a/third_party/WebKit/LayoutTests/imported/wpt/html/semantics/interfaces-expected.txt +++ b/third_party/WebKit/LayoutTests/imported/wpt/html/semantics/interfaces-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 19: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 19: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. This is a testharness.js-based test. PASS Interfaces for a PASS Interfaces for A
diff --git a/third_party/WebKit/LayoutTests/imported/wpt/html/syntax/parsing/html5lib_tests19-expected.txt b/third_party/WebKit/LayoutTests/imported/wpt/html/syntax/parsing/html5lib_tests19-expected.txt index 6aab81b..fc64c96f 100644 --- a/third_party/WebKit/LayoutTests/imported/wpt/html/syntax/parsing/html5lib_tests19-expected.txt +++ b/third_party/WebKit/LayoutTests/imported/wpt/html/syntax/parsing/html5lib_tests19-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. This is a testharness.js-based test. PASS html5lib_tests19.html 6135e0cbdbb22a97e8a13c2442c3e9a9e0a53298 PASS html5lib_tests19.html 6b46dba2f4d7d1a08359ab21fe5e011463dd8746
diff --git a/third_party/WebKit/LayoutTests/imported/wpt/html/syntax/parsing/html5lib_tests25-expected.txt b/third_party/WebKit/LayoutTests/imported/wpt/html/syntax/parsing/html5lib_tests25-expected.txt index d0987452..66c0f2a3 100644 --- a/third_party/WebKit/LayoutTests/imported/wpt/html/syntax/parsing/html5lib_tests25-expected.txt +++ b/third_party/WebKit/LayoutTests/imported/wpt/html/syntax/parsing/html5lib_tests25-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. This is a testharness.js-based test. PASS html5lib_tests25.html 025adbb619bdef9ad228a6b378b9dd6bef9f93dc PASS html5lib_tests25.html 7e561454888535bc5c68e7396de2f4206c81e97d
diff --git a/third_party/WebKit/LayoutTests/imported/wpt/html/syntax/serializing-html-fragments/serializing-expected.txt b/third_party/WebKit/LayoutTests/imported/wpt/html/syntax/serializing-html-fragments/serializing-expected.txt index 7eecb58..fac9e47 100644 --- a/third_party/WebKit/LayoutTests/imported/wpt/html/syntax/serializing-html-fragments/serializing-expected.txt +++ b/third_party/WebKit/LayoutTests/imported/wpt/html/syntax/serializing-html-fragments/serializing-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 248: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 248: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. This is a testharness.js-based test. PASS innerHTML 0 PASS innerHTML 1 <a></a>
diff --git a/third_party/WebKit/LayoutTests/imported/wpt/imagebitmap-renderingcontext/bitmaprenderer-as-imagesource-expected.txt b/third_party/WebKit/LayoutTests/imported/wpt/imagebitmap-renderingcontext/bitmaprenderer-as-imagesource-expected.txt deleted file mode 100644 index 4c3af0cf..0000000 --- a/third_party/WebKit/LayoutTests/imported/wpt/imagebitmap-renderingcontext/bitmaprenderer-as-imagesource-expected.txt +++ /dev/null
@@ -1,6 +0,0 @@ -This is a testharness.js-based test. -FAIL Test that createImageBitmap from a bitmaprenderer canvas produces correct result assert_equals: expected 10 but got 20 -PASS Test that createImageBitmap on a bitmaprenderer canvas that never consumes any source produces correct result -PASS Test that createImageBitmap on a bitmaprenderer canvas that consumes null produces correct result -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/imported/wpt/imagebitmap-renderingcontext/context-creation-with-alpha-expected.txt b/third_party/WebKit/LayoutTests/imported/wpt/imagebitmap-renderingcontext/context-creation-with-alpha-expected.txt deleted file mode 100644 index 84b4e5f..0000000 --- a/third_party/WebKit/LayoutTests/imported/wpt/imagebitmap-renderingcontext/context-creation-with-alpha-expected.txt +++ /dev/null
@@ -1,7 +0,0 @@ -CONSOLE ERROR: Uncaught (in promise) Error: assert_array_equals: property 1, expected 127 but got 255 -This is a testharness.js-based test. -FAIL Test that an ImageBitmapRenderingContext with alpha disabled makes the canvas opaque assert_not_equals: got disallowed value undefined -FAIL Test that an ImageBitmapRenderingContext with alpha enabled preserves the alpha assert_not_equals: got disallowed value undefined -FAIL Test that the 'alpha' context creation attribute is true by default assert_not_equals: got disallowed value undefined -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/imported/wpt/imagebitmap-renderingcontext/context-creation-with-alpha.html b/third_party/WebKit/LayoutTests/imported/wpt/imagebitmap-renderingcontext/context-creation-with-alpha.html deleted file mode 100644 index 88d12d1..0000000 --- a/third_party/WebKit/LayoutTests/imported/wpt/imagebitmap-renderingcontext/context-creation-with-alpha.html +++ /dev/null
@@ -1,75 +0,0 @@ -<!DOCTYPE html> -<meta charset="utf-8"> -<title>Canvas's ImageBitmapRenderingContext test</title> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<link rel="help" href="https://html.spec.whatwg.org/multipage/scripting.html#the-imagebitmap-rendering-context"> -<script> -var width = 10; -var height = 10; - -function testCanvas(ctx, r, g, b, a) -{ - var color = ctx.getImageData(5, 5, 1, 1).data; - assert_array_equals(color, [r, g, b, a]); -} - -function consumeImageBitmap(image, alphaVal, expectedR, expectedG, expectedB, expectedA) -{ - var dstCanvas = document.createElement('canvas'); - dstCanvas.width = width; - dstCanvas.height = height; - var dstCtx; - if (alphaVal == 'true') - dstCtx = dstCanvas.getContext('bitmaprenderer', { alpha: true }); - else if (alphaVal == 'false') - dstCtx = dstCanvas.getContext('bitmaprenderer', { alpha: false }); - else - dstCtx = dstCanvas.getContext('bitmaprenderer'); - dstCtx.transferFromImageBitmap(image); - - var myCanvas = document.createElement('canvas'); - myCanvas.width = width; - myCanvas.height = height; - var myCtx = myCanvas.getContext('2d'); - myCtx.drawImage(dstCanvas, 0, 0); - testCanvas(myCtx, expectedR, expectedG, expectedB, expectedA); -} - -promise_test(function() { - var srcCanvas = document.createElement('canvas'); - srcCanvas.width = width; - srcCanvas.height = height; - var ctx = srcCanvas.getContext('2d'); - ctx.fillStyle = 'rgba(0, 255, 0, 0.5)'; - ctx.fillRect(0, 0, width, height); - createImageBitmap(srcCanvas).then(function(image) { - consumeImageBitmap(image, 'false', 0, 127, 0, 255); - }); -}, "Test that an ImageBitmapRenderingContext with alpha disabled makes the canvas opaque"); - -promise_test(function() { - var srcCanvas = document.createElement('canvas'); - srcCanvas.width = width; - srcCanvas.height = height; - var ctx = srcCanvas.getContext('2d'); - ctx.fillStyle = 'rgba(0, 255, 0, 0.5)'; - ctx.fillRect(0, 0, width, height); - createImageBitmap(srcCanvas).then(function(image) { - consumeImageBitmap(image, 'true', 0, 255, 0, 127); - }); -}, "Test that an ImageBitmapRenderingContext with alpha enabled preserves the alpha"); - -promise_test(function() { - var srcCanvas = document.createElement('canvas'); - srcCanvas.width = width; - srcCanvas.height = height; - var ctx = srcCanvas.getContext('2d'); - ctx.fillStyle = 'rgba(0, 255, 0, 0.5)'; - ctx.fillRect(0, 0, width, height); - createImageBitmap(srcCanvas).then(function(image) { - consumeImageBitmap(image, '', 0, 255, 0, 127); - }); -}, "Test that the 'alpha' context creation attribute is true by default"); - -</script>
diff --git a/third_party/WebKit/LayoutTests/imported/wpt/imagebitmap-renderingcontext/context-creation.html b/third_party/WebKit/LayoutTests/imported/wpt/imagebitmap-renderingcontext/context-creation.html deleted file mode 100644 index 3daa397..0000000 --- a/third_party/WebKit/LayoutTests/imported/wpt/imagebitmap-renderingcontext/context-creation.html +++ /dev/null
@@ -1,19 +0,0 @@ -<!DOCTYPE html> -<meta charset="utf-8"> -<title>Canvas's ImageBitmapRenderingContext test</title> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<link rel="help" href="https://html.spec.whatwg.org/multipage/scripting.html#the-imagebitmap-rendering-context"> -<script> -var width = 10; -var height = 10; - -test(function() { - var canvas = document.createElement("canvas"); - canvas.width = width; - canvas.height = height; - var ctx = canvas.getContext('bitmaprenderer'); - assert_true(ctx instanceof ImageBitmapRenderingContext); -}, "Test that canvas.getContext('bitmaprenderer') returns an instance of ImageBitmapRenderingContext"); - -</script>
diff --git a/third_party/WebKit/LayoutTests/imported/wpt/imagebitmap-renderingcontext/context-preserves-canvas.html b/third_party/WebKit/LayoutTests/imported/wpt/imagebitmap-renderingcontext/context-preserves-canvas.html deleted file mode 100644 index eca7afe..0000000 --- a/third_party/WebKit/LayoutTests/imported/wpt/imagebitmap-renderingcontext/context-preserves-canvas.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<meta charset="utf-8"> -<title>Canvas's ImageBitmapRenderingContext test</title> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<link rel="help" href="https://html.spec.whatwg.org/multipage/scripting.html#the-imagebitmap-rendering-context"> -<script> -var width = 10; -var height = 10; - -test(function() { - var canvas = document.createElement("canvas"); - canvas.width = width; - canvas.height = height; - var ctx = canvas.getContext('bitmaprenderer'); - var dstCanvas = ctx.canvas; - assert_equals(dstCanvas.width, width); - assert_equals(dstCanvas.height, height); -}, "Test that ctx.canvas on a ImageBitmapRenderingContext returns the original canvas"); - -</script>
diff --git a/third_party/WebKit/LayoutTests/imported/wpt/imagebitmap-renderingcontext/tranferFromImageBitmap-null.html b/third_party/WebKit/LayoutTests/imported/wpt/imagebitmap-renderingcontext/tranferFromImageBitmap-null.html deleted file mode 100644 index c12a8c9..0000000 --- a/third_party/WebKit/LayoutTests/imported/wpt/imagebitmap-renderingcontext/tranferFromImageBitmap-null.html +++ /dev/null
@@ -1,75 +0,0 @@ -<!DOCTYPE html> -<meta charset="utf-8"> -<title>Canvas's ImageBitmapRenderingContext test</title> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<link rel="help" href="https://html.spec.whatwg.org/multipage/scripting.html#the-imagebitmap-rendering-context"> -<script> -var width = 10; -var height = 10; - -function testCanvas(ctx, r, g, b, a) -{ - var color = ctx.getImageData(5, 5, 1, 1).data; - assert_array_equals(color, [r, g, b, a]); -} - -promise_test(function() { - function testTransferFromImageBitmapNullability(greenImage, redImage) { - var bitmapCanvas = document.createElement('canvas'); - bitmapCanvas.width = width; - bitmapCanvas.height = height; - var bitmapCtx = bitmapCanvas.getContext('bitmaprenderer'); - bitmapCtx.transferFromImageBitmap(greenImage); - - // Make sure the bitmap renderer canvas is filled correctly. - var myCanvas = document.createElement('canvas'); - myCanvas.width = width; - myCanvas.height = height; - var myCtx = myCanvas.getContext('2d'); - myCtx.drawImage(bitmapCanvas, 0, 0); - testCanvas(myCtx, 0, 255, 0, 255); - - // Test if passing null resets the bitmap renderer canvas. - // Drawing the resetted canvas cannot change the destination canvas. - bitmapCtx.transferFromImageBitmap(null); - var myCanvas2 = document.createElement('canvas'); - myCanvas2.width = width; - myCanvas2.height = height; - var myCtx2 = myCanvas2.getContext('2d'); - myCtx2.drawImage(bitmapCanvas, 0, 0); - testCanvas(myCtx2, 0, 0, 0, 0); - - // Test if we can redraw the bitmap canvas correctly after reset. - bitmapCtx.transferFromImageBitmap(redImage); - var myCanvas3 = document.createElement('canvas'); - myCanvas3.width = width; - myCanvas3.height = height; - var myCtx3 = myCanvas3.getContext('2d'); - myCtx3.drawImage(bitmapCanvas, 0, 0); - testCanvas(myCtx3, 255, 0, 0, 255); - } - - var greenCanvas = document.createElement('canvas'); - greenCanvas.width = width; - greenCanvas.height = height; - var greenCtx = greenCanvas.getContext('2d'); - greenCtx.fillStyle = '#0f0'; - greenCtx.fillRect(0, 0, width, height); - - var redCanvas = document.createElement('canvas'); - redCanvas.width = width; - redCanvas.height = height; - var redCtx = redCanvas.getContext('2d'); - redCtx.fillStyle = '#f00'; - redCtx.fillRect(0, 0, width, height); - - return Promise.all([ - createImageBitmap(greenCanvas), - createImageBitmap(redCanvas), - ]).then(([greenImage, redImage]) => { - testTransferFromImageBitmapNullability(greenImage, redImage); - }); -},'Test that transferFromImageBitmap(null) discards the previously transferred image'); - -</script>
diff --git a/third_party/WebKit/LayoutTests/imported/wpt/imagebitmap-renderingcontext/transferFromImageBitmap-detached-expected.txt b/third_party/WebKit/LayoutTests/imported/wpt/imagebitmap-renderingcontext/transferFromImageBitmap-detached-expected.txt deleted file mode 100644 index 96e2baa..0000000 --- a/third_party/WebKit/LayoutTests/imported/wpt/imagebitmap-renderingcontext/transferFromImageBitmap-detached-expected.txt +++ /dev/null
@@ -1,4 +0,0 @@ -This is a testharness.js-based test. -FAIL Test transferFromImageBitmap(image) with a detached image should throw InvalidStateError assert_not_equals: got disallowed value undefined -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/imported/wpt/imagebitmap-renderingcontext/transferFromImageBitmap-detached.html b/third_party/WebKit/LayoutTests/imported/wpt/imagebitmap-renderingcontext/transferFromImageBitmap-detached.html deleted file mode 100644 index 2c547ee..0000000 --- a/third_party/WebKit/LayoutTests/imported/wpt/imagebitmap-renderingcontext/transferFromImageBitmap-detached.html +++ /dev/null
@@ -1,34 +0,0 @@ -<!DOCTYPE html> -<meta charset="utf-8"> -<title>Canvas's ImageBitmapRenderingContext test</title> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<link rel="help" href="https://html.spec.whatwg.org/multipage/scripting.html#the-imagebitmap-rendering-context"> -<script> -var width = 10; -var height = 10; - -promise_test(function() { - function testException(image) { - var dstCanvas = document.createElement('canvas'); - dstCanvas.width = width; - dstCanvas.height = height; - var dstCtx = dstCanvas.getContext('bitmaprenderer'); - dstCtx.transferFromImageBitmap(image); - - // The image should be detached after transferFromImageBitmap. - assert_equals(image.width, 0); - assert_equals(image.height, 0); - assert_throws("InvalidStateError", function() { dstCtx.transferFromImageBitmap(image); }); - } - - var srcCanvas = document.createElement('canvas'); - srcCanvas.width = width; - srcCanvas.height = height; - var ctx = srcCanvas.getContext('2d'); - ctx.fillStyle = 'rgba(0, 255, 0, 0.5)'; - ctx.fillRect(0, 0, width, height); - createImageBitmap(srcCanvas).then(testException); -}, "Test transferFromImageBitmap(image) with a detached image should throw InvalidStateError"); - -</script>
diff --git a/third_party/WebKit/LayoutTests/imported/wpt/svg/historical-expected.txt b/third_party/WebKit/LayoutTests/imported/wpt/svg/historical-expected.txt index 27150ce..cc7738fe 100644 --- a/third_party/WebKit/LayoutTests/imported/wpt/svg/historical-expected.txt +++ b/third_party/WebKit/LayoutTests/imported/wpt/svg/historical-expected.txt
@@ -31,7 +31,7 @@ PASS SVGSVGElement.prototype.currentView must be removed PASS SVGSVGElement.prototype.useCurrentView must be removed PASS SVGSVGElement.prototype.viewport must be removed -FAIL SVGViewElement.prototype.viewTarget must be removed assert_false: expected false got true +PASS SVGViewElement.prototype.viewTarget must be removed PASS SVGPathElement.prototype.getPointAtLength must be moved to SVGGeometryElement.prototype PASS SVGPathElement.prototype.getTotalLength must be moved to SVGGeometryElement.prototype FAIL SVGPathElement.prototype.pathLength must be moved to SVGGeometryElement.prototype assert_false: expected false got true
diff --git a/third_party/WebKit/LayoutTests/inspector-enabled/sources/debugger/script-formatter-breakpoints-1-expected.txt b/third_party/WebKit/LayoutTests/inspector-enabled/sources/debugger/script-formatter-breakpoints-1-expected.txt index 63bf8d358..935a13de 100644 --- a/third_party/WebKit/LayoutTests/inspector-enabled/sources/debugger/script-formatter-breakpoints-1-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector-enabled/sources/debugger/script-formatter-breakpoints-1-expected.txt
@@ -6,15 +6,12 @@ Running: testBreakpointsInOriginalAndFormattedSource Script execution paused. Breakpoint sidebar pane while paused in raw - - script-formatter-breakpoints-1.html:12 var f=0; +script-formatter-breakpoints-1.html:12 var f=0; Script execution resumed. Script execution paused. Breakpoint sidebar pane while paused in pretty printed - - script-formatter-breakpoints-1.html:formatted:14 var f = 0; +script-formatter-breakpoints-1.html:formatted:14 var f = 0; Breakpoint sidebar pane while paused in raw - - script-formatter-breakpoints-1.html:12 var f=0; +script-formatter-breakpoints-1.html:12 var f=0; Script execution resumed.
diff --git a/third_party/WebKit/LayoutTests/inspector-enabled/sources/debugger/script-formatter-breakpoints-1.html b/third_party/WebKit/LayoutTests/inspector-enabled/sources/debugger/script-formatter-breakpoints-1.html index 044afb0..d019b52 100644 --- a/third_party/WebKit/LayoutTests/inspector-enabled/sources/debugger/script-formatter-breakpoints-1.html +++ b/third_party/WebKit/LayoutTests/inspector-enabled/sources/debugger/script-formatter-breakpoints-1.html
@@ -73,7 +73,7 @@ { InspectorTest.dumpBreakpointSidebarPane("while paused in pretty printed"); scriptFormatter._discardFormattedUISourceCodeScript(panel.visibleView.uiSourceCode()); - InspectorTest.addSniffer(Sources.JavaScriptBreakpointsSidebarPane.prototype, "didReceiveBreakpointLineForTest", onBreakpointsUpdated); + InspectorTest.waitBreakpointSidebarPane().then(onBreakpointsUpdated); } function onBreakpointsUpdated()
diff --git a/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/debugger-reload-breakpoints-with-source-maps-expected.txt b/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/debugger-reload-breakpoints-with-source-maps-expected.txt index 8e73fec..bd15332f 100644 --- a/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/debugger-reload-breakpoints-with-source-maps-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/debugger-reload-breakpoints-with-source-maps-expected.txt
@@ -1,13 +1,11 @@ Tests "reload" from within inspector window while on pause. -Breakpoint sidebar pane Breakpoints before reload: - - source1.js:15 var handler = new ClickHandler(); - source1.js:17} +Breakpoint sidebar pane before reload: +source1.js:15 var handler = new ClickHandler(); +source1.js:17} Page reloaded. -Breakpoint sidebar pane Breakpoints after reload: - - source1.js:15 var handler = new ClickHandler(); - source1.js:17} +Breakpoint sidebar pane after reload: +source1.js:15 var handler = new ClickHandler(); +source1.js:17}
diff --git a/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/debugger-reload-breakpoints-with-source-maps.html b/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/debugger-reload-breakpoints-with-source-maps.html index 5d92133..0e19c18 100644 --- a/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/debugger-reload-breakpoints-with-source-maps.html +++ b/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/debugger-reload-breakpoints-with-source-maps.html
@@ -16,76 +16,47 @@ function step2(sourceFrame) { - InspectorTest.addSniffer(Bindings.BreakpointManager.TargetBreakpoint.prototype, "_addResolvedLocation", didSetBreakpointInDebugger, true); - + InspectorTest.waitBreakpointSidebarPane() + .then(waitUntilReady) + .then(onBreakpointsReady); InspectorTest.setBreakpoint(sourceFrame, 14, "", true); InspectorTest.setBreakpoint(sourceFrame, 15, "", true); - var counter = 2; - - function didSetBreakpointInDebugger() - { - counter--; - if (counter) - return; - //Both breakpoints are resolved before reload - InspectorTest.addSniffer(Sources.JavaScriptBreakpointsSidebarPane.prototype, "didReceiveBreakpointLineForTest", onBreakpointsReady); - } - function onBreakpointsReady() { - InspectorTest.dumpBreakpointSidebarPane("Breakpoints before reload:"); - waitForBreakpoints(); - InspectorTest.reloadPage(onPageReloaded); + InspectorTest.dumpBreakpointSidebarPane("before reload:"); + Promise.all([InspectorTest.waitBreakpointSidebarPane().then(waitUntilReady), new Promise(resolve => InspectorTest.reloadPage(resolve))]) + .then(finishIfReady); } - function waitForBreakpoints() - { - var expectedBreakpointLocations = [[14, 0], [16, 4]]; - var jsBreakpoints = self.runtime.sharedInstance(Sources.JavaScriptBreakpointsSidebarPane); - jsBreakpoints.didReceiveBreakpointLineForTest = function(uiSourceCode, line, column) - { - if (Bindings.CompilerScriptMapping.StubProjectID === uiSourceCode.project().id()) - return; - if (!uiSourceCode.url().endsWith("source1.js")) - return; - - expectedBreakpointLocations = - expectedBreakpointLocations.filter((location) => (location[0] != line && location[1] != column)); - if (expectedBreakpointLocations.length) - return; - breakpointSourcesReceived = true; - maybeCompleteTest(); - } + function finishIfReady() { + InspectorTest.dumpBreakpointSidebarPane("after reload:"); + InspectorTest.completeDebuggerTest(); } - } - var breakpointSourcesReceived = false; - var pageReloaded = false; - - function onPageReloaded() - { - pageReloaded = true; - maybeCompleteTest(); - } - - function maybeCompleteTest() - { - if (!pageReloaded || !breakpointSourcesReceived) - return; - InspectorTest.dumpBreakpointSidebarPane("Breakpoints after reload:"); - InspectorTest.completeDebuggerTest(); + function waitUntilReady() { + var expectedBreakpointLocations = [[14, 0], [16, 4]]; + var paneElement = self.runtime.sharedInstance(Sources.JavaScriptBreakpointsSidebarPane).contentElement; + var entries = Array.from(paneElement.querySelectorAll('.breakpoint-entry')); + for (var entry of entries) { + var uiLocation = entry[Sources.JavaScriptBreakpointsSidebarPane._locationSymbol]; + if (Bindings.CompilerScriptMapping.StubProjectID === uiLocation.uiSourceCode.project().id()) + return InspectorTest.waitBreakpointSidebarPane().then(waitUntilReady); + if (!uiLocation.uiSourceCode.url().endsWith("source1.js")) + return InspectorTest.waitBreakpointSidebarPane().then(waitUntilReady); + expectedBreakpointLocations = + expectedBreakpointLocations.filter((location) => (location[0] != uiLocation.lineNumber && location[1] != uiLocation.columnNumber)); + } + if (expectedBreakpointLocations.length) + return InspectorTest.waitBreakpointSidebarPane().then(waitUntilReady); + return Promise.resolve(); } } </script> </head> - <body onload="runTest()"> -<p> - Tests "reload" from within inspector window while on pause. -</p> - +<p>Tests "reload" from within inspector window while on pause.</p> </body> </html>
diff --git a/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/disable-breakpoints-expected.txt b/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/disable-breakpoints-expected.txt index 78dde3a..7de7323 100644 --- a/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/disable-breakpoints-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/disable-breakpoints-expected.txt
@@ -11,8 +11,7 @@ Call stack: 0) testFunction (disable-breakpoints.html:8) Breakpoint sidebar pane - - disable-breakpoints.html:8 var x = Math.sqrt(10); +disable-breakpoints.html:8 var x = Math.sqrt(10); Script execution resumed. Test function finished. Disabling breakpoints... @@ -28,13 +27,11 @@ Call stack: 0) testFunction (disable-breakpoints.html:8) Breakpoint sidebar pane - - disable-breakpoints.html:8 var x = Math.sqrt(10); +disable-breakpoints.html:8 var x = Math.sqrt(10); Script execution resumed. Test function finished. Breakpoint sidebar pane - - disable-breakpoints.html:8 var x = Math.sqrt(10); +disable-breakpoints.html:8 var x = Math.sqrt(10); Breakpoints removed. Breakpoint sidebar pane No Breakpoints
diff --git a/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/disable-breakpoints.html b/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/disable-breakpoints.html index c70db45..8603c47 100644 --- a/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/disable-breakpoints.html +++ b/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/disable-breakpoints.html
@@ -92,7 +92,7 @@ { InspectorTest.addResult("Test function finished."); InspectorTest.dumpBreakpointSidebarPane(); - InspectorTest.addSniffer(currentSourceFrame, "_removeBreakpointDecoration", breakpointRemoved); + InspectorTest.waitBreakpointSidebarPane().then(breakpointRemoved); InspectorTest.removeBreakpoint(currentSourceFrame, 7); }
diff --git a/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/set-breakpoint-expected.txt b/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/set-breakpoint-expected.txt index e2bafaf..69af84d3 100644 --- a/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/set-breakpoint-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/set-breakpoint-expected.txt
@@ -8,8 +8,7 @@ Call stack: 0) testFunction (set-breakpoint.html:17) Breakpoint sidebar pane - - set-breakpoint.html:17 var x = Math.sqrt(10); +set-breakpoint.html:17 var x = Math.sqrt(10); Breakpoint sidebar pane No Breakpoints Script execution resumed.
diff --git a/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/set-breakpoint.html b/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/set-breakpoint.html index 4adbd93..7ebbad84 100644 --- a/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/set-breakpoint.html +++ b/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/set-breakpoint.html
@@ -40,7 +40,7 @@ InspectorTest.addResult("Script execution paused."); InspectorTest.captureStackTrace(callFrames); InspectorTest.dumpBreakpointSidebarPane(); - InspectorTest.addSniffer(currentSourceFrame, "_removeBreakpointDecoration", breakpointRemoved); + InspectorTest.waitBreakpointSidebarPane().then(breakpointRemoved); InspectorTest.removeBreakpoint(currentSourceFrame, 16); }
diff --git a/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/set-conditional-breakpoint-expected.txt b/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/set-conditional-breakpoint-expected.txt index 3c3a1b4d..14ba5c4 100644 --- a/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/set-conditional-breakpoint-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/set-conditional-breakpoint-expected.txt
@@ -10,8 +10,7 @@ Call stack: 0) testFunction (set-conditional-breakpoint.html:17) Breakpoint sidebar pane - - set-conditional-breakpoint.html:17 var x = Math.sqrt(10); +set-conditional-breakpoint.html:17 var x = Math.sqrt(10); Breakpoint sidebar pane No Breakpoints Script execution resumed. @@ -21,8 +20,7 @@ Set timer for test function. Test function finished. Breakpoint sidebar pane - - set-conditional-breakpoint.html:17 var x = Math.sqrt(10); +set-conditional-breakpoint.html:17 var x = Math.sqrt(10); Breakpoints removed. Breakpoint sidebar pane No Breakpoints
diff --git a/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/set-conditional-breakpoint.html b/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/set-conditional-breakpoint.html index b310a79..201e6adb 100644 --- a/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/set-conditional-breakpoint.html +++ b/third_party/WebKit/LayoutTests/inspector/sources/debugger-breakpoints/set-conditional-breakpoint.html
@@ -41,7 +41,7 @@ InspectorTest.addResult("Script execution paused."); InspectorTest.captureStackTrace(callFrames); InspectorTest.dumpBreakpointSidebarPane(); - InspectorTest.addSniffer(currentSourceFrame, "_removeBreakpointDecoration", breakpointRemoved); + InspectorTest.waitBreakpointSidebarPane().then(breakpointRemoved); InspectorTest.removeBreakpoint(currentSourceFrame, 16); } @@ -68,7 +68,7 @@ InspectorTest.addResult("Script source was shown."); setBreakpoint(currentSourceFrame, 16, "false"); InspectorTest.runTestFunction(); - InspectorTest.addConsoleSniffer(testFunctionFinished); + InspectorTest.waitBreakpointSidebarPane().then(testFunctionFinished); } @@ -76,7 +76,7 @@ { InspectorTest.addResult("Test function finished."); InspectorTest.dumpBreakpointSidebarPane(); - InspectorTest.addSniffer(currentSourceFrame, "_removeBreakpointDecoration", breakpointRemoved); + InspectorTest.waitBreakpointSidebarPane().then(breakpointRemoved); InspectorTest.removeBreakpoint(currentSourceFrame, 16); }
diff --git a/third_party/WebKit/LayoutTests/inspector/sources/debugger-ui/click-gutter-breakpoint-expected.txt b/third_party/WebKit/LayoutTests/inspector/sources/debugger-ui/click-gutter-breakpoint-expected.txt index eae5504..a8349836 100644 --- a/third_party/WebKit/LayoutTests/inspector/sources/debugger-ui/click-gutter-breakpoint-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector/sources/debugger-ui/click-gutter-breakpoint-expected.txt
@@ -2,7 +2,6 @@ Script execution paused. Breakpoint sidebar pane while paused - - click-breakpoints.js:4 var b = 1; // The breakpoint should happen here +click-breakpoints.js:4 var b = 1; // The breakpoint should happen here Script execution resumed.
diff --git a/third_party/WebKit/LayoutTests/inspector/sources/debugger-ui/click-gutter-breakpoint.html b/third_party/WebKit/LayoutTests/inspector/sources/debugger-ui/click-gutter-breakpoint.html index e2554ef..c44e52b 100644 --- a/third_party/WebKit/LayoutTests/inspector/sources/debugger-ui/click-gutter-breakpoint.html +++ b/third_party/WebKit/LayoutTests/inspector/sources/debugger-ui/click-gutter-breakpoint.html
@@ -41,16 +41,11 @@ function runScript() { - InspectorTest.waitUntilPaused(pausedInF2); + Promise.all([InspectorTest.waitBreakpointSidebarPane(), new Promise(resolve => InspectorTest.waitUntilPaused(resolve))]) + .then(() => InspectorTest.dumpBreakpointSidebarPane("while paused")) + .then(() => InspectorTest.completeDebuggerTest()); InspectorTest.evaluateInPageWithTimeout("f2()"); } - - function pausedInF2(callFrames) - { - InspectorTest.dumpBreakpointSidebarPane("while paused"); - InspectorTest.completeDebuggerTest(); - } - } </script> </head>
diff --git a/third_party/WebKit/LayoutTests/inspector/sources/debugger-ui/script-formatter-breakpoints-2-expected.txt b/third_party/WebKit/LayoutTests/inspector/sources/debugger-ui/script-formatter-breakpoints-2-expected.txt index 3544367..b6a7802 100644 --- a/third_party/WebKit/LayoutTests/inspector/sources/debugger-ui/script-formatter-breakpoints-2-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector/sources/debugger-ui/script-formatter-breakpoints-2-expected.txt
@@ -6,8 +6,7 @@ Running: testBreakpointsSetAndRemoveInFormattedSource Script execution paused. Breakpoint sidebar pane while paused in pretty printed - - unformatted2.js:formatted:4 var c = 3; +unformatted2.js:formatted:4 var c = 3; Breakpoint sidebar pane while paused in raw No Breakpoints Script execution resumed.
diff --git a/third_party/WebKit/LayoutTests/inspector/sources/debugger-ui/script-formatter-breakpoints-2.html b/third_party/WebKit/LayoutTests/inspector/sources/debugger-ui/script-formatter-breakpoints-2.html index 2575000b..7704045 100644 --- a/third_party/WebKit/LayoutTests/inspector/sources/debugger-ui/script-formatter-breakpoints-2.html +++ b/third_party/WebKit/LayoutTests/inspector/sources/debugger-ui/script-formatter-breakpoints-2.html
@@ -34,6 +34,10 @@ { formattedSourceFrame = panel.visibleView; InspectorTest.setBreakpoint(formattedSourceFrame, 3, "", true); + InspectorTest.waitBreakpointSidebarPane().then(evaluateF2); + } + + function evaluateF2() { InspectorTest.waitUntilPaused(pausedInF2); InspectorTest.evaluateInPageWithTimeout("f2()"); } @@ -41,10 +45,11 @@ function pausedInF2(callFrames) { InspectorTest.dumpBreakpointSidebarPane("while paused in pretty printed"); + InspectorTest.waitBreakpointSidebarPane() + .then(() => InspectorTest.dumpBreakpointSidebarPane("while paused in raw")) + .then(() => InspectorTest.resumeExecution(next)); InspectorTest.removeBreakpoint(formattedSourceFrame, 3); scriptFormatter._discardFormattedUISourceCodeScript(panel.visibleView.uiSourceCode()); - InspectorTest.dumpBreakpointSidebarPane("while paused in raw"); - InspectorTest.resumeExecution(next); } } ]);
diff --git a/third_party/WebKit/LayoutTests/inspector/sources/debugger-ui/script-formatter-breakpoints-3-expected.txt b/third_party/WebKit/LayoutTests/inspector/sources/debugger-ui/script-formatter-breakpoints-3-expected.txt index b8313f7..565528a 100644 --- a/third_party/WebKit/LayoutTests/inspector/sources/debugger-ui/script-formatter-breakpoints-3-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector/sources/debugger-ui/script-formatter-breakpoints-3-expected.txt
@@ -6,8 +6,7 @@ Running: testBreakpointsSetInFormattedAndRemoveInOriginalSource Script execution paused. Breakpoint sidebar pane while paused in pretty printed - - unformatted3.js:formatted:4 var c = 3; +unformatted3.js:formatted:4 var c = 3; Breakpoint sidebar pane while paused in raw No Breakpoints Script execution resumed.
diff --git a/third_party/WebKit/LayoutTests/inspector/sources/debugger-ui/script-formatter-breakpoints-3.html b/third_party/WebKit/LayoutTests/inspector/sources/debugger-ui/script-formatter-breakpoints-3.html index c501f6f..0783978 100644 --- a/third_party/WebKit/LayoutTests/inspector/sources/debugger-ui/script-formatter-breakpoints-3.html +++ b/third_party/WebKit/LayoutTests/inspector/sources/debugger-ui/script-formatter-breakpoints-3.html
@@ -33,17 +33,23 @@ { var formattedSourceFrame = panel.visibleView; InspectorTest.setBreakpoint(formattedSourceFrame, 3, "", true); + InspectorTest.waitBreakpointSidebarPane().then(evaluateF2); + } + + function evaluateF2() { InspectorTest.waitUntilPaused(pausedInF2); InspectorTest.evaluateInPageWithTimeout("f2()"); } + function pausedInF2(callFrames) { InspectorTest.dumpBreakpointSidebarPane("while paused in pretty printed"); - scriptFormatter._discardFormattedUISourceCodeScript(panel.visibleView.uiSourceCode()); - InspectorTest.dumpBreakpointSidebarPane("while paused in raw"); + InspectorTest.waitBreakpointSidebarPane() + .then(() => InspectorTest.dumpBreakpointSidebarPane("while paused in raw")) + .then(() => InspectorTest.resumeExecution(next)); // No need to remove breakpoint since formattedUISourceCode was removed. - InspectorTest.resumeExecution(next); + scriptFormatter._discardFormattedUISourceCodeScript(panel.visibleView.uiSourceCode()); } } ]);
diff --git a/third_party/WebKit/LayoutTests/inspector/sources/debugger/js-with-inline-stylesheets-expected.txt b/third_party/WebKit/LayoutTests/inspector/sources/debugger/js-with-inline-stylesheets-expected.txt index 9f14a368..9c0873b 100644 --- a/third_party/WebKit/LayoutTests/inspector/sources/debugger/js-with-inline-stylesheets-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector/sources/debugger/js-with-inline-stylesheets-expected.txt
@@ -8,8 +8,7 @@ Call stack: 0) testFunction (js-with-inline-stylesheets.html:10) Breakpoint sidebar pane - - js-with-inline-stylesheets.html:10 var x = Math.sqrt(10); +js-with-inline-stylesheets.html:10 var x = Math.sqrt(10); Breakpoint sidebar pane No Breakpoints Script execution resumed.
diff --git a/third_party/WebKit/LayoutTests/inspector/sources/debugger/js-with-inline-stylesheets.html b/third_party/WebKit/LayoutTests/inspector/sources/debugger/js-with-inline-stylesheets.html index 7bef006..26cacfb4 100644 --- a/third_party/WebKit/LayoutTests/inspector/sources/debugger/js-with-inline-stylesheets.html +++ b/third_party/WebKit/LayoutTests/inspector/sources/debugger/js-with-inline-stylesheets.html
@@ -34,7 +34,7 @@ InspectorTest.addResult("Script execution paused."); InspectorTest.captureStackTrace(callFrames); InspectorTest.dumpBreakpointSidebarPane(); - InspectorTest.addSniffer(currentSourceFrame, "_removeBreakpointDecoration", breakpointRemoved); + InspectorTest.waitBreakpointSidebarPane().then(breakpointRemoved); InspectorTest.removeBreakpoint(currentSourceFrame, 9); }
diff --git a/third_party/WebKit/LayoutTests/media/controls/volumechange-muted-attribute-expected.html b/third_party/WebKit/LayoutTests/media/controls/volumechange-muted-attribute-expected.html new file mode 100644 index 0000000..bbc38a8 --- /dev/null +++ b/third_party/WebKit/LayoutTests/media/controls/volumechange-muted-attribute-expected.html
@@ -0,0 +1,15 @@ +<!DOCTYPE html> +<html> +<script src="../media-file.js"></script> +<audio controls></audio> +<video controls></video> +<script> + var audio = document.querySelector('audio') + audio.src = findMediaFile('audio', '../content/test'); + audio.muted = true; + + var video = document.querySelector('video'); + video.src = findMediaFile('video', '../content/test'); + video.muted = true; +</script> +</html>
diff --git a/third_party/WebKit/LayoutTests/media/controls/volumechange-muted-attribute.html b/third_party/WebKit/LayoutTests/media/controls/volumechange-muted-attribute.html new file mode 100644 index 0000000..e86ac1c --- /dev/null +++ b/third_party/WebKit/LayoutTests/media/controls/volumechange-muted-attribute.html
@@ -0,0 +1,18 @@ +<!DOCTYPE html> +<html> +<title>This tests that controls are properly updated when muted content attribute is changed.</title> +<script src="../media-file.js"></script> +<audio controls></audio> +<video controls></video> +<script> + var audio = document.querySelector('audio'); + // TODO(mlamouri): per spec, this should do nothing but Blink will mute the + // media in this case, see https://crbug.com/350303 + audio.setAttribute('muted', true); + audio.src = findMediaFile('audio', '../content/test'); + + var video = document.querySelector('video'); + video.setAttribute('muted', true); + video.src = findMediaFile('video', '../content/test'); +</script> +</html>
diff --git a/third_party/WebKit/LayoutTests/media/controls/volumechange-stopimmediatepropagation-expected.html b/third_party/WebKit/LayoutTests/media/controls/volumechange-stopimmediatepropagation-expected.html new file mode 100644 index 0000000..2cd2991f --- /dev/null +++ b/third_party/WebKit/LayoutTests/media/controls/volumechange-stopimmediatepropagation-expected.html
@@ -0,0 +1,25 @@ +<!DOCTYPE html> +<html> +<script src="../media-file.js"></script> +<div> + <audio controls muted></audio> +</div> +<div> + <video controls muted></video> +</div> +<div> + <audio controls></audio> <!-- should be muted --> +</div> +<div> + <video controls></video> <!-- should be muted --> +</div> +<script> + var audios = document.querySelectorAll('audio'); + for (var i = 0; i < audios.length; ++i) + audios[i].src = findMediaFile('audio', '../content/test'); + + var videos = document.querySelectorAll('video'); + for (var i = 0; i < videos.length; ++i) + videos[i].src = findMediaFile('video', '../content/test'); +</script> +</html>
diff --git a/third_party/WebKit/LayoutTests/media/controls/volumechange-stopimmediatepropagation.html b/third_party/WebKit/LayoutTests/media/controls/volumechange-stopimmediatepropagation.html new file mode 100644 index 0000000..3a44866 --- /dev/null +++ b/third_party/WebKit/LayoutTests/media/controls/volumechange-stopimmediatepropagation.html
@@ -0,0 +1,44 @@ +<!DOCTYPE html> +<html> +<title>This tests that controls are properly updated when stopImmediatePropagation is used in event handler.</title> +<script src="../media-file.js"></script> +<div> + <audio></audio> +</div> +<div> + <video></video> +</div> +<div id='a'> +</div> +<div id='v'> +</div> +<script> + // Elements created from script. + var audio = document.createElement('audio'); + audio.onvolumechange = e => { e.stopImmediatePropagation() }; + document.querySelector('#a').appendChild(audio); + audio.src = findMediaFile('audio', '../content/test'); + audio.controls = true; + audio.onloadedmetadata = () => { audio.muted = true; } + + var video = document.createElement('video'); + video.onvolumechange = e => { e.stopImmediatePropagation() }; + document.querySelector('#v').appendChild(video); + video.src = findMediaFile('video', '../content/test'); + video.controls = true; + video.onloadedmetadata = () => { video.muted = true; } + + // Elements created during parsing. + var audio = document.querySelector('audio'); + audio.onvolumechange = e => { e.stopImmediatePropagation() }; + audio.src = findMediaFile('audio', '../content/test'); + audio.controls = true; + audio.muted = true; + + var video = document.querySelector('video'); + video.onvolumechange = e => { e.stopImmediatePropagation() }; + video.src = findMediaFile('video', '../content/test'); + video.controls = true; + video.muted = true; +</script> +</html>
diff --git a/third_party/WebKit/LayoutTests/media/effective-media-volume.html b/third_party/WebKit/LayoutTests/media/effective-media-volume.html deleted file mode 100644 index 382993b6..0000000 --- a/third_party/WebKit/LayoutTests/media/effective-media-volume.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<title>effective media volume</title> -<script src="../resources/testharness.js"></script> -<script src="../resources/testharnessreport.js"></script> -<script> -[0, 0.5, 1].forEach(function(volume) -{ - [false, true].forEach(function(muted) - { - test(function() - { - var audio = new Audio(); - audio.volume = volume; - audio.muted = muted; - assert_equals(internals.effectiveMediaVolume(audio), - volume * (muted ? 0 : 1)); - }, "volume: " + volume + ", muted: " + muted); - }); -}); -</script>
diff --git a/third_party/WebKit/LayoutTests/media/video-controls-hidden-audio.html b/third_party/WebKit/LayoutTests/media/video-controls-hidden-audio.html index dcccca0..5d023ca2 100644 --- a/third_party/WebKit/LayoutTests/media/video-controls-hidden-audio.html +++ b/third_party/WebKit/LayoutTests/media/video-controls-hidden-audio.html
@@ -7,38 +7,46 @@ <video controls></video> <script> async_test(function(t) { - var video = document.querySelector("video"); + var video = document.querySelector("video"); - video.oncanplaythrough = t.step_func_done(function() { - // Request non-hidden audio controls. - internals.settings.setPreferHiddenVolumeControls(false); - video.muted = false; - muteButton = mediaControlsButton(video, "mute-button"); - volumeSlider = mediaControlsButton(video, "volume-slider"); + video.oncanplaythrough = t.step_func(function() { + // Request non-hidden audio controls. + internals.settings.setPreferHiddenVolumeControls(false); + video.muted = false; + muteButton = mediaControlsButton(video, "mute-button"); + volumeSlider = mediaControlsButton(video, "volume-slider"); - // Make sure that both are visible. - assert_not_equals(getComputedStyle(muteButton).display, "none"); - assert_not_equals(getComputedStyle(volumeSlider).display, "none"); + // Make sure that both are visible. + assert_not_equals(getComputedStyle(muteButton).display, "none"); + assert_not_equals(getComputedStyle(volumeSlider).display, "none"); - // Switch to muted video. Both should still be visible. - video.muted = true; - assert_not_equals(getComputedStyle(muteButton).display, "none"); - assert_not_equals(getComputedStyle(volumeSlider).display, "none"); + video.onvolumechange = t.step_func(_ => { + assert_not_equals(getComputedStyle(muteButton).display, "none"); + assert_not_equals(getComputedStyle(volumeSlider).display, "none"); - internals.settings.setPreferHiddenVolumeControls(true); - - // Switch back to unmuted video. - video.muted = false; + video.onvolumechange = t.step_func(_ => { assert_not_equals(getComputedStyle(muteButton).display, "none"); assert_equals(getComputedStyle(volumeSlider).display, "none"); + video.onvolumechange = t.step_func_done(_ => { + assert_not_equals(getComputedStyle(muteButton).display, "none"); + assert_equals(getComputedStyle(volumeSlider).display, "none"); + }); + // For muted video, the volume slider will hide but the mute button // should stay, since we always have it present for media which have audio. video.muted = true; - assert_not_equals(getComputedStyle(muteButton).display, "none"); - assert_equals(getComputedStyle(volumeSlider).display, "none"); + }); + + // Switch back to unmuted video and hide volume slider. + internals.settings.setPreferHiddenVolumeControls(true); + video.muted = false; }); - video.src = findMediaFile("video", "content/test"); + // Switch to muted video. Both should still be visible. + video.muted = true; + }); + + video.src = findMediaFile("video", "content/test"); }) </script>
diff --git a/third_party/WebKit/LayoutTests/nfc/push-expected.txt b/third_party/WebKit/LayoutTests/nfc/push-expected.txt deleted file mode 100644 index 51eaa4d..0000000 --- a/third_party/WebKit/LayoutTests/nfc/push-expected.txt +++ /dev/null
@@ -1,42 +0,0 @@ -This is a testharness.js-based test. -PASS Test that passing undefined to nfc.push would raise TypeMismatchError. -PASS Test that promise is rejected with SyntaxError if NFCMessage is invalid. -PASS nfc.push should fail when NFC HW is disabled. -PASS nfc.push should fail when NFC HW is not supported. -PASS nfc.push should succeed when NFC HW is enabled -PASS nfc.push should fail with TimeoutError when push operation is not completed before specified timeout value. -PASS nfc.push NFCMessage containing text, json, opaque and url records with default NFCPushOptions. -PASS nfc.push String with default NFCPushOptions. -PASS nfc.push ArrayBuffer with default NFCPushOptions. -PASS Check that default NFCPushOptions values are correctly set. -PASS Check that provided NFCPushOptions values are correctly converted. -PASS Push ArrayBuffer with default NFCPushOptions. -PASS nfc.cancelPush should succeed if there is pending push operation. -PASS nfc.push should fail with TimeoutError when push operation is not completed before specified timeout value. -PASS nfc.cancelPush should reject pending promise with AbortError. -FAIL Reject promise with TypeMismatchError if invalid type is provided. assert_not_equals: got disallowed value undefined -FAIL Promise rejected with SyntaxError. assert_not_equals: got disallowed value undefined -FAIL Promise rejected with SyntaxError. assert_not_equals: got disallowed value undefined -FAIL Promise rejected with SyntaxError. assert_not_equals: got disallowed value undefined -FAIL Promise rejected with SyntaxError. assert_not_equals: got disallowed value undefined -FAIL Promise rejected with SyntaxError. assert_not_equals: got disallowed value undefined -FAIL Promise rejected with SyntaxError. assert_not_equals: got disallowed value undefined -FAIL Promise rejected with SyntaxError. assert_not_equals: got disallowed value undefined -FAIL Promise rejected with SyntaxError. assert_not_equals: got disallowed value undefined -FAIL Promise rejected with SyntaxError. assert_not_equals: got disallowed value undefined -FAIL Promise rejected with SyntaxError. assert_not_equals: got disallowed value undefined -FAIL Promise rejected with SyntaxError. assert_not_equals: got disallowed value undefined -FAIL Promise rejected with SyntaxError. assert_not_equals: got disallowed value undefined -FAIL Promise rejected with SyntaxError. assert_not_equals: got disallowed value undefined -FAIL Promise rejected with SyntaxError. assert_not_equals: got disallowed value undefined -FAIL Promise rejected with SyntaxError. assert_not_equals: got disallowed value undefined -FAIL Promise rejected with SyntaxError. assert_not_equals: got disallowed value undefined -FAIL Promise rejected with SyntaxError. assert_not_equals: got disallowed value undefined -FAIL Promise rejected with SyntaxError. assert_not_equals: got disallowed value undefined -FAIL Promise rejected with NotSupportedError. assert_not_equals: got disallowed value undefined -FAIL Promise rejected with NotSupportedError. assert_not_equals: got disallowed value undefined -FAIL Promise rejected with TimeoutError. assert_not_equals: got disallowed value undefined -FAIL Promise rejected with TimeoutError. assert_not_equals: got disallowed value undefined -FAIL Promise rejected with AbortError. assert_not_equals: got disallowed value undefined -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/nfc/push.html b/third_party/WebKit/LayoutTests/nfc/push.html index ae44e25c..5b71458 100644 --- a/third_party/WebKit/LayoutTests/nfc/push.html +++ b/third_party/WebKit/LayoutTests/nfc/push.html
@@ -17,7 +17,7 @@ // NFCRecord must have data. createMessage([createTextRecord()]), - // NFCRecord.mediaType for 'text' record must be text/* . + // NFCRecord.mediaType for 'text' record must be 'text/*'. createMessage([createRecord('text', 'application/json', test_number_data)]), @@ -56,34 +56,29 @@ ]; nfc_test(nfc => { - return promise_test(test => { - promise_rejects(test, 'TypeMismatchError', navigator.nfc.push(undefined)); - }, 'Reject promise with TypeMismatchError if invalid type is provided.'); + return assertRejectsWithError(navigator.nfc.push(undefined), + 'TypeMismatchError'); }, 'Test that passing undefined to nfc.push would raise TypeMismatchError.'); nfc_test(nfc => { let promises = []; invalid_messages.forEach(message => { - promises.push(promise_test(test => { - promise_rejects(test, 'SyntaxError', navigator.nfc.push(message)); - }, 'Promise rejected with SyntaxError.')); + promises.push( + assertRejectsWithError(navigator.nfc.push(message), 'SyntaxError')); }); return Promise.all(promises) }, 'Test that promise is rejected with SyntaxError if NFCMessage is invalid.'); - nfc_test(nfc => { nfc.mockNFC.setHWStatus(NFCHWStatus.DISABLED); - return promise_test(test => { - promise_rejects(test, 'NotSupportedError', navigator.nfc.push(test_text_data)); - }, 'Promise rejected with NotSupportedError.'); + return assertRejectsWithError(navigator.nfc.push(test_text_data), + 'NotSupportedError'); }, 'nfc.push should fail when NFC HW is disabled.') nfc_test(nfc => { nfc.mockNFC.setHWStatus(NFCHWStatus.NOT_SUPPORTED); - return promise_test(test => { - promise_rejects(test, 'NotSupportedError', navigator.nfc.push(test_text_data)); - }, 'Promise rejected with NotSupportedError.'); + return assertRejectsWithError(navigator.nfc.push(test_text_data), + 'NotSupportedError'); }, 'nfc.push should fail when NFC HW is not supported.') nfc_test(nfc => { @@ -92,10 +87,9 @@ nfc_test(nfc => { nfc.mockNFC.setPendingPushCompleted(false); - return promise_test(test => { - promise_rejects(test, 'TimeoutError', - navigator.nfc.push(test_text_data,{ timeout: 1 })); - }, 'Promise rejected with TimeoutError.'); + return assertRejectsWithError( + navigator.nfc.push(test_text_data,{ timeout: 1 }), + 'TimeoutError'); }, 'nfc.push should fail with TimeoutError when push operation is not' + ' completed before specified timeout value.') @@ -109,8 +103,8 @@ return navigator.nfc.push(message).then(() => { nfc.assertNFCMessagesEqual(message, nfc.mockNFC.pushedMessage()); }); -}, 'nfc.push NFCMessage containing text, json, opaque and url records with default ' - + 'NFCPushOptions.'); +}, 'nfc.push NFCMessage containing text, json, opaque and url records with' + + ' default NFCPushOptions.'); nfc_test(nfc => { return navigator.nfc.push(test_text_data).then(() => { @@ -151,20 +145,9 @@ nfc_test(nfc => { nfc.mockNFC.setPendingPushCompleted(false); - return promise_test(test => { - promise_rejects(test, 'TimeoutError', - navigator.nfc.push(test_text_data,{ timeout: 1 })); - }, 'Promise rejected with TimeoutError.'); -}, 'nfc.push should fail with TimeoutError when push operation is not' + - ' completed before specified timeout value.') - -nfc_test(nfc => { - nfc.mockNFC.setPendingPushCompleted(false); let promise = navigator.nfc.push(test_text_data, { timeout: 100 }); navigator.nfc.cancelPush(); - return promise_test(test => { - promise_rejects(test, 'AbortError', promise); - }, 'Promise rejected with AbortError.'); + return assertRejectsWithError(promise, 'AbortError'); }, 'nfc.cancelPush should reject pending promise with AbortError.') </script>
diff --git a/third_party/WebKit/LayoutTests/nfc/resources/nfc-helpers.js b/third_party/WebKit/LayoutTests/nfc/resources/nfc-helpers.js index 886a9898..7d366ba 100644 --- a/third_party/WebKit/LayoutTests/nfc/resources/nfc-helpers.js +++ b/third_party/WebKit/LayoutTests/nfc/resources/nfc-helpers.js
@@ -14,6 +14,14 @@ NFCHWStatus.NOT_SUPPORTED = NFCHWStatus.ENABLED + 1; NFCHWStatus.DISABLED = NFCHWStatus.NOT_SUPPORTED + 1; +function assertRejectsWithError(promise, name) { + return promise.then(() => { + assert_unreached('expected promise to reject with ' + name); + }, error => { + assert_equals(error.name, name); + }); +} + function createMessage(records) { if (records !== undefined) { let message = {}
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/resize-scrollable-div-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/resize-scrollable-div-expected.txt index 898c853f..9033393 100644 --- a/third_party/WebKit/LayoutTests/paint/invalidation/resize-scrollable-div-expected.txt +++ b/third_party/WebKit/LayoutTests/paint/invalidation/resize-scrollable-div-expected.txt
@@ -8,8 +8,8 @@ "paintInvalidations": [ { "object": "LayoutBlockFlow DIV id='div'", - "rect": [8, 108, 300, 300], - "reason": "border box change" + "rect": [8, 208, 300, 200], + "reason": "incremental" }, { "object": "LayoutBlockFlow DIV id='div'", @@ -18,6 +18,11 @@ }, { "object": "LayoutBlockFlow DIV id='div'", + "rect": [108, 108, 200, 300], + "reason": "incremental" + }, + { + "object": "LayoutBlockFlow DIV id='div'", "rect": [8, 193, 85, 15], "reason": "scroll" }, @@ -47,7 +52,7 @@ "objectPaintInvalidations": [ { "object": "LayoutBlockFlow DIV id='div'", - "reason": "border box change" + "reason": "incremental" }, { "object": "LayoutBlockFlow DIV id='div'",
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/scrollbar-invalidation-on-resize-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/scrollbar-invalidation-on-resize-expected.txt index 310e9e6..e661184 100644 --- a/third_party/WebKit/LayoutTests/paint/invalidation/scrollbar-invalidation-on-resize-expected.txt +++ b/third_party/WebKit/LayoutTests/paint/invalidation/scrollbar-invalidation-on-resize-expected.txt
@@ -8,13 +8,13 @@ "paintInvalidations": [ { "object": "LayoutBlockFlow (positioned) DIV id='scrollable'", - "rect": [8, 50, 300, 100], - "reason": "border box change" + "rect": [8, 135, 285, 15], + "reason": "scroll" }, { "object": "LayoutBlockFlow (positioned) DIV id='scrollable'", - "rect": [8, 135, 285, 15], - "reason": "scroll" + "rect": [108, 50, 200, 100], + "reason": "incremental" }, { "object": "LayoutBlockFlow (positioned) DIV id='scrollable'", @@ -47,7 +47,7 @@ "objectPaintInvalidations": [ { "object": "LayoutBlockFlow (positioned) DIV id='scrollable'", - "reason": "border box change" + "reason": "incremental" }, { "object": "LayoutBlockFlow (positioned) DIV id='scrollable'",
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/scrollbar-invalidation-on-resize-with-border-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/scrollbar-invalidation-on-resize-with-border-expected.txt index fd44f45..00b14b56 100644 --- a/third_party/WebKit/LayoutTests/paint/invalidation/scrollbar-invalidation-on-resize-with-border-expected.txt +++ b/third_party/WebKit/LayoutTests/paint/invalidation/scrollbar-invalidation-on-resize-with-border-expected.txt
@@ -8,13 +8,13 @@ "paintInvalidations": [ { "object": "LayoutBlockFlow (positioned) DIV id='scrollable'", - "rect": [8, 50, 320, 120], - "reason": "border box change" + "rect": [18, 145, 285, 15], + "reason": "scroll" }, { "object": "LayoutBlockFlow (positioned) DIV id='scrollable'", - "rect": [18, 145, 285, 15], - "reason": "scroll" + "rect": [118, 50, 210, 120], + "reason": "incremental" }, { "object": "LayoutBlockFlow (positioned) DIV id='scrollable'", @@ -47,7 +47,7 @@ "objectPaintInvalidations": [ { "object": "LayoutBlockFlow (positioned) DIV id='scrollable'", - "reason": "border box change" + "reason": "incremental" }, { "object": "LayoutBlockFlow (positioned) DIV id='scrollable'",
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/table-cell-collapsed-border-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/table-cell-collapsed-border-expected.txt index c8b10b4..cd078c63 100644 --- a/third_party/WebKit/LayoutTests/paint/invalidation/table-cell-collapsed-border-expected.txt +++ b/third_party/WebKit/LayoutTests/paint/invalidation/table-cell-collapsed-border-expected.txt
@@ -7,11 +7,6 @@ "drawsContent": true, "paintInvalidations": [ { - "object": "LayoutTable TABLE", - "rect": [3, 60, 441, 405], - "reason": "invalidate paint rectangle" - }, - { "object": "LayoutTableCell TD id='t3'", "rect": [220, 260, 122, 110], "reason": "style change" @@ -31,8 +26,48 @@ ], "objectPaintInvalidations": [ { - "object": "LayoutTable TABLE", - "reason": "invalidate paint rectangle" + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD id='t1'", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD id='t2'", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD id='t3'", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" }, { "object": "LayoutTableCell TD id='t1'",
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/table-outer-border-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/table-outer-border-expected.txt index dd21182..b06d1cb 100644 --- a/third_party/WebKit/LayoutTests/paint/invalidation/table-outer-border-expected.txt +++ b/third_party/WebKit/LayoutTests/paint/invalidation/table-outer-border-expected.txt
@@ -95,6 +95,14 @@ "reason": "layoutObject removal" }, { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { "object": "LayoutTable TABLE id='table' class='green'", "reason": "layoutObject insertion" },
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/table/border-collapse-change-separate-to-collapse-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/table/border-collapse-change-separate-to-collapse-expected.txt index ba69534..18cc801 100644 --- a/third_party/WebKit/LayoutTests/paint/invalidation/table/border-collapse-change-separate-to-collapse-expected.txt +++ b/third_party/WebKit/LayoutTests/paint/invalidation/table/border-collapse-change-separate-to-collapse-expected.txt
@@ -51,6 +51,14 @@ ], "objectPaintInvalidations": [ { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { "object": "LayoutTable TABLE id='table'", "reason": "style change" },
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-cell-append-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-cell-append-expected.txt index 3a611cf..59ef756 100644 --- a/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-cell-append-expected.txt +++ b/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-cell-append-expected.txt
@@ -8,11 +8,6 @@ "paintInvalidations": [ { "object": "LayoutTable TABLE", - "rect": [8, 8, 120, 56], - "reason": "invalidate paint rectangle" - }, - { - "object": "LayoutTable TABLE", "rect": [8, 59, 120, 5], "reason": "incremental" }, @@ -36,8 +31,12 @@ ], "objectPaintInvalidations": [ { - "object": "LayoutTable TABLE", - "reason": "invalidate paint rectangle" + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" }, { "object": "LayoutTable TABLE",
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-cell-border-color-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-cell-border-color-expected.txt index 89451a0..76964c5 100644 --- a/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-cell-border-color-expected.txt +++ b/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-cell-border-color-expected.txt
@@ -7,11 +7,6 @@ "drawsContent": true, "paintInvalidations": [ { - "object": "LayoutTable TABLE", - "rect": [8, 8, 114, 54], - "reason": "invalidate paint rectangle" - }, - { "object": "LayoutTableCell TD id='foo'", "rect": [8, 8, 60, 54], "reason": "style change" @@ -21,8 +16,12 @@ ], "objectPaintInvalidations": [ { - "object": "LayoutTable TABLE", - "reason": "invalidate paint rectangle" + "object": "LayoutTableCell TD id='foo'", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" }, { "object": "LayoutTableCell TD id='foo'",
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-cell-border-width-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-cell-border-width-expected.txt index 930bb9f5..6a5f6dc0 100644 --- a/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-cell-border-width-expected.txt +++ b/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-cell-border-width-expected.txt
@@ -8,11 +8,6 @@ "paintInvalidations": [ { "object": "LayoutTable TABLE", - "rect": [8, 8, 114, 54], - "reason": "invalidate paint rectangle" - }, - { - "object": "LayoutTable TABLE", "rect": [8, 58, 114, 4], "reason": "incremental" }, @@ -41,8 +36,12 @@ ], "objectPaintInvalidations": [ { - "object": "LayoutTable TABLE", - "reason": "invalidate paint rectangle" + "object": "LayoutTableCell TD id='foo'", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" }, { "object": "LayoutTable TABLE",
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-col-border-color-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-col-border-color-expected.txt index 09774d8..27c93b4 100644 --- a/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-col-border-color-expected.txt +++ b/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-col-border-color-expected.txt
@@ -7,11 +7,6 @@ "drawsContent": true, "paintInvalidations": [ { - "object": "LayoutTable TABLE", - "rect": [8, 8, 113, 104], - "reason": "invalidate paint rectangle" - }, - { "object": "LayoutTableCol COL id='col'", "rect": [8, 8, 113, 104], "reason": "style change" @@ -21,8 +16,20 @@ ], "objectPaintInvalidations": [ { - "object": "LayoutTable TABLE", - "reason": "invalidate paint rectangle" + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" }, { "object": "LayoutTableCol COL id='col'",
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-col-border-width-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-col-border-width-expected.txt index 39e6514d..5ba2070 100644 --- a/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-col-border-width-expected.txt +++ b/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-col-border-width-expected.txt
@@ -7,11 +7,6 @@ "drawsContent": true, "paintInvalidations": [ { - "object": "LayoutTable TABLE", - "rect": [8, 8, 113, 104], - "reason": "invalidate paint rectangle" - }, - { "object": "LayoutTableCol COL id='col'", "rect": [8, 8, 113, 104], "reason": "style change" @@ -66,8 +61,20 @@ ], "objectPaintInvalidations": [ { - "object": "LayoutTable TABLE", - "reason": "invalidate paint rectangle" + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" }, { "object": "LayoutTable TABLE",
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-colgroup-border-color-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-colgroup-border-color-expected.txt index 5629d33..71449ce 100644 --- a/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-colgroup-border-color-expected.txt +++ b/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-colgroup-border-color-expected.txt
@@ -7,11 +7,6 @@ "drawsContent": true, "paintInvalidations": [ { - "object": "LayoutTable TABLE", - "rect": [7, 7, 167, 104], - "reason": "invalidate paint rectangle" - }, - { "object": "LayoutTableCol COLGROUP id='colgroup'", "rect": [8, 8, 166, 102], "reason": "style change" @@ -21,8 +16,28 @@ ], "objectPaintInvalidations": [ { - "object": "LayoutTable TABLE", - "reason": "invalidate paint rectangle" + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" }, { "object": "LayoutTableCol COLGROUP id='colgroup'",
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-colgroup-border-width-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-colgroup-border-width-expected.txt index d83e8b9..7f1d98f 100644 --- a/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-colgroup-border-width-expected.txt +++ b/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-colgroup-border-width-expected.txt
@@ -7,11 +7,6 @@ "drawsContent": true, "paintInvalidations": [ { - "object": "LayoutTable TABLE", - "rect": [7, 7, 167, 104], - "reason": "invalidate paint rectangle" - }, - { "object": "LayoutTableCol COLGROUP id='colgroup'", "rect": [8, 8, 166, 102], "reason": "style change" @@ -76,8 +71,28 @@ ], "objectPaintInvalidations": [ { - "object": "LayoutTable TABLE", - "reason": "invalidate paint rectangle" + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" }, { "object": "LayoutTable TABLE",
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-row-border-width-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-row-border-width-expected.txt index 3bc0e1e..4013197 100644 --- a/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-row-border-width-expected.txt +++ b/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-row-border-width-expected.txt
@@ -7,11 +7,6 @@ "drawsContent": true, "paintInvalidations": [ { - "object": "LayoutTable TABLE", - "rect": [8, 8, 60, 103], - "reason": "invalidate paint rectangle" - }, - { "object": "LayoutTableCell TD", "rect": [8, 8, 60, 54], "reason": "forced by layout" @@ -46,8 +41,12 @@ ], "objectPaintInvalidations": [ { - "object": "LayoutTable TABLE", - "reason": "invalidate paint rectangle" + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" }, { "object": "LayoutTable TABLE",
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-table-border-color-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-table-border-color-expected.txt index e9ea09b..5a9447d 100644 --- a/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-table-border-color-expected.txt +++ b/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-table-border-color-expected.txt
@@ -16,6 +16,10 @@ ], "objectPaintInvalidations": [ { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { "object": "LayoutTable TABLE id='tbl'", "reason": "style change" }
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-table-border-width-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-table-border-width-expected.txt index c2f06f30..7ebee422 100644 --- a/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-table-border-width-expected.txt +++ b/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-table-border-width-expected.txt
@@ -21,6 +21,10 @@ ], "objectPaintInvalidations": [ { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { "object": "LayoutTable TABLE id='tbl'", "reason": "style change" },
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-tbody-border-width-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-tbody-border-width-expected.txt index 27ee5850..2b0dc2a 100644 --- a/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-tbody-border-width-expected.txt +++ b/third_party/WebKit/LayoutTests/paint/invalidation/table/cached-change-tbody-border-width-expected.txt
@@ -8,11 +8,6 @@ "paintInvalidations": [ { "object": "LayoutTable TABLE", - "rect": [8, 8, 114, 153], - "reason": "invalidate paint rectangle" - }, - { - "object": "LayoutTable TABLE", "rect": [8, 159, 114, 2], "reason": "incremental" }, @@ -86,8 +81,28 @@ ], "objectPaintInvalidations": [ { - "object": "LayoutTable TABLE", - "reason": "invalidate paint rectangle" + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" }, { "object": "LayoutTable TABLE",
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/table/composited-cell-change-collapsed-border-color-expected.html b/third_party/WebKit/LayoutTests/paint/invalidation/table/composited-cell-change-collapsed-border-color-expected.html deleted file mode 100644 index cf6608bf..0000000 --- a/third_party/WebKit/LayoutTests/paint/invalidation/table/composited-cell-change-collapsed-border-color-expected.html +++ /dev/null
@@ -1,7 +0,0 @@ -<!DOCTYPE html> -<p style="height: 50px">Passes if green borders are visible surrounding A's cell and no red. -<table style="border-collapse: collapse;"> - <tr> - <td id="a" style="border: 5px solid green; width: 100px; height: 100px">A</td> - </tr> -</table>
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/table/composited-cell-change-collapsed-border-color-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/table/composited-cell-change-collapsed-border-color-expected.txt deleted file mode 100644 index 992af1b..0000000 --- a/third_party/WebKit/LayoutTests/paint/invalidation/table/composited-cell-change-collapsed-border-color-expected.txt +++ /dev/null
@@ -1,45 +0,0 @@ -{ - "layers": [ - { - "name": "LayoutView #document", - "bounds": [800, 600], - "contentsOpaque": true, - "drawsContent": true, - "paintInvalidations": [ - { - "object": "LayoutTable TABLE", - "rect": [8, 82, 112, 112], - "reason": "invalidate paint rectangle" - } - ] - }, - { - "name": "LayoutTableCell TD id='a'", - "position": [10, 84], - "bounds": [107, 107], - "drawsContent": true, - "paintInvalidations": [ - { - "object": "LayoutTableCell TD id='a'", - "rect": [-2, -2, 112, 112], - "reason": "style change" - } - ] - } - ], - "objectPaintInvalidations": [ - { - "object": "LayoutTable TABLE", - "reason": "invalidate paint rectangle" - }, - { - "object": "LayoutTableCell TD id='a'", - "reason": "style change" - }, - { - "object": "RootInlineBox", - "reason": "style change" - } - ] -} -
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/table/composited-cell-change-collapsed-border-color.html b/third_party/WebKit/LayoutTests/paint/invalidation/table/composited-cell-change-collapsed-border-color.html deleted file mode 100644 index 96981e21..0000000 --- a/third_party/WebKit/LayoutTests/paint/invalidation/table/composited-cell-change-collapsed-border-color.html +++ /dev/null
@@ -1,14 +0,0 @@ -<!DOCTYPE html> -<p style="height: 50px">Passes if green borders are visible surrounding A's cell and no red. -<table style="border-collapse: collapse;"> - <tr> - <td id="a" style="border: 5px solid red; width: 100px; height: 100px; will-change: transform">A</td> - </tr> -</table> -<script src="../resources/text-based-repaint.js"></script> -<script> -function repaintTest() { - a.style.borderColor = 'green'; -} -onload = runRepaintAndPixelTest; -</script>
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/table/composited-row-change-collapsed-border-color-expected.html b/third_party/WebKit/LayoutTests/paint/invalidation/table/composited-row-change-collapsed-border-color-expected.html deleted file mode 100644 index dc1f099..0000000 --- a/third_party/WebKit/LayoutTests/paint/invalidation/table/composited-row-change-collapsed-border-color-expected.html +++ /dev/null
@@ -1,7 +0,0 @@ -<!DOCTYPE html> -<p style="height: 50px">Passes if green borders are visible surrounding A's cell and no red. -<table style="border-collapse: collapse;"> - <tr id="a" style="border: 5px solid green"> - <td style="width: 100px; height: 100px">A</td> - </tr> -</table>
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/table/composited-row-change-collapsed-border-color-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/table/composited-row-change-collapsed-border-color-expected.txt deleted file mode 100644 index c26169a..0000000 --- a/third_party/WebKit/LayoutTests/paint/invalidation/table/composited-row-change-collapsed-border-color-expected.txt +++ /dev/null
@@ -1,41 +0,0 @@ -{ - "layers": [ - { - "name": "LayoutView #document", - "bounds": [800, 600], - "contentsOpaque": true, - "drawsContent": true, - "paintInvalidations": [ - { - "object": "LayoutTable TABLE", - "rect": [8, 82, 112, 112], - "reason": "invalidate paint rectangle" - } - ] - }, - { - "name": "LayoutTableRow TR id='a'", - "position": [10, 84], - "bounds": [107, 107], - "drawsContent": true, - "paintInvalidations": [ - { - "object": "LayoutTableRow TR id='a'", - "rect": [0, 0, 107, 107], - "reason": "style change" - } - ] - } - ], - "objectPaintInvalidations": [ - { - "object": "LayoutTable TABLE", - "reason": "invalidate paint rectangle" - }, - { - "object": "LayoutTableRow TR id='a'", - "reason": "style change" - } - ] -} -
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/table/composited-row-change-collapsed-border-color.html b/third_party/WebKit/LayoutTests/paint/invalidation/table/composited-row-change-collapsed-border-color.html deleted file mode 100644 index b3f51b3..0000000 --- a/third_party/WebKit/LayoutTests/paint/invalidation/table/composited-row-change-collapsed-border-color.html +++ /dev/null
@@ -1,14 +0,0 @@ -<!DOCTYPE html> -<p style="height: 50px">Passes if green borders are visible surrounding A's cell and no red. -<table style="border-collapse: collapse;"> - <tr id="a" style="border: 5px solid red; will-change: transform"> - <td style="width: 100px; height: 100px">A</td> - </tr> -</table> -<script src="../resources/text-based-repaint.js"></script> -<script> -function repaintTest() { - a.style.borderColor = 'green'; -} -onload = runRepaintAndPixelTest; -</script>
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/table/composited-section-change-collapsed-border-color-expected.html b/third_party/WebKit/LayoutTests/paint/invalidation/table/composited-section-change-collapsed-border-color-expected.html deleted file mode 100644 index b76f9bf..0000000 --- a/third_party/WebKit/LayoutTests/paint/invalidation/table/composited-section-change-collapsed-border-color-expected.html +++ /dev/null
@@ -1,9 +0,0 @@ -<!DOCTYPE html> -<p style="height: 50px">Passes if green borders are visible surrounding A's cell and no red. -<table style="border-collapse: collapse;"> - <thead id="a" style="border: 5px solid green"> - <tr> - <td style="width: 100px; height: 100px">A</td> - </tr> - </head> -</table>
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/table/composited-section-change-collapsed-border-color-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/table/composited-section-change-collapsed-border-color-expected.txt deleted file mode 100644 index 8505bd02..0000000 --- a/third_party/WebKit/LayoutTests/paint/invalidation/table/composited-section-change-collapsed-border-color-expected.txt +++ /dev/null
@@ -1,41 +0,0 @@ -{ - "layers": [ - { - "name": "LayoutView #document", - "bounds": [800, 600], - "contentsOpaque": true, - "drawsContent": true, - "paintInvalidations": [ - { - "object": "LayoutTable TABLE", - "rect": [8, 82, 112, 112], - "reason": "invalidate paint rectangle" - } - ] - }, - { - "name": "LayoutTableSection THEAD id='a'", - "position": [10, 84], - "bounds": [107, 107], - "drawsContent": true, - "paintInvalidations": [ - { - "object": "LayoutTableSection THEAD id='a'", - "rect": [0, 0, 107, 107], - "reason": "style change" - } - ] - } - ], - "objectPaintInvalidations": [ - { - "object": "LayoutTable TABLE", - "reason": "invalidate paint rectangle" - }, - { - "object": "LayoutTableSection THEAD id='a'", - "reason": "style change" - } - ] -} -
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/table/composited-section-change-collapsed-border-color.html b/third_party/WebKit/LayoutTests/paint/invalidation/table/composited-section-change-collapsed-border-color.html deleted file mode 100644 index c7b9932..0000000 --- a/third_party/WebKit/LayoutTests/paint/invalidation/table/composited-section-change-collapsed-border-color.html +++ /dev/null
@@ -1,16 +0,0 @@ -<!DOCTYPE html> -<p style="height: 50px">Passes if green borders are visible surrounding A's cell and no red. -<table style="border-collapse: collapse;"> - <thead id="a" style="border: 5px solid red; will-change: transform"> - <tr> - <td style="width: 100px; height: 100px">A</td> - </tr> - </head> -</table> -<script src="../resources/text-based-repaint.js"></script> -<script> -function repaintTest() { - a.style.borderColor = 'green'; -} -onload = runRepaintAndPixelTest; -</script>
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/video-mute-repaint-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/video-mute-repaint-expected.txt index 9b5afaaa..564c70c 100644 --- a/third_party/WebKit/LayoutTests/paint/invalidation/video-mute-repaint-expected.txt +++ b/third_party/WebKit/LayoutTests/paint/invalidation/video-mute-repaint-expected.txt
@@ -25,65 +25,7 @@ "name": "Squashing Layer (first squashed layer: LayoutFlexibleBox (relative positioned) DIV)", "position": [8, 8], "bounds": [700, 525], - "drawsContent": true, - "paintInvalidations": [ - { - "object": "LayoutBlockFlow DIV id='track'", - "rect": [562, 485, 106, 48], - "reason": "subtree" - }, - { - "object": "LayoutFlexibleBox DIV", - "rect": [580, 508, 70, 2], - "reason": "subtree" - }, - { - "object": "LayoutSlider INPUT", - "rect": [580, 508, 70, 2], - "reason": "subtree" - }, - { - "object": "LayoutBlockFlow DIV id='thumb'", - "rect": [632, 485, 36, 48], - "reason": "subtree" - }, - { - "object": "LayoutBlockFlow DIV id='thumb'", - "rect": [562, 485, 36, 48], - "reason": "subtree" - }, - { - "object": "LayoutButton INPUT", - "rect": [530, 493, 32, 32], - "reason": "subtree" - } - ] - } - ], - "objectPaintInvalidations": [ - { - "object": "LayoutVideo VIDEO id='v'", - "reason": "style change" - }, - { - "object": "LayoutButton INPUT", - "reason": "subtree" - }, - { - "object": "LayoutSlider INPUT", - "reason": "subtree" - }, - { - "object": "LayoutFlexibleBox DIV", - "reason": "subtree" - }, - { - "object": "LayoutBlockFlow DIV id='track'", - "reason": "subtree" - }, - { - "object": "LayoutBlockFlow DIV id='thumb'", - "reason": "subtree" + "drawsContent": true } ] }
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/video-unmute-repaint-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/video-unmute-repaint-expected.txt index 6178341e..564c70c 100644 --- a/third_party/WebKit/LayoutTests/paint/invalidation/video-unmute-repaint-expected.txt +++ b/third_party/WebKit/LayoutTests/paint/invalidation/video-unmute-repaint-expected.txt
@@ -25,65 +25,7 @@ "name": "Squashing Layer (first squashed layer: LayoutFlexibleBox (relative positioned) DIV)", "position": [8, 8], "bounds": [700, 525], - "drawsContent": true, - "paintInvalidations": [ - { - "object": "LayoutBlockFlow DIV id='track'", - "rect": [562, 485, 106, 48], - "reason": "subtree" - }, - { - "object": "LayoutFlexibleBox DIV", - "rect": [580, 508, 70, 2], - "reason": "subtree" - }, - { - "object": "LayoutSlider INPUT", - "rect": [580, 508, 70, 2], - "reason": "subtree" - }, - { - "object": "LayoutBlockFlow DIV id='thumb'", - "rect": [597, 485, 36, 48], - "reason": "subtree" - }, - { - "object": "LayoutBlockFlow DIV id='thumb'", - "rect": [562, 485, 36, 48], - "reason": "subtree" - }, - { - "object": "LayoutButton INPUT", - "rect": [530, 493, 32, 32], - "reason": "subtree" - } - ] - } - ], - "objectPaintInvalidations": [ - { - "object": "LayoutVideo VIDEO id='v'", - "reason": "style change" - }, - { - "object": "LayoutButton INPUT", - "reason": "subtree" - }, - { - "object": "LayoutSlider INPUT", - "reason": "subtree" - }, - { - "object": "LayoutFlexibleBox DIV", - "reason": "subtree" - }, - { - "object": "LayoutBlockFlow DIV id='track'", - "reason": "subtree" - }, - { - "object": "LayoutBlockFlow DIV id='thumb'", - "reason": "subtree" + "drawsContent": true } ] }
diff --git a/third_party/WebKit/LayoutTests/platform/android/fast/html/keygen-expected.txt b/third_party/WebKit/LayoutTests/platform/android/fast/html/keygen-expected.txt index fad7c63..0140d4f 100644 --- a/third_party/WebKit/LayoutTests/platform/android/fast/html/keygen-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/android/fast/html/keygen-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. layer at (0,0) size 800x600 LayoutView at (0,0) size 800x600 layer at (0,0) size 800x600
diff --git a/third_party/WebKit/LayoutTests/platform/linux/editing/deleting/forward-delete-expected.png b/third_party/WebKit/LayoutTests/platform/linux/editing/deleting/forward-delete-expected.png deleted file mode 100644 index c977ba42..0000000 --- a/third_party/WebKit/LayoutTests/platform/linux/editing/deleting/forward-delete-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/editing/deleting/forward-delete-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/editing/deleting/forward-delete-expected.txt deleted file mode 100644 index 0e7c0704..0000000 --- a/third_party/WebKit/LayoutTests/platform/linux/editing/deleting/forward-delete-expected.txt +++ /dev/null
@@ -1,24 +0,0 @@ -EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification -EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification -EDITING DELEGATE: webViewDidChange:WebViewDidChangeNotification -EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification -EDITING DELEGATE: webViewDidChange:WebViewDidChangeNotification -EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification -EDITING DELEGATE: webViewDidChange:WebViewDidChangeNotification -EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification -EDITING DELEGATE: webViewDidChange:WebViewDidChangeNotification -layer at (0,0) size 800x600 - LayoutView at (0,0) size 800x600 -layer at (0,0) size 800x600 - LayoutBlockFlow {HTML} at (0,0) size 800x600 - LayoutBlockFlow {BODY} at (8,8) size 784x584 - LayoutBlockFlow {DIV} at (0,0) size 784x84 [border: (2px solid #0000FF)] - LayoutText {#text} at (14,14) size 725x55 - text run at (14,14) width 719: "Should see \"bar\" in the red box. Insertion point should be at the start of the" - text run at (733,14) width 6: " " - text run at (14,42) width 101: "document." - LayoutBlockFlow {DIV} at (0,108) size 784x56 - LayoutBlockFlow {DIV} at (0,0) size 784x56 [border: (2px solid #FF0000)] - LayoutText {#text} at (14,14) size 31x27 - text run at (14,14) width 31: "bar" -caret: position 0 of child 0 {#text} of child 1 {DIV} of child 3 {DIV} of body
diff --git a/third_party/WebKit/LayoutTests/platform/linux/fast/forms/form-radio-img-node-list-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/fast/forms/form-radio-img-node-list-expected.txt index dde0da9a..baf968c 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/fast/forms/form-radio-img-node-list-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/linux/fast/forms/form-radio-img-node-list-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Test RadioNodeLists returned by the HTMLFormElement named-getter. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/platform/linux/fast/html/keygen-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/fast/html/keygen-expected.txt index 07d3102..736f9df 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/fast/html/keygen-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/linux/fast/html/keygen-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. layer at (0,0) size 800x600 LayoutView at (0,0) size 800x600 layer at (0,0) size 800x600
diff --git a/third_party/WebKit/LayoutTests/platform/linux/paint/invalidation/table-cell-collapsed-border-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/paint/invalidation/table-cell-collapsed-border-expected.txt index b1b1bfb..e452e1f 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/paint/invalidation/table-cell-collapsed-border-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/linux/paint/invalidation/table-cell-collapsed-border-expected.txt
@@ -7,11 +7,6 @@ "drawsContent": true, "paintInvalidations": [ { - "object": "LayoutTable TABLE", - "rect": [3, 64, 441, 405], - "reason": "invalidate paint rectangle" - }, - { "object": "LayoutTableCell TD id='t3'", "rect": [220, 264, 122, 110], "reason": "style change" @@ -31,8 +26,48 @@ ], "objectPaintInvalidations": [ { - "object": "LayoutTable TABLE", - "reason": "invalidate paint rectangle" + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD id='t1'", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD id='t2'", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD id='t3'", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" }, { "object": "LayoutTableCell TD id='t1'",
diff --git a/third_party/WebKit/LayoutTests/platform/linux/paint/invalidation/table-collapsed-border-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/paint/invalidation/table-collapsed-border-expected.txt index 15129f2..71fa8da 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/paint/invalidation/table-collapsed-border-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/linux/paint/invalidation/table-collapsed-border-expected.txt
@@ -147,6 +147,30 @@ "reason": "layoutObject removal" }, { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { "object": "LayoutTable TABLE id='t'", "reason": "style change" },
diff --git a/third_party/WebKit/LayoutTests/platform/linux/paint/invalidation/table/cached-change-cell-sl-border-color-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/paint/invalidation/table/cached-change-cell-sl-border-color-expected.txt index 2882c0c..6bb9255 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/paint/invalidation/table/cached-change-cell-sl-border-color-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/linux/paint/invalidation/table/cached-change-cell-sl-border-color-expected.txt
@@ -7,11 +7,6 @@ "drawsContent": true, "paintInvalidations": [ { - "object": "LayoutTable (relative positioned) TABLE", - "rect": [8, 8, 114, 54], - "reason": "invalidate paint rectangle" - }, - { "object": "LayoutTableCell TD id='foo'", "rect": [8, 8, 60, 54], "reason": "style change" @@ -35,8 +30,12 @@ "reason": "layoutObject removal" }, { - "object": "LayoutTable (relative positioned) TABLE", - "reason": "invalidate paint rectangle" + "object": "LayoutTableCell TD id='foo'", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" }, { "object": "LayoutTableCell TD id='foo'",
diff --git a/third_party/WebKit/LayoutTests/platform/linux/virtual/stable/webexposed/global-interface-listing-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/virtual/stable/webexposed/global-interface-listing-expected.txt index 59905c73..11390d5 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/virtual/stable/webexposed/global-interface-listing-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/linux/virtual/stable/webexposed/global-interface-listing-expected.txt
@@ -5171,7 +5171,6 @@ attribute SVG_ZOOMANDPAN_UNKNOWN getter preserveAspectRatio getter viewBox - getter viewTarget getter zoomAndPan method constructor setter zoomAndPan
diff --git a/third_party/WebKit/LayoutTests/platform/mac-mac10.10/fast/html/keygen-expected.txt b/third_party/WebKit/LayoutTests/platform/mac-mac10.10/fast/html/keygen-expected.txt index 7d656f7f..e30d8e6 100644 --- a/third_party/WebKit/LayoutTests/platform/mac-mac10.10/fast/html/keygen-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/mac-mac10.10/fast/html/keygen-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. layer at (0,0) size 800x600 LayoutView at (0,0) size 800x600 layer at (0,0) size 800x600
diff --git a/third_party/WebKit/LayoutTests/platform/mac-mac10.9/fast/html/keygen-expected.txt b/third_party/WebKit/LayoutTests/platform/mac-mac10.9/fast/html/keygen-expected.txt index 3c1fc3eb4..62118d17 100644 --- a/third_party/WebKit/LayoutTests/platform/mac-mac10.9/fast/html/keygen-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/mac-mac10.9/fast/html/keygen-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. layer at (0,0) size 800x600 LayoutView at (0,0) size 800x600 layer at (0,0) size 800x600
diff --git a/third_party/WebKit/LayoutTests/platform/mac/editing/deleting/forward-delete-expected.png b/third_party/WebKit/LayoutTests/platform/mac/editing/deleting/forward-delete-expected.png deleted file mode 100644 index 81c86e9..0000000 --- a/third_party/WebKit/LayoutTests/platform/mac/editing/deleting/forward-delete-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/editing/deleting/forward-delete-expected.txt b/third_party/WebKit/LayoutTests/platform/mac/editing/deleting/forward-delete-expected.txt deleted file mode 100644 index 99e6f06..0000000 --- a/third_party/WebKit/LayoutTests/platform/mac/editing/deleting/forward-delete-expected.txt +++ /dev/null
@@ -1,24 +0,0 @@ -EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification -EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification -EDITING DELEGATE: webViewDidChange:WebViewDidChangeNotification -EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification -EDITING DELEGATE: webViewDidChange:WebViewDidChangeNotification -EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification -EDITING DELEGATE: webViewDidChange:WebViewDidChangeNotification -EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification -EDITING DELEGATE: webViewDidChange:WebViewDidChangeNotification -layer at (0,0) size 800x600 - LayoutView at (0,0) size 800x600 -layer at (0,0) size 800x600 - LayoutBlockFlow {HTML} at (0,0) size 800x600 - LayoutBlockFlow {BODY} at (8,8) size 784x584 - LayoutBlockFlow {DIV} at (0,0) size 784x84 [border: (2px solid #0000FF)] - LayoutText {#text} at (14,14) size 725x56 - text run at (14,14) width 719: "Should see \"bar\" in the red box. Insertion point should be at the start of the" - text run at (732,14) width 7: " " - text run at (14,42) width 101: "document." - LayoutBlockFlow {DIV} at (0,108) size 784x56 - LayoutBlockFlow {DIV} at (0,0) size 784x56 [border: (2px solid #FF0000)] - LayoutText {#text} at (14,14) size 31x28 - text run at (14,14) width 31: "bar" -caret: position 0 of child 0 {#text} of child 1 {DIV} of child 3 {DIV} of body
diff --git a/third_party/WebKit/LayoutTests/platform/mac/fast/html/keygen-expected.txt b/third_party/WebKit/LayoutTests/platform/mac/fast/html/keygen-expected.txt index 590703f..5038d78 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/fast/html/keygen-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/mac/fast/html/keygen-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. layer at (0,0) size 800x600 LayoutView at (0,0) size 800x600 layer at (0,0) size 800x600
diff --git a/third_party/WebKit/LayoutTests/platform/mac/paint/invalidation/table-collapsed-border-expected.txt b/third_party/WebKit/LayoutTests/platform/mac/paint/invalidation/table-collapsed-border-expected.txt index 38b14e4..d64d6549 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/paint/invalidation/table-collapsed-border-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/mac/paint/invalidation/table-collapsed-border-expected.txt
@@ -147,6 +147,30 @@ "reason": "layoutObject removal" }, { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { "object": "LayoutTable TABLE id='t'", "reason": "style change" },
diff --git a/third_party/WebKit/LayoutTests/platform/mac/paint/invalidation/table/cached-change-cell-sl-border-color-expected.txt b/third_party/WebKit/LayoutTests/platform/mac/paint/invalidation/table/cached-change-cell-sl-border-color-expected.txt index d682150..1804202 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/paint/invalidation/table/cached-change-cell-sl-border-color-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/mac/paint/invalidation/table/cached-change-cell-sl-border-color-expected.txt
@@ -7,11 +7,6 @@ "drawsContent": true, "paintInvalidations": [ { - "object": "LayoutTable (relative positioned) TABLE", - "rect": [8, 8, 114, 54], - "reason": "invalidate paint rectangle" - }, - { "object": "LayoutTableCell TD id='foo'", "rect": [8, 8, 60, 54], "reason": "style change" @@ -35,8 +30,12 @@ "reason": "layoutObject removal" }, { - "object": "LayoutTable (relative positioned) TABLE", - "reason": "invalidate paint rectangle" + "object": "LayoutTableCell TD id='foo'", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" }, { "object": "LayoutTableCell TD id='foo'",
diff --git a/third_party/WebKit/LayoutTests/platform/win/editing/deleting/forward-delete-expected.png b/third_party/WebKit/LayoutTests/platform/win/editing/deleting/forward-delete-expected.png deleted file mode 100644 index fcdeb4a..0000000 --- a/third_party/WebKit/LayoutTests/platform/win/editing/deleting/forward-delete-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/editing/deleting/forward-delete-expected.txt b/third_party/WebKit/LayoutTests/platform/win/editing/deleting/forward-delete-expected.txt deleted file mode 100644 index 8cd58d0..0000000 --- a/third_party/WebKit/LayoutTests/platform/win/editing/deleting/forward-delete-expected.txt +++ /dev/null
@@ -1,24 +0,0 @@ -EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification -EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification -EDITING DELEGATE: webViewDidChange:WebViewDidChangeNotification -EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification -EDITING DELEGATE: webViewDidChange:WebViewDidChangeNotification -EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification -EDITING DELEGATE: webViewDidChange:WebViewDidChangeNotification -EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification -EDITING DELEGATE: webViewDidChange:WebViewDidChangeNotification -layer at (0,0) size 800x600 - LayoutView at (0,0) size 800x600 -layer at (0,0) size 800x600 - LayoutBlockFlow {HTML} at (0,0) size 800x600 - LayoutBlockFlow {BODY} at (8,8) size 784x584 - LayoutBlockFlow {DIV} at (0,0) size 784x82 [border: (2px solid #0000FF)] - LayoutText {#text} at (14,14) size 725x53 - text run at (14,14) width 719: "Should see \"bar\" in the red box. Insertion point should be at the start of the" - text run at (732,14) width 7: " " - text run at (14,41) width 101: "document." - LayoutBlockFlow {DIV} at (0,106) size 784x55 - LayoutBlockFlow {DIV} at (0,0) size 784x55 [border: (2px solid #FF0000)] - LayoutText {#text} at (14,14) size 31x26 - text run at (14,14) width 31: "bar" -caret: position 0 of child 0 {#text} of child 1 {DIV} of child 3 {DIV} of body
diff --git a/third_party/WebKit/LayoutTests/platform/win/fast/forms/form-radio-img-node-list-expected.txt b/third_party/WebKit/LayoutTests/platform/win/fast/forms/form-radio-img-node-list-expected.txt index 10b7fdc..73a5544 100644 --- a/third_party/WebKit/LayoutTests/platform/win/fast/forms/form-radio-img-node-list-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/win/fast/forms/form-radio-img-node-list-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. Test RadioNodeLists returned by the HTMLFormElement named-getter. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/platform/win/fast/html/keygen-expected.txt b/third_party/WebKit/LayoutTests/platform/win/fast/html/keygen-expected.txt index 283ecee..c1678bb9 100644 --- a/third_party/WebKit/LayoutTests/platform/win/fast/html/keygen-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/win/fast/html/keygen-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. layer at (0,0) size 800x600 LayoutView at (0,0) size 800x600 layer at (0,0) size 800x600
diff --git a/third_party/WebKit/LayoutTests/platform/win/paint/invalidation/table-collapsed-border-expected.txt b/third_party/WebKit/LayoutTests/platform/win/paint/invalidation/table-collapsed-border-expected.txt index 9eac676d..5eba99d 100644 --- a/third_party/WebKit/LayoutTests/platform/win/paint/invalidation/table-collapsed-border-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/win/paint/invalidation/table-collapsed-border-expected.txt
@@ -147,6 +147,30 @@ "reason": "layoutObject removal" }, { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" + }, + { "object": "LayoutTable TABLE id='t'", "reason": "style change" },
diff --git a/third_party/WebKit/LayoutTests/platform/win/paint/invalidation/table/cached-change-cell-sl-border-color-expected.txt b/third_party/WebKit/LayoutTests/platform/win/paint/invalidation/table/cached-change-cell-sl-border-color-expected.txt index 1904492..560cab9 100644 --- a/third_party/WebKit/LayoutTests/platform/win/paint/invalidation/table/cached-change-cell-sl-border-color-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/win/paint/invalidation/table/cached-change-cell-sl-border-color-expected.txt
@@ -7,11 +7,6 @@ "drawsContent": true, "paintInvalidations": [ { - "object": "LayoutTable (relative positioned) TABLE", - "rect": [8, 8, 114, 54], - "reason": "invalidate paint rectangle" - }, - { "object": "LayoutTableCell TD id='foo'", "rect": [8, 8, 60, 54], "reason": "style change" @@ -35,8 +30,12 @@ "reason": "layoutObject removal" }, { - "object": "LayoutTable (relative positioned) TABLE", - "reason": "invalidate paint rectangle" + "object": "LayoutTableCell TD id='foo'", + "reason": "style change" + }, + { + "object": "LayoutTableCell TD", + "reason": "style change" }, { "object": "LayoutTableCell TD id='foo'",
diff --git a/third_party/WebKit/LayoutTests/platform/win/virtual/stable/webexposed/global-interface-listing-expected.txt b/third_party/WebKit/LayoutTests/platform/win/virtual/stable/webexposed/global-interface-listing-expected.txt index 59905c73..11390d5 100644 --- a/third_party/WebKit/LayoutTests/platform/win/virtual/stable/webexposed/global-interface-listing-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/win/virtual/stable/webexposed/global-interface-listing-expected.txt
@@ -5171,7 +5171,6 @@ attribute SVG_ZOOMANDPAN_UNKNOWN getter preserveAspectRatio getter viewBox - getter viewTarget getter zoomAndPan method constructor setter zoomAndPan
diff --git a/third_party/WebKit/LayoutTests/printing/offscreencanvas-2d-printing-expected.html b/third_party/WebKit/LayoutTests/printing/offscreencanvas-2d-printing-expected.html new file mode 100644 index 0000000..b546dc6 --- /dev/null +++ b/third_party/WebKit/LayoutTests/printing/offscreencanvas-2d-printing-expected.html
@@ -0,0 +1,12 @@ +<!DOCTYPE html> +<canvas id='c'></canvas> +<script> +var can = document.getElementById('c'); +can.width = can.height = 100; +var ctx = can.getContext("2d"); +ctx.fillStyle = 'green'; +ctx.fillRect(0, 0, 100, 100); +if (window.testRunner) { + testRunner.setPrinting(); +} +</script>
diff --git a/third_party/WebKit/LayoutTests/printing/offscreencanvas-2d-printing.html b/third_party/WebKit/LayoutTests/printing/offscreencanvas-2d-printing.html new file mode 100644 index 0000000..671c0a9 --- /dev/null +++ b/third_party/WebKit/LayoutTests/printing/offscreencanvas-2d-printing.html
@@ -0,0 +1,20 @@ +<!DOCTYPE html> +<canvas id='c'></canvas> +<script> +var can = document.getElementById('c'); +can.width = can.height = 100; +var ctx = can.transferControlToOffscreen().getContext("2d"); +ctx.fillStyle = 'green'; +ctx.fillRect(0, 0, 100, 100); +ctx.commit(); +if (window.testRunner) { + testRunner.setPrinting(); + testRunner.waitUntilDone(); + setTimeout(function() { + // The setTimeout is a synchronization barrier that guarantees + // the commit will be processed by the event loop before the test + // is done. + testRunner.notifyDone(); + }, 0); +} +</script>
diff --git a/third_party/WebKit/LayoutTests/printing/offscreencanvas-webgl-printing-expected.html b/third_party/WebKit/LayoutTests/printing/offscreencanvas-webgl-printing-expected.html new file mode 100644 index 0000000..995b356 --- /dev/null +++ b/third_party/WebKit/LayoutTests/printing/offscreencanvas-webgl-printing-expected.html
@@ -0,0 +1,12 @@ +<!DOCTYPE html> +<canvas id='c'></canvas> +<script> +var can = document.getElementById('c'); +can.width = can.height = 100; +var ctx = can.getContext("webgl"); +ctx.clearColor(0, 1, 0, 1); +ctx.clear(ctx.COLOR_BUFFER_BIT); +if (window.testRunner) { + testRunner.setPrinting(); +} +</script>
diff --git a/third_party/WebKit/LayoutTests/printing/offscreencanvas-webgl-printing.html b/third_party/WebKit/LayoutTests/printing/offscreencanvas-webgl-printing.html new file mode 100644 index 0000000..b5d4ea3 --- /dev/null +++ b/third_party/WebKit/LayoutTests/printing/offscreencanvas-webgl-printing.html
@@ -0,0 +1,20 @@ +<!DOCTYPE html> +<canvas id='c'></canvas> +<script> +var can = document.getElementById('c'); +can.width = can.height = 100; +var ctx = can.transferControlToOffscreen().getContext("webgl"); +ctx.clearColor(0, 1, 0, 1); +ctx.clear(ctx.COLOR_BUFFER_BIT); +ctx.commit(); +if (window.testRunner) { + testRunner.setPrinting(); + testRunner.waitUntilDone(); + setTimeout(function() { + // The setTimeout is a synchronization barrier that guarantees + // the commit will be processed by the event loop before the test + // is done. + testRunner.notifyDone(); + }, 0); +} +</script>
diff --git a/third_party/WebKit/LayoutTests/sensor/ambient-light-sensor.html b/third_party/WebKit/LayoutTests/sensor/ambient-light-sensor.html index a3e8856..1fd4e10 100644 --- a/third_party/WebKit/LayoutTests/sensor/ambient-light-sensor.html +++ b/third_party/WebKit/LayoutTests/sensor/ambient-light-sensor.html
@@ -3,6 +3,7 @@ <script src="../resources/testharnessreport.js"></script> <script src="../resources/mojo-helpers.js"></script> <script src="resources/sensor-helpers.js"></script> +<script src="resources/generic-sensor-tests.js"></script> <script> 'use strict'; @@ -17,277 +18,9 @@ buffer[2] = kDefaultReadingValue; } -test(() => assert_throws( - new RangeError(), - () => new AmbientLightSensor({frequency: -60})), - 'Test that negative frequency causes exception from constructor.'); +function verify_sensor_reading(reading) { + return reading.illuminance == kDefaultReadingValue; +} -sensor_test(sensor => { - sensor.mockSensorProvider.setGetSensorShouldFail(true); - let ambientLightSensor = new AmbientLightSensor(); - ambientLightSensor.start(); - return new Promise((resolve, reject) => { - let wrapper = new CallbackWrapper(event => { - assert_equals(ambientLightSensor.state, 'errored'); - assert_equals(event.error.name, 'NotFoundError'); - ambientLightSensor.onerror = null; - resolve(); - }, reject); - - ambientLightSensor.onerror = wrapper.callback; - }); -}, 'Test that "onerror" is send when sensor is not supported.'); - -sensor_test(sensor => { - let ambientLightSensor = new AmbientLightSensor({frequency: 560}); - ambientLightSensor.start(); - - let testPromise = sensor.mockSensorProvider.getCreatedSensor() - .then(mockSensor => { - mockSensor.setStartShouldFail(true); - return mockSensor.addConfigurationCalled(); }) - .then(mockSensor => { - return new Promise((resolve, reject) => { - let wrapper = new CallbackWrapper(event => { - assert_equals(ambientLightSensor.state, 'errored'); - assert_equals(event.error.name, 'OperationError'); - ambientLightSensor.onerror = null; - resolve(); - }, reject); - - ambientLightSensor.onerror = wrapper.callback; - }); - }); - return testPromise; -}, 'Test that "onerror" is send when start() call has failed.'); - -sensor_test(sensor => { - let ambientLightSensor = new AmbientLightSensor({frequency: 560}); - ambientLightSensor.start(); - - let testPromise = sensor.mockSensorProvider.getCreatedSensor() - .then(mockSensor => { return mockSensor.addConfigurationCalled(); }) - .then(mockSensor => { - return new Promise((resolve, reject) => { - let wrapper = new CallbackWrapper(() => { - let configuration = mockSensor.active_sensor_configurations_[0]; - assert_equals(configuration.frequency, 60); - ambientLightSensor.stop(); - assert_equals(ambientLightSensor.state, 'idle'); - resolve(mockSensor); - }, reject); - - ambientLightSensor.onactivate = wrapper.callback; - ambientLightSensor.onerror = reject; - }); - }) - .then(mockSensor => { return mockSensor.removeConfigurationCalled(); }); - - return testPromise; -}, 'Test that frequency is capped to 60.0 Hz.'); - -sensor_test(sensor => { - let maxSupportedFrequency = 15; - sensor.mockSensorProvider.setMaximumSupportedFrequency(maxSupportedFrequency); - let ambientLightSensor = new AmbientLightSensor({frequency: 50}); - ambientLightSensor.start(); - - let testPromise = sensor.mockSensorProvider.getCreatedSensor() - .then(mockSensor => { return mockSensor.addConfigurationCalled(); }) - .then(mockSensor => { - return new Promise((resolve, reject) => { - let wrapper = new CallbackWrapper(() => { - let configuration = mockSensor.active_sensor_configurations_[0]; - assert_equals(configuration.frequency, maxSupportedFrequency); - ambientLightSensor.stop(); - assert_equals(ambientLightSensor.state, 'idle'); - resolve(mockSensor); - }, reject); - - ambientLightSensor.onactivate = wrapper.callback; - ambientLightSensor.onerror = reject; - }); - }) - .then(mockSensor => { return mockSensor.removeConfigurationCalled(); }); - - return testPromise; -}, 'Test that frequency is capped to the maximum supported from frequency.'); - -sensor_test(sensor => { - let ambientLightSensor = new AmbientLightSensor({frequency: 60}); - ambientLightSensor.start(); - let testPromise = sensor.mockSensorProvider.getCreatedSensor() - .then((mockSensor) => { - return new Promise((resolve, reject) => { - let wrapper = new CallbackWrapper(() => { - assert_equals(ambientLightSensor.state, 'active'); - ambientLightSensor.stop(); - assert_equals(ambientLightSensor.state, 'idle'); - resolve(mockSensor); - }, reject); - - ambientLightSensor.onactivate = wrapper.callback; - ambientLightSensor.onerror = reject; - }); - }) - .then(mockSensor => { return mockSensor.removeConfigurationCalled(); }); - - return testPromise; -}, 'Test that sensor can be successfully created if sensor is supported.'); - -sensor_test(sensor => { - let ambientLightSensor = new AmbientLightSensor(); - ambientLightSensor.start(); - let testPromise = sensor.mockSensorProvider.getCreatedSensor() - .then((mockSensor) => { - return new Promise((resolve, reject) => { - let wrapper = new CallbackWrapper(() => { - assert_equals(ambientLightSensor.state, 'active'); - ambientLightSensor.stop(); - assert_equals(ambientLightSensor.state, 'idle'); - resolve(mockSensor); - }, reject); - - ambientLightSensor.onactivate = wrapper.callback; - ambientLightSensor.onerror = reject; - }); - }) - .then(mockSensor => { return mockSensor.removeConfigurationCalled(); }); - - return testPromise; -}, 'Test that sensor can be constructed with default configuration.'); - -sensor_test(sensor => { - let ambientLightSensor = new AmbientLightSensor({frequency: 60}); - ambientLightSensor.start(); - - let testPromise = sensor.mockSensorProvider.getCreatedSensor() - .then(mockSensor => { return mockSensor.addConfigurationCalled(); }) - .then(mockSensor => { - return new Promise((resolve, reject) => { - let wrapper = new CallbackWrapper(() => { - assert_equals(ambientLightSensor.state, 'active'); - ambientLightSensor.stop(); - assert_equals(ambientLightSensor.state, 'idle'); - resolve(mockSensor); - }, reject); - - ambientLightSensor.onactivate = wrapper.callback; - ambientLightSensor.onerror = reject; - }); - }) - .then(mockSensor => { return mockSensor.removeConfigurationCalled(); }); - - return testPromise; -}, 'Test that addConfiguration and removeConfiguration is called.'); - -sensor_test(sensor => { - let ambientLightSensor = new AmbientLightSensor({frequency: 60}); - ambientLightSensor.start(); - let testPromise = sensor.mockSensorProvider.getCreatedSensor() - .then(mockSensor => { - return mockSensor.setUpdateSensorReadingFunction(update_sensor_reading); - }) - .then((mockSensor) => { - return new Promise((resolve, reject) => { - let wrapper = new CallbackWrapper(() => { - assert_equals(ambientLightSensor.reading.illuminance, - kDefaultReadingValue); - ambientLightSensor.stop(); - assert_equals(ambientLightSensor.reading, null); - resolve(mockSensor); - }, reject); - - ambientLightSensor.onchange = wrapper.callback; - ambientLightSensor.onerror = reject; - }); - }) - .then(mockSensor => { return mockSensor.removeConfigurationCalled(); }); - - return testPromise; -}, 'Test that onChange is called and sensor reading is valid.'); - -sensor_test(sensor => { - let ambientLightSensor = new AmbientLightSensor(); - ambientLightSensor.start(); - let testPromise = sensor.mockSensorProvider.getCreatedSensor() - .then(mockSensor => { - return mockSensor.setUpdateSensorReadingFunction(update_sensor_reading); - }) - .then((mockSensor) => { - return new Promise((resolve, reject) => { - ambientLightSensor.onchange = () => { - if (ambientLightSensor.reading.illuminance - == kDefaultReadingValue) { - resolve(mockSensor); - } - } - ambientLightSensor.onerror = reject; - }); - }) - .then((mockSensor) => { - testRunner.setPageVisibility("hidden"); - return mockSensor.suspendCalled(); - }) - .then((mockSensor) => { - testRunner.setPageVisibility("visible"); - return mockSensor.resumeCalled(); - }) - .then((mockSensor) => { - return new Promise((resolve, reject) => { - ambientLightSensor.stop(); - resolve(mockSensor); - ambientLightSensor.onerror = reject; - }); - }) - .then(mockSensor => { return mockSensor.removeConfigurationCalled(); }); - - return testPromise; -}, 'Test that sensor receives suspend / resume notifications when page' - +' visibility changes.'); - -sensor_test(sensor => { - let sensor1 = new AmbientLightSensor({frequency: 60}); - sensor1.start(); - - let sensor2 = new AmbientLightSensor({frequency: 20}); - sensor2.start(); - let testPromise = sensor.mockSensorProvider.getCreatedSensor() - .then(mockSensor => { - return mockSensor.setUpdateSensorReadingFunction(update_sensor_reading); - }) - .then((mockSensor) => { - return new Promise((resolve, reject) => { - let wrapper = new CallbackWrapper(() => { - // Reading value is correct. - assert_equals(sensor1.reading.illuminance, kDefaultReadingValue); - - // Both sensors share the same reading instance. - let reading = sensor1.reading; - assert_equals(reading, sensor2.reading); - - // After first sensor stops its reading is null, reading for second - // sensor sensor remains. - sensor1.stop(); - assert_equals(sensor1.reading, null); - assert_equals(sensor2.reading.illuminance, kDefaultReadingValue); - - sensor2.stop(); - assert_equals(sensor2.reading, null); - - // Cached reading remains. - assert_equals(reading.illuminance, kDefaultReadingValue); - resolve(mockSensor); - }, reject); - - sensor1.onchange = wrapper.callback; - sensor1.onerror = reject; - sensor2.onerror = reject; - }); - }) - .then(mockSensor => { return mockSensor.removeConfigurationCalled(); }); - - return testPromise; -}, 'Test that sensor reading is correct.'); - +runGenericSensorTests(AmbientLightSensor, update_sensor_reading, verify_sensor_reading); </script>
diff --git a/third_party/WebKit/LayoutTests/sensor/resources/generic-sensor-tests.js b/third_party/WebKit/LayoutTests/sensor/resources/generic-sensor-tests.js new file mode 100644 index 0000000..13de6272 --- /dev/null +++ b/third_party/WebKit/LayoutTests/sensor/resources/generic-sensor-tests.js
@@ -0,0 +1,270 @@ +'use strict'; + +// Run a set of tests for a given |sensorType|. |updateReading| is +// a called by the test to provide the mock values for sensor. |verifyReading| +// is called so that the value read in JavaScript are the values expected (the ones +// sent by |updateReading|). +function runGenericSensorTests(sensorType, updateReading, verifyReading) { + test(() => assert_throws( + new RangeError(), + () => new sensorType({frequency: -60})), + 'Test that negative frequency causes exception from constructor.'); + + sensor_test(sensor => { + sensor.mockSensorProvider.setGetSensorShouldFail(true); + let sensorObject = new sensorType; + sensorObject.start(); + return new Promise((resolve, reject) => { + let wrapper = new CallbackWrapper(event => { + assert_equals(sensorObject.state, 'errored'); + console.log(event.error.message); + assert_equals(event.error.name, 'NotFoundError'); + sensorObject.onerror = null; + resolve(); + }, reject); + + sensorObject.onerror = wrapper.callback; + }); + }, 'Test that "onerror" is send when sensor is not supported.'); + + sensor_test(sensor => { + let sensorObject = new sensorType({frequency: 560}); + sensorObject.start(); + + let testPromise = sensor.mockSensorProvider.getCreatedSensor() + .then(mockSensor => { + mockSensor.setStartShouldFail(true); + return mockSensor.addConfigurationCalled(); }) + .then(mockSensor => { + return new Promise((resolve, reject) => { + let wrapper = new CallbackWrapper(event => { + assert_equals(sensorObject.state, 'errored'); + assert_equals(event.error.name, 'OperationError'); + sensorObject.onerror = null; + resolve(); + }, reject); + + sensorObject.onerror = wrapper.callback; + }); + }); + return testPromise; + }, 'Test that "onerror" is send when start() call has failed.'); + + sensor_test(sensor => { + let sensorObject = new sensorType({frequency: 560}); + sensorObject.start(); + + let testPromise = sensor.mockSensorProvider.getCreatedSensor() + .then(mockSensor => { return mockSensor.addConfigurationCalled(); }) + .then(mockSensor => { + return new Promise((resolve, reject) => { + let wrapper = new CallbackWrapper(() => { + let configuration = mockSensor.active_sensor_configurations_[0]; + assert_equals(configuration.frequency, 60); + sensorObject.stop(); + assert_equals(sensorObject.state, 'idle'); + resolve(mockSensor); + }, reject); + sensorObject.onactivate = wrapper.callback; + sensorObject.onerror = reject; + }); + }) + .then(mockSensor => { return mockSensor.removeConfigurationCalled(); }); + return testPromise; + }, 'Test that frequency is capped to 60.0 Hz.'); + + sensor_test(sensor => { + let maxSupportedFrequency = 15; + sensor.mockSensorProvider.setMaximumSupportedFrequency(maxSupportedFrequency); + let sensorObject = new sensorType({frequency: 50}); + sensorObject.start(); + let testPromise = sensor.mockSensorProvider.getCreatedSensor() + .then(mockSensor => { return mockSensor.addConfigurationCalled(); }) + .then(mockSensor => { + return new Promise((resolve, reject) => { + let wrapper = new CallbackWrapper(() => { + let configuration = mockSensor.active_sensor_configurations_[0]; + assert_equals(configuration.frequency, maxSupportedFrequency); + sensorObject.stop(); + assert_equals(sensorObject.state, 'idle'); + resolve(mockSensor); + }, reject); + sensorObject.onactivate = wrapper.callback; + sensorObject.onerror = reject; + }); + }) + .then(mockSensor => { return mockSensor.removeConfigurationCalled(); }); + return testPromise; + }, 'Test that frequency is capped to the maximum supported from frequency.'); + + sensor_test(sensor => { + let sensorObject = new sensorType({frequency: 60}); + sensorObject.start(); + let testPromise = sensor.mockSensorProvider.getCreatedSensor() + .then((mockSensor) => { + return new Promise((resolve, reject) => { + let wrapper = new CallbackWrapper(() => { + assert_equals(sensorObject.state, 'active'); + sensorObject.stop(); + assert_equals(sensorObject.state, 'idle'); + resolve(mockSensor); + }, reject); + sensorObject.onactivate = wrapper.callback; + sensorObject.onerror = reject; + }); + }) + .then(mockSensor => { return mockSensor.removeConfigurationCalled(); }); + return testPromise; + }, 'Test that sensor can be successfully created if sensor is supported.'); + + sensor_test(sensor => { + let sensorObject = new sensorType(); + sensorObject.start(); + let testPromise = sensor.mockSensorProvider.getCreatedSensor() + .then((mockSensor) => { + return new Promise((resolve, reject) => { + let wrapper = new CallbackWrapper(() => { + assert_equals(sensorObject.state, 'active'); + sensorObject.stop(); + assert_equals(sensorObject.state, 'idle'); + resolve(mockSensor); + }, reject); + + sensorObject.onactivate = wrapper.callback; + sensorObject.onerror = reject; + }); + }) + .then(mockSensor => { return mockSensor.removeConfigurationCalled(); }); + return testPromise; + }, 'Test that sensor can be constructed with default configuration.'); + + sensor_test(sensor => { + let sensorObject = new sensorType({frequency: 60}); + sensorObject.start(); + + let testPromise = sensor.mockSensorProvider.getCreatedSensor() + .then(mockSensor => { return mockSensor.addConfigurationCalled(); }) + .then(mockSensor => { + return new Promise((resolve, reject) => { + let wrapper = new CallbackWrapper(() => { + assert_equals(sensorObject.state, 'active'); + sensorObject.stop(); + assert_equals(sensorObject.state, 'idle'); + resolve(mockSensor); + }, reject); + sensorObject.onactivate = wrapper.callback; + sensorObject.onerror = reject; + }); + }) + .then(mockSensor => { return mockSensor.removeConfigurationCalled(); }); + + return testPromise; + }, 'Test that addConfiguration and removeConfiguration is called.'); + + sensor_test(sensor => { + let sensorObject = new sensorType({frequency: 60}); + sensorObject.start(); + let testPromise = sensor.mockSensorProvider.getCreatedSensor() + .then(mockSensor => { + return mockSensor.setUpdateSensorReadingFunction(updateReading); + }) + .then((mockSensor) => { + return new Promise((resolve, reject) => { + let wrapper = new CallbackWrapper(() => { + assert_true(verifyReading(sensorObject.reading)); + sensorObject.stop(); + assert_equals(sensorObject.reading, null); + resolve(mockSensor); + }, reject); + + sensorObject.onchange = wrapper.callback; + sensorObject.onerror = reject; + }); + }) + .then(mockSensor => { return mockSensor.removeConfigurationCalled(); }); + + return testPromise; + }, 'Test that onChange is called and sensor reading is valid.'); + + sensor_test(sensor => { + let sensorObject = new sensorType; + sensorObject.start(); + let testPromise = sensor.mockSensorProvider.getCreatedSensor() + .then(mockSensor => { + return mockSensor.setUpdateSensorReadingFunction(updateReading); + }) + .then(mockSensor => { + return new Promise((resolve, reject) => { + sensorObject.onchange = () => { + if (verifyReading(sensorObject.reading)) { + resolve(mockSensor); + } + } + sensorObject.onerror = reject; + }); + }) + .then(mockSensor => { + testRunner.setPageVisibility('hidden'); + return mockSensor.suspendCalled(); + }) + .then(mockSensor => { + testRunner.setPageVisibility('visible'); + return mockSensor.resumeCalled(); + }) + .then(mockSensor => { + return new Promise((resolve, reject) => { + sensorObject.stop(); + resolve(mockSensor); + sensorObject.onerror = reject; + }); + }) + .then(mockSensor => { return mockSensor.removeConfigurationCalled(); }); + + return testPromise; + }, 'Test that sensor receives suspend / resume notifications when page' + + ' visibility changes.'); + +sensor_test(sensor => { + let sensor1 = new sensorType({frequency: 60}); + sensor1.start(); + + let sensor2 = new sensorType({frequency: 20}); + sensor2.start(); + let testPromise = sensor.mockSensorProvider.getCreatedSensor() + .then(mockSensor => { + return mockSensor.setUpdateSensorReadingFunction(update_sensor_reading); + }) + .then((mockSensor) => { + return new Promise((resolve, reject) => { + let wrapper = new CallbackWrapper(() => { + // Reading value is correct. + assert_true(verifyReading(sensor1.reading)); + + // Both sensors share the same reading instance. + let reading = sensor1.reading; + assert_equals(reading, sensor2.reading); + + // After first sensor stops its reading is null, reading for second + // sensor sensor remains. + sensor1.stop(); + assert_equals(sensor1.reading, null); + assert_true(verifyReading(sensor2.reading)); + + sensor2.stop(); + assert_equals(sensor2.reading, null); + + // Cached reading remains. + assert_true(verifyReading(reading)); + resolve(mockSensor); + }, reject); + + sensor1.onchange = wrapper.callback; + sensor1.onerror = reject; + sensor2.onerror = reject; + }); + }) + .then(mockSensor => { return mockSensor.removeConfigurationCalled(); }); + + return testPromise; +}, 'Test that sensor reading is correct.'); +}
diff --git a/third_party/WebKit/LayoutTests/shadow-dom/event-composed-ua.html b/third_party/WebKit/LayoutTests/shadow-dom/event-composed-ua.html index bedaed4..1dc02ac 100644 --- a/third_party/WebKit/LayoutTests/shadow-dom/event-composed-ua.html +++ b/third_party/WebKit/LayoutTests/shadow-dom/event-composed-ua.html
@@ -1,93 +1,72 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> -<script src="resources/shadow-dom.js"></script> -<input id="input"></input> -<div id="sandbox"> - <div id = "host"> - <template> - <input id="target" value="test"></div> - </template> - </div> -</div> +<form> + <input id="input" type="text"> + <input id="input2"> +</form> <script> -var e; -test(function() { - e = new Event('test'); - assert_equals(e.composed, false); -}, 'A new events composed value should be set to false by default.'); - -test(function() { - e = new Event('test', { composed: true }); - assert_equals(e.composed, true); -}, 'Users should be able to set a composed value.'); - -var input = document.getElementById('input'); -async_test(function(t) { - input.onselect = function(e) { - t.step(function() { assert_false(e.composed); t.done(); }); - }; -}, 'UA select events composed should be set to false.'); -input.select(); - -var sandbox = document.getElementById('sandbox'); -convertTemplatesToShadowRootsWithin(sandbox); -var target = getNodeInComposedTree('host/target'); -var host = getNodeInComposedTree('host'); - -async_test(function(t) { - target.onselect = function(e) { - t.step(function() { - assert_true(e.composedPath().includes(target)); - assert_false(e.composedPath().includes(host)); - t.done(); - }); - } -}, 'Select events should stop if created by UA.'); - -async_test(function(t) { - target.onerror = function(e) { - t.step(function() { - assert_true(e.composedPath().includes(target)); - assert_true(e.composedPath().includes(host)); - t.done(); - }); - } -}, 'Only certain trusted events should stop in bubbling.'); - -target.select(); -var userError = new Event('error'); -target.dispatchEvent(userError); - -function doubleClick(x, y) { - eventSender.mouseMoveTo(x, y); - eventSender.mouseDown(); - eventSender.mouseUp(); - eventSender.mouseDown(); - eventSender.mouseUp(); -} +const input = document.querySelector('#input'); +const input2 = document.querySelector('#input2'); function click(x, y) { - eventSender.mouseMoveTo(x, y); - eventSender.mouseDown(); - eventSender.mouseUp(); + window.eventSender.mouseMoveTo(x, y); + window.eventSender.mouseDown(); + window.eventSender.mouseUp(); } -async_test((test) => { - input.addEventListener('dblclick', test.step_func_done((e) => { - assert_true(e.composed); - })); -}, 'A dblclick event should be a composed event'); +function doubleClick(x, y) { + window.eventSender.mouseMoveTo(x, y); + window.eventSender.mouseDown(); + window.eventSender.mouseUp(); + window.eventSender.mouseDown(); + window.eventSender.mouseUp(); +} -doubleClick(input.offsetLeft, input.offsetTop); +const composedEventTypes = [ + // UI Events + 'blur', 'focus', 'focusin', 'focusout', + 'click', 'dblclick', + 'mousedown', 'mouseenter', 'mouseleave', 'mousemove', 'mouseout', 'mouseover', 'mouseup', + 'wheel', + 'beforeinput', 'input', + 'keydown', 'keyup', + 'compositionstart', 'compositionupdate', 'compositionend', + // Legacy UI Events + 'DOMActivate', 'DOMFocusIn', 'DOMFocusOut', 'keypress', +]; -async_test((test) => { - input.addEventListener('DOMActivate', test.step_func_done((e) => { - assert_true(e.composed); - })); -}, 'A DOMActivate event should be a composed event'); +for (const eventType of composedEventTypes) { + async_test((test) => { + input.addEventListener(eventType, test.step_func_done((e) => { + assert_true(e.composed); + })); + }, `A ${eventType} event should be a composed event`); +} click(input.offsetLeft, input.offsetTop); +doubleClick(input.offsetLeft, input.offsetTop); + +// For mouseenter/mouseleave +click(input2.offsetLeft, input2.offsetTop); + +// For focus/blur +input.blur(); +input.focus(); +input.blur(); + +// For keypress +input.focus(); +window.eventSender.keyDown(' '); + +// For wheel +window.eventSender.mouseMoveTo(input.offsetLeft + 5, input.offsetTop + 5); +window.eventSender.mouseScrollBy(-1, -2); + +// For composition +input.focus(); +window.textInputController.setMarkedText('1', 0, 1); +window.textInputController.insertText('1'); </script>
diff --git a/third_party/WebKit/LayoutTests/shadow-dom/event-composed.html b/third_party/WebKit/LayoutTests/shadow-dom/event-composed.html index c212aab..35a175c3 100644 --- a/third_party/WebKit/LayoutTests/shadow-dom/event-composed.html +++ b/third_party/WebKit/LayoutTests/shadow-dom/event-composed.html
@@ -60,20 +60,4 @@ test(() => { assertComposed(new FocusEvent('focus', { bubbles: true, composed: true })); }, 'A synthetic FocusEvent with composed=true should not be scoped'); - -function assertUAComposed(eventType, callback) { - let nodes = createTestTree(host); - let log = dispatchUAEventWithLog(nodes, nodes.target, eventType, callback); - let expectedPath = ['target', 'shadowRoot', 'host']; - assert_event_path_equals(log, - [['target', 'target', null, expectedPath], - ['shadowRoot', 'target', null, expectedPath], - ['host', 'host', null, expectedPath]]); -} - -test(() => { - assertUAComposed('click', (target) => { target.click(); }); -}, 'A UA click event should not be scoped'); - -// TODO(hayato): Test other UIEvents. </script>
diff --git a/third_party/WebKit/LayoutTests/shadow-dom/resources/shadow-dom.js b/third_party/WebKit/LayoutTests/shadow-dom/resources/shadow-dom.js index 9536b61..d64bb7f 100644 --- a/third_party/WebKit/LayoutTests/shadow-dom/resources/shadow-dom.js +++ b/third_party/WebKit/LayoutTests/shadow-dom/resources/shadow-dom.js
@@ -138,39 +138,6 @@ return log; } -// TODO(hayato): Merge this into dispatchEventWithLog -function dispatchUAEventWithLog(nodes, target, eventType, callback) { - - function labelFor(e) { - return e.id || e.tagName; - } - - let log = []; - let attachedNodes = []; - for (let label in nodes) { - let startingNode = nodes[label]; - for (let node = startingNode; node; node = node.parentNode) { - if (attachedNodes.indexOf(node) >= 0) - continue; - let id = node.id; - if (!id) - continue; - attachedNodes.push(node); - node.addEventListener(eventType, (e) => { - // Record [currentTarget, target, relatedTarget, composedPath()] - log.push([id, - labelFor(e.target), - e.relatedTarget ? labelFor(e.relatedTarget) : null, - e.composedPath().map((n) => { - return labelFor(n); - })]); - }); - } - } - callback(target); - return log; -} - function debugEventLog(log) { for (let i = 0; i < log.length; i++) { console.log('[' + i + '] currentTarget: ' + log[i][0] + ' target: ' + log[i][1] + ' relatedTarget: ' + log[i][2] + ' composedPath(): ' + log[i][3]);
diff --git a/third_party/WebKit/LayoutTests/storage/indexeddb/empty-transaction-order.html b/third_party/WebKit/LayoutTests/storage/indexeddb/empty-transaction-order.html deleted file mode 100644 index 1ba2cd3..0000000 --- a/third_party/WebKit/LayoutTests/storage/indexeddb/empty-transaction-order.html +++ /dev/null
@@ -1,74 +0,0 @@ -<!DOCTYPE html> -<title>IndexedDB: Commit ordering of empty transactions</title> -<script src='../../resources/testharness.js'></script> -<script src='../../resources/testharnessreport.js'></script> -<script src='resources/testharness-helpers.js'></script> -<script> - -indexeddb_test( - (t, db) => { - db.createObjectStore('store'); - }, - (t, db) => { - var saw = expect(t, ['rq1.onsuccess', - 'rq2.onsuccess', - 'tx1.oncomplete', - 'tx2.oncomplete']); - - var tx1 = db.transaction('store', 'readwrite'); - tx1.onabort = t.unreached_func('transaction should commit'); - tx1.oncomplete = t.step_func(() => saw('tx1.oncomplete')); - - var store = tx1.objectStore('store'); - var rq1 = store.put('a', 1); - rq1.onerror = t.unreached_func('put should succeed'); - rq1.onsuccess = t.step_func(() => { - saw('rq1.onsuccess'); - - var tx2 = db.transaction('store', 'readonly'); - tx2.onabort = t.unreached_func('transaction should commit'); - tx2.oncomplete = t.step_func(() => saw('tx2.oncomplete')); - - var rq2 = store.put('b', 2); - rq2.onsuccess = t.step_func(() => saw('rq2.onsuccess')); - rq2.onerror = t.unreached_func('request should succeed'); - }); - - }, - 'Transactions without requests complete in the expected order'); - -indexeddb_test( - (t, db) => { - db.createObjectStore('store'); - }, - (t, db) => { - var saw = expect(t, ['rq1.onsuccess', - 'rq2.onsuccess', - 'tx1.oncomplete', - 'tx2.oncomplete', - 'tx3.oncomplete']); - var tx1 = db.transaction('store', 'readwrite'); - tx1.onabort = t.unreached_func('transaction should commit'); - tx1.oncomplete = t.step_func(() => saw('tx1.oncomplete')); - - var store = tx1.objectStore('store'); - var rq1 = store.put('a', 1); - rq1.onerror = t.unreached_func('put should succeed'); - rq1.onsuccess = t.step_func(() => { - saw('rq1.onsuccess'); - - var tx2 = db.transaction('store', 'readonly'); - tx2.onabort = t.unreached_func('transaction should commit'); - tx2.oncomplete = t.step_func(() => saw('tx2.oncomplete')); - - var tx3 = db.transaction('store', 'readonly'); - tx3.onabort = t.unreached_func('transaction should commit'); - tx3.oncomplete = t.step_func(() => saw('tx3.oncomplete')); - - var rq2 = store.put('b', 2); - rq2.onsuccess = t.step_func(() => saw('rq2.onsuccess')); - rq2.onerror = t.unreached_func('request should succeed'); - }); - }, - 'Multiple transactions without requests complete in the expected order'); -</script>
diff --git a/third_party/WebKit/LayoutTests/svg/dom/SVGViewElement-viewTarget-expected.txt b/third_party/WebKit/LayoutTests/svg/dom/SVGViewElement-viewTarget-expected.txt deleted file mode 100644 index f699c01..0000000 --- a/third_party/WebKit/LayoutTests/svg/dom/SVGViewElement-viewTarget-expected.txt +++ /dev/null
@@ -1,5 +0,0 @@ -CONSOLE WARNING: line 10: SVGViewElement.viewTarget is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5665473114931200 for more details. -This is a testharness.js-based test. -PASS view.viewTarget should throw deprecation warning -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/svg/dom/SVGViewElement-viewTarget.html b/third_party/WebKit/LayoutTests/svg/dom/SVGViewElement-viewTarget.html deleted file mode 100644 index 44d190bd..0000000 --- a/third_party/WebKit/LayoutTests/svg/dom/SVGViewElement-viewTarget.html +++ /dev/null
@@ -1,12 +0,0 @@ -<!DOCTYPE html> -<script src="../../resources/testharness.js"></script> -<script src="../../resources/testharnessreport.js"></script> -<svg> - <view></view> -</svg> -<script> -test(function () { - var view = document.querySelector("view"); - view.viewTarget; -}, "view.viewTarget should throw deprecation warning"); -</script>
diff --git a/third_party/WebKit/LayoutTests/virtual/stable/webexposed/element-instance-property-listing-expected.txt b/third_party/WebKit/LayoutTests/virtual/stable/webexposed/element-instance-property-listing-expected.txt index fec7291..75d32d5a 100644 --- a/third_party/WebKit/LayoutTests/virtual/stable/webexposed/element-instance-property-listing-expected.txt +++ b/third_party/WebKit/LayoutTests/virtual/stable/webexposed/element-instance-property-listing-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 18: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 18: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. This test documents all properties on all element instances. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-expected.txt b/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-expected.txt index 763d080..9f18f70 100644 --- a/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-expected.txt +++ b/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-expected.txt
@@ -5229,7 +5229,6 @@ attribute SVG_ZOOMANDPAN_UNKNOWN getter preserveAspectRatio getter viewBox - getter viewTarget getter zoomAndPan method constructor setter zoomAndPan
diff --git a/third_party/WebKit/LayoutTests/webexposed/element-instance-property-listing-expected.txt b/third_party/WebKit/LayoutTests/webexposed/element-instance-property-listing-expected.txt index d8a86aad..97890cca1 100644 --- a/third_party/WebKit/LayoutTests/webexposed/element-instance-property-listing-expected.txt +++ b/third_party/WebKit/LayoutTests/webexposed/element-instance-property-listing-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE WARNING: line 18: The <keygen> element is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. +CONSOLE WARNING: line 18: The <keygen> element is deprecated and will be removed in M57, around March 2017. See https://www.chromestatus.com/features/5716060992962560 for more details. This test documents all properties on all element instances. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt index 1730477..9bca8fc 100644 --- a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt +++ b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt
@@ -6050,7 +6050,6 @@ attribute SVG_ZOOMANDPAN_UNKNOWN getter preserveAspectRatio getter viewBox - getter viewTarget getter zoomAndPan method constructor setter zoomAndPan
diff --git a/third_party/WebKit/Source/bindings/core/v8/RejectedPromises.cpp b/third_party/WebKit/Source/bindings/core/v8/RejectedPromises.cpp index f330db5..df79a05 100644 --- a/third_party/WebKit/Source/bindings/core/v8/RejectedPromises.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/RejectedPromises.cpp
@@ -226,7 +226,7 @@ std::unique_ptr<RejectedPromises::MessageQueue> RejectedPromises::createMessageQueue() { - return wrapUnique(new MessageQueue()); + return makeUnique<MessageQueue>(); } void RejectedPromises::dispose() {
diff --git a/third_party/WebKit/Source/bindings/core/v8/ScriptValueSerializer.cpp b/third_party/WebKit/Source/bindings/core/v8/ScriptValueSerializer.cpp index 379ef8f1..d34cebb 100644 --- a/third_party/WebKit/Source/bindings/core/v8/ScriptValueSerializer.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/ScriptValueSerializer.cpp
@@ -1329,7 +1329,7 @@ next); m_writer.writeTransferredOffscreenCanvas( offscreenCanvas->width(), offscreenCanvas->height(), - offscreenCanvas->getAssociatedCanvasId(), offscreenCanvas->clientId(), + offscreenCanvas->placeholderCanvasId(), offscreenCanvas->clientId(), offscreenCanvas->sinkId(), offscreenCanvas->localId(), offscreenCanvas->nonceHigh(), offscreenCanvas->nonceLow()); return nullptr; @@ -2600,7 +2600,7 @@ uint64_t nonceLow, v8::Local<v8::Value>* object) { OffscreenCanvas* offscreenCanvas = OffscreenCanvas::create(width, height); - offscreenCanvas->setAssociatedCanvasId(canvasId); + offscreenCanvas->setPlaceholderCanvasId(canvasId); offscreenCanvas->setSurfaceId(clientId, sinkId, localId, nonceHigh, nonceLow); *object = toV8(offscreenCanvas, m_reader.getScriptState()); if ((*object).IsEmpty())
diff --git a/third_party/WebKit/Source/bindings/core/v8/ScriptWrappableVisitorTest.cpp b/third_party/WebKit/Source/bindings/core/v8/ScriptWrappableVisitorTest.cpp index 87d9771..7cd229e 100644 --- a/third_party/WebKit/Source/bindings/core/v8/ScriptWrappableVisitorTest.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/ScriptWrappableVisitorTest.cpp
@@ -317,7 +317,9 @@ virtual void markWrapper(const v8::PersistentBase<v8::Value>* handle) const { *m_markedWrappers += 1; - ScriptWrappableVisitor::markWrapper(handle); + // Do not actually mark this visitor, as this would call into v8, which + // would + // require executing an actual GC. } size_t numberOfMarkedWrappers() const { return *m_markedWrappers; }
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8Initializer.cpp b/third_party/WebKit/Source/bindings/core/v8/V8Initializer.cpp index f0b2d9fe..a8199a17 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8Initializer.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/V8Initializer.cpp
@@ -407,8 +407,8 @@ if (RuntimeEnabledFeatures::v8IdleTasksEnabled()) { WebScheduler* scheduler = Platform::current()->currentThread()->scheduler(); - V8PerIsolateData::enableIdleTasks( - isolate, wrapUnique(new V8IdleTaskRunner(scheduler))); + V8PerIsolateData::enableIdleTasks(isolate, + makeUnique<V8IdleTaskRunner>(scheduler)); } isolate->SetPromiseRejectCallback(promiseRejectHandlerInMainThread); @@ -419,7 +419,7 @@ ASSERT(ThreadState::mainThreadState()); ThreadState::mainThreadState()->addInterruptor( - wrapUnique(new V8IsolateInterruptor(isolate))); + makeUnique<V8IsolateInterruptor>(isolate)); if (RuntimeEnabledFeatures::traceWrappablesEnabled()) { ThreadState::mainThreadState()->registerTraceDOMWrappers( isolate, V8GCController::traceDOMWrappers, @@ -431,7 +431,7 @@ } V8PerIsolateData::from(isolate)->setThreadDebugger( - wrapUnique(new MainThreadDebugger(isolate))); + makeUnique<MainThreadDebugger>(isolate)); } void V8Initializer::shutdownMainThread() {
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8PerContextData.cpp b/third_party/WebKit/Source/bindings/core/v8/V8PerContextData.cpp index 98f75afe..5fcbae5 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8PerContextData.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/V8PerContextData.cpp
@@ -46,7 +46,7 @@ : m_isolate(context->GetIsolate()), m_wrapperBoilerplates(m_isolate), m_constructorMap(m_isolate), - m_contextHolder(wrapUnique(new gin::ContextHolder(m_isolate))), + m_contextHolder(makeUnique<gin::ContextHolder>(m_isolate)), m_context(m_isolate, context), m_activityLogger(0), m_compiledPrivateScript(m_isolate) {
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8PerIsolateData.cpp b/third_party/WebKit/Source/bindings/core/v8/V8PerIsolateData.cpp index 323a630..dd91e90 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8PerIsolateData.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/V8PerIsolateData.cpp
@@ -56,7 +56,7 @@ } V8PerIsolateData::V8PerIsolateData() - : m_isolateHolder(wrapUnique(new gin::IsolateHolder())), + : m_isolateHolder(makeUnique<gin::IsolateHolder>()), m_stringCache(wrapUnique(new StringCache(isolate()))), m_hiddenValue(V8HiddenValue::create()), m_privateProperty(V8PrivateProperty::create()),
diff --git a/third_party/WebKit/Source/bindings/core/v8/serialization/V8ScriptValueDeserializer.cpp b/third_party/WebKit/Source/bindings/core/v8/serialization/V8ScriptValueDeserializer.cpp index 62c4020..7283ab2 100644 --- a/third_party/WebKit/Source/bindings/core/v8/serialization/V8ScriptValueDeserializer.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/serialization/V8ScriptValueDeserializer.cpp
@@ -243,7 +243,7 @@ !readUint64(&nonceHigh) || !readUint64(&nonceLow)) return nullptr; OffscreenCanvas* canvas = OffscreenCanvas::create(width, height); - canvas->setAssociatedCanvasId(canvasId); + canvas->setPlaceholderCanvasId(canvasId); canvas->setSurfaceId(clientId, sinkId, localId, nonceHigh, nonceLow); return canvas; }
diff --git a/third_party/WebKit/Source/bindings/core/v8/serialization/V8ScriptValueSerializer.cpp b/third_party/WebKit/Source/bindings/core/v8/serialization/V8ScriptValueSerializer.cpp index 9c45b714..aa54737138 100644 --- a/third_party/WebKit/Source/bindings/core/v8/serialization/V8ScriptValueSerializer.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/serialization/V8ScriptValueSerializer.cpp
@@ -278,7 +278,7 @@ writeTag(OffscreenCanvasTransferTag); writeUint32(canvas->width()); writeUint32(canvas->height()); - writeUint32(canvas->getAssociatedCanvasId()); + writeUint32(canvas->placeholderCanvasId()); writeUint32(canvas->clientId()); writeUint32(canvas->sinkId()); writeUint32(canvas->localId());
diff --git a/third_party/WebKit/Source/bindings/core/v8/serialization/V8ScriptValueSerializerTest.cpp b/third_party/WebKit/Source/bindings/core/v8/serialization/V8ScriptValueSerializerTest.cpp index 1fb262c..56ab63e 100644 --- a/third_party/WebKit/Source/bindings/core/v8/serialization/V8ScriptValueSerializerTest.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/serialization/V8ScriptValueSerializerTest.cpp
@@ -515,7 +515,7 @@ ScopedEnableV8BasedStructuredClone enable; V8TestingScope scope; OffscreenCanvas* canvas = OffscreenCanvas::create(10, 7); - canvas->setAssociatedCanvasId(519); + canvas->setPlaceholderCanvasId(519); v8::Local<v8::Value> wrapper = toV8(canvas, scope.getScriptState()); Transferables transferables; transferables.offscreenCanvases.append(canvas); @@ -525,7 +525,7 @@ OffscreenCanvas* newCanvas = V8OffscreenCanvas::toImpl(result.As<v8::Object>()); EXPECT_EQ(IntSize(10, 7), newCanvas->size()); - EXPECT_EQ(519, newCanvas->getAssociatedCanvasId()); + EXPECT_EQ(519, newCanvas->placeholderCanvasId()); EXPECT_TRUE(canvas->isNeutered()); EXPECT_FALSE(newCanvas->isNeutered()); }
diff --git a/third_party/WebKit/Source/bindings/modules/v8/serialization/V8ScriptValueSerializerForModulesTest.cpp b/third_party/WebKit/Source/bindings/modules/v8/serialization/V8ScriptValueSerializerForModulesTest.cpp index 92feb387..eb01435d 100644 --- a/third_party/WebKit/Source/bindings/modules/v8/serialization/V8ScriptValueSerializerForModulesTest.cpp +++ b/third_party/WebKit/Source/bindings/modules/v8/serialization/V8ScriptValueSerializerForModulesTest.cpp
@@ -427,8 +427,8 @@ // Check that one can decrypt data encrypted with the other. Vector<unsigned char> iv(16, 0); - WebCryptoAlgorithm encryptAlgorithm( - WebCryptoAlgorithmIdAesCbc, wrapUnique(new WebCryptoAesCbcParams(iv))); + WebCryptoAlgorithm encryptAlgorithm(WebCryptoAlgorithmIdAesCbc, + makeUnique<WebCryptoAesCbcParams>(iv)); Vector<unsigned char> plaintext{1, 2, 3}; WebVector<uint8_t> ciphertext = syncEncrypt(scriptState, encryptAlgorithm, key->key(), plaintext); @@ -459,8 +459,8 @@ Vector<uint8_t> iv(16, 0); Vector<uint8_t> ciphertext{0x33, 0x26, 0xe7, 0x64, 0x11, 0x5e, 0xf4, 0x60, 0x96, 0x08, 0x11, 0xaf, 0x65, 0x8b, 0x87, 0x04}; - WebCryptoAlgorithm encryptAlgorithm( - WebCryptoAlgorithmIdAesCbc, wrapUnique(new WebCryptoAesCbcParams(iv))); + WebCryptoAlgorithm encryptAlgorithm(WebCryptoAlgorithmIdAesCbc, + makeUnique<WebCryptoAesCbcParams>(iv)); WebVector<uint8_t> plaintext = syncDecrypt(scriptState, encryptAlgorithm, newKey->key(), ciphertext); EXPECT_THAT(plaintext, ElementsAre(1, 2, 3)); @@ -577,7 +577,7 @@ // Check that one can verify a message signed by the other. Vector<uint8_t> message{1, 2, 3}; WebCryptoAlgorithm algorithm(WebCryptoAlgorithmIdRsaPss, - wrapUnique(new WebCryptoRsaPssParams(16))); + makeUnique<WebCryptoRsaPssParams>(16)); WebVector<uint8_t> signature = syncSign(scriptState, algorithm, newPrivateKey->key(), message); EXPECT_TRUE(syncVerifySignature(scriptState, algorithm, publicKey->key(), @@ -629,7 +629,7 @@ 0xeb, 0x17, 0x68, 0x1f, 0xbd, 0xfa, 0xf7, 0xd6, 0x1f, 0xa4, 0x7c, 0x9e, 0x9e, 0xb1, 0x96, 0x8f, 0xe6, 0x5e, 0x89, 0x99}; WebCryptoAlgorithm algorithm(WebCryptoAlgorithmIdRsaPss, - wrapUnique(new WebCryptoRsaPssParams(16))); + makeUnique<WebCryptoRsaPssParams>(16)); EXPECT_TRUE(syncVerifySignature(scriptState, algorithm, newPublicKey->key(), signature, message)); } @@ -671,7 +671,7 @@ WebCryptoAlgorithm hash(WebCryptoAlgorithmIdSha256, nullptr); Vector<uint8_t> message{1, 2, 3}; WebCryptoAlgorithm algorithm(WebCryptoAlgorithmIdEcdsa, - wrapUnique(new WebCryptoEcdsaParams(hash))); + makeUnique<WebCryptoEcdsaParams>(hash)); WebVector<uint8_t> signature = syncSign(scriptState, algorithm, newPrivateKey->key(), message); EXPECT_TRUE(syncVerifySignature(scriptState, algorithm, publicKey->key(), @@ -713,7 +713,7 @@ 0x83, 0x27, 0x37, 0x69, 0x4d, 0x32, 0x63, 0x1e, 0x82}; WebCryptoAlgorithm hash(WebCryptoAlgorithmIdSha256, nullptr); WebCryptoAlgorithm algorithm(WebCryptoAlgorithmIdEcdsa, - wrapUnique(new WebCryptoEcdsaParams(hash))); + makeUnique<WebCryptoEcdsaParams>(hash)); EXPECT_TRUE(syncVerifySignature(scriptState, algorithm, newPublicKey->key(), signature, message)); }
diff --git a/third_party/WebKit/Source/config.gni b/third_party/WebKit/Source/config.gni index b291c35..8aab3e0 100644 --- a/third_party/WebKit/Source/config.gni +++ b/third_party/WebKit/Source/config.gni
@@ -3,6 +3,7 @@ # found in the LICENSE file. import("//build/config/ui.gni") +import("//third_party/WebKit/public/public_features.gni") if (is_android) { import("//build/config/android/config.gni") @@ -67,6 +68,9 @@ } if (use_default_render_theme) { + # Mirrors the USE_DEFAULT_RENDER_THEME buildflag_header in WebKit/public. + # If/when Blink can use buildflag headers, this should be removed in + # preference to that. feature_defines_list += [ "WTF_USE_DEFAULT_RENDER_THEME=1" ] } if (blink_logging_always_on) {
diff --git a/third_party/WebKit/Source/core/BUILD.gn b/third_party/WebKit/Source/core/BUILD.gn index f3441dc..8f8a41e2 100644 --- a/third_party/WebKit/Source/core/BUILD.gn +++ b/third_party/WebKit/Source/core/BUILD.gn
@@ -1179,6 +1179,7 @@ "html/HTMLImageElementTest.cpp", "html/HTMLInputElementTest.cpp", "html/HTMLLinkElementSizesAttributeTest.cpp", + "html/HTMLMediaElementTest.cpp", "html/HTMLOutputElementTest.cpp", "html/HTMLSelectElementTest.cpp", "html/HTMLTableRowElementTest.cpp", @@ -1287,7 +1288,6 @@ "paint/SVGInlineTextBoxPainterTest.cpp", "paint/StubChromeClientForSPv2.h", "paint/TableCellPainterTest.cpp", - "paint/TablePainterTest.cpp", "paint/TextPainterTest.cpp", "paint/VideoPainterTest.cpp", "streams/ReadableStreamOperationsTest.cpp",
diff --git a/third_party/WebKit/Source/core/animation/PropertyInterpolationTypesMapping.cpp b/third_party/WebKit/Source/core/animation/PropertyInterpolationTypesMapping.cpp index 9599874..b860c78 100644 --- a/third_party/WebKit/Source/core/animation/PropertyInterpolationTypesMapping.cpp +++ b/third_party/WebKit/Source/core/animation/PropertyInterpolationTypesMapping.cpp
@@ -64,7 +64,7 @@ return *entry->value.get(); std::unique_ptr<InterpolationTypes> applicableTypes = - wrapUnique(new InterpolationTypes()); + makeUnique<InterpolationTypes>(); if (property.isCSSProperty() || property.isPresentationAttribute()) { CSSPropertyID cssProperty = property.isCSSProperty() @@ -127,7 +127,7 @@ case CSSPropertyX: case CSSPropertyY: applicableTypes->append( - wrapUnique(new CSSLengthInterpolationType(usedProperty))); + makeUnique<CSSLengthInterpolationType>(usedProperty)); break; case CSSPropertyFlexGrow: case CSSPropertyFlexShrink: @@ -144,13 +144,13 @@ case CSSPropertyWidows: case CSSPropertyZIndex: applicableTypes->append( - wrapUnique(new CSSNumberInterpolationType(usedProperty))); + makeUnique<CSSNumberInterpolationType>(usedProperty)); break; case CSSPropertyLineHeight: applicableTypes->append( - wrapUnique(new CSSLengthInterpolationType(usedProperty))); + makeUnique<CSSLengthInterpolationType>(usedProperty)); applicableTypes->append( - wrapUnique(new CSSNumberInterpolationType(usedProperty))); + makeUnique<CSSNumberInterpolationType>(usedProperty)); break; case CSSPropertyBackgroundColor: case CSSPropertyBorderBottomColor: @@ -166,86 +166,86 @@ case CSSPropertyColumnRuleColor: case CSSPropertyWebkitTextStrokeColor: applicableTypes->append( - wrapUnique(new CSSColorInterpolationType(usedProperty))); + makeUnique<CSSColorInterpolationType>(usedProperty)); break; case CSSPropertyFill: case CSSPropertyStroke: applicableTypes->append( - wrapUnique(new CSSPaintInterpolationType(usedProperty))); + makeUnique<CSSPaintInterpolationType>(usedProperty)); break; case CSSPropertyD: applicableTypes->append( - wrapUnique(new CSSPathInterpolationType(usedProperty))); + makeUnique<CSSPathInterpolationType>(usedProperty)); break; case CSSPropertyBoxShadow: case CSSPropertyTextShadow: applicableTypes->append( - wrapUnique(new CSSShadowListInterpolationType(usedProperty))); + makeUnique<CSSShadowListInterpolationType>(usedProperty)); break; case CSSPropertyBorderImageSource: case CSSPropertyListStyleImage: case CSSPropertyWebkitMaskBoxImageSource: applicableTypes->append( - wrapUnique(new CSSImageInterpolationType(usedProperty))); + makeUnique<CSSImageInterpolationType>(usedProperty)); break; case CSSPropertyBackgroundImage: case CSSPropertyWebkitMaskImage: applicableTypes->append( - wrapUnique(new CSSImageListInterpolationType(usedProperty))); + makeUnique<CSSImageListInterpolationType>(usedProperty)); break; case CSSPropertyStrokeDasharray: applicableTypes->append( - wrapUnique(new CSSLengthListInterpolationType(usedProperty))); + makeUnique<CSSLengthListInterpolationType>(usedProperty)); break; case CSSPropertyFontWeight: applicableTypes->append( - wrapUnique(new CSSFontWeightInterpolationType(usedProperty))); + makeUnique<CSSFontWeightInterpolationType>(usedProperty)); break; case CSSPropertyVisibility: applicableTypes->append( - wrapUnique(new CSSVisibilityInterpolationType(usedProperty))); + makeUnique<CSSVisibilityInterpolationType>(usedProperty)); break; case CSSPropertyClip: applicableTypes->append( - wrapUnique(new CSSClipInterpolationType(usedProperty))); + makeUnique<CSSClipInterpolationType>(usedProperty)); break; case CSSPropertyOffsetRotation: applicableTypes->append( - wrapUnique(new CSSOffsetRotationInterpolationType(usedProperty))); + makeUnique<CSSOffsetRotationInterpolationType>(usedProperty)); break; case CSSPropertyBackgroundPositionX: case CSSPropertyBackgroundPositionY: case CSSPropertyWebkitMaskPositionX: case CSSPropertyWebkitMaskPositionY: applicableTypes->append( - wrapUnique(new CSSPositionAxisListInterpolationType(usedProperty))); + makeUnique<CSSPositionAxisListInterpolationType>(usedProperty)); break; case CSSPropertyObjectPosition: case CSSPropertyOffsetAnchor: case CSSPropertyOffsetPosition: case CSSPropertyPerspectiveOrigin: applicableTypes->append( - wrapUnique(new CSSPositionInterpolationType(usedProperty))); + makeUnique<CSSPositionInterpolationType>(usedProperty)); break; case CSSPropertyBorderBottomLeftRadius: case CSSPropertyBorderBottomRightRadius: case CSSPropertyBorderTopLeftRadius: case CSSPropertyBorderTopRightRadius: applicableTypes->append( - wrapUnique(new CSSLengthPairInterpolationType(usedProperty))); + makeUnique<CSSLengthPairInterpolationType>(usedProperty)); break; case CSSPropertyTranslate: applicableTypes->append( - wrapUnique(new CSSTranslateInterpolationType(usedProperty))); + makeUnique<CSSTranslateInterpolationType>(usedProperty)); break; case CSSPropertyTransformOrigin: applicableTypes->append( - wrapUnique(new CSSTransformOriginInterpolationType(usedProperty))); + makeUnique<CSSTransformOriginInterpolationType>(usedProperty)); break; case CSSPropertyBackgroundSize: case CSSPropertyWebkitMaskSize: applicableTypes->append( - wrapUnique(new CSSSizeListInterpolationType(usedProperty))); + makeUnique<CSSSizeListInterpolationType>(usedProperty)); break; case CSSPropertyBorderImageOutset: case CSSPropertyBorderImageWidth: @@ -256,56 +256,55 @@ break; case CSSPropertyScale: applicableTypes->append( - wrapUnique(new CSSScaleInterpolationType(usedProperty))); + makeUnique<CSSScaleInterpolationType>(usedProperty)); break; case CSSPropertyFontSize: applicableTypes->append( - wrapUnique(new CSSFontSizeInterpolationType(usedProperty))); + makeUnique<CSSFontSizeInterpolationType>(usedProperty)); break; case CSSPropertyTextIndent: applicableTypes->append( - wrapUnique(new CSSTextIndentInterpolationType(usedProperty))); + makeUnique<CSSTextIndentInterpolationType>(usedProperty)); break; case CSSPropertyBorderImageSlice: case CSSPropertyWebkitMaskBoxImageSlice: applicableTypes->append( - wrapUnique(new CSSImageSliceInterpolationType(usedProperty))); + makeUnique<CSSImageSliceInterpolationType>(usedProperty)); break; case CSSPropertyClipPath: case CSSPropertyShapeOutside: applicableTypes->append( - wrapUnique(new CSSBasicShapeInterpolationType(usedProperty))); + makeUnique<CSSBasicShapeInterpolationType>(usedProperty)); break; case CSSPropertyRotate: applicableTypes->append( - wrapUnique(new CSSRotateInterpolationType(usedProperty))); + makeUnique<CSSRotateInterpolationType>(usedProperty)); break; case CSSPropertyBackdropFilter: case CSSPropertyFilter: applicableTypes->append( - wrapUnique(new CSSFilterListInterpolationType(usedProperty))); + makeUnique<CSSFilterListInterpolationType>(usedProperty)); break; case CSSPropertyTransform: applicableTypes->append( - wrapUnique(new CSSTransformInterpolationType(usedProperty))); + makeUnique<CSSTransformInterpolationType>(usedProperty)); break; default: DCHECK(!CSSPropertyMetadata::isInterpolableProperty(cssProperty)); } applicableTypes->append( - wrapUnique(new CSSValueInterpolationType(usedProperty))); + makeUnique<CSSValueInterpolationType>(usedProperty)); } else { const QualifiedName& attribute = property.svgAttribute(); if (attribute == SVGNames::orientAttr) { - applicableTypes->append( - wrapUnique(new SVGAngleInterpolationType(attribute))); + applicableTypes->append(makeUnique<SVGAngleInterpolationType>(attribute)); } else if (attribute == SVGNames::numOctavesAttr || attribute == SVGNames::targetXAttr || attribute == SVGNames::targetYAttr) { applicableTypes->append( - wrapUnique(new SVGIntegerInterpolationType(attribute))); + makeUnique<SVGIntegerInterpolationType>(attribute)); } else if (attribute == SVGNames::orderAttr) { applicableTypes->append(wrapUnique( new SVGIntegerOptionalIntegerInterpolationType(attribute))); @@ -324,17 +323,17 @@ attribute == SVGNames::x1Attr || attribute == SVGNames::x2Attr || attribute == SVGNames::y1Attr || attribute == SVGNames::y2Attr) { applicableTypes->append( - wrapUnique(new SVGLengthInterpolationType(attribute))); + makeUnique<SVGLengthInterpolationType>(attribute)); } else if (attribute == SVGNames::dxAttr || attribute == SVGNames::dyAttr) { applicableTypes->append( - wrapUnique(new SVGNumberInterpolationType(attribute))); + makeUnique<SVGNumberInterpolationType>(attribute)); applicableTypes->append( - wrapUnique(new SVGLengthListInterpolationType(attribute))); + makeUnique<SVGLengthListInterpolationType>(attribute)); } else if (attribute == SVGNames::xAttr || attribute == SVGNames::yAttr) { applicableTypes->append( - wrapUnique(new SVGLengthInterpolationType(attribute))); + makeUnique<SVGLengthInterpolationType>(attribute)); applicableTypes->append( - wrapUnique(new SVGLengthListInterpolationType(attribute))); + makeUnique<SVGLengthListInterpolationType>(attribute)); } else if (attribute == SVGNames::amplitudeAttr || attribute == SVGNames::azimuthAttr || attribute == SVGNames::biasAttr || @@ -359,33 +358,31 @@ attribute == SVGNames::surfaceScaleAttr || attribute == SVGNames::zAttr) { applicableTypes->append( - wrapUnique(new SVGNumberInterpolationType(attribute))); + makeUnique<SVGNumberInterpolationType>(attribute)); } else if (attribute == SVGNames::kernelMatrixAttr || attribute == SVGNames::rotateAttr || attribute == SVGNames::tableValuesAttr || attribute == SVGNames::valuesAttr) { applicableTypes->append( - wrapUnique(new SVGNumberListInterpolationType(attribute))); + makeUnique<SVGNumberListInterpolationType>(attribute)); } else if (attribute == SVGNames::baseFrequencyAttr || attribute == SVGNames::kernelUnitLengthAttr || attribute == SVGNames::radiusAttr || attribute == SVGNames::stdDeviationAttr) { applicableTypes->append( - wrapUnique(new SVGNumberOptionalNumberInterpolationType(attribute))); + makeUnique<SVGNumberOptionalNumberInterpolationType>(attribute)); } else if (attribute == SVGNames::dAttr) { - applicableTypes->append( - wrapUnique(new SVGPathInterpolationType(attribute))); + applicableTypes->append(makeUnique<SVGPathInterpolationType>(attribute)); } else if (attribute == SVGNames::pointsAttr) { applicableTypes->append( - wrapUnique(new SVGPointListInterpolationType(attribute))); + makeUnique<SVGPointListInterpolationType>(attribute)); } else if (attribute == SVGNames::viewBoxAttr) { - applicableTypes->append( - wrapUnique(new SVGRectInterpolationType(attribute))); + applicableTypes->append(makeUnique<SVGRectInterpolationType>(attribute)); } else if (attribute == SVGNames::gradientTransformAttr || attribute == SVGNames::patternTransformAttr || attribute == SVGNames::transformAttr) { applicableTypes->append( - wrapUnique(new SVGTransformListInterpolationType(attribute))); + makeUnique<SVGTransformListInterpolationType>(attribute)); } else if (attribute == HTMLNames::classAttr || attribute == SVGNames::clipPathUnitsAttr || attribute == SVGNames::edgeModeAttr || @@ -419,8 +416,7 @@ NOTREACHED(); } - applicableTypes->append( - wrapUnique(new SVGValueInterpolationType(attribute))); + applicableTypes->append(makeUnique<SVGValueInterpolationType>(attribute)); } auto addResult = applicableTypesMap.add(property, std::move(applicableTypes));
diff --git a/third_party/WebKit/Source/core/css/CSSStyleSheetResourceTest.cpp b/third_party/WebKit/Source/core/css/CSSStyleSheetResourceTest.cpp index 830ebd8..f7e30182 100644 --- a/third_party/WebKit/Source/core/css/CSSStyleSheetResourceTest.cpp +++ b/third_party/WebKit/Source/core/css/CSSStyleSheetResourceTest.cpp
@@ -86,7 +86,7 @@ CSSImageValue::create(String("image"), imageURL), CSSPrimitiveValue::create(1.0, CSSPrimitiveValue::UnitType::Number)); Vector<std::unique_ptr<CSSParserSelector>> selectors; - selectors.append(wrapUnique(new CSSParserSelector())); + selectors.append(makeUnique<CSSParserSelector>()); selectors[0]->setMatch(CSSSelector::Id); selectors[0]->setValue("foo"); CSSProperty property(CSSPropertyBackground, *crossfade);
diff --git a/third_party/WebKit/Source/core/css/invalidation/StyleInvalidator.cpp b/third_party/WebKit/Source/core/css/invalidation/StyleInvalidator.cpp index e5177919..74da9585 100644 --- a/third_party/WebKit/Source/core/css/invalidation/StyleInvalidator.cpp +++ b/third_party/WebKit/Source/core/css/invalidation/StyleInvalidator.cpp
@@ -144,7 +144,7 @@ PendingInvalidationMap::AddResult addResult = m_pendingInvalidationMap.add(&node, nullptr); if (addResult.isNewEntry) - addResult.storedValue->value = wrapUnique(new PendingInvalidations()); + addResult.storedValue->value = makeUnique<PendingInvalidations>(); return *addResult.storedValue->value; }
diff --git a/third_party/WebKit/Source/core/css/parser/CSSParserMode.cpp b/third_party/WebKit/Source/core/css/parser/CSSParserMode.cpp index 761ac63..90ae17da 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSParserMode.cpp +++ b/third_party/WebKit/Source/core/css/parser/CSSParserMode.cpp
@@ -47,10 +47,12 @@ CSSParserContext::CSSParserContext(const Document& document, UseCounter* useCounter, const KURL& baseURL, - const String& charset) + const String& charset, + SelectorProfile profile) : m_baseURL(baseURL.isNull() ? document.baseURL() : baseURL), m_charset(charset), m_mode(document.inQuirksMode() ? HTMLQuirksMode : HTMLStandardMode), + m_profile(profile), m_referrer(m_baseURL.strippedForUseAsReferrer(), document.getReferrerPolicy()), m_isHTMLDocument(document.isHTMLDocument()), @@ -79,6 +81,7 @@ m_charset(other.m_charset), m_mode(other.m_mode), m_matchMode(other.m_matchMode), + m_profile(other.m_profile), m_referrer(other.m_referrer), m_isHTMLDocument(other.m_isHTMLDocument), m_useLegacyBackgroundSizeShorthandBehavior( @@ -90,6 +93,7 @@ bool CSSParserContext::operator==(const CSSParserContext& other) const { return m_baseURL == other.m_baseURL && m_charset == other.m_charset && m_mode == other.m_mode && m_matchMode == other.m_matchMode && + m_profile == other.m_profile && m_isHTMLDocument == other.m_isHTMLDocument && m_useLegacyBackgroundSizeShorthandBehavior == other.m_useLegacyBackgroundSizeShorthandBehavior;
diff --git a/third_party/WebKit/Source/core/css/parser/CSSParserMode.h b/third_party/WebKit/Source/core/css/parser/CSSParserMode.h index 442dbc8..9b2c770 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSParserMode.h +++ b/third_party/WebKit/Source/core/css/parser/CSSParserMode.h
@@ -85,6 +85,9 @@ USING_FAST_MALLOC(CSSParserContext); public: + // https://drafts.csswg.org/selectors/#profiles + enum SelectorProfile { DynamicProfile, StaticProfile }; + CSSParserContext(CSSParserMode, UseCounter*); // FIXME: We shouldn't need the UseCounter argument as we could infer it from // the Document but some callers want to disable use counting (e.g. the @@ -92,7 +95,8 @@ CSSParserContext(const Document&, UseCounter*, const KURL& baseURL = KURL(), - const String& charset = emptyString()); + const String& charset = emptyString(), + SelectorProfile = DynamicProfile); // FIXME: This constructor shouldn't exist if we properly piped the UseCounter // through the CSS subsystem. Currently the UseCounter life time is too crazy // and we need a way to override it. @@ -109,6 +113,8 @@ const String& charset() const { return m_charset; } const Referrer& referrer() const { return m_referrer; } bool isHTMLDocument() const { return m_isHTMLDocument; } + bool isDynamicProfile() const { return m_profile == DynamicProfile; } + bool isStaticProfile() const { return m_profile == StaticProfile; } // This quirk is to maintain compatibility with Android apps built on // the Android SDK prior to and including version 18. Presumably, this @@ -140,6 +146,7 @@ String m_charset; CSSParserMode m_mode; CSSParserMode m_matchMode; + SelectorProfile m_profile = DynamicProfile; Referrer m_referrer; bool m_isHTMLDocument; bool m_useLegacyBackgroundSizeShorthandBehavior;
diff --git a/third_party/WebKit/Source/core/css/parser/CSSParserSelector.cpp b/third_party/WebKit/Source/core/css/parser/CSSParserSelector.cpp index c4fd184d..fb281e8a 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSParserSelector.cpp +++ b/third_party/WebKit/Source/core/css/parser/CSSParserSelector.cpp
@@ -27,11 +27,11 @@ namespace blink { CSSParserSelector::CSSParserSelector() - : m_selector(wrapUnique(new CSSSelector())) {} + : m_selector(makeUnique<CSSSelector>()) {} CSSParserSelector::CSSParserSelector(const QualifiedName& tagQName, bool isImplicit) - : m_selector(wrapUnique(new CSSSelector(tagQName, isImplicit))) {} + : m_selector(makeUnique<CSSSelector>(tagQName, isImplicit)) {} CSSParserSelector::~CSSParserSelector() { if (!m_tagHistory) @@ -101,7 +101,7 @@ second->m_selector = std::move(m_selector); second->m_tagHistory = std::move(m_tagHistory); m_tagHistory = std::move(second); - m_selector = wrapUnique(new CSSSelector(tagQName, isImplicit)); + m_selector = makeUnique<CSSSelector>(tagQName, isImplicit); } bool CSSParserSelector::isHostPseudoSelector() const {
diff --git a/third_party/WebKit/Source/core/css/parser/CSSParserSelector.h b/third_party/WebKit/Source/core/css/parser/CSSParserSelector.h index d5c5080b..40c93a6 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSParserSelector.h +++ b/third_party/WebKit/Source/core/css/parser/CSSParserSelector.h
@@ -42,7 +42,7 @@ } static std::unique_ptr<CSSParserSelector> create(const QualifiedName& name, bool isImplicit = false) { - return wrapUnique(new CSSParserSelector(name, isImplicit)); + return makeUnique<CSSParserSelector>(name, isImplicit); } ~CSSParserSelector();
diff --git a/third_party/WebKit/Source/core/css/parser/CSSSelectorParser.cpp b/third_party/WebKit/Source/core/css/parser/CSSSelectorParser.cpp index e759d46..6b8666c 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSSelectorParser.cpp +++ b/third_party/WebKit/Source/core/css/parser/CSSSelectorParser.cpp
@@ -533,7 +533,7 @@ DisallowPseudoElementsScope scope(this); std::unique_ptr<CSSSelectorList> selectorList = - wrapUnique(new CSSSelectorList()); + makeUnique<CSSSelectorList>(); *selectorList = consumeCompoundSelectorList(block); if (!selectorList->isValid() || !block.atEnd()) return nullptr;
diff --git a/third_party/WebKit/Source/core/dom/BUILD.gn b/third_party/WebKit/Source/core/dom/BUILD.gn index c41bad3..1731108 100644 --- a/third_party/WebKit/Source/core/dom/BUILD.gn +++ b/third_party/WebKit/Source/core/dom/BUILD.gn
@@ -265,6 +265,10 @@ "StyleSheetCandidate.h", "StyleSheetCollection.cpp", "StyleSheetCollection.h", + "SynchronousMutationNotifier.cpp", + "SynchronousMutationNotifier.h", + "SynchronousMutationObserver.cpp", + "SynchronousMutationObserver.h", "TagCollection.cpp", "TagCollection.h", "TaskRunnerHelper.cpp",
diff --git a/third_party/WebKit/Source/core/dom/ContextFeatures.cpp b/third_party/WebKit/Source/core/dom/ContextFeatures.cpp index a9ee343..7dc3b49 100644 --- a/third_party/WebKit/Source/core/dom/ContextFeatures.cpp +++ b/third_party/WebKit/Source/core/dom/ContextFeatures.cpp
@@ -36,7 +36,7 @@ namespace blink { std::unique_ptr<ContextFeaturesClient> ContextFeaturesClient::empty() { - return wrapUnique(new ContextFeaturesClient()); + return makeUnique<ContextFeaturesClient>(); } const char* ContextFeatures::supplementName() {
diff --git a/third_party/WebKit/Source/core/dom/Document.cpp b/third_party/WebKit/Source/core/dom/Document.cpp index 116247e4..4ea28a7 100644 --- a/third_party/WebKit/Source/core/dom/Document.cpp +++ b/third_party/WebKit/Source/core/dom/Document.cpp
@@ -572,7 +572,7 @@ SelectorQueryCache& Document::selectorQueryCache() { if (!m_selectorQueryCache) - m_selectorQueryCache = wrapUnique(new SelectorQueryCache()); + m_selectorQueryCache = makeUnique<SelectorQueryCache>(); return *m_selectorQueryCache; } @@ -2287,7 +2287,7 @@ if (TextAutosizer* autosizer = textAutosizer()) autosizer->updatePageInfo(); - m_frame->selection().documentAttached(this); + m_frame->documentAttached(); m_lifecycle.advanceTo(DocumentLifecycle::StyleClean); if (view()) @@ -2385,6 +2385,9 @@ frameHost()->eventHandlerRegistry().documentDetached(*this); + // Since |Document| class has multiple |LifecycleNotifier| as base class, + // we need to have |static_cast<SynchronousMutationNotifier>| here. + static_cast<SynchronousMutationNotifier*>(this)->notifyContextDestroyed(); m_frame->selection().documentDetached(*this); m_frame->eventHandler().selectionController().documentDetached(); m_frame->inputMethodController().documentDetached(); @@ -5014,10 +5017,8 @@ Attr* Document::createAttribute(const AtomicString& name, ExceptionState& exceptionState) { - if (isHTMLDocument() && name != name.lower()) - UseCounter::count(*this, - UseCounter::HTMLDocumentCreateAttributeNameNotLowercase); - return createAttributeNS(nullAtom, name, exceptionState, true); + return createAttributeNS(nullAtom, convertLocalName(name), exceptionState, + true); } Attr* Document::createAttributeNS(const AtomicString& namespaceURI, @@ -6396,6 +6397,7 @@ ContainerNode::trace(visitor); ExecutionContext::trace(visitor); SecurityContext::trace(visitor); + SynchronousMutationNotifier::trace(visitor); } void Document::maybeRecordLoadReason(WouldLoadReason reason) {
diff --git a/third_party/WebKit/Source/core/dom/Document.h b/third_party/WebKit/Source/core/dom/Document.h index cb2c1e4..5bc1abb 100644 --- a/third_party/WebKit/Source/core/dom/Document.h +++ b/third_party/WebKit/Source/core/dom/Document.h
@@ -41,6 +41,8 @@ #include "core/dom/DocumentTiming.h" #include "core/dom/ExecutionContext.h" #include "core/dom/MutationObserver.h" +#include "core/dom/SynchronousMutationNotifier.h" +#include "core/dom/SynchronousMutationObserver.h" #include "core/dom/TextLinkColors.h" #include "core/dom/TreeScope.h" #include "core/dom/UserActionElementSet.h" @@ -257,6 +259,7 @@ public TreeScope, public SecurityContext, public ExecutionContext, + public SynchronousMutationNotifier, public Supplementable<Document> { DEFINE_WRAPPERTYPEINFO(); USING_GARBAGE_COLLECTED_MIXIN(Document);
diff --git a/third_party/WebKit/Source/core/dom/DocumentTest.cpp b/third_party/WebKit/Source/core/dom/DocumentTest.cpp index 248fbd35..3b8622e 100644 --- a/third_party/WebKit/Source/core/dom/DocumentTest.cpp +++ b/third_party/WebKit/Source/core/dom/DocumentTest.cpp
@@ -30,6 +30,7 @@ #include "core/dom/Document.h" +#include "core/dom/SynchronousMutationObserver.h" #include "core/frame/FrameView.h" #include "core/html/HTMLHeadElement.h" #include "core/html/HTMLLinkElement.h" @@ -69,6 +70,40 @@ document().view()->updateAllLifecyclePhases(); } +namespace { + +class TestSynchronousMutationObserver + : public GarbageCollectedFinalized<TestSynchronousMutationObserver>, + public SynchronousMutationObserver { + USING_GARBAGE_COLLECTED_MIXIN(TestSynchronousMutationObserver); + + public: + TestSynchronousMutationObserver(Document&); + virtual ~TestSynchronousMutationObserver() = default; + + int countContextDestroyedCalled() const { + return m_contextDestroyedCalledCounter; + } + + private: + void contextDestroyed() final; + + int m_contextDestroyedCalledCounter = 0; + + DISALLOW_COPY_AND_ASSIGN(TestSynchronousMutationObserver); +}; + +TestSynchronousMutationObserver::TestSynchronousMutationObserver( + Document& document) { + setContext(&document); +} + +void TestSynchronousMutationObserver::contextDestroyed() { + ++m_contextDestroyedCalledCounter; +} + +} // anonymous namespace + // This tests that we properly resize and re-layout pages for printing in the // presence of media queries effecting elements in a subtree layout boundary TEST_F(DocumentTest, PrintRelayout) { @@ -297,4 +332,15 @@ EXPECT_TRUE(document().getSecurityOrigin()->isPotentiallyTrustworthy()); } +TEST_F(DocumentTest, SynchronousMutationNotifier) { + auto& observer = *new TestSynchronousMutationObserver(document()); + + EXPECT_EQ(observer.lifecycleContext(), document()); + EXPECT_EQ(observer.countContextDestroyedCalled(), 0); + + document().shutdown(); + EXPECT_EQ(observer.lifecycleContext(), nullptr); + EXPECT_EQ(observer.countContextDestroyedCalled(), 1); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/core/dom/SelectorQuery.cpp b/third_party/WebKit/Source/core/dom/SelectorQuery.cpp index e614db0f..bb2599bfc 100644 --- a/third_party/WebKit/Source/core/dom/SelectorQuery.cpp +++ b/third_party/WebKit/Source/core/dom/SelectorQuery.cpp
@@ -629,7 +629,9 @@ return it->value.get(); CSSSelectorList selectorList = CSSParser::parseSelector( - CSSParserContext(document, nullptr), nullptr, selectors); + CSSParserContext(document, nullptr, KURL(), emptyString(), + CSSParserContext::StaticProfile), + nullptr, selectors); if (!selectorList.first()) { exceptionState.throwDOMException(
diff --git a/third_party/WebKit/Source/core/dom/SelectorQueryTest.cpp b/third_party/WebKit/Source/core/dom/SelectorQueryTest.cpp index 7c82d08..a283697 100644 --- a/third_party/WebKit/Source/core/dom/SelectorQueryTest.cpp +++ b/third_party/WebKit/Source/core/dom/SelectorQueryTest.cpp
@@ -21,7 +21,9 @@ ASSERT_NO_EXCEPTION); CSSSelectorList selectorList = CSSParser::parseSelector( - CSSParserContext(*document, nullptr), nullptr, "span::before"); + CSSParserContext(*document, nullptr, KURL(), emptyString(), + CSSParserContext::StaticProfile), + nullptr, "span::before"); std::unique_ptr<SelectorQuery> query = SelectorQuery::adopt(std::move(selectorList)); Element* elm = query->queryFirst(*document);
diff --git a/third_party/WebKit/Source/core/dom/SynchronousMutationNotifier.cpp b/third_party/WebKit/Source/core/dom/SynchronousMutationNotifier.cpp new file mode 100644 index 0000000..a78225d0 --- /dev/null +++ b/third_party/WebKit/Source/core/dom/SynchronousMutationNotifier.cpp
@@ -0,0 +1,14 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "core/dom/SynchronousMutationNotifier.h" + +#include "core/dom/Document.h" +#include "core/dom/SynchronousMutationObserver.h" + +namespace blink { + +SynchronousMutationNotifier::SynchronousMutationNotifier() = default; + +} // namespace blink
diff --git a/third_party/WebKit/Source/core/dom/SynchronousMutationNotifier.h b/third_party/WebKit/Source/core/dom/SynchronousMutationNotifier.h new file mode 100644 index 0000000..7a08dc0 --- /dev/null +++ b/third_party/WebKit/Source/core/dom/SynchronousMutationNotifier.h
@@ -0,0 +1,34 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef SynchronousMutationNotifier_h +#define SynchronousMutationNotifier_h + +#include "base/macros.h" +#include "core/CoreExport.h" +#include "platform/LifecycleNotifier.h" + +namespace blink { + +class CharacterData; +class Document; +class Node; +class SynchronousMutationObserver; + +class CORE_EXPORT SynchronousMutationNotifier + : public LifecycleNotifier<Document, SynchronousMutationObserver> { + public: + // TODO(yosin): We will have |notifyXXX()| functions defined in + // |SynchronousMutationObserver|. + + protected: + SynchronousMutationNotifier(); + + private: + DISALLOW_COPY_AND_ASSIGN(SynchronousMutationNotifier); +}; + +} // namespace dom + +#endif // SynchronousMutationNotifier_h
diff --git a/third_party/WebKit/Source/core/dom/SynchronousMutationObserver.cpp b/third_party/WebKit/Source/core/dom/SynchronousMutationObserver.cpp new file mode 100644 index 0000000..cc4d18c --- /dev/null +++ b/third_party/WebKit/Source/core/dom/SynchronousMutationObserver.cpp
@@ -0,0 +1,15 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "core/dom/SynchronousMutationObserver.h" + +#include "core/dom/Document.h" +#include "core/dom/SynchronousMutationNotifier.h" + +namespace blink { + +SynchronousMutationObserver::SynchronousMutationObserver() + : LifecycleObserver(nullptr) {} + +} // namespace blink
diff --git a/third_party/WebKit/Source/core/dom/SynchronousMutationObserver.h b/third_party/WebKit/Source/core/dom/SynchronousMutationObserver.h new file mode 100644 index 0000000..312801d18 --- /dev/null +++ b/third_party/WebKit/Source/core/dom/SynchronousMutationObserver.h
@@ -0,0 +1,52 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef SynchronousMutationObserver_h +#define SynchronousMutationObserver_h + +#include "base/macros.h" +#include "core/CoreExport.h" +#include "platform/LifecycleObserver.h" + +namespace blink { + +class Document; + +// This class is a base class for classes which observe DOM tree mutation +// synchronously. If you want to observe DOM tree mutation asynchronously see +// MutationObserver Web API. +// +// TODO(yosin): Following classes should be derived from this class to +// simplify Document class. +// - DragCaretController +// - DocumentMarkerController +// - EventHandler +// - FrameCaret +// - InputMethodController +// - SelectionController +// - Range set +// - NodeIterator set +class CORE_EXPORT SynchronousMutationObserver + : public LifecycleObserver<Document, SynchronousMutationObserver> { + public: + // TODO(yosin): We will have following member functions: + // - dataWillBeChanged(const CharacterData&); + // - didMoveTreeToNewDocument(const Node& root); + // - nodeWillBeRemoved(Node&); + // - nodeChildrenWillBeRemoved(ContainerNode&) + // - didInsertText(Node*, unsigned offset, unsigned length); + // - didRemoveText(Node*, unsigned offset, unsigned length); + // - didMergeTextNodes(Text& oldNode, unsigned offset); + // - didSplitTextNode(Text& oldNode); + + protected: + SynchronousMutationObserver(); + + private: + DISALLOW_COPY_AND_ASSIGN(SynchronousMutationObserver); +}; + +} // namespace blink + +#endif // SynchronousMutationObserver_h
diff --git a/third_party/WebKit/Source/core/editing/FrameSelection.cpp b/third_party/WebKit/Source/core/editing/FrameSelection.cpp index 185a0f6..80ffa65 100644 --- a/third_party/WebKit/Source/core/editing/FrameSelection.cpp +++ b/third_party/WebKit/Source/core/editing/FrameSelection.cpp
@@ -1315,9 +1315,9 @@ return m_granularityStrategy.get(); if (strategyType == SelectionStrategy::Direction) - m_granularityStrategy = wrapUnique(new DirectionGranularityStrategy()); + m_granularityStrategy = makeUnique<DirectionGranularityStrategy>(); else - m_granularityStrategy = wrapUnique(new CharacterGranularityStrategy()); + m_granularityStrategy = makeUnique<CharacterGranularityStrategy>(); return m_granularityStrategy.get(); }
diff --git a/third_party/WebKit/Source/core/editing/iterators/SearchBuffer.cpp b/third_party/WebKit/Source/core/editing/iterators/SearchBuffer.cpp index 22623b24..0b22ed51 100644 --- a/third_party/WebKit/Source/core/editing/iterators/SearchBuffer.cpp +++ b/third_party/WebKit/Source/core/editing/iterators/SearchBuffer.cpp
@@ -83,7 +83,7 @@ } } - m_textSearcher = wrapUnique(new TextSearcherICU()); + m_textSearcher = makeUnique<TextSearcherICU>(); m_textSearcher->setPattern(StringView(m_target.data(), m_target.size()), !(m_options & CaseInsensitive));
diff --git a/third_party/WebKit/Source/core/events/Event.idl b/third_party/WebKit/Source/core/events/Event.idl index 19c6326..82bd377 100644 --- a/third_party/WebKit/Source/core/events/Event.idl +++ b/third_party/WebKit/Source/core/events/Event.idl
@@ -35,8 +35,8 @@ const unsigned short BUBBLING_PHASE = 3; readonly attribute unsigned short eventPhase; - void stopPropagation(); - void stopImmediatePropagation(); + [Measure] void stopPropagation(); + [Measure] void stopImmediatePropagation(); readonly attribute boolean bubbles; readonly attribute boolean cancelable;
diff --git a/third_party/WebKit/Source/core/events/EventFactory.h b/third_party/WebKit/Source/core/events/EventFactory.h index 31f31975..1b69f46 100644 --- a/third_party/WebKit/Source/core/events/EventFactory.h +++ b/third_party/WebKit/Source/core/events/EventFactory.h
@@ -52,7 +52,7 @@ class EventFactory final : public EventFactoryBase { public: static std::unique_ptr<EventFactory> create() { - return wrapUnique(new EventFactory()); + return makeUnique<EventFactory>(); } Event* create(ExecutionContext*, const String& eventType) override;
diff --git a/third_party/WebKit/Source/core/events/EventTypeNames.in b/third_party/WebKit/Source/core/events/EventTypeNames.in index 7c55e4b..ed772c7 100644 --- a/third_party/WebKit/Source/core/events/EventTypeNames.in +++ b/third_party/WebKit/Source/core/events/EventTypeNames.in
@@ -255,6 +255,8 @@ vrdisplaydisconnect vrdisplayactivate vrdisplaydeactivate +vrdisplayblur +vrdisplayfocus vrdisplaypresentchange waiting waitingforkey
diff --git a/third_party/WebKit/Source/core/events/InputEvent.cpp b/third_party/WebKit/Source/core/events/InputEvent.cpp index 83581081..3025458 100644 --- a/third_party/WebKit/Source/core/events/InputEvent.cpp +++ b/third_party/WebKit/Source/core/events/InputEvent.cpp
@@ -117,7 +117,7 @@ inputEventInit.setIsComposing(isComposing == IsComposing); if (ranges) inputEventInit.setRanges(*ranges); - + inputEventInit.setComposed(true); return InputEvent::create(EventTypeNames::beforeinput, inputEventInit); } @@ -136,7 +136,7 @@ inputEventInit.setIsComposing(isComposing == IsComposing); if (ranges) inputEventInit.setRanges(*ranges); - + inputEventInit.setComposed(true); return InputEvent::create(EventTypeNames::beforeinput, inputEventInit); } @@ -157,7 +157,7 @@ inputEventInit.setIsComposing(isComposing == IsComposing); if (ranges) inputEventInit.setRanges(*ranges); - + inputEventInit.setComposed(true); return InputEvent::create(EventTypeNames::input, inputEventInit); }
diff --git a/third_party/WebKit/Source/core/events/KeyboardEvent.cpp b/third_party/WebKit/Source/core/events/KeyboardEvent.cpp index 140f082..ed487427 100644 --- a/third_party/WebKit/Source/core/events/KeyboardEvent.cpp +++ b/third_party/WebKit/Source/core/events/KeyboardEvent.cpp
@@ -97,7 +97,7 @@ static_cast<PlatformEvent::Modifiers>(key.modifiers), key.timeStampSeconds, InputDeviceCapabilities::doesntFireTouchEventsSourceCapabilities()), - m_keyEvent(wrapUnique(new WebKeyboardEvent(key))), + m_keyEvent(makeUnique<WebKeyboardEvent>(key)), // TODO(crbug.com/482880): Fix this initialization to lazy initialization. m_code(Platform::current()->domCodeStringFromEnum(key.domCode)), m_key(Platform::current()->domKeyStringFromEnum(key.domKey)),
diff --git a/third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp b/third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp index e4a90c0..8c5fbea 100644 --- a/third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp +++ b/third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp
@@ -1080,7 +1080,7 @@ if (!m_preloads) return; - logPreloadStats(); + logPreloadStats(policy); for (const auto& resource : *m_preloads) { if (policy == ClearAllPreloads || !resource->isLinkPreload()) { @@ -1455,7 +1455,7 @@ } } -void ResourceFetcher::logPreloadStats() { +void ResourceFetcher::logPreloadStats(ClearPreloadsPolicy policy) { if (!m_preloads) return; unsigned scripts = 0; @@ -1475,6 +1475,11 @@ unsigned raws = 0; unsigned rawMisses = 0; for (const auto& resource : *m_preloads) { + // Do not double count link rel preloads. These do not get cleared if the + // ClearPreloadsPolicy is only clearing speculative markup preloads. + if (resource->isLinkPreload() && policy == ClearSpeculativeMarkupPreloads) { + continue; + } int missCount = resource->getPreloadResult() == Resource::PreloadNotReferenced ? 1 : 0; switch (resource->getType()) { @@ -1514,9 +1519,6 @@ NOTREACHED(); } } - // TODO(csharrison): These can falsely attribute link rel="preload" requests - // as misses if they are referenced after parsing completes. Migrate this - // logic to the memory cache / individual resources to prevent this. DEFINE_STATIC_LOCAL(CustomCountHistogram, imagePreloads, ("PreloadScanner.Counts2.Image", 0, 100, 25)); DEFINE_STATIC_LOCAL(CustomCountHistogram, imagePreloadMisses,
diff --git a/third_party/WebKit/Source/core/fetch/ResourceFetcher.h b/third_party/WebKit/Source/core/fetch/ResourceFetcher.h index cc59c87..09e983f 100644 --- a/third_party/WebKit/Source/core/fetch/ResourceFetcher.h +++ b/third_party/WebKit/Source/core/fetch/ResourceFetcher.h
@@ -107,7 +107,7 @@ int countPreloads() const { return m_preloads ? m_preloads->size() : 0; } void clearPreloads(ClearPreloadsPolicy = ClearAllPreloads); void preloadStarted(Resource*); - void logPreloadStats(); + void logPreloadStats(ClearPreloadsPolicy); void warnUnusedPreloads(); MHTMLArchive* archive() const { return m_archive.get(); }
diff --git a/third_party/WebKit/Source/core/fileapi/FileReaderLoader.cpp b/third_party/WebKit/Source/core/fileapi/FileReaderLoader.cpp index aaae328..04a018b 100644 --- a/third_party/WebKit/Source/core/fileapi/FileReaderLoader.cpp +++ b/third_party/WebKit/Source/core/fileapi/FileReaderLoader.cpp
@@ -218,7 +218,7 @@ } if (initialBufferLength < 0) - m_rawData = wrapUnique(new ArrayBufferBuilder()); + m_rawData = makeUnique<ArrayBufferBuilder>(); else m_rawData = wrapUnique( new ArrayBufferBuilder(static_cast<unsigned>(initialBufferLength)));
diff --git a/third_party/WebKit/Source/core/frame/Deprecation.cpp b/third_party/WebKit/Source/core/frame/Deprecation.cpp index 871e3629..4d3b4c9f 100644 --- a/third_party/WebKit/Source/core/frame/Deprecation.cpp +++ b/third_party/WebKit/Source/core/frame/Deprecation.cpp
@@ -407,7 +407,7 @@ "invalid and therefore ignored. Please use camelCase instead."; case UseCounter::HTMLKeygenElement: - return willBeRemoved("The <keygen> element", M56, "5716060992962560"); + return willBeRemoved("The <keygen> element", M57, "5716060992962560"); case UseCounter::EncryptedMediaAllSelectedContentTypesMissingCodecs: return String::format( @@ -417,10 +417,6 @@ "Please specify the desired codec(s) as part of the contentType.", milestoneString(M56)); - case UseCounter::V8SVGViewElement_ViewTarget_AttributeGetter: - return willBeRemoved("SVGViewElement.viewTarget", M56, - "5665473114931200"); - case UseCounter::VRDeprecatedFieldOfView: return replacedBy("VREyeParameters.fieldOfView", "projection matrices provided by VRFrameData");
diff --git a/third_party/WebKit/Source/core/frame/FrameView.cpp b/third_party/WebKit/Source/core/frame/FrameView.cpp index 2fd72686..41c82e1 100644 --- a/third_party/WebKit/Source/core/frame/FrameView.cpp +++ b/third_party/WebKit/Source/core/frame/FrameView.cpp
@@ -38,6 +38,7 @@ #include "core/dom/IntersectionObserverCallback.h" #include "core/dom/IntersectionObserverController.h" #include "core/dom/IntersectionObserverInit.h" +#include "core/dom/TaskRunnerHelper.h" #include "core/editing/EditingUtilities.h" #include "core/editing/FrameSelection.h" #include "core/editing/RenderedPosition.h" @@ -149,14 +150,18 @@ static bool s_initialTrackAllPaintInvalidations = false; -FrameView::FrameView(LocalFrame* frame) +FrameView::FrameView(LocalFrame& frame) : m_frame(frame), m_displayMode(WebDisplayModeBrowser), m_canHaveScrollbars(true), m_hasPendingLayout(false), m_inSynchronousPostLayout(false), - m_postLayoutTasksTimer(this, &FrameView::postLayoutTimerFired), - m_updateWidgetsTimer(this, &FrameView::updateWidgetsTimerFired), + m_postLayoutTasksTimer(TaskRunnerHelper::get(TaskType::Internal, &frame), + this, + &FrameView::postLayoutTimerFired), + m_updateWidgetsTimer(TaskRunnerHelper::get(TaskType::Internal, &frame), + this, + &FrameView::updateWidgetsTimerFired), m_isTransparent(false), m_baseBackgroundColor(Color::white), m_mediaType(MediaTypeNames::screen), @@ -190,17 +195,16 @@ m_needsScrollbarsUpdate(false), m_suppressAdjustViewSize(false), m_allowsLayoutInvalidationAfterLayoutClean(true) { - ASSERT(m_frame); init(); } -FrameView* FrameView::create(LocalFrame* frame) { +FrameView* FrameView::create(LocalFrame& frame) { FrameView* view = new FrameView(frame); view->show(); return view; } -FrameView* FrameView::create(LocalFrame* frame, const IntSize& initialSize) { +FrameView* FrameView::create(LocalFrame& frame, const IntSize& initialSize) { FrameView* view = new FrameView(frame); view->Widget::setFrameRect(IntRect(view->location(), initialSize)); view->setLayoutSizeInternal(initialSize); @@ -981,7 +985,7 @@ return; } if (!m_analyzer) - m_analyzer = wrapUnique(new LayoutAnalyzer()); + m_analyzer = makeUnique<LayoutAnalyzer>(); m_analyzer->reset(); } @@ -2294,7 +2298,6 @@ void FrameView::updateWidgetsTimerFired(TimerBase*) { ASSERT(!isInPerformLayout()); - m_updateWidgetsTimer.stop(); for (unsigned i = 0; i < maxUpdateWidgetsIterations; ++i) { if (updateWidgets()) return; @@ -2305,8 +2308,10 @@ ASSERT(!isInPerformLayout()); if (m_postLayoutTasksTimer.isActive()) performPostLayoutTasks(); - if (m_updateWidgetsTimer.isActive()) - updateWidgetsTimerFired(0); + if (m_updateWidgetsTimer.isActive()) { + m_updateWidgetsTimer.stop(); + updateWidgetsTimerFired(nullptr); + } } void FrameView::scheduleUpdateWidgetsIfNecessary() {
diff --git a/third_party/WebKit/Source/core/frame/FrameView.h b/third_party/WebKit/Source/core/frame/FrameView.h index bddc522..fba3907f 100644 --- a/third_party/WebKit/Source/core/frame/FrameView.h +++ b/third_party/WebKit/Source/core/frame/FrameView.h
@@ -100,8 +100,8 @@ friend class LayoutPart; // for invalidateTreeIfNeeded public: - static FrameView* create(LocalFrame*); - static FrameView* create(LocalFrame*, const IntSize& initialSize); + static FrameView* create(LocalFrame&); + static FrameView* create(LocalFrame&, const IntSize& initialSize); ~FrameView() override; @@ -794,7 +794,7 @@ void invalidateTreeIfNeeded(const PaintInvalidationState&); private: - explicit FrameView(LocalFrame*); + explicit FrameView(LocalFrame&); class ScrollbarManager : public blink::ScrollbarManager { DISALLOW_NEW(); @@ -977,8 +977,8 @@ bool m_inSynchronousPostLayout; int m_layoutCount; unsigned m_nestedLayoutCount; - Timer<FrameView> m_postLayoutTasksTimer; - Timer<FrameView> m_updateWidgetsTimer; + TaskRunnerTimer<FrameView> m_postLayoutTasksTimer; + TaskRunnerTimer<FrameView> m_updateWidgetsTimer; bool m_firstLayout; bool m_isTransparent;
diff --git a/third_party/WebKit/Source/core/frame/ImageBitmap.cpp b/third_party/WebKit/Source/core/frame/ImageBitmap.cpp index ea65053..585a641 100644 --- a/third_party/WebKit/Source/core/frame/ImageBitmap.cpp +++ b/third_party/WebKit/Source/core/frame/ImageBitmap.cpp
@@ -108,7 +108,7 @@ } bool dstBufferSizeHasOverflow(ParsedOptions options) { - CheckedNumeric<size_t> totalBytes = options.cropRect.width(); + CheckedNumeric<unsigned> totalBytes = options.cropRect.width(); totalBytes *= options.cropRect.height(); totalBytes *= options.bytesPerPixel; if (!totalBytes.IsValid()) @@ -131,8 +131,8 @@ const SkImageInfo& info) { // The function dstBufferSizeHasOverflow() is being called at the beginning of // each ImageBitmap() constructor, which makes sure that doing - // width * height * bytesPerPixel will never overflow size_t. - size_t width = static_cast<size_t>(input->width()); + // width * height * bytesPerPixel will never overflow unsigned. + unsigned width = static_cast<unsigned>(input->width()); RefPtr<ArrayBuffer> dstBuffer = ArrayBuffer::createOrNull(width * input->height(), info.bytesPerPixel()); if (!dstBuffer) @@ -146,7 +146,7 @@ static sk_sp<SkImage> newSkImageFromRaster(const SkImageInfo& info, PassRefPtr<Uint8Array> imagePixels, - size_t imageRowBytes) { + unsigned imageRowBytes) { SkPixmap pixmap(info, imagePixels->data(), imageRowBytes); return SkImage::MakeFromRaster(pixmap, [](const void*, void* pixels) { @@ -156,15 +156,15 @@ } static void swizzleImageData(unsigned char* srcAddr, - size_t height, - size_t bytesPerRow, + unsigned height, + unsigned bytesPerRow, bool flipY) { if (flipY) { - for (size_t i = 0; i < height / 2; i++) { - size_t topRowStartPosition = i * bytesPerRow; - size_t bottomRowStartPosition = (height - 1 - i) * bytesPerRow; + for (unsigned i = 0; i < height / 2; i++) { + unsigned topRowStartPosition = i * bytesPerRow; + unsigned bottomRowStartPosition = (height - 1 - i) * bytesPerRow; if (kN32_SkColorType == kBGRA_8888_SkColorType) { // needs to swizzle - for (size_t j = 0; j < bytesPerRow; j += 4) { + for (unsigned j = 0; j < bytesPerRow; j += 4) { std::swap(srcAddr[topRowStartPosition + j], srcAddr[bottomRowStartPosition + j + 2]); std::swap(srcAddr[topRowStartPosition + j + 1], @@ -182,27 +182,27 @@ } } else { if (kN32_SkColorType == kBGRA_8888_SkColorType) // needs to swizzle - for (size_t i = 0; i < height * bytesPerRow; i += 4) + for (unsigned i = 0; i < height * bytesPerRow; i += 4) std::swap(srcAddr[i], srcAddr[i + 2]); } } static sk_sp<SkImage> flipSkImageVertically(SkImage* input, AlphaDisposition alphaOp) { - size_t width = static_cast<size_t>(input->width()); - size_t height = static_cast<size_t>(input->height()); + unsigned width = static_cast<unsigned>(input->width()); + unsigned height = static_cast<unsigned>(input->height()); SkImageInfo info = SkImageInfo::MakeN32(input->width(), input->height(), (alphaOp == PremultiplyAlpha) ? kPremul_SkAlphaType : kUnpremul_SkAlphaType); - size_t imageRowBytes = width * info.bytesPerPixel(); + unsigned imageRowBytes = width * info.bytesPerPixel(); RefPtr<Uint8Array> imagePixels = copySkImageData(input, info); if (!imagePixels) return nullptr; - for (size_t i = 0; i < height / 2; i++) { - size_t topFirstElement = i * imageRowBytes; - size_t topLastElement = (i + 1) * imageRowBytes; - size_t bottomFirstElement = (height - 1 - i) * imageRowBytes; + for (unsigned i = 0; i < height / 2; i++) { + unsigned topFirstElement = i * imageRowBytes; + unsigned topLastElement = (i + 1) * imageRowBytes; + unsigned bottomFirstElement = (height - 1 - i) * imageRowBytes; std::swap_ranges(imagePixels->data() + topFirstElement, imagePixels->data() + topLastElement, imagePixels->data() + bottomFirstElement); @@ -218,7 +218,7 @@ return nullptr; return newSkImageFromRaster( info, std::move(dstPixels), - static_cast<size_t>(input->width()) * info.bytesPerPixel()); + static_cast<unsigned>(input->width()) * info.bytesPerPixel()); } static sk_sp<SkImage> unPremulSkImageToPremul(SkImage* input) { @@ -229,7 +229,7 @@ return nullptr; return newSkImageFromRaster( info, std::move(dstPixels), - static_cast<size_t>(input->width()) * info.bytesPerPixel()); + static_cast<unsigned>(input->width()) * info.bytesPerPixel()); } sk_sp<SkImage> ImageBitmap::getSkImageFromDecoder( @@ -290,7 +290,7 @@ SkImageInfo::Make(parsedOptions.resizeWidth, parsedOptions.resizeHeight, kN32_SkColorType, kUnpremul_SkAlphaType); RefPtr<ArrayBuffer> dstBuffer = ArrayBuffer::createOrNull( - static_cast<size_t>(info.width()) * info.height(), + static_cast<unsigned>(info.width()) * info.height(), info.bytesPerPixel()); if (!dstBuffer) return nullptr; @@ -298,7 +298,7 @@ Uint8Array::create(dstBuffer, 0, dstBuffer->byteLength()); return StaticBitmapImage::create(newSkImageFromRaster( info, std::move(dstPixels), - static_cast<size_t>(info.width()) * info.bytesPerPixel())); + static_cast<unsigned>(info.width()) * info.bytesPerPixel())); } sk_sp<SkImage> skiaImage = image->imageForCurrentFrame(); @@ -471,7 +471,7 @@ ASSERT(canvas->isPaintable()); RefPtr<Image> input = canvas->copiedImage(BackBuffer, PreferAcceleration); ParsedOptions parsedOptions = - parseOptions(options, cropRect, canvas->bitmapSourceSize()); + parseOptions(options, cropRect, IntSize(input->width(), input->height())); if (dstBufferSizeHasOverflow(parsedOptions)) return; @@ -524,7 +524,7 @@ Uint8Array::create(dstBuffer, 0, dstBuffer->byteLength()); SkPixmap pixmap( resizedInfo, resizedPixels->data(), - static_cast<size_t>(resizeWidth) * resizedInfo.bytesPerPixel()); + static_cast<unsigned>(resizeWidth) * resizedInfo.bytesPerPixel()); skImage->scalePixels(pixmap, resizeQuality); return SkImage::MakeFromRaster(pixmap, [](const void*, void* pixels) { @@ -553,9 +553,10 @@ SkImageInfo info = SkImageInfo::Make( parsedOptions.cropRect.width(), parsedOptions.cropRect.height(), kN32_SkColorType, kUnpremul_SkAlphaType); - size_t bytesPerPixel = static_cast<size_t>(info.bytesPerPixel()); - size_t srcPixelBytesPerRow = bytesPerPixel * data->size().width(); - size_t dstPixelBytesPerRow = bytesPerPixel * parsedOptions.cropRect.width(); + unsigned bytesPerPixel = static_cast<unsigned>(info.bytesPerPixel()); + unsigned srcPixelBytesPerRow = bytesPerPixel * data->size().width(); + unsigned dstPixelBytesPerRow = + bytesPerPixel * parsedOptions.cropRect.width(); sk_sp<SkImage> skImage; if (parsedOptions.cropRect == IntRect(IntPoint(), data->size())) { swizzleImageData(srcAddr, data->size().height(), srcPixelBytesPerRow, @@ -567,7 +568,7 @@ parsedOptions.flipY); } else { RefPtr<ArrayBuffer> dstBuffer = ArrayBuffer::createOrNull( - static_cast<size_t>(parsedOptions.cropRect.height()) * + static_cast<unsigned>(parsedOptions.cropRect.height()) * parsedOptions.cropRect.width(), bytesPerPixel); if (!dstBuffer) @@ -589,12 +590,12 @@ if (parsedOptions.cropRect.width() < copyWidth) copyWidth = parsedOptions.cropRect.width(); for (int i = 0; i < copyHeight; i++) { - size_t srcStartCopyPosition = + unsigned srcStartCopyPosition = (i + srcPoint.y()) * srcPixelBytesPerRow + srcPoint.x() * bytesPerPixel; - size_t srcEndCopyPosition = + unsigned srcEndCopyPosition = srcStartCopyPosition + copyWidth * bytesPerPixel; - size_t dstStartCopyPosition; + unsigned dstStartCopyPosition; if (parsedOptions.flipY) dstStartCopyPosition = (parsedOptions.cropRect.height() - 1 - dstPoint.y() - i) * @@ -603,7 +604,7 @@ else dstStartCopyPosition = (dstPoint.y() + i) * dstPixelBytesPerRow + dstPoint.x() * bytesPerPixel; - for (size_t j = 0; j < srcEndCopyPosition - srcStartCopyPosition; + for (unsigned j = 0; j < srcEndCopyPosition - srcStartCopyPosition; j++) { // swizzle when necessary if (kN32_SkColorType == kBGRA_8888_SkColorType) {
diff --git a/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp b/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp index cf5a2af..0973ebc 100644 --- a/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp +++ b/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp
@@ -494,7 +494,9 @@ void LocalDOMWindow::reset() { DCHECK(document()); - document()->notifyContextDestroyed(); + // Since |Document| class has multiple |LifecycleNotifier| as base class, + // we need to have |static_cast<ExecutionContext>| here. + static_cast<ExecutionContext*>(document())->notifyContextDestroyed(); frameDestroyed(); m_screen = nullptr;
diff --git a/third_party/WebKit/Source/core/frame/LocalFrame.cpp b/third_party/WebKit/Source/core/frame/LocalFrame.cpp index c73faf4a..56f87337 100644 --- a/third_party/WebKit/Source/core/frame/LocalFrame.cpp +++ b/third_party/WebKit/Source/core/frame/LocalFrame.cpp
@@ -290,12 +290,12 @@ FrameView* frameView = nullptr; if (isLocalRoot) { - frameView = FrameView::create(this, viewportSize); + frameView = FrameView::create(*this, viewportSize); // The layout size is set by WebViewImpl to support @viewport frameView->setLayoutSizeFixedToFrameSize(false); } else { - frameView = FrameView::create(this); + frameView = FrameView::create(*this); } frameView->setScrollbarModes(horizontalScrollbarMode, verticalScrollbarMode, @@ -491,6 +491,11 @@ ChildFrameDisconnector(*document).disconnect(); } +void LocalFrame::documentAttached() { + DCHECK(document()); + selection().documentAttached(document()); +} + void LocalFrame::setDOMWindow(LocalDOMWindow* domWindow) { // TODO(haraken): Update this comment. // Oilpan: setDOMWindow() cannot be used when finalizing. Which
diff --git a/third_party/WebKit/Source/core/frame/LocalFrame.h b/third_party/WebKit/Source/core/frame/LocalFrame.h index 03df674..6b796ab2 100644 --- a/third_party/WebKit/Source/core/frame/LocalFrame.h +++ b/third_party/WebKit/Source/core/frame/LocalFrame.h
@@ -125,6 +125,7 @@ void setDocumentHasReceivedUserGesture() override; void detachChildren(); + void documentAttached(); LocalDOMWindow* localDOMWindow() const; void setDOMWindow(LocalDOMWindow*);
diff --git a/third_party/WebKit/Source/core/frame/UseCounter.h b/third_party/WebKit/Source/core/frame/UseCounter.h index 2ed2075..71722c4 100644 --- a/third_party/WebKit/Source/core/frame/UseCounter.h +++ b/third_party/WebKit/Source/core/frame/UseCounter.h
@@ -637,7 +637,6 @@ FormDataAppendBlob = 841, FormDataAppendBlobWithFilename = 842, FormDataAppendNull = 843, - HTMLDocumentCreateAttributeNameNotLowercase = 844, NonHTMLElementSetAttributeNodeFromHTMLDocumentNameNotLowercase = 845, DOMStringList_Item_AttributeGetter_IndexedDB = 846, DOMStringList_Item_AttributeGetter_Location = 847, @@ -845,7 +844,6 @@ CrossOriginApplicationScript = 1070, CrossOriginOtherScript = 1071, SVG1DOMSVGTests = 1072, - V8SVGViewElement_ViewTarget_AttributeGetter = 1073, DisableRemotePlaybackAttribute = 1074, V8SloppyMode = 1075, V8StrictMode = 1076, @@ -1387,6 +1385,8 @@ GenericSensorStop = 1681, TouchEventPreventedNoTouchAction = 1682, TouchEventPreventedForcedDocumentPassiveNoTouchAction = 1683, + V8Event_StopPropagation_Method = 1684, + V8Event_StopImmediatePropagation_Method = 1685, // Add new features immediately above this line. Don't change assigned // numbers of any item, and don't reuse removed slots.
diff --git a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp index 104a89d0..58472ed3 100644 --- a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp +++ b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp
@@ -145,8 +145,8 @@ // // See http://blog.innerht.ml/csp-2015/#danglingmarkupinjection for an example // of the kind of attack this is aimed at mitigating. - DEFINE_STATIC_LOCAL(AtomicString, scriptString, ("<script")); - DEFINE_STATIC_LOCAL(AtomicString, styleString, ("<style")); + static const char scriptString[] = "<script"; + static const char styleString[] = "<style"; for (const Attribute& attr : element->attributes()) { AtomicString name = attr.localName().lowerASCII(); AtomicString value = attr.value().lowerASCII(); @@ -831,6 +831,7 @@ case WebURLRequest::RequestContextEventSource: case WebURLRequest::RequestContextFetch: case WebURLRequest::RequestContextXMLHttpRequest: + case WebURLRequest::RequestContextSubresource: return allowConnectToSource(url, redirectStatus, reportingStatus); case WebURLRequest::RequestContextEmbed: case WebURLRequest::RequestContextObject: @@ -869,7 +870,6 @@ case WebURLRequest::RequestContextPing: case WebURLRequest::RequestContextPlugin: case WebURLRequest::RequestContextPrefetch: - case WebURLRequest::RequestContextSubresource: case WebURLRequest::RequestContextUnspecified: return true; } @@ -1310,23 +1310,21 @@ } void ContentSecurityPolicy::reportUnsupportedDirective(const String& name) { - DEFINE_STATIC_LOCAL(String, allow, ("allow")); - DEFINE_STATIC_LOCAL(String, options, ("options")); - DEFINE_STATIC_LOCAL(String, policyURI, ("policy-uri")); - DEFINE_STATIC_LOCAL( - String, allowMessage, - ("The 'allow' directive has been replaced with 'default-src'. Please use " - "that directive instead, as 'allow' has no effect.")); - DEFINE_STATIC_LOCAL( - String, optionsMessage, - ("The 'options' directive has been replaced with 'unsafe-inline' and " - "'unsafe-eval' source expressions for the 'script-src' and 'style-src' " - "directives. Please use those directives instead, as 'options' has no " - "effect.")); - DEFINE_STATIC_LOCAL(String, policyURIMessage, - ("The 'policy-uri' directive has been removed from the " - "specification. Please specify a complete policy via " - "the Content-Security-Policy header.")); + static const char allow[] = "allow"; + static const char options[] = "options"; + static const char policyURI[] = "policy-uri"; + static const char allowMessage[] = + "The 'allow' directive has been replaced with 'default-src'. Please use " + "that directive instead, as 'allow' has no effect."; + static const char optionsMessage[] = + "The 'options' directive has been replaced with 'unsafe-inline' and " + "'unsafe-eval' source expressions for the 'script-src' and 'style-src' " + "directives. Please use those directives instead, as 'options' has no " + "effect."; + static const char policyURIMessage[] = + "The 'policy-uri' directive has been removed from the " + "specification. Please specify a complete policy via " + "the Content-Security-Policy header."; String message = "Unrecognized Content-Security-Policy directive '" + name + "'.\n";
diff --git a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicyTest.cpp b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicyTest.cpp index b615e47..b254f6f 100644 --- a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicyTest.cpp +++ b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicyTest.cpp
@@ -263,6 +263,37 @@ ContentSecurityPolicy::SuppressReport)); } +TEST_F(ContentSecurityPolicyTest, ConnectSrc) { + KURL url(KURL(), "https://example.test"); + csp->bindToExecutionContext(document.get()); + csp->didReceiveHeader("connect-src 'none';", + ContentSecurityPolicyHeaderTypeEnforce, + ContentSecurityPolicyHeaderSourceMeta); + EXPECT_FALSE(csp->allowRequest(WebURLRequest::RequestContextSubresource, url, + String(), IntegrityMetadataSet(), + ParserInserted, + ResourceRequest::RedirectStatus::NoRedirect, + ContentSecurityPolicy::SuppressReport)); + EXPECT_FALSE(csp->allowRequest(WebURLRequest::RequestContextXMLHttpRequest, + url, String(), IntegrityMetadataSet(), + ParserInserted, + ResourceRequest::RedirectStatus::NoRedirect, + ContentSecurityPolicy::SuppressReport)); + EXPECT_FALSE(csp->allowRequest(WebURLRequest::RequestContextBeacon, url, + String(), IntegrityMetadataSet(), + ParserInserted, + ResourceRequest::RedirectStatus::NoRedirect, + ContentSecurityPolicy::SuppressReport)); + EXPECT_FALSE(csp->allowRequest( + WebURLRequest::RequestContextFetch, url, String(), IntegrityMetadataSet(), + ParserInserted, ResourceRequest::RedirectStatus::NoRedirect, + ContentSecurityPolicy::SuppressReport)); + EXPECT_TRUE(csp->allowRequest(WebURLRequest::RequestContextPlugin, url, + String(), IntegrityMetadataSet(), + ParserInserted, + ResourceRequest::RedirectStatus::NoRedirect, + ContentSecurityPolicy::SuppressReport)); +} // Tests that requests for scripts and styles are blocked // if `require-sri-for` delivered in HTTP header requires integrity be present TEST_F(ContentSecurityPolicyTest, RequireSRIForInHeaderMissingIntegrity) {
diff --git a/third_party/WebKit/Source/core/html/BUILD.gn b/third_party/WebKit/Source/core/html/BUILD.gn index 8f8632ee..48ede6b 100644 --- a/third_party/WebKit/Source/core/html/BUILD.gn +++ b/third_party/WebKit/Source/core/html/BUILD.gn
@@ -446,6 +446,8 @@ "shadow/MediaControlElements.h", "shadow/MediaControls.cpp", "shadow/MediaControls.h", + "shadow/MediaControlsMediaEventListener.cpp", + "shadow/MediaControlsMediaEventListener.h", "shadow/MediaControlsWindowEventListener.cpp", "shadow/MediaControlsWindowEventListener.h", "shadow/PickerIndicatorElement.cpp",
diff --git a/third_party/WebKit/Source/core/html/HTMLAreaElement.cpp b/third_party/WebKit/Source/core/html/HTMLAreaElement.cpp index 3e266c3..4b711195 100644 --- a/third_party/WebKit/Source/core/html/HTMLAreaElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLAreaElement.cpp
@@ -166,7 +166,7 @@ } // Cache the original path, not depending on containerObject. - m_path = wrapUnique(new Path(path)); + m_path = makeUnique<Path>(path); } // Zoom the path into coordinates of the container object.
diff --git a/third_party/WebKit/Source/core/html/HTMLAudioElement.h b/third_party/WebKit/Source/core/html/HTMLAudioElement.h index cb9b569..28d28f6b 100644 --- a/third_party/WebKit/Source/core/html/HTMLAudioElement.h +++ b/third_party/WebKit/Source/core/html/HTMLAudioElement.h
@@ -27,13 +27,14 @@ #ifndef HTMLAudioElement_h #define HTMLAudioElement_h +#include "core/CoreExport.h" #include "core/html/HTMLMediaElement.h" namespace blink { class Document; -class HTMLAudioElement final : public HTMLMediaElement { +class CORE_EXPORT HTMLAudioElement final : public HTMLMediaElement { DEFINE_WRAPPERTYPEINFO(); public:
diff --git a/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp b/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp index fbae873..6554425 100644 --- a/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp
@@ -145,6 +145,8 @@ } void HTMLCanvasElement::dispose() { + releasePlaceholderFrame(); + if (m_context) { m_context->detachCanvas(); m_context = nullptr; @@ -470,8 +472,9 @@ } bool HTMLCanvasElement::paintsIntoCanvasBuffer() const { + if (placeholderFrame()) + return false; DCHECK(m_context); - if (!m_context->isAccelerated()) return true; if (layoutBox() && layoutBox()->hasAcceleratedCompositing()) @@ -515,7 +518,7 @@ void HTMLCanvasElement::paint(GraphicsContext& context, const LayoutRect& r) { // FIXME: crbug.com/438240; there is a bug with the new CSS blending and // compositing feature. - if (!m_context) + if (!m_context && !placeholderFrame()) return; const ComputedStyle* style = ensureComputedStyle(); @@ -536,6 +539,12 @@ if (!paintsIntoCanvasBuffer() && !document().printing()) return; + if (placeholderFrame()) { + DCHECK(document().printing()); + context.drawImage(placeholderFrame().get(), pixelSnappedIntRect(r)); + return; + } + // TODO(junov): Paint is currently only implemented by ImageBitmap contexts. // We could improve the abstraction by making all context types paint // themselves (implement paint()). @@ -619,19 +628,22 @@ imageData = ImageData::create(m_size); - if (!m_context || !imageData) + if ((!m_context || !imageData) && !placeholderFrame()) return imageData; - DCHECK(m_context->is2d()); + DCHECK((m_context && m_context->is2d()) || placeholderFrame()); + sk_sp<SkImage> snapshot; if (hasImageBuffer()) { - sk_sp<SkImage> snapshot = - buffer()->newSkImageSnapshot(PreferNoAcceleration, reason); - if (snapshot) { - SkImageInfo imageInfo = SkImageInfo::Make( - width(), height(), kRGBA_8888_SkColorType, kUnpremul_SkAlphaType); - snapshot->readPixels(imageInfo, imageData->data()->data(), - imageInfo.minRowBytes(), 0, 0); - } + snapshot = buffer()->newSkImageSnapshot(PreferNoAcceleration, reason); + } else if (placeholderFrame()) { + snapshot = placeholderFrame()->imageForCurrentFrame(); + } + + if (snapshot) { + SkImageInfo imageInfo = SkImageInfo::Make( + width(), height(), kRGBA_8888_SkColorType, kUnpremul_SkAlphaType); + snapshot->readPixels(imageInfo, imageData->data()->data(), + imageInfo.minRowBytes(), 0, 0); } return imageData; @@ -683,13 +695,6 @@ String HTMLCanvasElement::toDataURL(const String& mimeType, const ScriptValue& qualityArgument, ExceptionState& exceptionState) const { - if (surfaceLayerBridge()) { - exceptionState.throwDOMException(InvalidStateError, - "canvas.toDataURL is not allowed for a " - "canvas that has transferred its control " - "to offscreen."); - return String(); - } if (!originClean()) { exceptionState.throwSecurityError("Tainted canvases may not be exported."); return String(); @@ -709,14 +714,6 @@ const String& mimeType, const ScriptValue& qualityArgument, ExceptionState& exceptionState) { - if (surfaceLayerBridge()) { - exceptionState.throwDOMException(InvalidStateError, - "canvas.toBlob is not allowed for a " - "canvas that has transferred its control " - "to offscreen."); - return; - } - if (!originClean()) { exceptionState.throwSecurityError("Tainted canvases may not be exported."); return; @@ -942,7 +939,7 @@ // here. } - auto surfaceFactory = wrapUnique(new UnacceleratedSurfaceFactory()); + auto surfaceFactory = makeUnique<UnacceleratedSurfaceFactory>(); auto surface = surfaceFactory->createSurface(deviceSize, opacityMode, m_context->skColorSpace(), m_context->colorType()); @@ -1124,6 +1121,18 @@ if (!m_context) return createTransparentImage(size()); + if (m_context->getContextType() == + CanvasRenderingContext::ContextImageBitmap) { + RefPtr<Image> image = + m_context->getImage(hint, SnapshotReasonGetCopiedImage); + if (image) + return m_context->getImage(hint, SnapshotReasonGetCopiedImage); + // Special case: transferFromImageBitmap is not yet called. + sk_sp<SkSurface> surface = + SkSurface::MakeRasterN32Premul(width(), height()); + return StaticBitmapImage::create(surface->makeImageSnapshot()); + } + bool needToUpdate = !m_copiedImage; // The concept of SourceDrawingBuffer is valid on only WebGL. if (m_context->is3d()) @@ -1200,11 +1209,19 @@ return nullptr; } + if (placeholderFrame()) { + *status = NormalSourceImageStatus; + return placeholderFrame(); + } + if (!m_context) { *status = NormalSourceImageStatus; return createTransparentImage(size()); } + if (m_context->getContextType() == CanvasRenderingContext::ContextImageBitmap) + return m_context->getImage(hint, reason); + sk_sp<SkImage> skImage; if (m_context->is3d()) { // Because WebGL sources always require making a copy of the back buffer, we @@ -1240,6 +1257,15 @@ } FloatSize HTMLCanvasElement::elementSize(const FloatSize&) const { + if (m_context && + m_context->getContextType() == + CanvasRenderingContext::ContextImageBitmap) { + RefPtr<Image> image = + m_context->getImage(PreferNoAcceleration, SnapshotReasonDrawImage); + if (image) + return FloatSize(image->width(), image->height()); + return FloatSize(0, 0); + } return FloatSize(width(), height()); }
diff --git a/third_party/WebKit/Source/core/html/HTMLCanvasElement.h b/third_party/WebKit/Source/core/html/HTMLCanvasElement.h index 73ab97f..aed02126 100644 --- a/third_party/WebKit/Source/core/html/HTMLCanvasElement.h +++ b/third_party/WebKit/Source/core/html/HTMLCanvasElement.h
@@ -46,6 +46,7 @@ #include "platform/graphics/GraphicsTypes.h" #include "platform/graphics/GraphicsTypes3D.h" #include "platform/graphics/ImageBufferClient.h" +#include "platform/graphics/OffscreenCanvasPlaceholder.h" #include "platform/heap/Handle.h" #include <memory> @@ -77,7 +78,8 @@ public PageVisibilityObserver, public CanvasImageSource, public ImageBufferClient, - public ImageBitmapSource { + public ImageBitmapSource, + public OffscreenCanvasPlaceholder { DEFINE_WRAPPERTYPEINFO(); USING_GARBAGE_COLLECTED_MIXIN(HTMLCanvasElement); USING_PRE_FINALIZER(HTMLCanvasElement, dispose);
diff --git a/third_party/WebKit/Source/core/html/HTMLInputElement.cpp b/third_party/WebKit/Source/core/html/HTMLInputElement.cpp index 5b6142f1..fb6d3be 100644 --- a/third_party/WebKit/Source/core/html/HTMLInputElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLInputElement.cpp
@@ -101,8 +101,6 @@ bool createdByParser) : HTMLTextFormControlElement(inputTag, document, form), m_size(defaultSize), - m_maxLength(-1), - m_minLength(-1), m_hasDirtyValue(false), m_isChecked(false), m_dirtyCheckedness(false), @@ -749,9 +747,9 @@ } pseudoStateChanged(CSSSelector::PseudoDefault); } else if (name == maxlengthAttr) { - parseMaxLengthAttribute(value); + setNeedsValidityCheck(); } else if (name == minlengthAttr) { - parseMinLengthAttribute(value); + setNeedsValidityCheck(); } else if (name == sizeAttr) { int oldSize = m_size; m_size = defaultSize; @@ -1389,42 +1387,6 @@ return fastGetAttribute(altAttr); } -int HTMLInputElement::maxLength() const { - return m_maxLength; -} - -int HTMLInputElement::minLength() const { - return m_minLength; -} - -void HTMLInputElement::setMaxLength(int maxLength, - ExceptionState& exceptionState) { - if (maxLength < 0) - exceptionState.throwDOMException( - IndexSizeError, - "The value provided (" + String::number(maxLength) + ") is negative."); - else if (maxLength < m_minLength) - exceptionState.throwDOMException( - IndexSizeError, ExceptionMessages::indexExceedsMinimumBound( - "maxLength", maxLength, m_minLength)); - else - setIntegralAttribute(maxlengthAttr, maxLength); -} - -void HTMLInputElement::setMinLength(int minLength, - ExceptionState& exceptionState) { - if (minLength < 0) - exceptionState.throwDOMException( - IndexSizeError, - "The value provided (" + String::number(minLength) + ") is negative."); - else if (m_maxLength >= 0 && minLength > m_maxLength) - exceptionState.throwDOMException( - IndexSizeError, ExceptionMessages::indexExceedsMaximumBound( - "minLength", minLength, m_maxLength)); - else - setIntegralAttribute(minlengthAttr, minLength); -} - bool HTMLInputElement::multiple() const { return fastHasAttribute(multipleAttr); } @@ -1701,22 +1663,6 @@ return m_inputTypeView->updatePlaceholderText(); } -void HTMLInputElement::parseMaxLengthAttribute(const AtomicString& value) { - int maxLength; - if (!parseHTMLInteger(value, maxLength) || maxLength < 0) - maxLength = -1; - m_maxLength = maxLength; - setNeedsValidityCheck(); -} - -void HTMLInputElement::parseMinLengthAttribute(const AtomicString& value) { - int minLength; - if (!parseHTMLInteger(value, minLength) || minLength < 0) - minLength = -1; - m_minLength = minLength; - setNeedsValidityCheck(); -} - bool HTMLInputElement::supportsAutocapitalize() const { return m_inputType->supportsAutocapitalize(); }
diff --git a/third_party/WebKit/Source/core/html/HTMLInputElement.h b/third_party/WebKit/Source/core/html/HTMLInputElement.h index be4be2e..f002d41f4 100644 --- a/third_party/WebKit/Source/core/html/HTMLInputElement.h +++ b/third_party/WebKit/Source/core/html/HTMLInputElement.h
@@ -193,12 +193,6 @@ void setSize(unsigned, ExceptionState&); KURL src() const; - - int maxLength() const; - int minLength() const; - void setMaxLength(int, ExceptionState&); - void setMinLength(int, ExceptionState&); - bool multiple() const; FileList* files() const; @@ -409,8 +403,6 @@ String m_nonAttributeValue; String m_suggestedValue; int m_size; - int m_maxLength; - int m_minLength; // https://html.spec.whatwg.org/multipage/forms.html#concept-input-value-dirty-flag unsigned m_hasDirtyValue : 1; // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-checked
diff --git a/third_party/WebKit/Source/core/html/HTMLLIElement.cpp b/third_party/WebKit/Source/core/html/HTMLLIElement.cpp index 011dab2..319dfea 100644 --- a/third_party/WebKit/Source/core/html/HTMLLIElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLLIElement.cpp
@@ -26,6 +26,7 @@ #include "core/CSSValueKeywords.h" #include "core/HTMLNames.h" #include "core/dom/LayoutTreeBuilderTraversal.h" +#include "core/html/parser/HTMLParserIdioms.h" #include "core/layout/LayoutListItem.h" #include "core/layout/api/LayoutLIItem.h" @@ -124,9 +125,8 @@ DCHECK(layoutObject()); DCHECK(layoutObject()->isListItem()); - bool valueOK; - int requestedValue = value.toInt(&valueOK); - if (valueOK) + int requestedValue = 0; + if (parseHTMLInteger(value, requestedValue)) toLayoutListItem(layoutObject())->setExplicitValue(requestedValue); else toLayoutListItem(layoutObject())->clearExplicitValue();
diff --git a/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp b/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp index c812add..b46bfee 100644 --- a/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp
@@ -1091,7 +1091,6 @@ if (fastHasAttribute(mutedAttr)) m_muted = true; - updateVolume(); DCHECK(!m_mediaSource); @@ -2427,7 +2426,9 @@ } m_volume = vol; - updateVolume(); + + if (webMediaPlayer()) + webMediaPlayer()->setVolume(effectiveMediaVolume()); scheduleEvent(EventTypeNames::volumechange); } @@ -2469,7 +2470,8 @@ // This is called after the volumechange event to make sure isAutoplayingMuted // returns the right value when webMediaPlayer receives the volume update. - updateVolume(); + if (webMediaPlayer()) + webMediaPlayer()->setVolume(effectiveMediaVolume()); // If an element was a candidate for autoplay muted but not visible, it will // have a visibility observer ready to start its playback. @@ -2479,14 +2481,6 @@ } } -void HTMLMediaElement::updateVolume() { - if (webMediaPlayer()) - webMediaPlayer()->setVolume(effectiveMediaVolume()); - - if (mediaControls()) - mediaControls()->updateVolume(); -} - double HTMLMediaElement::effectiveMediaVolume() const { if (m_muted) return 0; @@ -3345,7 +3339,7 @@ // media engine was setup. The media engine should just stash the rate // and muted values since it isn't already playing. webMediaPlayer()->setRate(playbackRate()); - updateVolume(); + webMediaPlayer()->setVolume(effectiveMediaVolume()); webMediaPlayer()->play(); m_autoplayHelper->playbackStarted(); } @@ -3817,14 +3811,6 @@ return fastHasAttribute(controlsAttr); } -void HTMLMediaElement::defaultEventHandler(Event* event) { - if (event->type() == EventTypeNames::focusin) { - if (mediaControls()) - mediaControls()->mediaElementFocused(); - } - HTMLElement::defaultEventHandler(event); -} - DEFINE_TRACE(HTMLMediaElement) { visitor->trace(m_playedTimeRanges); visitor->trace(m_asyncEventQueue);
diff --git a/third_party/WebKit/Source/core/html/HTMLMediaElement.h b/third_party/WebKit/Source/core/html/HTMLMediaElement.h index 68c5c31..0bd98bca 100644 --- a/third_party/WebKit/Source/core/html/HTMLMediaElement.h +++ b/third_party/WebKit/Source/core/html/HTMLMediaElement.h
@@ -195,7 +195,7 @@ bool shouldShowControls( const RecordMetricsBehavior = RecordMetricsBehavior::DoNotRecord) const; double volume() const; - void setVolume(double, ExceptionState&); + void setVolume(double, ExceptionState& = ASSERT_NO_EXCEPTION); bool muted() const; void setMuted(bool); @@ -353,7 +353,6 @@ void didBecomeFullscreenElement() final; void willStopBeingFullscreenElement() final; bool isInteractiveContent() const final; - void defaultEventHandler(Event*) final; // ActiveDOMObject functions. void contextDestroyed() final;
diff --git a/third_party/WebKit/Source/core/html/HTMLMediaElementTest.cpp b/third_party/WebKit/Source/core/html/HTMLMediaElementTest.cpp new file mode 100644 index 0000000..7b04d525 --- /dev/null +++ b/third_party/WebKit/Source/core/html/HTMLMediaElementTest.cpp
@@ -0,0 +1,58 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "core/html/HTMLMediaElement.h" + +#include "core/html/HTMLAudioElement.h" +#include "core/html/HTMLVideoElement.h" +#include "core/testing/DummyPageHolder.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace blink { + +enum class TestParam { Audio, Video }; + +class HTMLMediaElementTest : public ::testing::TestWithParam<TestParam> { + protected: + void SetUp() { + m_dummyPageHolder = DummyPageHolder::create(); + + if (GetParam() == TestParam::Audio) + m_media = HTMLAudioElement::create(m_dummyPageHolder->document()); + else + m_media = HTMLVideoElement::create(m_dummyPageHolder->document()); + } + + HTMLMediaElement* media() { return m_media.get(); } + + private: + std::unique_ptr<DummyPageHolder> m_dummyPageHolder; + Persistent<HTMLMediaElement> m_media; +}; + +INSTANTIATE_TEST_CASE_P(Audio, + HTMLMediaElementTest, + ::testing::Values(TestParam::Audio)); +INSTANTIATE_TEST_CASE_P(Video, + HTMLMediaElementTest, + ::testing::Values(TestParam::Video)); + +TEST_P(HTMLMediaElementTest, effectiveMediaVolume) { + struct TestData { + double volume; + bool muted; + double effectiveVolume; + } test_data[] = { + {0.0, false, 0.0}, {0.5, false, 0.5}, {1.0, false, 1.0}, + {0.0, true, 0.0}, {0.5, true, 0.0}, {1.0, true, 0.0}, + }; + + for (const auto& data : test_data) { + media()->setVolume(data.volume); + media()->setMuted(data.muted); + EXPECT_EQ(data.effectiveVolume, media()->effectiveMediaVolume()); + } +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/core/html/HTMLMenuItemElement.idl b/third_party/WebKit/Source/core/html/HTMLMenuItemElement.idl index 6fba343a..c6ed0af 100644 --- a/third_party/WebKit/Source/core/html/HTMLMenuItemElement.idl +++ b/third_party/WebKit/Source/core/html/HTMLMenuItemElement.idl
@@ -7,7 +7,7 @@ [ RuntimeEnabled=ContextMenu, ] interface HTMLMenuItemElement : HTMLElement { - [CEReactions, Reflect] attribute DOMString type; + [CEReactions, Reflect, ReflectOnly=("checkbox","radio"), ReflectInvalid="command", ReflectMissing="command"] attribute DOMString type; [CEReactions, Reflect] attribute DOMString label; [CEReactions, Reflect, URL] attribute DOMString icon; [CEReactions, Reflect] attribute boolean disabled;
diff --git a/third_party/WebKit/Source/core/html/HTMLTextAreaElement.cpp b/third_party/WebKit/Source/core/html/HTMLTextAreaElement.cpp index 457301e..b948041a7 100644 --- a/third_party/WebKit/Source/core/html/HTMLTextAreaElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLTextAreaElement.cpp
@@ -496,50 +496,6 @@ setNonDirtyValue(value); } -int HTMLTextAreaElement::maxLength() const { - int value; - if (!parseHTMLInteger(getAttribute(maxlengthAttr), value)) - return -1; - return value >= 0 ? value : -1; -} - -int HTMLTextAreaElement::minLength() const { - int value; - if (!parseHTMLInteger(getAttribute(minlengthAttr), value)) - return -1; - return value >= 0 ? value : -1; -} - -void HTMLTextAreaElement::setMaxLength(int newValue, - ExceptionState& exceptionState) { - int min = minLength(); - if (newValue < 0) - exceptionState.throwDOMException( - IndexSizeError, "The value provided (" + String::number(newValue) + - ") is not positive or 0."); - else if (min >= 0 && newValue < min) - exceptionState.throwDOMException( - IndexSizeError, ExceptionMessages::indexExceedsMinimumBound( - "maxLength", newValue, min)); - else - setIntegralAttribute(maxlengthAttr, newValue); -} - -void HTMLTextAreaElement::setMinLength(int newValue, - ExceptionState& exceptionState) { - int max = maxLength(); - if (newValue < 0) - exceptionState.throwDOMException( - IndexSizeError, "The value provided (" + String::number(newValue) + - ") is not positive or 0."); - else if (max >= 0 && newValue > max) - exceptionState.throwDOMException( - IndexSizeError, ExceptionMessages::indexExceedsMaximumBound( - "minLength", newValue, max)); - else - setIntegralAttribute(minlengthAttr, newValue); -} - String HTMLTextAreaElement::suggestedValue() const { return m_suggestedValue; }
diff --git a/third_party/WebKit/Source/core/html/HTMLTextAreaElement.h b/third_party/WebKit/Source/core/html/HTMLTextAreaElement.h index 2fc1ac7..6d8da17 100644 --- a/third_party/WebKit/Source/core/html/HTMLTextAreaElement.h +++ b/third_party/WebKit/Source/core/html/HTMLTextAreaElement.h
@@ -51,10 +51,6 @@ String defaultValue() const; void setDefaultValue(const String&); int textLength() const { return value().length(); } - int maxLength() const; - int minLength() const; - void setMaxLength(int, ExceptionState&); - void setMinLength(int, ExceptionState&); String suggestedValue() const; void setSuggestedValue(const String&);
diff --git a/third_party/WebKit/Source/core/html/HTMLTextFormControlElement.cpp b/third_party/WebKit/Source/core/html/HTMLTextFormControlElement.cpp index 8c6d287..8593a12 100644 --- a/third_party/WebKit/Source/core/html/HTMLTextFormControlElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLTextFormControlElement.cpp
@@ -43,6 +43,7 @@ #include "core/frame/LocalFrame.h" #include "core/frame/UseCounter.h" #include "core/html/HTMLBRElement.h" +#include "core/html/parser/HTMLParserIdioms.h" #include "core/html/shadow/ShadowElementNames.h" #include "core/layout/LayoutBlock.h" #include "core/layout/LayoutBlockFlow.h" @@ -636,6 +637,52 @@ setAttribute(autocapitalizeAttr, autocapitalize); } +int HTMLTextFormControlElement::maxLength() const { + int value; + if (!parseHTMLInteger(fastGetAttribute(maxlengthAttr), value)) + return -1; + return value >= 0 ? value : -1; +} + +int HTMLTextFormControlElement::minLength() const { + int value; + if (!parseHTMLInteger(fastGetAttribute(minlengthAttr), value)) + return -1; + return value >= 0 ? value : -1; +} + +void HTMLTextFormControlElement::setMaxLength(int newValue, + ExceptionState& exceptionState) { + int min = minLength(); + if (newValue < 0) { + exceptionState.throwDOMException( + IndexSizeError, "The value provided (" + String::number(newValue) + + ") is not positive or 0."); + } else if (min >= 0 && newValue < min) { + exceptionState.throwDOMException( + IndexSizeError, ExceptionMessages::indexExceedsMinimumBound( + "maxLength", newValue, min)); + } else { + setIntegralAttribute(maxlengthAttr, newValue); + } +} + +void HTMLTextFormControlElement::setMinLength(int newValue, + ExceptionState& exceptionState) { + int max = maxLength(); + if (newValue < 0) { + exceptionState.throwDOMException( + IndexSizeError, "The value provided (" + String::number(newValue) + + ") is not positive or 0."); + } else if (max >= 0 && newValue > max) { + exceptionState.throwDOMException( + IndexSizeError, ExceptionMessages::indexExceedsMaximumBound( + "minLength", newValue, max)); + } else { + setIntegralAttribute(minlengthAttr, newValue); + } +} + void HTMLTextFormControlElement::restoreCachedSelection() { if (setSelectionRange(m_cachedSelectionStart, m_cachedSelectionEnd, m_cachedSelectionDirection))
diff --git a/third_party/WebKit/Source/core/html/HTMLTextFormControlElement.h b/third_party/WebKit/Source/core/html/HTMLTextFormControlElement.h index 53bf678..7615720b 100644 --- a/third_party/WebKit/Source/core/html/HTMLTextFormControlElement.h +++ b/third_party/WebKit/Source/core/html/HTMLTextFormControlElement.h
@@ -103,6 +103,11 @@ const AtomicString& autocapitalize() const; void setAutocapitalize(const AtomicString&); + int maxLength() const; + int minLength() const; + void setMaxLength(int, ExceptionState&); + void setMinLength(int, ExceptionState&); + // Dispatch 'input' event, and update // m_wasChangedSinceLastFormControlChangeEvent flag. void dispatchFormControlInputEvent();
diff --git a/third_party/WebKit/Source/core/html/LinkStyle.cpp b/third_party/WebKit/Source/core/html/LinkStyle.cpp index 8dfaaad..c86b8615 100644 --- a/third_party/WebKit/Source/core/html/LinkStyle.cpp +++ b/third_party/WebKit/Source/core/html/LinkStyle.cpp
@@ -283,6 +283,82 @@ m_fetchFollowingCORS = false; } +// TODO(yoav): move that logic to LinkLoader +LinkStyle::LoadReturnValue LinkStyle::loadStylesheetIfNeeded( + const LinkRequestBuilder& builder, + const String& type) { + if (m_disabledState == Disabled || !m_owner->relAttribute().isStyleSheet() || + !styleSheetTypeIsSupported(type) || !shouldLoadResource() || + !builder.url().isValid()) + return NotNeeded; + + if (resource()) { + removePendingSheet(); + clearResource(); + clearFetchFollowingCORS(); + } + + if (!m_owner->shouldLoadLink()) + return Bail; + + m_loading = true; + + String title = m_owner->title(); + if (!title.isEmpty() && !m_owner->isAlternate() && + m_disabledState != EnabledViaScript && m_owner->isInDocumentTree()) { + document().styleEngine().setPreferredStylesheetSetNameIfNotSet( + title, StyleEngine::DontUpdateActiveSheets); + } + + bool mediaQueryMatches = true; + LocalFrame* frame = loadingFrame(); + if (!m_owner->media().isEmpty() && frame) { + MediaQuerySet* media = MediaQuerySet::create(m_owner->media()); + MediaQueryEvaluator evaluator(frame); + mediaQueryMatches = evaluator.eval(media); + } + + // Don't hold up layout tree construction and script execution on + // stylesheets that are not needed for the layout at the moment. + bool blocking = mediaQueryMatches && !m_owner->isAlternate() && + m_owner->isCreatedByParser(); + addPendingSheet(blocking ? Blocking : NonBlocking); + + // Load stylesheets that are not needed for the layout immediately with low + // priority. When the link element is created by scripts, load the + // stylesheets asynchronously but in high priority. + bool lowPriority = !mediaQueryMatches || m_owner->isAlternate(); + FetchRequest request = builder.build(lowPriority); + CrossOriginAttributeValue crossOrigin = crossOriginAttributeValue( + m_owner->fastGetAttribute(HTMLNames::crossoriginAttr)); + if (crossOrigin != CrossOriginAttributeNotSet) { + request.setCrossOriginAccessControl(document().getSecurityOrigin(), + crossOrigin); + setFetchFollowingCORS(); + } + + String integrityAttr = m_owner->fastGetAttribute(HTMLNames::integrityAttr); + if (!integrityAttr.isEmpty()) { + IntegrityMetadataSet metadataSet; + SubresourceIntegrity::parseIntegrityAttribute(integrityAttr, metadataSet); + request.setIntegrityMetadata(metadataSet); + } + setResource(CSSStyleSheetResource::fetch(request, document().fetcher())); + + if (m_loading && !resource()) { + // The request may have been denied if (for example) the stylesheet is + // local and the document is remote, or if there was a Content Security + // Policy Failure. setCSSStyleSheet() can be called synchronuosly in + // setResource() and thus resource() is null and |m_loading| is false in + // such cases even if the request succeeds. + m_loading = false; + removePendingSheet(); + notifyLoadedSheetAndAllCriticalSubresources( + Node::ErrorOccurredLoadingSubresource); + } + return Loaded; +} + void LinkStyle::process() { DCHECK(m_owner->shouldProcessStyle()); String type = m_owner->typeValue().lower(); @@ -309,74 +385,7 @@ builder.url())) return; - if (m_disabledState != Disabled && m_owner->relAttribute().isStyleSheet() && - styleSheetTypeIsSupported(type) && shouldLoadResource() && - builder.url().isValid()) { - if (resource()) { - removePendingSheet(); - clearResource(); - clearFetchFollowingCORS(); - } - - if (!m_owner->shouldLoadLink()) - return; - - m_loading = true; - - String title = m_owner->title(); - if (!title.isEmpty() && !m_owner->isAlternate() && - m_disabledState != EnabledViaScript && m_owner->isInDocumentTree()) { - document().styleEngine().setPreferredStylesheetSetNameIfNotSet( - title, StyleEngine::DontUpdateActiveSheets); - } - - bool mediaQueryMatches = true; - LocalFrame* frame = loadingFrame(); - if (!m_owner->media().isEmpty() && frame) { - MediaQuerySet* media = MediaQuerySet::create(m_owner->media()); - MediaQueryEvaluator evaluator(frame); - mediaQueryMatches = evaluator.eval(media); - } - - // Don't hold up layout tree construction and script execution on - // stylesheets that are not needed for the layout at the moment. - bool blocking = mediaQueryMatches && !m_owner->isAlternate() && - m_owner->isCreatedByParser(); - addPendingSheet(blocking ? Blocking : NonBlocking); - - // Load stylesheets that are not needed for the layout immediately with low - // priority. When the link element is created by scripts, load the - // stylesheets asynchronously but in high priority. - bool lowPriority = !mediaQueryMatches || m_owner->isAlternate(); - FetchRequest request = builder.build(lowPriority); - CrossOriginAttributeValue crossOrigin = crossOriginAttributeValue( - m_owner->fastGetAttribute(HTMLNames::crossoriginAttr)); - if (crossOrigin != CrossOriginAttributeNotSet) { - request.setCrossOriginAccessControl(document().getSecurityOrigin(), - crossOrigin); - setFetchFollowingCORS(); - } - - String integrityAttr = m_owner->fastGetAttribute(HTMLNames::integrityAttr); - if (!integrityAttr.isEmpty()) { - IntegrityMetadataSet metadataSet; - SubresourceIntegrity::parseIntegrityAttribute(integrityAttr, metadataSet); - request.setIntegrityMetadata(metadataSet); - } - setResource(CSSStyleSheetResource::fetch(request, document().fetcher())); - - if (m_loading && !resource()) { - // The request may have been denied if (for example) the stylesheet is - // local and the document is remote, or if there was a Content Security - // Policy Failure. setCSSStyleSheet() can be called synchronuosly in - // setResource() and thus resource() is null and |m_loading| is false in - // such cases even if the request succeeds. - m_loading = false; - removePendingSheet(); - notifyLoadedSheetAndAllCriticalSubresources( - Node::ErrorOccurredLoadingSubresource); - } - } else if (m_sheet) { + if (loadStylesheetIfNeeded(builder, type) == NotNeeded && m_sheet) { // we no longer contain a stylesheet, e.g. perhaps rel or type was changed StyleSheet* removedSheet = m_sheet.get(); clearSheet();
diff --git a/third_party/WebKit/Source/core/html/LinkStyle.h b/third_party/WebKit/Source/core/html/LinkStyle.h index d7cfc45..fff4d0f 100644 --- a/third_party/WebKit/Source/core/html/LinkStyle.h +++ b/third_party/WebKit/Source/core/html/LinkStyle.h
@@ -66,6 +66,9 @@ const String& charset, const CSSStyleSheetResource*) override; String debugName() const override { return "LinkStyle"; } + enum LoadReturnValue { Loaded, NotNeeded, Bail }; + LoadReturnValue loadStylesheetIfNeeded(const LinkRequestBuilder&, + const String& type); enum DisabledState { Unset, EnabledViaScript, Disabled };
diff --git a/third_party/WebKit/Source/core/html/parser/AtomicHTMLToken.h b/third_party/WebKit/Source/core/html/parser/AtomicHTMLToken.h index e12f039..514c955 100644 --- a/third_party/WebKit/Source/core/html/parser/AtomicHTMLToken.h +++ b/third_party/WebKit/Source/core/html/parser/AtomicHTMLToken.h
@@ -140,7 +140,7 @@ break; case HTMLToken::DOCTYPE: m_name = AtomicString(token.data()); - m_doctypeData = wrapUnique(new DoctypeData()); + m_doctypeData = makeUnique<DoctypeData>(); m_doctypeData->m_hasPublicIdentifier = true; token.publicIdentifier().appendTo(m_doctypeData->m_publicIdentifier); m_doctypeData->m_hasSystemIdentifier = true;
diff --git a/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.cpp b/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.cpp index 0648e0f..b049b8b 100644 --- a/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.cpp +++ b/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.cpp
@@ -1142,7 +1142,7 @@ if (!m_haveBackgroundParser) startBackgroundParser(); - std::unique_ptr<Vector<char>> buffer = wrapUnique(new Vector<char>(length)); + std::unique_ptr<Vector<char>> buffer = makeUnique<Vector<char>>(length); memcpy(buffer->data(), data, length); TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("blink.debug"), "HTMLDocumentParser::appendBytes", "size", (unsigned)length);
diff --git a/third_party/WebKit/Source/core/html/shadow/MediaControlElements.cpp b/third_party/WebKit/Source/core/html/shadow/MediaControlElements.cpp index e602545..ab7ea8b 100644 --- a/third_party/WebKit/Source/core/html/shadow/MediaControlElements.cpp +++ b/third_party/WebKit/Source/core/html/shadow/MediaControlElements.cpp
@@ -299,7 +299,12 @@ } void MediaControlMuteButtonElement::updateDisplayType() { - setDisplayType(mediaElement().muted() ? MediaUnMuteButton : MediaMuteButton); + // TODO(mlamouri): checking for volume == 0 because the mute button will look + // 'muted' when the volume is 0 even if the element is not muted. This allows + // the painting and the display type to actually match. + setDisplayType((mediaElement().muted() || mediaElement().volume() == 0) + ? MediaUnMuteButton + : MediaMuteButton); updateOverflowString(); } @@ -832,7 +837,7 @@ UserMetricsAction("Media.Controls.VolumeChangeEnd")); double volume = value().toDouble(); - mediaElement().setVolume(volume, ASSERT_NO_EXCEPTION); + mediaElement().setVolume(volume); mediaElement().setMuted(false); }
diff --git a/third_party/WebKit/Source/core/html/shadow/MediaControls.cpp b/third_party/WebKit/Source/core/html/shadow/MediaControls.cpp index 74780f9..bcd0d7c4 100644 --- a/third_party/WebKit/Source/core/html/shadow/MediaControls.cpp +++ b/third_party/WebKit/Source/core/html/shadow/MediaControls.cpp
@@ -32,6 +32,7 @@ #include "core/events/MouseEvent.h" #include "core/frame/Settings.h" #include "core/html/HTMLMediaElement.h" +#include "core/html/shadow/MediaControlsMediaEventListener.h" #include "core/html/shadow/MediaControlsWindowEventListener.h" #include "core/html/track/TextTrackContainer.h" #include "core/html/track/TextTrackList.h" @@ -122,6 +123,7 @@ m_castButton(nullptr), m_fullscreenButton(nullptr), m_downloadButton(nullptr), + m_mediaEventListener(new MediaControlsMediaEventListener(this)), m_windowEventListener(MediaControlsWindowEventListener::create( this, WTF::bind(&MediaControls::hideAllMenus, wrapWeakPersistent(this)))), @@ -336,7 +338,7 @@ m_timeline->setDuration(duration); m_timeline->setPosition(mediaElement().currentTime()); - updateVolume(); + onVolumeChange(); refreshClosedCaptionsButtonVisibility(); @@ -360,13 +362,6 @@ m_overlayPlayButton->updateDisplayType(); } -void MediaControls::mediaElementFocused() { - if (mediaElement().shouldShowControls()) { - show(); - resetHideMediaControlsTimer(); - } -} - void MediaControls::hide() { m_panel->setIsWanted(false); m_panel->setIsDisplayed(false); @@ -485,32 +480,6 @@ m_currentTimeDisplay->setCurrentValue(now); } -void MediaControls::updateVolume() { - m_muteButton->updateDisplayType(); - // Invalidate the mute button because it paints differently according to - // volume. - invalidate(m_muteButton); - - if (mediaElement().muted()) - m_volumeSlider->setVolume(0); - else - m_volumeSlider->setVolume(mediaElement().volume()); - - // Update the visibility of our audio elements. - // We never want the volume slider if there's no audio. - // If there is audio, then we want it unless we prefer to hide it. - BatchedControlUpdate batch(this); - m_volumeSlider->setIsWanted(mediaElement().hasAudio() && - !preferHiddenVolumeControls(document())); - - // If there is no audio track, then hide the mute button. - m_muteButton->setIsWanted(mediaElement().hasAudio()); - - // Invalidate the volume slider because it paints differently according to - // volume. - invalidate(m_volumeSlider); -} - void MediaControls::changedClosedCaptionsVisibility() { m_toggleClosedCaptionsButton->updateDisplayType(); } @@ -727,6 +696,28 @@ return contains(relatedTarget->toNode()); } +void MediaControls::onVolumeChange() { + m_muteButton->updateDisplayType(); + m_volumeSlider->setVolume(mediaElement().muted() ? 0 + : mediaElement().volume()); + + // Update visibility of volume controls. + // TODO(mlamouri): it should not be part of the volumechange handling because + // it is using audio availability as input. + BatchedControlUpdate batch(this); + m_volumeSlider->setIsWanted(mediaElement().hasAudio() && + !preferHiddenVolumeControls(document())); + m_muteButton->setIsWanted(mediaElement().hasAudio()); +} + +void MediaControls::onFocusIn() { + if (!mediaElement().shouldShowControls()) + return; + + show(); + resetHideMediaControlsTimer(); +} + void MediaControls::notifyPanelWidthChanged(const LayoutUnit& newWidth) { // Don't bother to do any work if this matches the most recent panel // width, since we're called after layout. @@ -918,6 +909,7 @@ visitor->trace(m_overflowList); visitor->trace(m_castButton); visitor->trace(m_overlayCastButton); + visitor->trace(m_mediaEventListener); visitor->trace(m_windowEventListener); HTMLDivElement::trace(visitor); }
diff --git a/third_party/WebKit/Source/core/html/shadow/MediaControls.h b/third_party/WebKit/Source/core/html/shadow/MediaControls.h index 93e9fe8f..923c6db0 100644 --- a/third_party/WebKit/Source/core/html/shadow/MediaControls.h +++ b/third_party/WebKit/Source/core/html/shadow/MediaControls.h
@@ -33,6 +33,7 @@ namespace blink { class Event; +class MediaControlsMediaEventListener; class MediaControlsWindowEventListener; class CORE_EXPORT MediaControls final : public HTMLDivElement { @@ -56,8 +57,6 @@ void updateCurrentTimeDisplay(); - void updateVolume(); - void changedClosedCaptionsVisibility(); void refreshClosedCaptionsButtonVisibility(); void toggleTextTrackList(); @@ -77,8 +76,6 @@ void setAllowHiddenVolumeControls(bool); - void mediaElementFocused(); - // Returns the layout object for the part of the controls that should be // used for overlap checking during text track layout. May be null. LayoutObject* layoutObjectForTextTrackLayout(); @@ -105,6 +102,7 @@ DECLARE_VIRTUAL_TRACE(); private: + friend class MediaControlsMediaEventListener; friend class MediaControlsTest; void invalidate(Element*); @@ -148,6 +146,10 @@ void defaultEventHandler(Event*) override; bool containsRelatedTarget(Event*); + // Methods called by MediaControlsMediaEventListener. + void onVolumeChange(); + void onFocusIn(); + Member<HTMLMediaElement> m_mediaElement; // Media control elements. @@ -172,6 +174,7 @@ Member<MediaControlFullscreenButtonElement> m_fullscreenButton; Member<MediaControlDownloadButtonElement> m_downloadButton; + Member<MediaControlsMediaEventListener> m_mediaEventListener; Member<MediaControlsWindowEventListener> m_windowEventListener; Timer<MediaControls> m_hideMediaControlsTimer;
diff --git a/third_party/WebKit/Source/core/html/shadow/MediaControlsMediaEventListener.cpp b/third_party/WebKit/Source/core/html/shadow/MediaControlsMediaEventListener.cpp new file mode 100644 index 0000000..c607fce --- /dev/null +++ b/third_party/WebKit/Source/core/html/shadow/MediaControlsMediaEventListener.cpp
@@ -0,0 +1,48 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "core/html/shadow/MediaControlsMediaEventListener.h" + +#include "core/events/Event.h" +#include "core/html/HTMLMediaElement.h" +#include "core/html/shadow/MediaControls.h" + +namespace blink { + +MediaControlsMediaEventListener::MediaControlsMediaEventListener( + MediaControls* mediaControls) + : EventListener(CPPEventListenerType), m_mediaControls(mediaControls) { + m_mediaControls->m_mediaElement->addEventListener( + EventTypeNames::volumechange, this, false); + m_mediaControls->m_mediaElement->addEventListener(EventTypeNames::focusin, + this, false); +} + +bool MediaControlsMediaEventListener::operator==( + const EventListener& other) const { + return this == &other; +} + +void MediaControlsMediaEventListener::handleEvent( + ExecutionContext* executionContext, + Event* event) { + if (event->type() == EventTypeNames::volumechange) { + m_mediaControls->onVolumeChange(); + return; + } + + if (event->type() == EventTypeNames::focusin) { + m_mediaControls->onFocusIn(); + return; + } + + NOTREACHED(); +} + +DEFINE_TRACE(MediaControlsMediaEventListener) { + EventListener::trace(visitor); + visitor->trace(m_mediaControls); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/core/html/shadow/MediaControlsMediaEventListener.h b/third_party/WebKit/Source/core/html/shadow/MediaControlsMediaEventListener.h new file mode 100644 index 0000000..016c7035 --- /dev/null +++ b/third_party/WebKit/Source/core/html/shadow/MediaControlsMediaEventListener.h
@@ -0,0 +1,30 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef MediaControlsMediaEventListener_h +#define MediaControlsMediaEventListener_h + +#include "core/events/EventListener.h" + +namespace blink { + +class MediaControls; + +class MediaControlsMediaEventListener final : public EventListener { + public: + explicit MediaControlsMediaEventListener(MediaControls*); + + bool operator==(const EventListener&) const override; + + DECLARE_VIRTUAL_TRACE(); + + private: + void handleEvent(ExecutionContext*, Event*) override; + + Member<MediaControls> m_mediaControls; +}; + +} // namespace blink + +#endif // MediaControlsMediaEventListener_h
diff --git a/third_party/WebKit/Source/core/html/shadow/TextControlInnerElements.cpp b/third_party/WebKit/Source/core/html/shadow/TextControlInnerElements.cpp index 4a8aa5a9..11f274a 100644 --- a/third_party/WebKit/Source/core/html/shadow/TextControlInnerElements.cpp +++ b/third_party/WebKit/Source/core/html/shadow/TextControlInnerElements.cpp
@@ -133,7 +133,7 @@ LayoutObject* TextControlInnerEditorElement::createLayoutObject( const ComputedStyle&) { - return new LayoutTextControlInnerBlock(this); + return new LayoutTextControlInnerEditor(this); } PassRefPtr<ComputedStyle>
diff --git a/third_party/WebKit/Source/core/input/ScrollManager.cpp b/third_party/WebKit/Source/core/input/ScrollManager.cpp index d6791e6..fa78d4c 100644 --- a/third_party/WebKit/Source/core/input/ScrollManager.cpp +++ b/third_party/WebKit/Source/core/input/ScrollManager.cpp
@@ -224,7 +224,7 @@ m_currentScrollChain.clear(); std::unique_ptr<ScrollStateData> scrollStateData = - wrapUnique(new ScrollStateData()); + makeUnique<ScrollStateData>(); scrollStateData->position_x = gestureEvent.position().x(); scrollStateData->position_y = gestureEvent.position().y(); scrollStateData->is_beginning = true; @@ -270,7 +270,7 @@ } std::unique_ptr<ScrollStateData> scrollStateData = - wrapUnique(new ScrollStateData()); + makeUnique<ScrollStateData>(); scrollStateData->delta_x = delta.width(); scrollStateData->delta_y = delta.height(); scrollStateData->delta_granularity = @@ -326,7 +326,7 @@ if (node && node->layoutObject()) { passScrollGestureEventToWidget(gestureEvent, node->layoutObject()); std::unique_ptr<ScrollStateData> scrollStateData = - wrapUnique(new ScrollStateData()); + makeUnique<ScrollStateData>(); scrollStateData->is_ending = true; scrollStateData->is_in_inertial_phase = gestureEvent.inertialPhase() == ScrollInertialPhaseMomentum;
diff --git a/third_party/WebKit/Source/core/inspector/InspectorDOMAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorDOMAgent.cpp index 1a05a30..cf8c0ab 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorDOMAgent.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorDOMAgent.cpp
@@ -1164,7 +1164,7 @@ protocol::DOM::HighlightConfig* config = highlightInspectorObject.fromJust(); std::unique_ptr<InspectorHighlightConfig> highlightConfig = - wrapUnique(new InspectorHighlightConfig()); + makeUnique<InspectorHighlightConfig>(); highlightConfig->showInfo = config->getShowInfo(false); highlightConfig->showRulers = config->getShowRulers(false); highlightConfig->showExtensionLines = config->getShowExtensionLines(false); @@ -1228,7 +1228,7 @@ std::unique_ptr<protocol::Array<double>> quadArray, Maybe<protocol::DOM::RGBA> color, Maybe<protocol::DOM::RGBA> outlineColor) { - std::unique_ptr<FloatQuad> quad = wrapUnique(new FloatQuad()); + std::unique_ptr<FloatQuad> quad = makeUnique<FloatQuad>(); if (!parseQuad(std::move(quadArray), quad.get())) return Response::Error("Invalid Quad format"); innerHighlightQuad(std::move(quad), std::move(color), @@ -1241,7 +1241,7 @@ Maybe<protocol::DOM::RGBA> color, Maybe<protocol::DOM::RGBA> outlineColor) { std::unique_ptr<InspectorHighlightConfig> highlightConfig = - wrapUnique(new InspectorHighlightConfig()); + makeUnique<InspectorHighlightConfig>(); highlightConfig->content = parseColor(color.fromMaybe(nullptr)); highlightConfig->contentOutline = parseColor(outlineColor.fromMaybe(nullptr)); if (m_client) @@ -1308,7 +1308,7 @@ // FIXME: Inspector doesn't currently work cross process. if (frame && frame->deprecatedLocalOwner()) { std::unique_ptr<InspectorHighlightConfig> highlightConfig = - wrapUnique(new InspectorHighlightConfig()); + makeUnique<InspectorHighlightConfig>(); highlightConfig->showInfo = true; // Always show tooltips for frames. highlightConfig->content = parseColor(color.fromMaybe(nullptr)); highlightConfig->contentOutline = @@ -2208,7 +2208,7 @@ Response response = assertNode(nodeId, node); if (!response.isSuccess()) return response; - m_v8Session->addInspectedObject(wrapUnique(new InspectableNode(node))); + m_v8Session->addInspectedObject(makeUnique<InspectableNode>(node)); if (m_client) m_client->setInspectedNode(node); return Response::OK();
diff --git a/third_party/WebKit/Source/core/inspector/InspectorStyleSheet.cpp b/third_party/WebKit/Source/core/inspector/InspectorStyleSheet.cpp index 0f73dc2..55da42e 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorStyleSheet.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorStyleSheet.cpp
@@ -969,10 +969,10 @@ InspectorStyleSheetBase::InspectorStyleSheetBase(Listener* listener) : m_id(IdentifiersFactory::createIdentifier()), m_listener(listener), - m_lineEndings(wrapUnique(new LineEndings())) {} + m_lineEndings(makeUnique<LineEndings>()) {} void InspectorStyleSheetBase::onStyleSheetTextChanged() { - m_lineEndings = wrapUnique(new LineEndings()); + m_lineEndings = makeUnique<LineEndings>(); if (listener()) listener()->styleSheetChanged(this); } @@ -1468,7 +1468,7 @@ m_parsedFlatRules.clear(); collectFlatRules(sourceDataSheet, &m_parsedFlatRules); - m_sourceData = wrapUnique(new RuleSourceDataList()); + m_sourceData = makeUnique<RuleSourceDataList>(); flattenSourceData(ruleTree, m_sourceData.get()); m_text = text;
diff --git a/third_party/WebKit/Source/core/inspector/MainThreadDebugger.cpp b/third_party/WebKit/Source/core/inspector/MainThreadDebugger.cpp index 1fb65d26..035fb1b 100644 --- a/third_party/WebKit/Source/core/inspector/MainThreadDebugger.cpp +++ b/third_party/WebKit/Source/core/inspector/MainThreadDebugger.cpp
@@ -96,7 +96,7 @@ MainThreadDebugger::MainThreadDebugger(v8::Isolate* isolate) : ThreadDebugger(isolate), - m_taskRunner(wrapUnique(new InspectorTaskRunner())), + m_taskRunner(makeUnique<InspectorTaskRunner>()), m_paused(false) { MutexLocker locker(creationMutex()); ASSERT(!s_instance);
diff --git a/third_party/WebKit/Source/core/layout/LayoutBlockFlow.cpp b/third_party/WebKit/Source/core/layout/LayoutBlockFlow.cpp index 9254bcd..8b5d8f7 100644 --- a/third_party/WebKit/Source/core/layout/LayoutBlockFlow.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutBlockFlow.cpp
@@ -2184,7 +2184,7 @@ return; if (!m_rareData) - m_rareData = wrapUnique(new LayoutBlockFlowRareData(this)); + m_rareData = makeUnique<LayoutBlockFlowRareData>(this); m_rareData->m_discardMarginBefore = value; } @@ -2199,7 +2199,7 @@ return; if (!m_rareData) - m_rareData = wrapUnique(new LayoutBlockFlowRareData(this)); + m_rareData = makeUnique<LayoutBlockFlowRareData>(this); m_rareData->m_discardMarginAfter = value; } @@ -2258,7 +2258,7 @@ if (pos == LayoutBlockFlowRareData::positiveMarginBeforeDefault(this) && neg == LayoutBlockFlowRareData::negativeMarginBeforeDefault(this)) return; - m_rareData = wrapUnique(new LayoutBlockFlowRareData(this)); + m_rareData = makeUnique<LayoutBlockFlowRareData>(this); } m_rareData->m_margins.setPositiveMarginBefore(pos); m_rareData->m_margins.setNegativeMarginBefore(neg); @@ -2269,7 +2269,7 @@ if (pos == LayoutBlockFlowRareData::positiveMarginAfterDefault(this) && neg == LayoutBlockFlowRareData::negativeMarginAfterDefault(this)) return; - m_rareData = wrapUnique(new LayoutBlockFlowRareData(this)); + m_rareData = makeUnique<LayoutBlockFlowRareData>(this); } m_rareData->m_margins.setPositiveMarginAfter(pos); m_rareData->m_margins.setNegativeMarginAfter(neg); @@ -4112,7 +4112,7 @@ if (!m_rareData) { if (!strut) return; - m_rareData = wrapUnique(new LayoutBlockFlowRareData(this)); + m_rareData = makeUnique<LayoutBlockFlowRareData>(this); } m_rareData->m_paginationStrutPropagatedFromChild = strut; } @@ -4121,7 +4121,7 @@ if (!m_rareData) { if (!blockOffset) return; - m_rareData = wrapUnique(new LayoutBlockFlowRareData(this)); + m_rareData = makeUnique<LayoutBlockFlowRareData>(this); } m_rareData->m_firstForcedBreakOffset = blockOffset; } @@ -4273,7 +4273,7 @@ if (m_rareData) return *m_rareData; - m_rareData = wrapUnique(new LayoutBlockFlowRareData(this)); + m_rareData = makeUnique<LayoutBlockFlowRareData>(this); return *m_rareData; }
diff --git a/third_party/WebKit/Source/core/layout/LayoutBox.h b/third_party/WebKit/Source/core/layout/LayoutBox.h index 4179e73..85408fb 100644 --- a/third_party/WebKit/Source/core/layout/LayoutBox.h +++ b/third_party/WebKit/Source/core/layout/LayoutBox.h
@@ -1481,7 +1481,7 @@ LayoutBoxRareData& ensureRareData() { if (!m_rareData) - m_rareData = wrapUnique(new LayoutBoxRareData()); + m_rareData = makeUnique<LayoutBoxRareData>(); return *m_rareData.get(); }
diff --git a/third_party/WebKit/Source/core/layout/LayoutBoxModelObject.cpp b/third_party/WebKit/Source/core/layout/LayoutBoxModelObject.cpp index 84204c41..34be0896 100644 --- a/third_party/WebKit/Source/core/layout/LayoutBoxModelObject.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutBoxModelObject.cpp
@@ -429,7 +429,7 @@ void LayoutBoxModelObject::createLayer() { ASSERT(!m_layer); - m_layer = wrapUnique(new PaintLayer(this)); + m_layer = makeUnique<PaintLayer>(this); setHasLayer(true); m_layer->insertOnlyThisLayerAfterStyleChange(); } @@ -784,9 +784,15 @@ // allowed to move. LayoutUnit maxWidth = containingBlock->availableLogicalWidth(); - // Map the containing block to the scroll ancestor without transforms. + // Map the containing block to the inner corner of the scroll ancestor without + // transforms. FloatRect scrollContainerRelativePaddingBoxRect( containingBlock->layoutOverflowRect()); + FloatSize scrollContainerBorderOffset; + if (scrollAncestor) { + scrollContainerBorderOffset = + FloatSize(scrollAncestor->borderLeft(), scrollAncestor->borderTop()); + } if (containingBlock != scrollAncestor) { FloatQuad localQuad(FloatRect(containingBlock->paddingBoxRect())); TransformState transformState(TransformState::ApplyTransformDirection, @@ -807,6 +813,8 @@ : FloatSize()); scrollContainerRelativePaddingBoxRect.move(scrollOffset); } + // Remove top-left border offset from overflow scroller. + scrollContainerRelativePaddingBoxRect.move(-scrollContainerBorderOffset); LayoutRect scrollContainerRelativeContainingBlockRect( scrollContainerRelativePaddingBoxRect); @@ -842,12 +850,12 @@ // The scrollContainerRelativePaddingBoxRect's position is the padding box so // we need to remove the border when finding the position of the sticky box - // within the scroll ancestor if the container is not our scroll ancestor. - if (containingBlock != scrollAncestor) { - FloatSize containerBorderOffset(containingBlock->borderLeft(), - containingBlock->borderTop()); - stickyLocation -= containerBorderOffset; - } + // within the scroll ancestor if the container is not our scroll ancestor. If + // the container is our scroll ancestor, we also need to remove the border + // box because we want the position from within the scroller border. + FloatSize containerBorderOffset(containingBlock->borderLeft(), + containingBlock->borderTop()); + stickyLocation -= containerBorderOffset; constraints.setScrollContainerRelativeStickyBoxRect( FloatRect(scrollContainerRelativePaddingBoxRect.location() + toFloatSize(stickyLocation), @@ -929,8 +937,9 @@ constrainingRect = FloatRect(enclosingClippingBox->overflowClipRect(LayoutPoint(DoublePoint( enclosingClippingBox->getScrollableArea()->scrollPosition())))); - constrainingRect.move(enclosingClippingBox->paddingLeft(), - enclosingClippingBox->paddingTop()); + constrainingRect.move( + -enclosingClippingBox->borderLeft() + enclosingClippingBox->paddingLeft(), + -enclosingClippingBox->borderTop() + enclosingClippingBox->paddingTop()); constrainingRect.contract( FloatSize(enclosingClippingBox->paddingLeft() + enclosingClippingBox->paddingRight(),
diff --git a/third_party/WebKit/Source/core/layout/LayoutBoxModelObject.h b/third_party/WebKit/Source/core/layout/LayoutBoxModelObject.h index 57836cc..3fee2b9 100644 --- a/third_party/WebKit/Source/core/layout/LayoutBoxModelObject.h +++ b/third_party/WebKit/Source/core/layout/LayoutBoxModelObject.h
@@ -511,7 +511,7 @@ LayoutBoxModelObjectRareData& ensureRareData() { if (!m_rareData) - m_rareData = wrapUnique(new LayoutBoxModelObjectRareData()); + m_rareData = makeUnique<LayoutBoxModelObjectRareData>(); return *m_rareData.get(); }
diff --git a/third_party/WebKit/Source/core/layout/LayoutBoxModelObjectTest.cpp b/third_party/WebKit/Source/core/layout/LayoutBoxModelObjectTest.cpp index 8a08b866..9fbdbbdc 100644 --- a/third_party/WebKit/Source/core/layout/LayoutBoxModelObjectTest.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutBoxModelObjectTest.cpp
@@ -34,8 +34,8 @@ "}" "#container { box-sizing: border-box; position: relative; top: 100px; " "height: 400px; width: 200px; padding: 10px; border: 5px solid black; }" - "#scroller { height: 100px; overflow: auto; position: relative; top: " - "200px; }" + "#scroller { width: 400px; height: 100px; overflow: auto; " + "position: relative; top: 200px; border: 2px solid black; }" ".spacer { height: 1000px; }</style>" "<div id='scroller'><div id='container'><div " "id='sticky'></div></div><div class='spacer'></div></div>"); @@ -62,6 +62,52 @@ ASSERT_EQ( IntRect(15, 115, 100, 100), enclosingIntRect(getScrollContainerRelativeStickyBoxRect(constraints))); + + // The sticky constraining rect also doesn't include the border offset. + ASSERT_EQ(IntRect(0, 50, 400, 100), + enclosingIntRect(sticky->computeStickyConstrainingRect())); +} + +// Verifies that the sticky constraints are correctly computed in right to left. +TEST_F(LayoutBoxModelObjectTest, StickyPositionVerticalRLConstraints) { + setBodyInnerHTML( + "<style> html { -webkit-writing-mode: vertical-rl; } " + "#sticky { position: sticky; top: 0; width: 100px; height: 100px; " + "}" + "#container { box-sizing: border-box; position: relative; top: 100px; " + "height: 400px; width: 200px; padding: 10px; border: 5px solid black; }" + "#scroller { width: 400px; height: 100px; overflow: auto; " + "position: relative; top: 200px; border: 2px solid black; }" + ".spacer { height: 1000px; }</style>" + "<div id='scroller'><div id='container'><div " + "id='sticky'></div></div><div class='spacer'></div></div>"); + LayoutBoxModelObject* scroller = + toLayoutBoxModelObject(getLayoutObjectByElementId("scroller")); + PaintLayerScrollableArea* scrollableArea = scroller->getScrollableArea(); + scrollableArea->scrollToAbsolutePosition( + FloatPoint(scrollableArea->scrollOffsetInt().width(), 50)); + ASSERT_EQ(50.0, scrollableArea->scrollPosition().y()); + LayoutBoxModelObject* sticky = + toLayoutBoxModelObject(getLayoutObjectByElementId("sticky")); + sticky->updateStickyPositionConstraints(); + ASSERT_EQ(scroller->layer(), sticky->layer()->ancestorOverflowLayer()); + + const StickyPositionScrollingConstraints& constraints = + scrollableArea->stickyConstraintsMap().get(sticky->layer()); + ASSERT_EQ(0.f, constraints.topOffset()); + + // The coordinates of the constraint rects should all be with respect to the + // unscrolled scroller. + ASSERT_EQ(IntRect(215, 115, 170, 370), + enclosingIntRect( + getScrollContainerRelativeContainingBlockRect(constraints))); + ASSERT_EQ( + IntRect(285, 115, 100, 100), + enclosingIntRect(getScrollContainerRelativeStickyBoxRect(constraints))); + + // The sticky constraining rect also doesn't include the border offset. + ASSERT_EQ(IntRect(0, 50, 400, 100), + enclosingIntRect(sticky->computeStickyConstrainingRect())); } // Verifies that the sticky constraints are not affected by transforms @@ -144,7 +190,7 @@ "<style>#sticky { position: sticky; top: 0; width: 100px; height: 100px; " "}" "#scroller { height: 100px; width: 400px; overflow: auto; position: " - "relative; top: 200px; }" + "relative; top: 200px; border: 2px solid black; }" ".spacer { height: 1000px; }</style>" "<div id='scroller'><div id='sticky'></div><div " "class='spacer'></div></div>");
diff --git a/third_party/WebKit/Source/core/layout/LayoutGrid.cpp b/third_party/WebKit/Source/core/layout/LayoutGrid.cpp index e323b52..cb52b7ac 100644 --- a/third_party/WebKit/Source/core/layout/LayoutGrid.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutGrid.cpp
@@ -1009,7 +1009,7 @@ leftOverSpace -= baseSize; flexFactorSum -= flexFactor; if (!additionalTracksToTreatAsInflexible) - additionalTracksToTreatAsInflexible = wrapUnique(new TrackIndexSet()); + additionalTracksToTreatAsInflexible = makeUnique<TrackIndexSet>(); additionalTracksToTreatAsInflexible->add(index); validFlexFactorUnit = false; }
diff --git a/third_party/WebKit/Source/core/layout/LayoutTable.cpp b/third_party/WebKit/Source/core/layout/LayoutTable.cpp index 44373b79..9ae7165 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTable.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutTable.cpp
@@ -92,9 +92,9 @@ // explicit width is specified on the table. Auto width implies auto table // layout. if (style()->isFixedTableLayout()) - m_tableLayout = wrapUnique(new TableLayoutAlgorithmFixed(this)); + m_tableLayout = makeUnique<TableLayoutAlgorithmFixed>(this); else - m_tableLayout = wrapUnique(new TableLayoutAlgorithmAuto(this)); + m_tableLayout = makeUnique<TableLayoutAlgorithmAuto>(this); } // If border was changed, invalidate collapsed borders cache. @@ -752,7 +752,7 @@ } void LayoutTable::invalidateCollapsedBorders() { - m_collapsedBordersInfo = nullptr; + m_collapsedBorders.clear(); if (!collapseBorders()) return; @@ -765,15 +765,10 @@ // cache of its containing section, and invalidates itself if any border // changes. This method doesn't affect layout. void LayoutTable::recalcCollapsedBordersIfNeeded() { - if (m_collapsedBordersValid) + if (m_collapsedBordersValid || !collapseBorders()) return; m_collapsedBordersValid = true; - m_collapsedBordersInfo = nullptr; - if (!collapseBorders()) - return; - - LayoutRect boundsOfChangedCells; - Vector<CollapsedBorderValue> values; + m_collapsedBorders.clear(); for (LayoutObject* section = firstChild(); section; section = section->nextSibling()) { if (!section->isTableSection()) @@ -782,23 +777,12 @@ row = row->nextRow()) { for (LayoutTableCell* cell = row->firstCell(); cell; cell = cell->nextCell()) { - DCHECK(cell->table() == this); - if (cell->collectBorderValues(values) && - !shouldDoFullPaintInvalidation()) { - LayoutRect cellRect = cell->localVisualRect(); - cell->mapToVisualRectInAncestorSpace(this, cellRect); - boundsOfChangedCells.unite(cellRect); - } + ASSERT(cell->table() == this); + cell->collectBorderValues(m_collapsedBorders); } } } - if (!values.isEmpty()) { - LayoutTableCell::sortBorderValues(values); - m_collapsedBordersInfo = - wrapUnique(new CollapsedBordersInfo(std::move(values))); - } - - invalidatePaintRectangle(boundsOfChangedCells); + LayoutTableCell::sortBorderValues(m_collapsedBorders); } void LayoutTable::addOverflowFromChildren() { @@ -1678,10 +1662,10 @@ PaintInvalidationReason LayoutTable::invalidatePaintIfNeeded( const PaintInvalidationState& paintInvalidationState) { - if (hasCollapsedBorders()) { + if (collapseBorders() && !m_collapsedBorders.isEmpty()) paintInvalidationState.paintingLayer() .setNeedsPaintPhaseDescendantBlockBackgrounds(); - } + return LayoutBlock::invalidatePaintIfNeeded(paintInvalidationState); }
diff --git a/third_party/WebKit/Source/core/layout/LayoutTable.h b/third_party/WebKit/Source/core/layout/LayoutTable.h index 5f1bcde..adc7a6b 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTable.h +++ b/third_party/WebKit/Source/core/layout/LayoutTable.h
@@ -29,9 +29,7 @@ #include "core/CSSPropertyNames.h" #include "core/CoreExport.h" #include "core/layout/LayoutBlock.h" -#include "core/paint/PaintResult.h" #include "core/style/CollapsedBorderValue.h" -#include "platform/graphics/paint/CullRect.h" #include "wtf/Vector.h" #include <memory> @@ -377,6 +375,7 @@ LayoutTableCell* cellBefore(const LayoutTableCell*) const; LayoutTableCell* cellAfter(const LayoutTableCell*) const; + typedef Vector<CollapsedBorderValue> CollapsedBorderValues; void invalidateCollapsedBorders(); bool hasSections() const { return m_head || m_foot || m_firstBody; } @@ -406,23 +405,9 @@ void paintMask(const PaintInfo&, const LayoutPoint&) const final; - struct CollapsedBordersInfo { - explicit CollapsedBordersInfo(const Vector<CollapsedBorderValue>& values) - : values(std::move(values)) {} - - PaintResult lastPaintResult = FullyPainted; - CullRect lastPaintRect; - const Vector<CollapsedBorderValue> values; - }; - - bool hasCollapsedBorders() const { - DCHECK(m_collapsedBordersValid); - DCHECK(!m_collapsedBordersInfo || collapseBorders()); - return !!m_collapsedBordersInfo; - } - CollapsedBordersInfo& getCollapsedBordersInfo() const { - DCHECK(hasCollapsedBorders()); - return *m_collapsedBordersInfo; + const CollapsedBorderValues& collapsedBorders() const { + ASSERT(m_collapsedBordersValid); + return m_collapsedBorders; } void subtractCaptionRect(LayoutRect&) const; @@ -565,7 +550,7 @@ // need to compare a cells border against all the adjoining cells, rows, // row groups, column, column groups and table. Thus we cache them in this // field. - std::unique_ptr<CollapsedBordersInfo> m_collapsedBordersInfo; + CollapsedBorderValues m_collapsedBorders; bool m_collapsedBordersValid : 1; mutable bool m_hasColElements : 1;
diff --git a/third_party/WebKit/Source/core/layout/LayoutTableCell.cpp b/third_party/WebKit/Source/core/layout/LayoutTableCell.cpp index e848406e..b842de0d 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTableCell.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutTableCell.cpp
@@ -66,6 +66,34 @@ updateColAndRowSpanFlags(); } +LayoutTableCell::CollapsedBorderValues::CollapsedBorderValues( + const LayoutTable& layoutTable, + const CollapsedBorderValue& startBorder, + const CollapsedBorderValue& endBorder, + const CollapsedBorderValue& beforeBorder, + const CollapsedBorderValue& afterBorder) + : m_layoutTable(layoutTable), + m_startBorder(startBorder), + m_endBorder(endBorder), + m_beforeBorder(beforeBorder), + m_afterBorder(afterBorder) {} + +void LayoutTableCell::CollapsedBorderValues::setCollapsedBorderValues( + const CollapsedBorderValues& other) { + m_startBorder = other.startBorder(); + m_endBorder = other.endBorder(); + m_beforeBorder = other.beforeBorder(); + m_afterBorder = other.afterBorder(); +} + +String LayoutTableCell::CollapsedBorderValues::debugName() const { + return "CollapsedBorderValues"; +} + +LayoutRect LayoutTableCell::CollapsedBorderValues::visualRect() const { + return m_layoutTable.visualRect(); +} + void LayoutTableCell::willBeRemovedFromTree() { LayoutBlockFlow::willBeRemovedFromTree(); @@ -1252,7 +1280,7 @@ TableCellPainter(*this).paint(paintInfo, paintOffset); } -static void addBorderStyle(Vector<CollapsedBorderValue>& borderValues, +static void addBorderStyle(LayoutTable::CollapsedBorderValues& borderValues, CollapsedBorderValue borderValue) { if (!borderValue.isVisible()) return; @@ -1264,45 +1292,56 @@ borderValues.append(borderValue); } -bool LayoutTableCell::collectBorderValues( - Vector<CollapsedBorderValue>& borderValues) { - CollapsedBorderValues newValues = { - computeCollapsedStartBorder(), computeCollapsedEndBorder(), - computeCollapsedBeforeBorder(), computeCollapsedAfterBorder()}; +void LayoutTableCell::collectBorderValues( + LayoutTable::CollapsedBorderValues& borderValues) { + CollapsedBorderValues newValues( + *table(), computeCollapsedStartBorder(), computeCollapsedEndBorder(), + computeCollapsedBeforeBorder(), computeCollapsedAfterBorder()); bool changed = false; - if (!newValues.startBorder.isVisible() && !newValues.endBorder.isVisible() && - !newValues.beforeBorder.isVisible() && - !newValues.afterBorder.isVisible()) { + if (!newValues.startBorder().isVisible() && + !newValues.endBorder().isVisible() && + !newValues.beforeBorder().isVisible() && + !newValues.afterBorder().isVisible()) { changed = !!m_collapsedBorderValues; m_collapsedBorderValues = nullptr; } else if (!m_collapsedBorderValues) { changed = true; - m_collapsedBorderValues = wrapUnique(new CollapsedBorderValues(newValues)); + m_collapsedBorderValues = wrapUnique(new CollapsedBorderValues( + *table(), newValues.startBorder(), newValues.endBorder(), + newValues.beforeBorder(), newValues.afterBorder())); } else { // We check visuallyEquals so that the table cell is invalidated only if a // changed collapsed border is visible in the first place. - changed = !m_collapsedBorderValues->startBorder.visuallyEquals( - newValues.startBorder) || - !m_collapsedBorderValues->endBorder.visuallyEquals( - newValues.endBorder) || - !m_collapsedBorderValues->beforeBorder.visuallyEquals( - newValues.beforeBorder) || - !m_collapsedBorderValues->afterBorder.visuallyEquals( - newValues.afterBorder); + changed = !m_collapsedBorderValues->startBorder().visuallyEquals( + newValues.startBorder()) || + !m_collapsedBorderValues->endBorder().visuallyEquals( + newValues.endBorder()) || + !m_collapsedBorderValues->beforeBorder().visuallyEquals( + newValues.beforeBorder()) || + !m_collapsedBorderValues->afterBorder().visuallyEquals( + newValues.afterBorder()); if (changed) - *m_collapsedBorderValues = newValues; + m_collapsedBorderValues->setCollapsedBorderValues(newValues); } - addBorderStyle(borderValues, newValues.startBorder); - addBorderStyle(borderValues, newValues.endBorder); - addBorderStyle(borderValues, newValues.beforeBorder); - addBorderStyle(borderValues, newValues.afterBorder); - return changed; + // If collapsed borders changed, invalidate the cell's display item client on + // the table's backing. + // TODO(crbug.com/451090#c5): Need a way to invalidate/repaint the borders + // only. + if (changed) + ObjectPaintInvalidator(*table()) + .slowSetPaintingLayerNeedsRepaintAndInvalidateDisplayItemClient( + *this, PaintInvalidationStyleChange); + + addBorderStyle(borderValues, newValues.startBorder()); + addBorderStyle(borderValues, newValues.endBorder()); + addBorderStyle(borderValues, newValues.beforeBorder()); + addBorderStyle(borderValues, newValues.afterBorder()); } void LayoutTableCell::sortBorderValues( - Vector<CollapsedBorderValue>& borderValues) { + LayoutTable::CollapsedBorderValues& borderValues) { std::sort(borderValues.begin(), borderValues.end(), compareBorders); } @@ -1377,6 +1416,23 @@ return LayoutBlockFlow::backgroundIsKnownToBeOpaqueInRect(localRect); } +bool LayoutTableCell::usesTableAsAdditionalDisplayItemClient() const { + // In certain cases such as collapsed borders for composited table cells we + // paint content for the cell into the table graphics layer backing and so + // must use the table's visual rect. + return (hasLayer() && layer()->compositingState() != NotComposited) || + RuntimeEnabledFeatures::slimmingPaintV2Enabled(); +} + +void LayoutTableCell::invalidateDisplayItemClients( + PaintInvalidationReason reason) const { + if (m_collapsedBorderValues && usesTableAsAdditionalDisplayItemClient()) { + ObjectPaintInvalidator(*this).invalidateDisplayItemClient( + *m_collapsedBorderValues, reason); + } + LayoutBlockFlow::invalidateDisplayItemClients(reason); +} + // TODO(lunalu): Deliberately dump the "inner" box of table cells, since that // is what current results reflect. We'd like to clean up the results to dump // both the outer box and the intrinsic padding so that both bits of information
diff --git a/third_party/WebKit/Source/core/layout/LayoutTableCell.h b/third_party/WebKit/Source/core/layout/LayoutTableCell.h index 0b0fd6a..6ce3209 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTableCell.h +++ b/third_party/WebKit/Source/core/layout/LayoutTableCell.h
@@ -185,9 +185,8 @@ int borderBefore() const override; int borderAfter() const override; - // Returns true if any collapsed borders related to this cell changed. - bool collectBorderValues(Vector<CollapsedBorderValue>&); - static void sortBorderValues(Vector<CollapsedBorderValue>&); + void collectBorderValues(LayoutTable::CollapsedBorderValues&); + static void sortBorderValues(LayoutTable::CollapsedBorderValues&); void layout() override; @@ -287,14 +286,38 @@ const char* name() const override { return "LayoutTableCell"; } bool backgroundIsKnownToBeOpaqueInRect(const LayoutRect&) const override; + void invalidateDisplayItemClients(PaintInvalidationReason) const override; - struct CollapsedBorderValues { - CollapsedBorderValue startBorder; - CollapsedBorderValue endBorder; - CollapsedBorderValue beforeBorder; - CollapsedBorderValue afterBorder; + // TODO(wkorman): Consider renaming to more clearly differentiate from + // CollapsedBorderValue. + class CollapsedBorderValues : public DisplayItemClient { + public: + CollapsedBorderValues(const LayoutTable&, + const CollapsedBorderValue& startBorder, + const CollapsedBorderValue& endBorder, + const CollapsedBorderValue& beforeBorder, + const CollapsedBorderValue& afterBorder); + + const CollapsedBorderValue& startBorder() const { return m_startBorder; } + const CollapsedBorderValue& endBorder() const { return m_endBorder; } + const CollapsedBorderValue& beforeBorder() const { return m_beforeBorder; } + const CollapsedBorderValue& afterBorder() const { return m_afterBorder; } + + void setCollapsedBorderValues(const CollapsedBorderValues& other); + + // DisplayItemClient methods. + String debugName() const; + LayoutRect visualRect() const; + + private: + const LayoutTable& m_layoutTable; + CollapsedBorderValue m_startBorder; + CollapsedBorderValue m_endBorder; + CollapsedBorderValue m_beforeBorder; + CollapsedBorderValue m_afterBorder; }; + bool usesTableAsAdditionalDisplayItemClient() const; const CollapsedBorderValues* collapsedBorderValues() const { return m_collapsedBorderValues.get(); } @@ -306,8 +329,6 @@ // A table cell's location is relative to its containing section. LayoutBox* locationContainer() const override { return section(); } - LayoutRect localVisualRect() const override; - protected: void styleDidChange(StyleDifference, const ComputedStyle* oldStyle) override; void computePreferredLogicalWidths() override; @@ -331,6 +352,7 @@ void paintMask(const PaintInfo&, const LayoutPoint&) const override; LayoutSize offsetFromContainer(const LayoutObject*) const override; + LayoutRect localVisualRect() const override; int borderHalfLeft(bool outer) const; int borderHalfRight(bool outer) const; @@ -368,8 +390,8 @@ // See also https://code.google.com/p/chromium/issues/detail?id=128227 for // some history. // - // Those functions are called before paint invalidation if the collapsed - // borders cache is invalidated on LayoutTable. + // Those functions are called when the cache (m_collapsedBorders) is + // invalidated on LayoutTable. CollapsedBorderValue computeCollapsedStartBorder( IncludeBorderColorOrNot = IncludeBorderColor) const; CollapsedBorderValue computeCollapsedEndBorder(
diff --git a/third_party/WebKit/Source/core/layout/LayoutTableSection.h b/third_party/WebKit/Source/core/layout/LayoutTableSection.h index 6c82c3ad..5c0b9f70 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTableSection.h +++ b/third_party/WebKit/Source/core/layout/LayoutTableSection.h
@@ -57,13 +57,6 @@ unsigned m_end; }; -inline bool operator==(const CellSpan& a, const CellSpan& b) { - return a.start() == b.start() && a.end() == b.end(); -} -inline bool operator!=(const CellSpan& a, const CellSpan& b) { - return !(a == b); -} - class LayoutTableCell; class LayoutTableRow; @@ -303,13 +296,8 @@ // columnPos vectors. LayoutRect logicalRectForWritingModeAndDirection(const LayoutRect&) const; - CellSpan fullTableRowSpan() const { return CellSpan(0, m_grid.size()); } - CellSpan fullTableEffectiveColumnSpan() const { - return CellSpan(0, table()->numEffectiveColumns()); - } CellSpan dirtiedRows(const LayoutRect& visualRect) const; CellSpan dirtiedEffectiveColumns(const LayoutRect& visualRect) const; - const HashSet<LayoutTableCell*>& overflowingCells() const { return m_overflowingCells; } @@ -413,6 +401,11 @@ void computeOverflowFromCells(unsigned totalRows, unsigned nEffCols); + CellSpan fullTableRowSpan() const { return CellSpan(0, m_grid.size()); } + CellSpan fullTableEffectiveColumnSpan() const { + return CellSpan(0, table()->numEffectiveColumns()); + } + // These two functions take a rectangle as input that has been flipped by // logicalRectForWritingModeAndDirection. // The returned span of rows or columns is end-exclusive, and empty if
diff --git a/third_party/WebKit/Source/core/layout/LayoutTestHelper.cpp b/third_party/WebKit/Source/core/layout/LayoutTestHelper.cpp index 34e47ae..b6ad8f79 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTestHelper.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutTestHelper.cpp
@@ -61,7 +61,7 @@ FrameLoaderClientWithParent::create(document().frame()); m_subframe = LocalFrame::create(m_childFrameLoaderClient.get(), document().frame()->host(), &iframe); - m_subframe->setView(FrameView::create(m_subframe.get(), IntSize(500, 500))); + m_subframe->setView(FrameView::create(*m_subframe, IntSize(500, 500))); m_subframe->init(); m_subframe->view()->setParentVisible(true); m_subframe->view()->setSelfVisible(true);
diff --git a/third_party/WebKit/Source/core/layout/LayoutTextControlSingleLine.h b/third_party/WebKit/Source/core/layout/LayoutTextControlSingleLine.h index dc0fe98..1c552730 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTextControlSingleLine.h +++ b/third_party/WebKit/Source/core/layout/LayoutTextControlSingleLine.h
@@ -92,9 +92,9 @@ // ---------------------------- -class LayoutTextControlInnerBlock : public LayoutBlockFlow { +class LayoutTextControlInnerEditor : public LayoutBlockFlow { public: - LayoutTextControlInnerBlock(Element* element) : LayoutBlockFlow(element) {} + LayoutTextControlInnerEditor(Element* element) : LayoutBlockFlow(element) {} bool shouldIgnoreOverflowPropertyForInlineBlockBaseline() const override { return true; }
diff --git a/third_party/WebKit/Source/core/layout/line/InlineFlowBox.cpp b/third_party/WebKit/Source/core/layout/line/InlineFlowBox.cpp index ab112b6..9ae81aba 100644 --- a/third_party/WebKit/Source/core/layout/line/InlineFlowBox.cpp +++ b/third_party/WebKit/Source/core/layout/line/InlineFlowBox.cpp
@@ -1183,7 +1183,7 @@ return; if (!m_overflow) - m_overflow = wrapUnique(new SimpleOverflowModel(frameBox, frameBox)); + m_overflow = makeUnique<SimpleOverflowModel>(frameBox, frameBox); m_overflow->setLayoutOverflow(rect); } @@ -1195,7 +1195,7 @@ return; if (!m_overflow) - m_overflow = wrapUnique(new SimpleOverflowModel(frameBox, frameBox)); + m_overflow = makeUnique<SimpleOverflowModel>(frameBox, frameBox); m_overflow->setVisualOverflow(rect); }
diff --git a/third_party/WebKit/Source/core/layout/shapes/Shape.cpp b/third_party/WebKit/Source/core/layout/shapes/Shape.cpp index a502cc7..7484888 100644 --- a/third_party/WebKit/Source/core/layout/shapes/Shape.cpp +++ b/third_party/WebKit/Source/core/layout/shapes/Shape.cpp
@@ -53,7 +53,7 @@ static std::unique_ptr<Shape> createInsetShape(const FloatRoundedRect& bounds) { ASSERT(bounds.rect().width() >= 0 && bounds.rect().height() >= 0); - return wrapUnique(new BoxShape(bounds)); + return makeUnique<BoxShape>(bounds); } static std::unique_ptr<Shape> createCircleShape(const FloatPoint& center, @@ -213,7 +213,7 @@ std::unique_ptr<Shape> Shape::createEmptyRasterShape(WritingMode writingMode, float margin) { std::unique_ptr<RasterShapeIntervals> intervals = - wrapUnique(new RasterShapeIntervals(0, 0)); + makeUnique<RasterShapeIntervals>(0, 0); std::unique_ptr<RasterShape> rasterShape = wrapUnique(new RasterShape(std::move(intervals), IntSize())); rasterShape->m_writingMode = writingMode;
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGShape.cpp b/third_party/WebKit/Source/core/layout/svg/LayoutSVGShape.cpp index c3b8714..932e938c0 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGShape.cpp +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGShape.cpp
@@ -72,7 +72,7 @@ void LayoutSVGShape::createPath() { if (!m_path) - m_path = wrapUnique(new Path()); + m_path = makeUnique<Path>(); *m_path = toSVGGeometryElement(element())->asPath(); if (m_rareData.get()) m_rareData->m_cachedNonScalingStrokePath.clear(); @@ -333,7 +333,7 @@ LayoutSVGShapeRareData& LayoutSVGShape::ensureRareData() const { if (!m_rareData) - m_rareData = wrapUnique(new LayoutSVGShapeRareData()); + m_rareData = makeUnique<LayoutSVGShapeRareData>(); return *m_rareData.get(); }
diff --git a/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp b/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp index 737dfbe9..1b98d50 100644 --- a/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp +++ b/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp
@@ -94,7 +94,7 @@ }; std::unique_ptr<Reader> obtainReader(Client* client) override { - return WTF::wrapUnique(new EmptyDataReader(client)); + return makeUnique<EmptyDataReader>(client); } const char* debugName() const override { return "EmptyDataHandle"; } }; @@ -527,8 +527,7 @@ // TODO(horo): If we support any API which expose the internal body, we will // have to read the body. And also HTTPCache changes will be needed because // it doesn't store the body of redirect responses. - responseReceived(resource, redirectResponse, - wrapUnique(new EmptyDataHandle())); + responseReceived(resource, redirectResponse, makeUnique<EmptyDataHandle>()); if (m_client) { DCHECK(m_actualRequest.isNull());
diff --git a/third_party/WebKit/Source/core/loader/EmptyClients.cpp b/third_party/WebKit/Source/core/loader/EmptyClients.cpp index e9cfc4d3..5afe336 100644 --- a/third_party/WebKit/Source/core/loader/EmptyClients.cpp +++ b/third_party/WebKit/Source/core/loader/EmptyClients.cpp
@@ -123,7 +123,7 @@ std::unique_ptr<WebFrameScheduler> EmptyChromeClient::createFrameScheduler( BlameContext*) { - return wrapUnique(new EmptyFrameScheduler()); + return makeUnique<EmptyFrameScheduler>(); } NavigationPolicy EmptyFrameLoaderClient::decidePolicyForNavigation( @@ -132,7 +132,8 @@ NavigationType, NavigationPolicy, bool, - bool) { + bool, + HTMLFormElement*) { return NavigationPolicyIgnore; }
diff --git a/third_party/WebKit/Source/core/loader/EmptyClients.h b/third_party/WebKit/Source/core/loader/EmptyClients.h index ebdeaf96..6384ae67 100644 --- a/third_party/WebKit/Source/core/loader/EmptyClients.h +++ b/third_party/WebKit/Source/core/loader/EmptyClients.h
@@ -274,7 +274,8 @@ NavigationType, NavigationPolicy, bool, - bool) override; + bool, + HTMLFormElement*) override; void dispatchWillSendSubmitEvent(HTMLFormElement*) override; void dispatchWillSubmitForm(HTMLFormElement*) override;
diff --git a/third_party/WebKit/Source/core/loader/FrameFetchContextTest.cpp b/third_party/WebKit/Source/core/loader/FrameFetchContextTest.cpp index 0ee5882..bbca2fa 100644 --- a/third_party/WebKit/Source/core/loader/FrameFetchContextTest.cpp +++ b/third_party/WebKit/Source/core/loader/FrameFetchContextTest.cpp
@@ -109,7 +109,7 @@ childClient = StubFrameLoaderClientWithParent::create(document->frame()); childFrame = LocalFrame::create(childClient.get(), document->frame()->host(), owner.get()); - childFrame->setView(FrameView::create(childFrame.get(), IntSize(500, 500))); + childFrame->setView(FrameView::create(*childFrame, IntSize(500, 500))); childFrame->init(); childDocumentLoader = DocumentLoader::create( childFrame.get(), ResourceRequest("http://www.example.com"),
diff --git a/third_party/WebKit/Source/core/loader/FrameLoader.cpp b/third_party/WebKit/Source/core/loader/FrameLoader.cpp index 1ed1019..2f3cd18 100644 --- a/third_party/WebKit/Source/core/loader/FrameLoader.cpp +++ b/third_party/WebKit/Source/core/loader/FrameLoader.cpp
@@ -1619,7 +1619,7 @@ policy = client()->decidePolicyForNavigation(request, loader, type, policy, replacesCurrentHistoryItem, - isClientRedirect); + isClientRedirect, form); if (policy == NavigationPolicyCurrentTab) return true; if (policy == NavigationPolicyIgnore)
diff --git a/third_party/WebKit/Source/core/loader/FrameLoaderClient.h b/third_party/WebKit/Source/core/loader/FrameLoaderClient.h index 3ca1cd5d..c65478d 100644 --- a/third_party/WebKit/Source/core/loader/FrameLoaderClient.h +++ b/third_party/WebKit/Source/core/loader/FrameLoaderClient.h
@@ -119,7 +119,8 @@ NavigationType, NavigationPolicy, bool shouldReplaceCurrentEntry, - bool isClientRedirect) = 0; + bool isClientRedirect, + HTMLFormElement*) = 0; virtual void dispatchWillSendSubmitEvent(HTMLFormElement*) = 0; virtual void dispatchWillSubmitForm(HTMLFormElement*) = 0;
diff --git a/third_party/WebKit/Source/core/loader/ImageLoader.cpp b/third_party/WebKit/Source/core/loader/ImageLoader.cpp index 3668923..549c3b20 100644 --- a/third_party/WebKit/Source/core/loader/ImageLoader.cpp +++ b/third_party/WebKit/Source/core/loader/ImageLoader.cpp
@@ -91,7 +91,7 @@ static std::unique_ptr<Task> create(ImageLoader* loader, UpdateFromElementBehavior updateBehavior, ReferrerPolicy referrerPolicy) { - return wrapUnique(new Task(loader, updateBehavior, referrerPolicy)); + return makeUnique<Task>(loader, updateBehavior, referrerPolicy); } Task(ImageLoader* loader,
diff --git a/third_party/WebKit/Source/core/loader/NavigationScheduler.cpp b/third_party/WebKit/Source/core/loader/NavigationScheduler.cpp index a52bf28..923e203a 100644 --- a/third_party/WebKit/Source/core/loader/NavigationScheduler.cpp +++ b/third_party/WebKit/Source/core/loader/NavigationScheduler.cpp
@@ -135,7 +135,7 @@ bool replacesCurrentItem() const { return m_replacesCurrentItem; } bool isLocationChange() const { return m_isLocationChange; } std::unique_ptr<UserGestureIndicator> createUserGestureIndicator() { - return wrapUnique(new UserGestureIndicator(m_userGestureToken)); + return makeUnique<UserGestureIndicator>(m_userGestureToken); } DEFINE_INLINE_VIRTUAL_TRACE() { visitor->trace(m_originDocument); }
diff --git a/third_party/WebKit/Source/core/loader/ProgressTracker.cpp b/third_party/WebKit/Source/core/loader/ProgressTracker.cpp index 23721d4..7861151 100644 --- a/third_party/WebKit/Source/core/loader/ProgressTracker.cpp +++ b/third_party/WebKit/Source/core/loader/ProgressTracker.cpp
@@ -142,8 +142,7 @@ (m_finishedParsing || priority < ResourceLoadPriorityHigh)) return; m_progressItems.set( - identifier, - wrapUnique(new ProgressItem(progressItemDefaultEstimatedLength))); + identifier, makeUnique<ProgressItem>(progressItemDefaultEstimatedLength)); } void ProgressTracker::incrementProgress(unsigned long identifier,
diff --git a/third_party/WebKit/Source/core/loader/ThreadableLoaderTest.cpp b/third_party/WebKit/Source/core/loader/ThreadableLoaderTest.cpp index 29b195a..30df93a 100644 --- a/third_party/WebKit/Source/core/loader/ThreadableLoaderTest.cpp +++ b/third_party/WebKit/Source/core/loader/ThreadableLoaderTest.cpp
@@ -176,7 +176,7 @@ ThreadableLoaderClient* client, CrossOriginRequestPolicy crossOriginRequestPolicy) override { std::unique_ptr<WaitableEvent> completionEvent = - wrapUnique(new WaitableEvent()); + makeUnique<WaitableEvent>(); postTaskToWorkerGlobalScope( BLINK_FROM_HERE, createCrossThreadTask( @@ -189,7 +189,7 @@ void startLoader(const ResourceRequest& request) override { std::unique_ptr<WaitableEvent> completionEvent = - wrapUnique(new WaitableEvent()); + makeUnique<WaitableEvent>(); postTaskToWorkerGlobalScope( BLINK_FROM_HERE, createCrossThreadTask( @@ -226,7 +226,7 @@ testing::runPendingTasks(); std::unique_ptr<WaitableEvent> completionEvent = - wrapUnique(new WaitableEvent()); + makeUnique<WaitableEvent>(); postTaskToWorkerGlobalScope( BLINK_FROM_HERE, createCrossThreadTask( @@ -237,7 +237,7 @@ } void onSetUp() override { - m_mockWorkerReportingProxy = wrapUnique(new MockWorkerReportingProxy()); + m_mockWorkerReportingProxy = makeUnique<MockWorkerReportingProxy>(); m_securityOrigin = document().getSecurityOrigin(); m_workerThread = wrapUnique(new WorkerThreadForTest( this, *m_mockWorkerReportingProxy, m_threadHeapMode));
diff --git a/third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp b/third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp index 49bb2af..f481366 100644 --- a/third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp +++ b/third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp
@@ -53,8 +53,7 @@ std::unique_ptr<Vector<char>> createVectorFromMemoryRegion( const char* data, unsigned dataLength) { - std::unique_ptr<Vector<char>> buffer = - wrapUnique(new Vector<char>(dataLength)); + std::unique_ptr<Vector<char>> buffer = makeUnique<Vector<char>>(dataLength); memcpy(buffer->data(), data, dataLength); return buffer; }
diff --git a/third_party/WebKit/Source/core/offscreencanvas/OffscreenCanvas.cpp b/third_party/WebKit/Source/core/offscreencanvas/OffscreenCanvas.cpp index 94cbf94..e0b6e08c 100644 --- a/third_party/WebKit/Source/core/offscreencanvas/OffscreenCanvas.cpp +++ b/third_party/WebKit/Source/core/offscreencanvas/OffscreenCanvas.cpp
@@ -32,7 +32,7 @@ void OffscreenCanvas::setWidth(unsigned width, ExceptionState& exceptionState) { // If this OffscreenCanvas is transferred control by an html canvas, // its size is determined by html canvas's size and cannot be resized. - if (m_canvasId >= 0) { + if (hasPlaceholderCanvas()) { exceptionState.throwDOMException(InvalidStateError, "Resizing is not allowed on an " "OffscreenCanvas that has been " @@ -45,7 +45,7 @@ void OffscreenCanvas::setHeight(unsigned height, ExceptionState& exceptionState) { // Same comment as above. - if (m_canvasId >= 0) { + if (hasPlaceholderCanvas()) { exceptionState.throwDOMException(InvalidStateError, "Resizing is not allowed on an " "OffscreenCanvas that has been " @@ -184,8 +184,8 @@ // (either main or worker) to the browser process and remains unchanged // throughout the lifetime of this OffscreenCanvas. m_frameDispatcher = wrapUnique(new OffscreenCanvasFrameDispatcherImpl( - m_clientId, m_sinkId, m_localId, m_nonceHigh, m_nonceLow, width(), - height())); + m_clientId, m_sinkId, m_localId, m_nonceHigh, m_nonceLow, + m_placeholderCanvasId, width(), height())); } return m_frameDispatcher.get(); }
diff --git a/third_party/WebKit/Source/core/offscreencanvas/OffscreenCanvas.h b/third_party/WebKit/Source/core/offscreencanvas/OffscreenCanvas.h index 656b4dd2..1a5c283 100644 --- a/third_party/WebKit/Source/core/offscreencanvas/OffscreenCanvas.h +++ b/third_party/WebKit/Source/core/offscreencanvas/OffscreenCanvas.h
@@ -47,8 +47,13 @@ ExceptionState&); IntSize size() const { return m_size; } - void setAssociatedCanvasId(int canvasId) { m_canvasId = canvasId; } - int getAssociatedCanvasId() const { return m_canvasId; } + void setPlaceholderCanvasId(int canvasId) { + m_placeholderCanvasId = canvasId; + } + int placeholderCanvasId() const { return m_placeholderCanvasId; } + bool hasPlaceholderCanvas() { + return m_placeholderCanvasId != kNoPlaceholderCanvas; + } bool isNeutered() const { return m_isNeutered; } void setNeutered(); CanvasRenderingContext* getCanvasRenderingContext( @@ -110,8 +115,12 @@ static CanvasRenderingContextFactory* getRenderingContextFactory(int); Member<CanvasRenderingContext> m_context; - int m_canvasId = -1; // DOMNodeIds starts from 0, using -1 to indicate no - // associated canvas element. + + enum { + kNoPlaceholderCanvas = -1, // DOMNodeIds starts from 0, using -1 to + // indicate no associated canvas element. + }; + int m_placeholderCanvasId = kNoPlaceholderCanvas; IntSize m_size; bool m_isNeutered = false;
diff --git a/third_party/WebKit/Source/core/origin_trials/OriginTrialContextTest.cpp b/third_party/WebKit/Source/core/origin_trials/OriginTrialContextTest.cpp index c96d5272..60339a3f 100644 --- a/third_party/WebKit/Source/core/origin_trials/OriginTrialContextTest.cpp +++ b/third_party/WebKit/Source/core/origin_trials/OriginTrialContextTest.cpp
@@ -73,7 +73,7 @@ OriginTrialContextTest() : m_frameworkWasEnabled(RuntimeEnabledFeatures::originTrialsEnabled()), m_executionContext(new NullExecutionContext()), - m_tokenValidator(wrapUnique(new MockTokenValidator())), + m_tokenValidator(makeUnique<MockTokenValidator>()), m_originTrialContext(new OriginTrialContext(m_executionContext.get(), m_tokenValidator.get())), m_histogramTester(new HistogramTester()) {
diff --git a/third_party/WebKit/Source/core/page/scrolling/ScrollState.cpp b/third_party/WebKit/Source/core/page/scrolling/ScrollState.cpp index 51d46ae..0a4ab78 100644 --- a/third_party/WebKit/Source/core/page/scrolling/ScrollState.cpp +++ b/third_party/WebKit/Source/core/page/scrolling/ScrollState.cpp
@@ -28,7 +28,7 @@ ScrollState* ScrollState::create(ScrollStateInit init) { std::unique_ptr<ScrollStateData> scrollStateData = - wrapUnique(new ScrollStateData()); + makeUnique<ScrollStateData>(); scrollStateData->delta_x = init.deltaX(); scrollStateData->delta_y = init.deltaY(); scrollStateData->position_x = init.positionX();
diff --git a/third_party/WebKit/Source/core/page/scrolling/ScrollStateTest.cpp b/third_party/WebKit/Source/core/page/scrolling/ScrollStateTest.cpp index 1dcf5a6f..42c8b7d2 100644 --- a/third_party/WebKit/Source/core/page/scrolling/ScrollStateTest.cpp +++ b/third_party/WebKit/Source/core/page/scrolling/ScrollStateTest.cpp
@@ -19,7 +19,7 @@ bool beginning, bool ending) { std::unique_ptr<ScrollStateData> scrollStateData = - wrapUnique(new ScrollStateData()); + makeUnique<ScrollStateData>(); scrollStateData->delta_x = deltaX; scrollStateData->delta_y = deltaY; scrollStateData->is_beginning = beginning;
diff --git a/third_party/WebKit/Source/core/paint/BoxPaintInvalidator.cpp b/third_party/WebKit/Source/core/paint/BoxPaintInvalidator.cpp index 2403781b..a97bd7d 100644 --- a/third_party/WebKit/Source/core/paint/BoxPaintInvalidator.cpp +++ b/third_party/WebKit/Source/core/paint/BoxPaintInvalidator.cpp
@@ -182,9 +182,6 @@ DCHECK(borderBoxChanged); - if (m_box.hasNonCompositedScrollbars()) - return PaintInvalidationBorderBoxChange; - if (style.hasVisualOverflowingEffect() || style.hasAppearance() || style.hasFilterInducingProperty() || style.resize() != RESIZE_NONE || style.hasMask())
diff --git a/third_party/WebKit/Source/core/paint/FramePainter.cpp b/third_party/WebKit/Source/core/paint/FramePainter.cpp index db2a9b9..6fcc221 100644 --- a/third_party/WebKit/Source/core/paint/FramePainter.cpp +++ b/third_party/WebKit/Source/core/paint/FramePainter.cpp
@@ -94,11 +94,20 @@ Optional<ScopedPaintChunkProperties> scopedPaintChunkProperties; if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { - if (TransformPaintPropertyNode* transform = - m_frameView->preTranslation()) { + if (const PropertyTreeState* contentsState = + m_frameView->totalPropertyTreeStateForContents()) { + // The scrollbar's property nodes are similar to the frame view's + // contents state but we want to exclude the content-specific + // properties. This prevents the scrollbars from scrolling, for example. PaintChunkProperties properties( context.getPaintController().currentPaintChunkProperties()); - properties.transform = transform; + properties.transform = m_frameView->preTranslation(); + properties.clip = m_frameView->contentClip()->parent(); + properties.effect = contentsState->effect(); + auto* scrollBarScroll = contentsState->scroll(); + if (m_frameView->scroll()) + scrollBarScroll = m_frameView->scroll()->parent(); + properties.scroll = scrollBarScroll; scopedPaintChunkProperties.emplace(context.getPaintController(), *frameView().layoutView(), properties);
diff --git a/third_party/WebKit/Source/core/paint/PaintInvalidator.cpp b/third_party/WebKit/Source/core/paint/PaintInvalidator.cpp index e75f691..23d71cbf 100644 --- a/third_party/WebKit/Source/core/paint/PaintInvalidator.cpp +++ b/third_party/WebKit/Source/core/paint/PaintInvalidator.cpp
@@ -214,8 +214,11 @@ context.paintingLayer->setNeedsPaintPhaseDescendantBlockBackgrounds(); } - if (object.isTable() && toLayoutTable(object).hasCollapsedBorders()) - context.paintingLayer->setNeedsPaintPhaseDescendantBlockBackgrounds(); + if (object.isTable()) { + const LayoutTable& table = toLayoutTable(object); + if (table.collapseBorders() && !table.collapsedBorders().isEmpty()) + context.paintingLayer->setNeedsPaintPhaseDescendantBlockBackgrounds(); + } } namespace {
diff --git a/third_party/WebKit/Source/core/paint/PaintLayer.cpp b/third_party/WebKit/Source/core/paint/PaintLayer.cpp index 9c040f8..ec0536a 100644 --- a/third_party/WebKit/Source/core/paint/PaintLayer.cpp +++ b/third_party/WebKit/Source/core/paint/PaintLayer.cpp
@@ -1026,7 +1026,7 @@ const AncestorDependentCompositingInputs& compositingInputs, bool hasAncestorWithClipPath) { m_ancestorDependentCompositingInputs = - wrapUnique(new AncestorDependentCompositingInputs(compositingInputs)); + makeUnique<AncestorDependentCompositingInputs>(compositingInputs); m_hasAncestorWithClipPath = hasAncestorWithClipPath; m_needsAncestorDependentCompositingInputsUpdate = false; } @@ -1541,7 +1541,7 @@ void PaintLayer::updateStackingNode() { DCHECK(!m_stackingNode); if (requiresStackingNode()) - m_stackingNode = wrapUnique(new PaintLayerStackingNode(this)); + m_stackingNode = makeUnique<PaintLayerStackingNode>(this); else m_stackingNode = nullptr; } @@ -3210,7 +3210,7 @@ // FIXME: Rename? void showLayerTree(const blink::PaintLayer* layer) { if (!layer) { - fprintf(stderr, "Cannot showLayerTree. Root is (nil)\n"); + LOG(INFO) << "Cannot showLayerTree. Root is (nil)"; return; } @@ -3224,13 +3224,13 @@ blink::LayoutAsTextDontUpdateLayout | blink::LayoutAsTextShowLayoutState, layer); - fprintf(stderr, "%s\n", output.utf8().data()); + LOG(INFO) << output.utf8().data(); } } void showLayerTree(const blink::LayoutObject* layoutObject) { if (!layoutObject) { - fprintf(stderr, "Cannot showLayerTree. Root is (nil)\n"); + LOG(INFO) << "Cannot showLayerTree. Root is (nil)"; return; } showLayerTree(layoutObject->enclosingLayer());
diff --git a/third_party/WebKit/Source/core/paint/PaintLayerPainter.cpp b/third_party/WebKit/Source/core/paint/PaintLayerPainter.cpp index c96cfca..e1c8fdc 100644 --- a/third_party/WebKit/Source/core/paint/PaintLayerPainter.cpp +++ b/third_party/WebKit/Source/core/paint/PaintLayerPainter.cpp
@@ -150,13 +150,17 @@ return false; // Create subsequence for only stacking contexts whose painting are atomic. - if (!paintLayer.stackingNode()->isStackingContext()) + // SVG is also painted atomically. + if (!paintLayer.stackingNode()->isStackingContext() && + !paintLayer.layoutObject()->isSVGRoot()) return false; // The layer doesn't have children. Subsequence caching is not worth because // normally the actual painting will be cheap. + // SVG is also painted atomically. if (!PaintLayerStackingNodeIterator(*paintLayer.stackingNode(), AllChildren) - .next()) + .next() && + !paintLayer.layoutObject()->isSVGRoot()) return false; // When in FOUC-avoidance mode, don't cache any subsequences, to avoid having
diff --git a/third_party/WebKit/Source/core/paint/PaintLayerPainterTest.cpp b/third_party/WebKit/Source/core/paint/PaintLayerPainterTest.cpp index e5c6c16..258637a 100644 --- a/third_party/WebKit/Source/core/paint/PaintLayerPainterTest.cpp +++ b/third_party/WebKit/Source/core/paint/PaintLayerPainterTest.cpp
@@ -197,6 +197,152 @@ } } +TEST_P(PaintLayerPainterTest, CachedSubsequenceForSVGRoot) { + setBodyInnerHTML( + "<svg id='svg' style='position: relative'>" + " <rect id='rect' x='10' y='10' width='100' height='100' rx='15' " + "ry='15'/>" + "</svg>" + "<div id='div' style='position: relative; width: 50x; height: " + "50px'></div>"); + document().view()->updateAllLifecyclePhases(); + + PaintLayer& htmlLayer = + *toLayoutBoxModelObject(document().documentElement()->layoutObject()) + ->layer(); + LayoutObject& svg = *document().getElementById("svg")->layoutObject(); + PaintLayer& svgLayer = *toLayoutBoxModelObject(svg).layer(); + LayoutObject& rect = *document().getElementById("rect")->layoutObject(); + LayoutObject& div = *document().getElementById("div")->layoutObject(); + + DisplayItem::Type clipBoxBegin = + DisplayItem::paintPhaseToClipBoxType(PaintPhaseForeground); + DisplayItem::Type clipBoxEnd = + DisplayItem::clipTypeToEndClipType(clipBoxBegin); + + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { + if (RuntimeEnabledFeatures::rootLayerScrollingEnabled()) { + // SPv2 slips the clip box (see BoxClipper). + EXPECT_DISPLAY_LIST( + rootPaintController().getDisplayItemList(), 10, + TestDisplayItem(*layoutView().layer(), DisplayItem::kSubsequence), + TestDisplayItem(layoutView(), documentBackgroundType), + TestDisplayItem(htmlLayer, DisplayItem::kSubsequence), + TestDisplayItem(svgLayer, DisplayItem::kSubsequence), + TestDisplayItem(svg, DisplayItem::kBeginTransform), + TestDisplayItem(rect, foregroundType), + TestDisplayItem(svg, DisplayItem::kEndTransform), + TestDisplayItem(svgLayer, DisplayItem::kEndSubsequence), + TestDisplayItem(htmlLayer, DisplayItem::kEndSubsequence), + TestDisplayItem(*layoutView().layer(), DisplayItem::kEndSubsequence)); + } else { + // SPv2 slips the clip box (see BoxClipper). + EXPECT_DISPLAY_LIST( + rootPaintController().getDisplayItemList(), 12, + TestDisplayItem(layoutView(), + DisplayItem::kClipFrameToVisibleContentRect), + TestDisplayItem(*layoutView().layer(), DisplayItem::kSubsequence), + TestDisplayItem(layoutView(), documentBackgroundType), + TestDisplayItem(htmlLayer, DisplayItem::kSubsequence), + TestDisplayItem(svgLayer, DisplayItem::kSubsequence), + TestDisplayItem(svg, DisplayItem::kBeginTransform), + TestDisplayItem(rect, foregroundType), + TestDisplayItem(svg, DisplayItem::kEndTransform), + TestDisplayItem(svgLayer, DisplayItem::kEndSubsequence), + TestDisplayItem(htmlLayer, DisplayItem::kEndSubsequence), + TestDisplayItem(*layoutView().layer(), DisplayItem::kEndSubsequence), + TestDisplayItem(layoutView(), + DisplayItem::clipTypeToEndClipType( + DisplayItem::kClipFrameToVisibleContentRect))); + } + } else { + EXPECT_DISPLAY_LIST( + rootPaintController().getDisplayItemList(), 10, + TestDisplayItem(layoutView(), documentBackgroundType), + TestDisplayItem(htmlLayer, DisplayItem::kSubsequence), + TestDisplayItem(svgLayer, DisplayItem::kSubsequence), + TestDisplayItem(svg, clipBoxBegin), + TestDisplayItem(svg, DisplayItem::kBeginTransform), + TestDisplayItem(rect, foregroundType), + TestDisplayItem(svg, DisplayItem::kEndTransform), + TestDisplayItem(svg, clipBoxEnd), + TestDisplayItem(svgLayer, DisplayItem::kEndSubsequence), + TestDisplayItem(htmlLayer, DisplayItem::kEndSubsequence)); + } + + // Change the color of the div. This should not invalidate the subsequence + // for the SVG root. + toHTMLElement(div.node()) + ->setAttribute(HTMLNames::styleAttr, + "position: relative; width: 50x; height: 50px; " + "background-color: green"); + document().view()->updateAllLifecyclePhasesExceptPaint(); + EXPECT_TRUE(paintWithoutCommit()); + + // Reuse of SVG and document background. 2 fewer with SPv2 enabled because + // clip display items don't appear in SPv2 display lists. + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) + EXPECT_EQ(6, numCachedNewItems()); + else + EXPECT_EQ(8, numCachedNewItems()); + + commit(); + + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { + if (RuntimeEnabledFeatures::rootLayerScrollingEnabled()) { + EXPECT_DISPLAY_LIST( + rootPaintController().getDisplayItemList(), 11, + TestDisplayItem(*layoutView().layer(), DisplayItem::kSubsequence), + TestDisplayItem(layoutView(), documentBackgroundType), + TestDisplayItem(htmlLayer, DisplayItem::kSubsequence), + TestDisplayItem(svgLayer, DisplayItem::kSubsequence), + TestDisplayItem(svg, DisplayItem::kBeginTransform), + TestDisplayItem(rect, foregroundType), + TestDisplayItem(svg, DisplayItem::kEndTransform), + TestDisplayItem(svgLayer, DisplayItem::kEndSubsequence), + TestDisplayItem(div, backgroundType), + TestDisplayItem(htmlLayer, DisplayItem::kEndSubsequence), + TestDisplayItem(*layoutView().layer(), DisplayItem::kEndSubsequence)); + } else { + EXPECT_DISPLAY_LIST( + rootPaintController().getDisplayItemList(), 13, + TestDisplayItem(layoutView(), + DisplayItem::kClipFrameToVisibleContentRect), + TestDisplayItem(*layoutView().layer(), DisplayItem::kSubsequence), + TestDisplayItem(layoutView(), documentBackgroundType), + TestDisplayItem(htmlLayer, DisplayItem::kSubsequence), + TestDisplayItem(svgLayer, DisplayItem::kSubsequence), + TestDisplayItem(svg, DisplayItem::kBeginTransform), + TestDisplayItem(rect, foregroundType), + TestDisplayItem(svg, DisplayItem::kEndTransform), + TestDisplayItem(svgLayer, DisplayItem::kEndSubsequence), + TestDisplayItem(div, backgroundType), + TestDisplayItem(htmlLayer, DisplayItem::kEndSubsequence), + TestDisplayItem(*layoutView().layer(), DisplayItem::kEndSubsequence), + TestDisplayItem(layoutView(), + DisplayItem::clipTypeToEndClipType( + DisplayItem::kClipFrameToVisibleContentRect))); + } + } else { + EXPECT_DISPLAY_LIST( + rootPaintController().getDisplayItemList(), 11, + TestDisplayItem(layoutView(), documentBackgroundType), + TestDisplayItem(htmlLayer, DisplayItem::kSubsequence), + TestDisplayItem(svgLayer, DisplayItem::kSubsequence), + TestDisplayItem(svg, clipBoxBegin), + TestDisplayItem(svg, DisplayItem::kBeginTransform), + TestDisplayItem(rect, foregroundType), + TestDisplayItem(svg, DisplayItem::kEndTransform), + TestDisplayItem(svg, clipBoxEnd), + TestDisplayItem(svgLayer, DisplayItem::kEndSubsequence), + TestDisplayItem(div, backgroundType), + TestDisplayItem(htmlLayer, DisplayItem::kEndSubsequence), + TestDisplayItem(layoutView(), + DisplayItem::clipTypeToEndClipType( + DisplayItem::kClipFrameToVisibleContentRect))); + } +} + TEST_P(PaintLayerPainterTest, CachedSubsequenceOnInterestRectChange) { // TODO(wangxianzhu): SPv2 deals with interest rect differently, so disable // this test for SPv2 temporarily.
diff --git a/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.h b/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.h index 5f36438..b469607 100644 --- a/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.h +++ b/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.h
@@ -520,7 +520,7 @@ PaintLayerScrollableAreaRareData& ensureRareData() { if (!m_rareData) - m_rareData = wrapUnique(new PaintLayerScrollableAreaRareData()); + m_rareData = makeUnique<PaintLayerScrollableAreaRareData>(); return *m_rareData.get(); }
diff --git a/third_party/WebKit/Source/core/paint/SVGInlineTextBoxPainter.cpp b/third_party/WebKit/Source/core/paint/SVGInlineTextBoxPainter.cpp index 549faaf..7c51909 100644 --- a/third_party/WebKit/Source/core/paint/SVGInlineTextBoxPainter.cpp +++ b/third_party/WebKit/Source/core/paint/SVGInlineTextBoxPainter.cpp
@@ -407,11 +407,9 @@ paint.setAntiAlias(true); if (hasShadow(paintInfo, style)) { - std::unique_ptr<DrawLooperBuilder> drawLooperBuilder = - style.textShadow()->createDrawLooper( - DrawLooperBuilder::ShadowRespectsAlpha, - style.visitedDependentColor(CSSPropertyColor)); - paint.setLooper(drawLooperBuilder->detachDrawLooper()); + paint.setLooper(style.textShadow()->createDrawLooper( + DrawLooperBuilder::ShadowRespectsAlpha, + style.visitedDependentColor(CSSPropertyColor))); } if (resourceMode == ApplyToStrokeMode) {
diff --git a/third_party/WebKit/Source/core/paint/TableCellPainter.cpp b/third_party/WebKit/Source/core/paint/TableCellPainter.cpp index ae5d437..2fc5973e 100644 --- a/third_party/WebKit/Source/core/paint/TableCellPainter.cpp +++ b/third_party/WebKit/Source/core/paint/TableCellPainter.cpp
@@ -19,40 +19,40 @@ const ComputedStyle& styleForCellFlow, const LayoutTableCell::CollapsedBorderValues& values) { if (styleForCellFlow.isHorizontalWritingMode()) { - return styleForCellFlow.isLeftToRightDirection() ? values.startBorder - : values.endBorder; + return styleForCellFlow.isLeftToRightDirection() ? values.startBorder() + : values.endBorder(); } - return styleForCellFlow.isFlippedBlocksWritingMode() ? values.afterBorder - : values.beforeBorder; + return styleForCellFlow.isFlippedBlocksWritingMode() ? values.afterBorder() + : values.beforeBorder(); } static const CollapsedBorderValue& collapsedRightBorder( const ComputedStyle& styleForCellFlow, const LayoutTableCell::CollapsedBorderValues& values) { if (styleForCellFlow.isHorizontalWritingMode()) { - return styleForCellFlow.isLeftToRightDirection() ? values.endBorder - : values.startBorder; + return styleForCellFlow.isLeftToRightDirection() ? values.endBorder() + : values.startBorder(); } - return styleForCellFlow.isFlippedBlocksWritingMode() ? values.beforeBorder - : values.afterBorder; + return styleForCellFlow.isFlippedBlocksWritingMode() ? values.beforeBorder() + : values.afterBorder(); } static const CollapsedBorderValue& collapsedTopBorder( const ComputedStyle& styleForCellFlow, const LayoutTableCell::CollapsedBorderValues& values) { if (styleForCellFlow.isHorizontalWritingMode()) - return values.beforeBorder; - return styleForCellFlow.isLeftToRightDirection() ? values.startBorder - : values.endBorder; + return values.beforeBorder(); + return styleForCellFlow.isLeftToRightDirection() ? values.startBorder() + : values.endBorder(); } static const CollapsedBorderValue& collapsedBottomBorder( const ComputedStyle& styleForCellFlow, const LayoutTableCell::CollapsedBorderValues& values) { if (styleForCellFlow.isHorizontalWritingMode()) - return values.afterBorder; - return styleForCellFlow.isLeftToRightDirection() ? values.endBorder - : values.startBorder; + return values.afterBorder(); + return styleForCellFlow.isLeftToRightDirection() ? values.endBorder() + : values.startBorder(); } void TableCellPainter::paint(const PaintInfo& paintInfo, @@ -68,6 +68,15 @@ return style; } +const DisplayItemClient& TableCellPainter::displayItemClientForBorders() const { + // TODO(wkorman): We may need to handle PaintInvalidationDelayedFull. + // http://crbug.com/657186 + return m_layoutTableCell.usesTableAsAdditionalDisplayItemClient() + ? static_cast<const DisplayItemClient&>( + *m_layoutTableCell.collapsedBorderValues()) + : m_layoutTableCell; +} + void TableCellPainter::paintCollapsedBorders( const PaintInfo& paintInfo, const LayoutPoint& paintOffset, @@ -95,6 +104,18 @@ const CollapsedBorderValue& bottomBorderValue = collapsedBottomBorder(styleForCellFlow, *values); + int displayItemType = DisplayItem::kTableCollapsedBorderBase; + if (topBorderValue.shouldPaint(currentBorderValue)) + displayItemType |= DisplayItem::TableCollapsedBorderTop; + if (bottomBorderValue.shouldPaint(currentBorderValue)) + displayItemType |= DisplayItem::TableCollapsedBorderBottom; + if (leftBorderValue.shouldPaint(currentBorderValue)) + displayItemType |= DisplayItem::TableCollapsedBorderLeft; + if (rightBorderValue.shouldPaint(currentBorderValue)) + displayItemType |= DisplayItem::TableCollapsedBorderRight; + if (displayItemType == DisplayItem::kTableCollapsedBorderBase) + return; + int topWidth = topBorderValue.width(); int bottomWidth = bottomBorderValue.width(); int leftWidth = leftBorderValue.width(); @@ -110,32 +131,41 @@ paintRect.height() + topWidth / 2 + (bottomWidth + 1) / 2); GraphicsContext& graphicsContext = paintInfo.context; + const DisplayItemClient& client = displayItemClientForBorders(); + if (DrawingRecorder::useCachedDrawingIfPossible( + graphicsContext, client, + static_cast<DisplayItem::Type>(displayItemType))) + return; + + DrawingRecorder recorder(graphicsContext, client, + static_cast<DisplayItem::Type>(displayItemType), + borderRect); Color cellColor = m_layoutTableCell.resolveColor(CSSPropertyColor); // We never paint diagonals at the joins. We simply let the border with the // highest precedence paint on top of borders with lower precedence. - if (topBorderValue.shouldPaint(currentBorderValue)) { + if (displayItemType & DisplayItem::TableCollapsedBorderTop) { ObjectPainter::drawLineForBoxSide( graphicsContext, borderRect.x(), borderRect.y(), borderRect.maxX(), borderRect.y() + topWidth, BSTop, topBorderValue.color().resolve(cellColor), collapsedBorderStyle(topBorderValue.style()), 0, 0, true); } - if (bottomBorderValue.shouldPaint(currentBorderValue)) { + if (displayItemType & DisplayItem::TableCollapsedBorderBottom) { ObjectPainter::drawLineForBoxSide( graphicsContext, borderRect.x(), borderRect.maxY() - bottomWidth, borderRect.maxX(), borderRect.maxY(), BSBottom, bottomBorderValue.color().resolve(cellColor), collapsedBorderStyle(bottomBorderValue.style()), 0, 0, true); } - if (leftBorderValue.shouldPaint(currentBorderValue)) { + if (displayItemType & DisplayItem::TableCollapsedBorderLeft) { ObjectPainter::drawLineForBoxSide( graphicsContext, borderRect.x(), borderRect.y(), borderRect.x() + leftWidth, borderRect.maxY(), BSLeft, leftBorderValue.color().resolve(cellColor), collapsedBorderStyle(leftBorderValue.style()), 0, 0, true); } - if (rightBorderValue.shouldPaint(currentBorderValue)) { + if (displayItemType & DisplayItem::TableCollapsedBorderRight) { ObjectPainter::drawLineForBoxSide( graphicsContext, borderRect.maxX() - rightWidth, borderRect.y(), borderRect.maxX(), borderRect.maxY(), BSRight,
diff --git a/third_party/WebKit/Source/core/paint/TableCellPainter.h b/third_party/WebKit/Source/core/paint/TableCellPainter.h index 749915c..a87c4b59 100644 --- a/third_party/WebKit/Source/core/paint/TableCellPainter.h +++ b/third_party/WebKit/Source/core/paint/TableCellPainter.h
@@ -39,6 +39,7 @@ void paintMask(const PaintInfo&, const LayoutPoint& paintOffset); private: + const DisplayItemClient& displayItemClientForBorders() const; LayoutRect paintRectNotIncludingVisualOverflow( const LayoutPoint& paintOffset); void paintBackground(const PaintInfo&,
diff --git a/third_party/WebKit/Source/core/paint/TableCellPainterTest.cpp b/third_party/WebKit/Source/core/paint/TableCellPainterTest.cpp index adce65d..1cd5830 100644 --- a/third_party/WebKit/Source/core/paint/TableCellPainterTest.cpp +++ b/third_party/WebKit/Source/core/paint/TableCellPainterTest.cpp
@@ -170,12 +170,11 @@ "100px solid yellow; background: green; }" " table { margin: 100px; border-collapse: collapse; }" "</style>" - "<table id='table'>" + "<table>" " <tr><td id='cell'></td></tr>" "</table>"); LayoutView& layoutView = *document().layoutView(); - LayoutObject& table = *getLayoutObjectByElementId("table"); LayoutObject& cell = *getLayoutObjectByElementId("cell"); rootPaintController().invalidateAll(); @@ -189,7 +188,7 @@ rootPaintController().getDisplayItemList(), 4, TestDisplayItem(layoutView, DisplayItem::kDocumentBackground), TestDisplayItem(cell, DisplayItem::kBoxDecorationBackground), - TestDisplayItem(table, DisplayItem::kTableCollapsedBorders), + TestDisplayItem(cell, DisplayItem::kTableCollapsedBorderLast), TestDisplayItem(cell, DisplayItem::paintPhaseToDrawingType( PaintPhaseSelfOutlineOnly))); }
diff --git a/third_party/WebKit/Source/core/paint/TablePainter.cpp b/third_party/WebKit/Source/core/paint/TablePainter.cpp index 65a069c..16f910484 100644 --- a/third_party/WebKit/Source/core/paint/TablePainter.cpp +++ b/third_party/WebKit/Source/core/paint/TablePainter.cpp
@@ -44,61 +44,31 @@ } } - if (shouldPaintDescendantBlockBackgrounds(paintPhase)) - paintCollapsedBorders(paintInfoForDescendants, paintOffset); + if (m_layoutTable.collapseBorders() && + shouldPaintDescendantBlockBackgrounds(paintPhase) && + m_layoutTable.style()->visibility() == EVisibility::Visible) { + // Using our cached sorted styles, we then do individual passes, + // painting each style of border from lowest precedence to highest + // precedence. + LayoutTable::CollapsedBorderValues collapsedBorders = + m_layoutTable.collapsedBorders(); + size_t count = collapsedBorders.size(); + for (size_t i = 0; i < count; ++i) { + for (LayoutTableSection* section = m_layoutTable.bottomSection(); + section; section = m_layoutTable.sectionAbove(section)) { + LayoutPoint childPoint = + m_layoutTable.flipForWritingModeForChild(section, paintOffset); + TableSectionPainter(*section).paintCollapsedBorders( + paintInfoForDescendants, childPoint, collapsedBorders[i]); + } + } + } } if (shouldPaintSelfOutline(paintPhase)) ObjectPainter(m_layoutTable).paintOutline(paintInfo, paintOffset); } -void TablePainter::paintCollapsedBorders(const PaintInfo& paintInfo, - const LayoutPoint& paintOffset) { - if (!m_layoutTable.hasCollapsedBorders() || - m_layoutTable.style()->visibility() != EVisibility::Visible) - return; - - LayoutTable::CollapsedBordersInfo& collapsedBorders = - m_layoutTable.getCollapsedBordersInfo(); - - // Normally we don't clip individual display items by paint dirty rect - // (aka interest rect), to keep display items independent with paint dirty - // rect so we can just depend on paint invalidation status to repaint them. - // However, the collapsed border display item may be too big to contain all - // collapsed borders in a huge table, so we clip it to paint dirty rect. - // We need to invalidate the display item if the previous paint is clipped - // and the paint dirty rect changed. - if (collapsedBorders.lastPaintResult != FullyPainted && - collapsedBorders.lastPaintRect != paintInfo.cullRect()) - m_layoutTable.setDisplayItemsUncached(); - - if (DrawingRecorder::useCachedDrawingIfPossible( - paintInfo.context, m_layoutTable, - DisplayItem::kTableCollapsedBorders)) - return; - - DrawingRecorder recorder( - paintInfo.context, m_layoutTable, DisplayItem::kTableCollapsedBorders, - FloatRect(LayoutRect(paintOffset, m_layoutTable.size()))); - - // Using our cached sorted styles, we then do individual passes, painting - // each style of border from lowest precedence to highest precedence. - PaintResult paintResult = FullyPainted; - for (const auto& borderValue : collapsedBorders.values) { - for (LayoutTableSection* section = m_layoutTable.bottomSection(); section; - section = m_layoutTable.sectionAbove(section)) { - LayoutPoint childPoint = - m_layoutTable.flipForWritingModeForChild(section, paintOffset); - if (TableSectionPainter(*section).paintCollapsedBorders( - paintInfo, childPoint, borderValue) == - MayBeClippedByPaintDirtyRect) - paintResult = MayBeClippedByPaintDirtyRect; - } - } - collapsedBorders.lastPaintResult = paintResult; - collapsedBorders.lastPaintRect = paintInfo.cullRect(); -} - void TablePainter::paintBoxDecorationBackground( const PaintInfo& paintInfo, const LayoutPoint& paintOffset) {
diff --git a/third_party/WebKit/Source/core/paint/TablePainter.h b/third_party/WebKit/Source/core/paint/TablePainter.h index ac57899..d3de8e0e 100644 --- a/third_party/WebKit/Source/core/paint/TablePainter.h +++ b/third_party/WebKit/Source/core/paint/TablePainter.h
@@ -24,8 +24,6 @@ void paintMask(const PaintInfo&, const LayoutPoint&); private: - void paintCollapsedBorders(const PaintInfo&, const LayoutPoint&); - const LayoutTable& m_layoutTable; };
diff --git a/third_party/WebKit/Source/core/paint/TablePainterTest.cpp b/third_party/WebKit/Source/core/paint/TablePainterTest.cpp deleted file mode 100644 index 7ebcdff1..0000000 --- a/third_party/WebKit/Source/core/paint/TablePainterTest.cpp +++ /dev/null
@@ -1,75 +0,0 @@ -// Copyright 2015 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 "core/paint/PaintControllerPaintTest.h" -#include "platform/graphics/paint/DrawingDisplayItem.h" - -namespace blink { - -using TablePainterTest = PaintControllerPaintTest; - -TEST_F(TablePainterTest, CollapsedBorderInterestRectChange) { - setBodyInnerHTML( - "<style>" - " table { border-collapse: collapse; position: absolute; }" - " td { width: 100px; height: 100px; border: 2px solid blue; }" - "</style>" - "<table id='table'>" - " <tr><td></td><td></td><td></td><td></td></tr>" - " <tr><td></td><td></td><td></td><td></td></tr>" - " <tr><td></td><td></td><td></td><td></td></tr>" - " <tr><td></td><td></td><td></td><td></td></tr>" - "</table>"); - - PaintLayer& htmlLayer = - *toLayoutBoxModelObject(document().documentElement()->layoutObject()) - ->layer(); - LayoutObject& table = *getLayoutObjectByElementId("table"); - - rootPaintController().invalidateAll(); - document().view()->updateAllLifecyclePhasesExceptPaint(); - IntRect interestRect(300, 300, 300, 300); - paint(&interestRect); - - EXPECT_DISPLAY_LIST( - rootPaintController().getDisplayItemList(), 4, - TestDisplayItem(layoutView(), documentBackgroundType), - TestDisplayItem(htmlLayer, DisplayItem::kSubsequence), - TestDisplayItem(table, DisplayItem::kTableCollapsedBorders), - TestDisplayItem(htmlLayer, DisplayItem::kEndSubsequence)); - // Painted collapsed borders of the central 4 cells, each 4 operations. - EXPECT_EQ(16, static_cast<const DrawingDisplayItem&>( - rootPaintController().getDisplayItemList()[2]) - .picture() - ->approximateOpCount()); - - // Should repaint collapsed borders if the previous paint didn't fully paint - // and interest rect changes. - document().view()->updateAllLifecyclePhasesExceptPaint(); - interestRect = IntRect(0, 0, 1000, 1000); - EXPECT_TRUE(paintWithoutCommit(&interestRect)); - EXPECT_EQ(1, numCachedNewItems()); - commit(); - EXPECT_DISPLAY_LIST( - rootPaintController().getDisplayItemList(), 4, - TestDisplayItem(layoutView(), documentBackgroundType), - TestDisplayItem(htmlLayer, DisplayItem::kSubsequence), - TestDisplayItem(table, DisplayItem::kTableCollapsedBorders), - TestDisplayItem(htmlLayer, DisplayItem::kEndSubsequence)); - // Painted collapsed borders of all 16 cells, each 4 operations. - EXPECT_EQ(64, static_cast<const DrawingDisplayItem&>( - rootPaintController().getDisplayItemList()[2]) - .picture() - ->approximateOpCount()); - - // Should not repaint collapsed borders if the previous paint fully painted - // and interest rect changes. - document().view()->updateAllLifecyclePhasesExceptPaint(); - interestRect = IntRect(0, 0, 400, 400); - EXPECT_TRUE(paintWithoutCommit(&interestRect)); - EXPECT_EQ(4, numCachedNewItems()); - commit(); -} - -} // namespace blink
diff --git a/third_party/WebKit/Source/core/paint/TableSectionPainter.cpp b/third_party/WebKit/Source/core/paint/TableSectionPainter.cpp index 44e1d61..685ba682 100644 --- a/third_party/WebKit/Source/core/paint/TableSectionPainter.cpp +++ b/third_party/WebKit/Source/core/paint/TableSectionPainter.cpp
@@ -149,27 +149,24 @@ return elem1->absoluteColumnIndex() < elem2->absoluteColumnIndex(); } -PaintResult TableSectionPainter::paintCollapsedBorders( +void TableSectionPainter::paintCollapsedBorders( const PaintInfo& paintInfo, const LayoutPoint& paintOffset, const CollapsedBorderValue& currentBorderValue) { - PaintResult result = - paintCollapsedSectionBorders(paintInfo, paintOffset, currentBorderValue); + paintCollapsedSectionBorders(paintInfo, paintOffset, currentBorderValue); LayoutTable* table = m_layoutTableSection.table(); - if (table->header() == m_layoutTableSection) { + if (table->header() == m_layoutTableSection) paintRepeatingHeaderGroup(paintInfo, paintOffset, currentBorderValue, PaintCollapsedBorders); - } - return result; } -PaintResult TableSectionPainter::paintCollapsedSectionBorders( +void TableSectionPainter::paintCollapsedSectionBorders( const PaintInfo& paintInfo, const LayoutPoint& paintOffset, const CollapsedBorderValue& currentBorderValue) { if (!m_layoutTableSection.numRows() || !m_layoutTableSection.table()->effectiveColumns().size()) - return FullyPainted; + return; LayoutPoint adjustedPaintOffset = paintOffset + m_layoutTableSection.location(); @@ -188,7 +185,7 @@ m_layoutTableSection.dirtiedEffectiveColumns(tableAlignedRect); if (dirtiedColumns.start() >= dirtiedColumns.end()) - return MayBeClippedByPaintDirtyRect; + return; // Collapsed borders are painted from the bottom right to the top left so that // precedence due to cell position is respected. @@ -210,11 +207,6 @@ currentBorderValue); } } - - if (dirtiedRows == m_layoutTableSection.fullTableRowSpan() && - dirtiedColumns == m_layoutTableSection.fullTableEffectiveColumnSpan()) - return FullyPainted; - return MayBeClippedByPaintDirtyRect; } void TableSectionPainter::paintObject(const PaintInfo& paintInfo,
diff --git a/third_party/WebKit/Source/core/paint/TableSectionPainter.h b/third_party/WebKit/Source/core/paint/TableSectionPainter.h index 9e33c022..d6ff986f 100644 --- a/third_party/WebKit/Source/core/paint/TableSectionPainter.h +++ b/third_party/WebKit/Source/core/paint/TableSectionPainter.h
@@ -6,7 +6,6 @@ #define TableSectionPainter_h #include "core/paint/PaintPhase.h" -#include "core/paint/PaintResult.h" #include "core/style/ShadowData.h" #include "wtf/Allocator.h" @@ -27,10 +26,9 @@ : m_layoutTableSection(layoutTableSection) {} void paint(const PaintInfo&, const LayoutPoint&); - - PaintResult paintCollapsedBorders(const PaintInfo&, - const LayoutPoint&, - const CollapsedBorderValue&); + void paintCollapsedBorders(const PaintInfo&, + const LayoutPoint&, + const CollapsedBorderValue&); private: void paintObject(const PaintInfo&, const LayoutPoint&); @@ -58,9 +56,9 @@ const CollapsedBorderValue& currentBorderValue, ItemToPaint); void paintSection(const PaintInfo&, const LayoutPoint&); - PaintResult paintCollapsedSectionBorders(const PaintInfo&, - const LayoutPoint&, - const CollapsedBorderValue&); + void paintCollapsedSectionBorders(const PaintInfo&, + const LayoutPoint&, + const CollapsedBorderValue&); const LayoutTableSection& m_layoutTableSection; };
diff --git a/third_party/WebKit/Source/core/paint/VideoPainterTest.cpp b/third_party/WebKit/Source/core/paint/VideoPainterTest.cpp index b481b99..c5a0834 100644 --- a/third_party/WebKit/Source/core/paint/VideoPainterTest.cpp +++ b/third_party/WebKit/Source/core/paint/VideoPainterTest.cpp
@@ -85,7 +85,7 @@ HTMLMediaElement&, const WebMediaPlayerSource&, WebMediaPlayerClient* client) override { - return wrapUnique(new StubWebMediaPlayer(client)); + return makeUnique<StubWebMediaPlayer>(client); } };
diff --git a/third_party/WebKit/Source/core/streams/WritableStream.js b/third_party/WebKit/Source/core/streams/WritableStream.js index 5ffadd7e..7e132d9 100644 --- a/third_party/WebKit/Source/core/streams/WritableStream.js +++ b/third_party/WebKit/Source/core/streams/WritableStream.js
@@ -499,7 +499,7 @@ if (!IsWritableStream(stream)) { throw new TypeError(errIllegalConstructor); } - if (stream[_controlledWritableStream] !== undefined) { + if (stream[_writableStreamController] !== undefined) { throw new TypeError(errIllegalConstructor); } this[_controlledWritableStream] = stream; @@ -791,10 +791,7 @@ } highWaterMark = Number(highWaterMark); - if (Number_isNaN(highWaterMark)) { - throw new TypeError(errInvalidHWM); - } - if (highWaterMark < 0) { + if (Number_isNaN(highWaterMark) || highWaterMark < 0) { throw new RangeError(errInvalidHWM); }
diff --git a/third_party/WebKit/Source/core/style/ComputedStyle.cpp b/third_party/WebKit/Source/core/style/ComputedStyle.cpp index da917c8..8fc3dab 100644 --- a/third_party/WebKit/Source/core/style/ComputedStyle.cpp +++ b/third_party/WebKit/Source/core/style/ComputedStyle.cpp
@@ -1138,9 +1138,10 @@ } void ComputedStyle::addPaintImage(StyleImage* image) { - if (!m_rareNonInheritedData.access()->m_paintImages) + if (!m_rareNonInheritedData.access()->m_paintImages) { m_rareNonInheritedData.access()->m_paintImages = - WTF::wrapUnique(new Vector<Persistent<StyleImage>>()); + makeUnique<Vector<Persistent<StyleImage>>>(); + } m_rareNonInheritedData.access()->m_paintImages->append(image); }
diff --git a/third_party/WebKit/Source/core/style/ShadowList.cpp b/third_party/WebKit/Source/core/style/ShadowList.cpp index 2a70a46..9aac3a0 100644 --- a/third_party/WebKit/Source/core/style/ShadowList.cpp +++ b/third_party/WebKit/Source/core/style/ShadowList.cpp
@@ -83,23 +83,22 @@ return ShadowList::adopt(shadows); } -std::unique_ptr<DrawLooperBuilder> ShadowList::createDrawLooper( +sk_sp<SkDrawLooper> ShadowList::createDrawLooper( DrawLooperBuilder::ShadowAlphaMode alphaMode, const Color& currentColor, bool isHorizontal) const { - std::unique_ptr<DrawLooperBuilder> drawLooperBuilder = - DrawLooperBuilder::create(); + DrawLooperBuilder drawLooperBuilder; for (size_t i = shadows().size(); i--;) { const ShadowData& shadow = shadows()[i]; float shadowX = isHorizontal ? shadow.x() : shadow.y(); float shadowY = isHorizontal ? shadow.y() : -shadow.x(); - drawLooperBuilder->addShadow(FloatSize(shadowX, shadowY), shadow.blur(), - shadow.color().resolve(currentColor), - DrawLooperBuilder::ShadowRespectsTransforms, - alphaMode); + drawLooperBuilder.addShadow(FloatSize(shadowX, shadowY), shadow.blur(), + shadow.color().resolve(currentColor), + DrawLooperBuilder::ShadowRespectsTransforms, + alphaMode); } - drawLooperBuilder->addUnmodifiedContent(); - return drawLooperBuilder; + drawLooperBuilder.addUnmodifiedContent(); + return drawLooperBuilder.detachDrawLooper(); } } // namespace blink
diff --git a/third_party/WebKit/Source/core/style/ShadowList.h b/third_party/WebKit/Source/core/style/ShadowList.h index 9618dbf9..fb79b7a 100644 --- a/third_party/WebKit/Source/core/style/ShadowList.h +++ b/third_party/WebKit/Source/core/style/ShadowList.h
@@ -72,10 +72,9 @@ void adjustRectForShadow(FloatRect&) const; - std::unique_ptr<DrawLooperBuilder> createDrawLooper( - DrawLooperBuilder::ShadowAlphaMode, - const Color& currentColor, - bool isHorizontal = true) const; + sk_sp<SkDrawLooper> createDrawLooper(DrawLooperBuilder::ShadowAlphaMode, + const Color& currentColor, + bool isHorizontal = true) const; private: ShadowList(ShadowDataVector& shadows) {
diff --git a/third_party/WebKit/Source/core/svg/SVGAttributeNames.in b/third_party/WebKit/Source/core/svg/SVGAttributeNames.in index 0d63f39..7952490 100644 --- a/third_party/WebKit/Source/core/svg/SVGAttributeNames.in +++ b/third_party/WebKit/Source/core/svg/SVGAttributeNames.in
@@ -225,7 +225,6 @@ vert-origin-x vert-origin-y viewBox -viewTarget visibility width widths
diff --git a/third_party/WebKit/Source/core/svg/SVGViewElement.cpp b/third_party/WebKit/Source/core/svg/SVGViewElement.cpp index 7047636..4cbf0fe 100644 --- a/third_party/WebKit/Source/core/svg/SVGViewElement.cpp +++ b/third_party/WebKit/Source/core/svg/SVGViewElement.cpp
@@ -22,31 +22,21 @@ #include "core/SVGNames.h" #include "core/frame/UseCounter.h" -#include "core/svg/SVGStaticStringList.h" namespace blink { inline SVGViewElement::SVGViewElement(Document& document) - : SVGElement(SVGNames::viewTag, document), - SVGFitToViewBox(this), - m_viewTarget( - SVGStaticStringList::create(this, SVGNames::viewTargetAttr)) { - addToPropertyMap(m_viewTarget); + : SVGElement(SVGNames::viewTag, document), SVGFitToViewBox(this) { UseCounter::count(document, UseCounter::SVGViewElement); } DEFINE_NODE_FACTORY(SVGViewElement) DEFINE_TRACE(SVGViewElement) { - visitor->trace(m_viewTarget); SVGElement::trace(visitor); SVGFitToViewBox::trace(visitor); } -SVGStringListTearOff* SVGViewElement::viewTarget() { - return m_viewTarget->tearOff(); -} - void SVGViewElement::parseAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& value) {
diff --git a/third_party/WebKit/Source/core/svg/SVGViewElement.h b/third_party/WebKit/Source/core/svg/SVGViewElement.h index a72b157d..9e3f2b9 100644 --- a/third_party/WebKit/Source/core/svg/SVGViewElement.h +++ b/third_party/WebKit/Source/core/svg/SVGViewElement.h
@@ -29,7 +29,6 @@ namespace blink { class SVGStaticStringList; -class SVGStringListTearOff; class SVGViewElement final : public SVGElement, public SVGFitToViewBox, @@ -39,9 +38,6 @@ public: DECLARE_NODE_FACTORY(SVGViewElement); - - SVGStringListTearOff* viewTarget(); - DECLARE_VIRTUAL_TRACE(); private: @@ -52,8 +48,6 @@ const AtomicString&) override; bool layoutObjectIsNeeded(const ComputedStyle&) override { return false; } - - Member<SVGStaticStringList> m_viewTarget; }; } // namespace blink
diff --git a/third_party/WebKit/Source/core/svg/SVGViewElement.idl b/third_party/WebKit/Source/core/svg/SVGViewElement.idl index d2d49f4..04d15e4 100644 --- a/third_party/WebKit/Source/core/svg/SVGViewElement.idl +++ b/third_party/WebKit/Source/core/svg/SVGViewElement.idl
@@ -26,7 +26,6 @@ // http://www.w3.org/TR/SVG2/linking.html#InterfaceSVGViewElement interface SVGViewElement : SVGElement { - [DeprecateAs=V8SVGViewElement_ViewTarget_AttributeGetter] readonly attribute SVGStringList viewTarget; }; SVGViewElement implements SVGFitToViewBox;
diff --git a/third_party/WebKit/Source/core/svg/graphics/SVGImage.cpp b/third_party/WebKit/Source/core/svg/graphics/SVGImage.cpp index 3b2c121..f0e41660 100644 --- a/third_party/WebKit/Source/core/svg/graphics/SVGImage.cpp +++ b/third_party/WebKit/Source/core/svg/graphics/SVGImage.cpp
@@ -589,7 +589,7 @@ TRACE_EVENT0("blink", "SVGImage::dataChanged::createFrame"); frame = LocalFrame::create(&dummyFrameLoaderClient, &page->frameHost(), 0); - frame->setView(FrameView::create(frame)); + frame->setView(FrameView::create(*frame)); frame->init(); }
diff --git a/third_party/WebKit/Source/core/testing/DummyPageHolder.cpp b/third_party/WebKit/Source/core/testing/DummyPageHolder.cpp index a8d0fd0..008c663 100644 --- a/third_party/WebKit/Source/core/testing/DummyPageHolder.cpp +++ b/third_party/WebKit/Source/core/testing/DummyPageHolder.cpp
@@ -82,7 +82,7 @@ m_frame = LocalFrame::create(m_frameLoaderClient.get(), &m_page->frameHost(), nullptr, interfaceProvider); - m_frame->setView(FrameView::create(m_frame.get(), initialViewSize)); + m_frame->setView(FrameView::create(*m_frame, initialViewSize)); m_frame->view()->page()->frameHost().visualViewport().setSize( initialViewSize); m_frame->init();
diff --git a/third_party/WebKit/Source/core/testing/Internals.cpp b/third_party/WebKit/Source/core/testing/Internals.cpp index 28863b3..fb9a34f 100644 --- a/third_party/WebKit/Source/core/testing/Internals.cpp +++ b/third_party/WebKit/Source/core/testing/Internals.cpp
@@ -146,6 +146,7 @@ #include "public/platform/WebLayer.h" #include "public/platform/modules/remoteplayback/WebRemotePlaybackAvailability.h" #include "wtf/InstanceCounter.h" +#include "wtf/Optional.h" #include "wtf/PtrUtil.h" #include "wtf/dtoa.h" #include "wtf/text/StringBuffer.h" @@ -172,20 +173,25 @@ } // namespace -static bool markerTypesFrom(const String& markerType, - DocumentMarker::MarkerTypes& result) { - if (markerType.isEmpty() || equalIgnoringCase(markerType, "all")) - result = DocumentMarker::AllMarkers(); - else if (equalIgnoringCase(markerType, "Spelling")) - result = DocumentMarker::Spelling; - else if (equalIgnoringCase(markerType, "Grammar")) - result = DocumentMarker::Grammar; - else if (equalIgnoringCase(markerType, "TextMatch")) - result = DocumentMarker::TextMatch; - else - return false; +static WTF::Optional<DocumentMarker::MarkerType> markerTypeFrom( + const String& markerType) { + if (equalIgnoringCase(markerType, "Spelling")) + return DocumentMarker::Spelling; + if (equalIgnoringCase(markerType, "Grammar")) + return DocumentMarker::Grammar; + if (equalIgnoringCase(markerType, "TextMatch")) + return DocumentMarker::TextMatch; + return WTF::nullopt; +} - return true; +static WTF::Optional<DocumentMarker::MarkerTypes> markerTypesFrom( + const String& markerType) { + if (markerType.isEmpty() || equalIgnoringCase(markerType, "all")) + return DocumentMarker::AllMarkers(); + WTF::Optional<DocumentMarker::MarkerType> type = markerTypeFrom(markerType); + if (!type) + return WTF::nullopt; + return DocumentMarker::MarkerTypes(type.value()); } static SpellCheckRequester* spellCheckRequester(Document* document) { @@ -913,19 +919,45 @@ layoutObject->absoluteBoundingBoxRectIgnoringTransforms()); } +void Internals::setMarker(Document* document, + const Range* range, + const String& markerType, + ExceptionState& exceptionState) { + if (!document) { + exceptionState.throwDOMException(InvalidAccessError, + "No context document is available."); + return; + } + + WTF::Optional<DocumentMarker::MarkerType> type = markerTypeFrom(markerType); + if (!type) { + exceptionState.throwDOMException( + SyntaxError, + "The marker type provided ('" + markerType + "') is invalid."); + return; + } + + document->markers().addMarker(range->startPosition(), range->endPosition(), + type.value()); +} + unsigned Internals::markerCountForNode(Node* node, const String& markerType, ExceptionState& exceptionState) { ASSERT(node); - DocumentMarker::MarkerTypes markerTypes = 0; - if (!markerTypesFrom(markerType, markerTypes)) { + WTF::Optional<DocumentMarker::MarkerTypes> markerTypes = + markerTypesFrom(markerType); + if (!markerTypes) { exceptionState.throwDOMException( SyntaxError, "The marker type provided ('" + markerType + "') is invalid."); return 0; } - return node->document().markers().markersFor(node, markerTypes).size(); + return node->document() + .markers() + .markersFor(node, markerTypes.value()) + .size(); } unsigned Internals::activeMarkerCountForNode(Node* node) { @@ -950,8 +982,9 @@ unsigned index, ExceptionState& exceptionState) { ASSERT(node); - DocumentMarker::MarkerTypes markerTypes = 0; - if (!markerTypesFrom(markerType, markerTypes)) { + WTF::Optional<DocumentMarker::MarkerTypes> markerTypes = + markerTypesFrom(markerType); + if (!markerTypes) { exceptionState.throwDOMException( SyntaxError, "The marker type provided ('" + markerType + "') is invalid."); @@ -959,7 +992,7 @@ } DocumentMarkerVector markers = - node->document().markers().markersFor(node, markerTypes); + node->document().markers().markersFor(node, markerTypes.value()); if (markers.size() <= index) return 0; return markers[index]; @@ -1826,6 +1859,20 @@ contextDocument()->frame()->spellChecker().toggleSpellCheckingEnabled(); } +void Internals::replaceMisspelled(Document* document, + const String& replacement, + ExceptionState& exceptionState) { + if (!document || !document->frame()) { + exceptionState.throwDOMException( + InvalidAccessError, + "No frame can be obtained from the provided document."); + return; + } + + document->updateStyleAndLayoutIgnorePendingStylesheets(); + document->frame()->spellChecker().replaceMisspelledRange(replacement); +} + bool Internals::canHyphenate(const AtomicString& locale) { return LayoutLocale::valueOrDefault(LayoutLocale::get(locale)) .getHyphenation(); @@ -2198,11 +2245,6 @@ document->page()->setIsCursorVisible(isVisible); } -double Internals::effectiveMediaVolume(HTMLMediaElement* mediaElement) { - ASSERT(mediaElement); - return mediaElement->effectiveMediaVolume(); -} - String Internals::effectivePreload(HTMLMediaElement* mediaElement) { ASSERT(mediaElement); return mediaElement->effectivePreload();
diff --git a/third_party/WebKit/Source/core/testing/Internals.h b/third_party/WebKit/Source/core/testing/Internals.h index f357b9c0..a0fc9fb 100644 --- a/third_party/WebKit/Source/core/testing/Internals.h +++ b/third_party/WebKit/Source/core/testing/Internals.h
@@ -185,6 +185,7 @@ ClientRect* boundingBox(Element*); + void setMarker(Document*, const Range*, const String&, ExceptionState&); unsigned markerCountForNode(Node*, const String&, ExceptionState&); unsigned activeMarkerCountForNode(Node*); Range* markerRangeForNode(Node*, @@ -294,6 +295,7 @@ bool hasSpellingMarker(Document*, int from, int length, ExceptionState&); bool hasGrammarMarker(Document*, int from, int length, ExceptionState&); void setSpellCheckingEnabled(bool, ExceptionState&); + void replaceMisspelled(Document*, const String&, ExceptionState&); bool canHyphenate(const AtomicString& locale); void setMockHyphenation(const AtomicString& locale); @@ -367,7 +369,6 @@ void setIsCursorVisible(Document*, bool, ExceptionState&); - double effectiveMediaVolume(HTMLMediaElement*); String effectivePreload(HTMLMediaElement*); void mediaPlayerRemoteRouteAvailabilityChanged(HTMLMediaElement*, bool);
diff --git a/third_party/WebKit/Source/core/testing/Internals.idl b/third_party/WebKit/Source/core/testing/Internals.idl index b45f5a9..06362a2 100644 --- a/third_party/WebKit/Source/core/testing/Internals.idl +++ b/third_party/WebKit/Source/core/testing/Internals.idl
@@ -105,6 +105,7 @@ ClientRect boundingBox(Element element); + [RaisesException] void setMarker(Document document, Range range, DOMString markerType); [RaisesException] unsigned long markerCountForNode(Node node, DOMString markerType); unsigned long activeMarkerCountForNode(Node node); [RaisesException] Range markerRangeForNode(Node node, DOMString markerType, unsigned long index); @@ -165,6 +166,7 @@ [RaisesException] boolean hasSpellingMarker(Document document, long from, long length); [RaisesException] boolean hasGrammarMarker(Document document, long from, long length); [RaisesException] void setSpellCheckingEnabled(boolean enabled); + [RaisesException] void replaceMisspelled(Document document, DOMString replacement); bool canHyphenate(DOMString locale); void setMockHyphenation(DOMString locale); @@ -219,7 +221,6 @@ [RaisesException] void setIsCursorVisible(Document document, boolean isVisible); - double effectiveMediaVolume(HTMLMediaElement mediaElement); DOMString effectivePreload(HTMLMediaElement mediaElement); void mediaPlayerRemoteRouteAvailabilityChanged(HTMLMediaElement mediaElement, boolean available); void mediaPlayerPlayingRemotelyChanged(HTMLMediaElement mediaElement, boolean remote);
diff --git a/third_party/WebKit/Source/core/workers/DedicatedWorkerTest.cpp b/third_party/WebKit/Source/core/workers/DedicatedWorkerTest.cpp index 71ecdd8..b63eb6f 100644 --- a/third_party/WebKit/Source/core/workers/DedicatedWorkerTest.cpp +++ b/third_party/WebKit/Source/core/workers/DedicatedWorkerTest.cpp
@@ -67,7 +67,7 @@ workerObjectProxy().m_maxIntervalInSec = kMaxIntervalInSec; m_mockWorkerLoaderProxyProvider = - wrapUnique(new MockWorkerLoaderProxyProvider()); + makeUnique<MockWorkerLoaderProxyProvider>(); m_workerThread = wrapUnique( new DedicatedWorkerThreadForTest(m_mockWorkerLoaderProxyProvider.get(), workerObjectProxy(), threadHeapMode)); @@ -172,7 +172,7 @@ void startWithSourceCode(const String& source) { std::unique_ptr<Vector<CSPHeaderAndType>> headers = - wrapUnique(new Vector<CSPHeaderAndType>()); + makeUnique<Vector<CSPHeaderAndType>>(); CSPHeaderAndType headerAndType("contentSecurityPolicy", ContentSecurityPolicyHeaderTypeReport); headers->append(headerAndType);
diff --git a/third_party/WebKit/Source/core/workers/WorkerBackingThread.cpp b/third_party/WebKit/Source/core/workers/WorkerBackingThread.cpp index 1382ae7..eebae53 100644 --- a/third_party/WebKit/Source/core/workers/WorkerBackingThread.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerBackingThread.cpp
@@ -69,7 +69,7 @@ V8Initializer::initializeWorker(m_isolate); std::unique_ptr<V8IsolateInterruptor> interruptor = - wrapUnique(new V8IsolateInterruptor(m_isolate)); + makeUnique<V8IsolateInterruptor>(m_isolate); ThreadState::current()->addInterruptor(std::move(interruptor)); ThreadState::current()->registerTraceDOMWrappers( m_isolate, V8GCController::traceDOMWrappers, nullptr, nullptr); @@ -81,7 +81,7 @@ Platform::current()->didStartWorkerThread(); V8PerIsolateData::from(m_isolate)->setThreadDebugger( - wrapUnique(new WorkerThreadDebugger(m_isolate))); + makeUnique<WorkerThreadDebugger>(m_isolate)); } void WorkerBackingThread::shutdown() {
diff --git a/third_party/WebKit/Source/core/workers/WorkerScriptLoader.cpp b/third_party/WebKit/Source/core/workers/WorkerScriptLoader.cpp index 17e5c20..4d172d4d 100644 --- a/third_party/WebKit/Source/core/workers/WorkerScriptLoader.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerScriptLoader.cpp
@@ -179,7 +179,7 @@ } void WorkerScriptLoader::didReceiveCachedMetadata(const char* data, int size) { - m_cachedMetadata = wrapUnique(new Vector<char>(size)); + m_cachedMetadata = makeUnique<Vector<char>>(size); memcpy(m_cachedMetadata->data(), data, size); }
diff --git a/third_party/WebKit/Source/core/workers/WorkerThread.cpp b/third_party/WebKit/Source/core/workers/WorkerThread.cpp index 8db2897..13f3317 100644 --- a/third_party/WebKit/Source/core/workers/WorkerThread.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerThread.cpp
@@ -296,7 +296,7 @@ WorkerReportingProxy& workerReportingProxy) : m_workerThreadId(getNextWorkerThreadId()), m_forcibleTerminationDelayInMs(kForcibleTerminationDelayInMs), - m_inspectorTaskRunner(wrapUnique(new InspectorTaskRunner())), + m_inspectorTaskRunner(makeUnique<InspectorTaskRunner>()), m_workerLoaderProxy(workerLoaderProxy), m_workerReportingProxy(workerReportingProxy), m_shutdownEvent(wrapUnique(
diff --git a/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp b/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp index fab3763..5477db9 100644 --- a/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp
@@ -62,7 +62,7 @@ m_addressSpace(addressSpace), m_workerSettings(std::move(workerSettings)), m_v8CacheOptions(v8CacheOptions) { - m_contentSecurityPolicyHeaders = wrapUnique(new Vector<CSPHeaderAndType>()); + m_contentSecurityPolicyHeaders = makeUnique<Vector<CSPHeaderAndType>>(); if (contentSecurityPolicyHeaders) { for (const auto& header : *contentSecurityPolicyHeaders) { CSPHeaderAndType copiedHeader(header.first.isolatedCopy(), header.second);
diff --git a/third_party/WebKit/Source/core/workers/WorkerThreadTest.cpp b/third_party/WebKit/Source/core/workers/WorkerThreadTest.cpp index ee53bf6a..fd0514d 100644 --- a/third_party/WebKit/Source/core/workers/WorkerThreadTest.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerThreadTest.cpp
@@ -40,8 +40,8 @@ WorkerThreadTest() : m_threadHeapMode(GetParam()) {} void SetUp() override { - m_loaderProxyProvider = wrapUnique(new MockWorkerLoaderProxyProvider()); - m_reportingProxy = wrapUnique(new MockWorkerReportingProxy()); + m_loaderProxyProvider = makeUnique<MockWorkerLoaderProxyProvider>(); + m_reportingProxy = makeUnique<MockWorkerReportingProxy>(); m_securityOrigin = SecurityOrigin::create(KURL(ParsedURLString, "http://fake.url/")); m_workerThread = wrapUnique(new WorkerThreadForTest( @@ -270,7 +270,7 @@ EXPECT_CALL(*m_lifecycleObserver, contextDestroyed()).Times(1); std::unique_ptr<Vector<CSPHeaderAndType>> headers = - wrapUnique(new Vector<CSPHeaderAndType>()); + makeUnique<Vector<CSPHeaderAndType>>(); CSPHeaderAndType headerAndType("contentSecurityPolicy", ContentSecurityPolicyHeaderTypeReport); headers->append(headerAndType);
diff --git a/third_party/WebKit/Source/core/workers/WorkerThreadTestHelper.h b/third_party/WebKit/Source/core/workers/WorkerThreadTestHelper.h index d933a41..53c4442 100644 --- a/third_party/WebKit/Source/core/workers/WorkerThreadTestHelper.h +++ b/third_party/WebKit/Source/core/workers/WorkerThreadTestHelper.h
@@ -131,7 +131,7 @@ void startWithSourceCode(SecurityOrigin* securityOrigin, const String& source) { std::unique_ptr<Vector<CSPHeaderAndType>> headers = - wrapUnique(new Vector<CSPHeaderAndType>()); + makeUnique<Vector<CSPHeaderAndType>>(); CSPHeaderAndType headerAndType("contentSecurityPolicy", ContentSecurityPolicyHeaderTypeReport); headers->append(headerAndType); @@ -147,7 +147,7 @@ void waitForInit() { std::unique_ptr<WaitableEvent> completionEvent = - wrapUnique(new WaitableEvent()); + makeUnique<WaitableEvent>(); workerBackingThread().backingThread().postTask( BLINK_FROM_HERE, crossThreadBind(&WaitableEvent::signal,
diff --git a/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp b/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp index 239ebe5..2d5f07f 100644 --- a/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp +++ b/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp
@@ -1065,7 +1065,7 @@ if (m_parserPaused) { m_pendingCallbacks.append( - wrapUnique(new PendingEndElementNSCallback(m_scriptStartPosition))); + makeUnique<PendingEndElementNSCallback>(m_scriptStartPosition)); return; } @@ -1153,7 +1153,7 @@ if (m_parserPaused) { m_pendingCallbacks.append( - wrapUnique(new PendingCharactersCallback(chars, length))); + makeUnique<PendingCharactersCallback>(chars, length)); return; } @@ -1187,7 +1187,7 @@ if (m_parserPaused) { m_pendingCallbacks.append( - wrapUnique(new PendingProcessingInstructionCallback(target, data))); + makeUnique<PendingProcessingInstructionCallback>(target, data)); return; } @@ -1228,7 +1228,7 @@ return; if (m_parserPaused) { - m_pendingCallbacks.append(wrapUnique(new PendingCDATABlockCallback(text))); + m_pendingCallbacks.append(makeUnique<PendingCDATABlockCallback>(text)); return; } @@ -1244,7 +1244,7 @@ return; if (m_parserPaused) { - m_pendingCallbacks.append(wrapUnique(new PendingCommentCallback(text))); + m_pendingCallbacks.append(makeUnique<PendingCommentCallback>(text)); return; } @@ -1550,7 +1550,7 @@ xmlDocPtr doc = xmlDocPtrForString(document(), m_originalSourceForTransform.toString(), document()->url().getString()); - document()->setTransformSource(wrapUnique(new TransformSource(doc))); + document()->setTransformSource(makeUnique<TransformSource>(doc)); DocumentParser::stopParsing(); } }
diff --git a/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.cpp b/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.cpp index a5f3a48..05b6333 100644 --- a/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.cpp +++ b/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.cpp
@@ -246,7 +246,8 @@ m_uploadComplete(false), m_sameOriginRequest(true), m_downloadingToFile(false), - m_responseTextOverflow(false) {} + m_responseTextOverflow(false), + m_sendFlag(false) {} XMLHttpRequest::~XMLHttpRequest() {} @@ -552,7 +553,7 @@ void XMLHttpRequest::setWithCredentials(bool value, ExceptionState& exceptionState) { - if (m_state > kOpened || m_loader) { + if (m_state > kOpened || m_sendFlag) { exceptionState.throwDOMException( InvalidStateError, "The value may only be set if the object's state is UNSENT or OPENED."); @@ -668,6 +669,7 @@ m_async = async; DCHECK(!m_loader); + m_sendFlag = false; // Check previous state to avoid dispatching readyState event // when calling open several times in a row. @@ -685,7 +687,7 @@ return false; } - if (m_state != kOpened || m_loader) { + if (m_state != kOpened || m_sendFlag) { exceptionState.throwDOMException(InvalidStateError, "The object's state must be OPENED."); return false; @@ -929,6 +931,7 @@ DCHECK(getExecutionContext()); ExecutionContext& executionContext = *getExecutionContext(); + m_sendFlag = true; // The presence of upload event listeners forces us to use preflighting // because POSTing to an URL that does not permit cross origin requests should // look exactly like POSTing to an URL that does not respond at all. @@ -1032,6 +1035,7 @@ request.setReportUploadProgress(true); DCHECK(!m_loader); + DCHECK(m_sendFlag); m_loader = ThreadableLoader::create(executionContext, this, options, resourceLoaderOptions); m_loader->start(request); @@ -1050,14 +1054,6 @@ void XMLHttpRequest::abort() { NETWORK_DVLOG(1) << this << " abort()"; - // internalAbort() clears |m_loader|. Compute |sendFlag| now. - // - // |sendFlag| corresponds to "the send() flag" defined in the XHR spec. - // - // |sendFlag| is only set when we have an active, asynchronous loader. - // Don't use it as "the send() flag" when the XHR is in sync mode. - bool sendFlag = m_loader.get(); - // internalAbort() clears the response. Save the data needed for // dispatching ProgressEvents. long long expectedLength = m_response.expectedContentLength(); @@ -1076,7 +1072,7 @@ // becomes true by that. We should implement more reliable treatment for // nested method invocations at some point. if (m_async) { - if ((m_state == kOpened && sendFlag) || m_state == kHeadersReceived || + if ((m_state == kOpened && m_sendFlag) || m_state == kHeadersReceived || m_state == kLoading) { DCHECK(!m_loader); handleRequestError(0, EventTypeNames::abort, receivedLength, @@ -1225,6 +1221,7 @@ InspectorInstrumentation::didFailXHRLoading(getExecutionContext(), this, this, m_method, m_url); + m_sendFlag = false; if (!m_async) { DCHECK(exceptionCode); m_state = kDone; @@ -1271,7 +1268,7 @@ void XMLHttpRequest::setRequestHeader(const AtomicString& name, const AtomicString& value, ExceptionState& exceptionState) { - if (m_state != kOpened || m_loader) { + if (m_state != kOpened || m_sendFlag) { exceptionState.throwDOMException(InvalidStateError, "The object's state must be OPENED."); return; @@ -1609,6 +1606,7 @@ m_loader = nullptr; } + m_sendFlag = false; changeState(kDone); if (!getExecutionContext() || !getExecutionContext()->isDocument() ||
diff --git a/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.h b/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.h index 2f74de10d..de8c1fd 100644 --- a/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.h +++ b/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.h
@@ -336,6 +336,7 @@ // option. bool m_downloadingToFile; bool m_responseTextOverflow; + bool m_sendFlag; }; std::ostream& operator<<(std::ostream&, const XMLHttpRequest*);
diff --git a/third_party/WebKit/Source/devtools/.eslintrc.js b/third_party/WebKit/Source/devtools/.eslintrc.js index b4f5379..f9a41f0 100644 --- a/third_party/WebKit/Source/devtools/.eslintrc.js +++ b/third_party/WebKit/Source/devtools/.eslintrc.js
@@ -39,6 +39,7 @@ "getWithoutSet": false, "setWithoutGet": false }], + "curly": [2, "multi-or-nest", "consistent"], // anti-patterns "no-with": 2,
diff --git a/third_party/WebKit/Source/devtools/.gitignore b/third_party/WebKit/Source/devtools/.gitignore index ddfab58..eb6f6b0 100644 --- a/third_party/WebKit/Source/devtools/.gitignore +++ b/third_party/WebKit/Source/devtools/.gitignore
@@ -13,3 +13,5 @@ /.test_cache /release /scripts/local_node/runtimes +/front_end/InspectorBackendCommands.js +/front_end/SupportedCSSProperties.js \ No newline at end of file
diff --git a/third_party/WebKit/Source/devtools/front_end/Runtime.js b/third_party/WebKit/Source/devtools/front_end/Runtime.js index aa3a298..060b400 100644 --- a/third_party/WebKit/Source/devtools/front_end/Runtime.js +++ b/third_party/WebKit/Source/devtools/front_end/Runtime.js
@@ -767,8 +767,11 @@ // Module namespaces. var namespace = this._name.replace('_lazy', ''); + // the namespace keyword confuses clang-format + // clang-format off if (namespace === 'sdk' || namespace === 'ui') - namespace = namespace.toUpperCase(); + namespace = namespace.toUpperCase(); + // clang-format on namespace = namespace.split('_').map(a => a.substring(0, 1).toUpperCase() + a.substring(1)).join(''); self[namespace] = self[namespace] || {};
diff --git a/third_party/WebKit/Source/devtools/front_end/Tests.js b/third_party/WebKit/Source/devtools/front_end/Tests.js index 98820a2..8ec346a 100644 --- a/third_party/WebKit/Source/devtools/front_end/Tests.js +++ b/third_party/WebKit/Source/devtools/front_end/Tests.js
@@ -329,10 +329,11 @@ function checkNoDuplicates() { var uiSourceCodes = test.nonAnonymousUISourceCodes_(); for (var i = 0; i < uiSourceCodes.length; i++) { - for (var j = i + 1; j < uiSourceCodes.length; j++) + for (var j = i + 1; j < uiSourceCodes.length; j++) { test.assertTrue( uiSourceCodes[i].url() !== uiSourceCodes[j].url(), 'Found script duplicates: ' + test.uiSourceCodesToString_(uiSourceCodes)); + } } } @@ -519,15 +520,16 @@ TestSuite.prototype.testConsoleOnNavigateBack = function() { function filteredMessages() { - return SDK.multitargetConsoleModel.messages().filter( - a => a.source !== SDK.ConsoleMessage.MessageSource.Violation); + return SDK.multitargetConsoleModel.messages().filter( + a => a.source !== SDK.ConsoleMessage.MessageSource.Violation); } - if (filteredMessages().length === 1) + if (filteredMessages().length === 1) { firstConsoleMessageReceived.call(this, null); - else + } else { SDK.multitargetConsoleModel.addEventListener( SDK.ConsoleModel.Events.MessageAdded, firstConsoleMessageReceived, this); + } function firstConsoleMessageReceived(event) { if (event && event.data.source === SDK.ConsoleMessage.MessageSource.Violation) @@ -690,14 +692,12 @@ messages.splice(index, 1); if (!messages.length) { - SDK.multitargetConsoleModel.removeEventListener( - SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this); + SDK.multitargetConsoleModel.removeEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this); next(); } } - SDK.multitargetConsoleModel.addEventListener( - SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this); + SDK.multitargetConsoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this); SDK.multitargetNetworkManager.setNetworkConditions(preset); } @@ -719,8 +719,8 @@ function step3() { testPreset( - Components.NetworkConditionsSelector._presets[8], - ['connection change event: type = wifi; downlinkMax = 30'], test.releaseControl.bind(test)); + Components.NetworkConditionsSelector._presets[8], ['connection change event: type = wifi; downlinkMax = 30'], + test.releaseControl.bind(test)); } }; @@ -889,8 +889,7 @@ this.fail(text); } - SDK.multitargetConsoleModel.addEventListener( - SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this); + SDK.multitargetConsoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this); this.takeControl(); }; @@ -934,14 +933,12 @@ Array.prototype.slice.call(arguments, 1, -1).map(arg => JSON.stringify(arg)).join(',') + ','; this.evaluateInConsole_( `${functionName}(${argsString} function() { console.log('${doneMessage}'); });`, function() {}); - SDK.multitargetConsoleModel.addEventListener( - SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage); + SDK.multitargetConsoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage); function onConsoleMessage(event) { var text = event.data.messageText; if (text === doneMessage) { - SDK.multitargetConsoleModel.removeEventListener( - SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage); + SDK.multitargetConsoleModel.removeEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage); callback(); } } @@ -976,7 +973,8 @@ continue; if (e.steps.length < 2) continue; - if (e.name.startsWith(prefix + 'Mouse') && typeof TimelineModel.TimelineData.forEvent(e.steps[0]).timeWaitingForMainThread !== 'number') + if (e.name.startsWith(prefix + 'Mouse') && + typeof TimelineModel.TimelineData.forEvent(e.steps[0]).timeWaitingForMainThread !== 'number') throw `Missing timeWaitingForMainThread on ${e.name}`; expectedEvents.delete(e.name.substr(prefix.length)); } @@ -1106,8 +1104,7 @@ if (runtimeModel.executionContexts().length >= n) callback.call(null); else - this.addSniffer( - SDK.RuntimeModel.prototype, '_executionContextCreated', checkForExecutionContexts.bind(this)); + this.addSniffer(SDK.RuntimeModel.prototype, '_executionContextCreated', checkForExecutionContexts.bind(this)); } };
diff --git a/third_party/WebKit/Source/devtools/front_end/accessibility/AXTreePane.js b/third_party/WebKit/Source/devtools/front_end/accessibility/AXTreePane.js index d1301d7..8dd1b5d3 100644 --- a/third_party/WebKit/Source/devtools/front_end/accessibility/AXTreePane.js +++ b/third_party/WebKit/Source/devtools/front_end/accessibility/AXTreePane.js
@@ -128,7 +128,7 @@ this._axNode = axNode; this._treePane = treePane; - this.element = createElementWithClass('button', 'inspect-dom-node'); + this.element = UI.Icon.create('smallicon-arrow-in-circle', 'inspect-dom-node'); this.element.addEventListener('mousedown', this._handleMouseDown.bind(this)); } @@ -161,8 +161,7 @@ this.selectable = true; - this._inspectNodeButton = - new Accessibility.InspectNodeButton(axNode, treePane); + this._inspectNodeButton = new Accessibility.InspectNodeButton(axNode, treePane); } /** @@ -321,8 +320,7 @@ this._treeElement = treeElement; this.element = createElementWithClass('button', 'expand-siblings'); - this.element.textContent = Common.UIString( - (numSiblings === 1 ? '+ %d node' : '+ %d nodes'), numSiblings); + this.element.textContent = Common.UIString((numSiblings === 1 ? '+ %d node' : '+ %d nodes'), numSiblings); this.element.addEventListener('mousedown', this._handleMouseDown.bind(this)); } @@ -360,10 +358,8 @@ super.onattach(); if (this._treePane.isExpanded(this._axNode.backendDOMNodeId())) this._listItemNode.classList.add('siblings-expanded'); - if (this._axNode.numChildren() > 1) { - this._listItemNode.insertBefore(this._expandSiblingsButton.element, - this._inspectNodeButton.element); - } + if (this._axNode.numChildren() > 1) + this._listItemNode.insertBefore(this._expandSiblingsButton.element, this._inspectNodeButton.element); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/accessibility/AccessibilityModel.js b/third_party/WebKit/Source/devtools/front_end/accessibility/AccessibilityModel.js index 20a5565..a0951b2 100644 --- a/third_party/WebKit/Source/devtools/front_end/accessibility/AccessibilityModel.js +++ b/third_party/WebKit/Source/devtools/front_end/accessibility/AccessibilityModel.js
@@ -19,9 +19,7 @@ if (payload.backendDOMNodeId) { accessibilityModel._setAXNodeForBackendDOMNodeId(payload.backendDOMNodeId, this); this._backendDOMNodeId = payload.backendDOMNodeId; - this._deferredDOMNode = - new SDK.DeferredDOMNode(this.target(), - payload.backendDOMNodeId); + this._deferredDOMNode = new SDK.DeferredDOMNode(this.target(), payload.backendDOMNodeId); } else { this._backendDOMNodeId = null; this._deferredDOMNode = null; @@ -68,8 +66,10 @@ if (this._name) properties.push(/** @type {!Protocol.Accessibility.AXProperty} */ ({name: 'name', value: this._name})); - if (this._description) - properties.push(/** @type {!Protocol.Accessibility.AXProperty} */ ({name: 'description', value: this._description})); + if (this._description) { + properties.push( + /** @type {!Protocol.Accessibility.AXProperty} */ ({name: 'description', value: this._description})); + } if (this._value) properties.push(/** @type {!Protocol.Accessibility.AXProperty} */ ({name: 'value', value: this._value})); @@ -253,9 +253,8 @@ new Accessibility.AccessibilityNode(this, payload); for (var axNode of this._axIdToAXNode.values()) { - for (var axChild of axNode.children()) { + for (var axChild of axNode.children()) axChild._setParentNode(axNode); - } } } return this._agent.getPartialAXTree(node.id, true, parsePayload.bind(this)); @@ -292,8 +291,7 @@ * @param {!Accessibility.AccessibilityNode} axNode */ _setAXNodeForBackendDOMNodeId(backendDOMNodeId, axNode) { - this._backendDOMNodeIdToAXNode.set(backendDOMNodeId, - axNode); + this._backendDOMNodeIdToAXNode.set(backendDOMNodeId, axNode); } // TODO(aboxhall): Remove once protocol is stable.
diff --git a/third_party/WebKit/Source/devtools/front_end/accessibility/AccessibilityNodeView.js b/third_party/WebKit/Source/devtools/front_end/accessibility/AccessibilityNodeView.js index 40e5d829..3805398 100644 --- a/third_party/WebKit/Source/devtools/front_end/accessibility/AccessibilityNodeView.js +++ b/third_party/WebKit/Source/devtools/front_end/accessibility/AccessibilityNodeView.js
@@ -9,8 +9,7 @@ super(Common.UIString('Computed Properties')); this._noNodeInfo = this.createInfo(Common.UIString('No accessibility node')); - this._ignoredInfo = - this.createInfo(Common.UIString('Accessibility node not exposed'), 'ax-ignored-info hidden'); + this._ignoredInfo = this.createInfo(Common.UIString('Accessibility node not exposed'), 'ax-ignored-info hidden'); this._treeOutline = this.createTreeOutline(); this._ignoredReasonsTree = this.createTreeOutline(); @@ -355,21 +354,20 @@ if (idrefs.length === 1) { var idref = idrefs[0]; var matchingNode = relatedNodes.find(node => node.idref === idref); - if (matchingNode) { + if (matchingNode) this.appendRelatedNodeWithIdref(matchingNode, 0, idref); - } else { + else this.listItemElement.appendChild(new Accessibility.AXRelatedNodeElement({idref: idref}).render()); - } + } else { // TODO(aboxhall): exclamation mark if not idreflist type for (var i = 0; i < idrefs.length; ++i) { var idref = idrefs[i]; var matchingNode = relatedNodes.find(node => node.idref === idref); - if (matchingNode) { + if (matchingNode) this.appendRelatedNodeWithIdref(matchingNode, i, idref); - } else { + else this.appendChild(new Accessibility.AXRelatedNodeSourceTreeElement({idref: idref})); - } } } } @@ -383,11 +381,11 @@ var numNodes = relatedNodes.length; if (value.type === Protocol.Accessibility.AXValueType.IdrefList || - value.type === Protocol.Accessibility.AXValueType.Idref) { + value.type === Protocol.Accessibility.AXValueType.Idref) this.appendIDRefValueElement(value); - } else { + else super.appendRelatedNodeListValueElement(value); - } + if (numNodes <= 3) this.expand(); @@ -507,9 +505,10 @@ if (!this._value) return; - if (this._value.text) + if (this._value.text) { this.listItemElement.appendChild(Accessibility.AXNodePropertyTreeElement.createSimpleValueElement( Protocol.Accessibility.AXValueType.ComputedString, this._value.text)); + } } };
diff --git a/third_party/WebKit/Source/devtools/front_end/accessibility/AccessibilitySidebarView.js b/third_party/WebKit/Source/devtools/front_end/accessibility/AccessibilitySidebarView.js index 4cb9cedb..56c7d8d 100644 --- a/third_party/WebKit/Source/devtools/front_end/accessibility/AccessibilitySidebarView.js +++ b/third_party/WebKit/Source/devtools/front_end/accessibility/AccessibilitySidebarView.js
@@ -62,10 +62,9 @@ return Promise.resolve(); var accessibilityModel = Accessibility.AccessibilityModel.fromTarget(node.target()); accessibilityModel.clear(); - return accessibilityModel.requestPartialAXTree(node) - .then(() => { - this.accessibilityNodeCallback(accessibilityModel.axNodeForDOMNode(node)); - }); + return accessibilityModel.requestPartialAXTree(node).then(() => { + this.accessibilityNodeCallback(accessibilityModel.axNodeForDOMNode(node)); + }); } /** @@ -78,10 +77,8 @@ this._axNodeSubPane.setNode(this.node()); this._ariaSubPane.setNode(this.node()); - SDK.targetManager.addModelListener( - SDK.DOMModel, SDK.DOMModel.Events.AttrModified, this._onAttrChange, this); - SDK.targetManager.addModelListener( - SDK.DOMModel, SDK.DOMModel.Events.AttrRemoved, this._onAttrChange, this); + SDK.targetManager.addModelListener(SDK.DOMModel, SDK.DOMModel.Events.AttrModified, this._onAttrChange, this); + SDK.targetManager.addModelListener(SDK.DOMModel, SDK.DOMModel.Events.AttrRemoved, this._onAttrChange, this); SDK.targetManager.addModelListener( SDK.DOMModel, SDK.DOMModel.Events.CharacterDataModified, this._onNodeChange, this); SDK.targetManager.addModelListener( @@ -92,10 +89,8 @@ * @override */ willHide() { - SDK.targetManager.removeModelListener( - SDK.DOMModel, SDK.DOMModel.Events.AttrModified, this._onAttrChange, this); - SDK.targetManager.removeModelListener( - SDK.DOMModel, SDK.DOMModel.Events.AttrRemoved, this._onAttrChange, this); + SDK.targetManager.removeModelListener(SDK.DOMModel, SDK.DOMModel.Events.AttrModified, this._onAttrChange, this); + SDK.targetManager.removeModelListener(SDK.DOMModel, SDK.DOMModel.Events.AttrRemoved, this._onAttrChange, this); SDK.targetManager.removeModelListener( SDK.DOMModel, SDK.DOMModel.Events.CharacterDataModified, this._onNodeChange, this); SDK.targetManager.removeModelListener(
diff --git a/third_party/WebKit/Source/devtools/front_end/accessibility/accessibilityNode.css b/third_party/WebKit/Source/devtools/front_end/accessibility/accessibilityNode.css index 0be8af2..55782db6 100644 --- a/third_party/WebKit/Source/devtools/front_end/accessibility/accessibilityNode.css +++ b/third_party/WebKit/Source/devtools/front_end/accessibility/accessibilityNode.css
@@ -170,12 +170,8 @@ display: none; } -button.inspect-dom-node { - -webkit-mask-image: url(Images/toolbarButtonGlyphs.png); - -webkit-mask-position: -10px -127px; +li .inspect-dom-node { background-color: #5a5a5a; - width: 11px; - height: 11px; padding: 0; margin-left: 5px; border: 0; @@ -184,6 +180,6 @@ top: 2px; } -.tree-outline:focus li.selected button.inspect-dom-node { +.tree-outline:focus li.selected .inspect-dom-node { background-color: white; }
diff --git a/third_party/WebKit/Source/devtools/front_end/animation/AnimationModel.js b/third_party/WebKit/Source/devtools/front_end/animation/AnimationModel.js index b69a705e..7b62f5b 100644 --- a/third_party/WebKit/Source/devtools/front_end/animation/AnimationModel.js +++ b/third_party/WebKit/Source/devtools/front_end/animation/AnimationModel.js
@@ -107,8 +107,7 @@ this._animationGroups.set(incomingGroup.id(), incomingGroup); this._screenshotCapture.captureScreenshots(incomingGroup.finiteDuration(), incomingGroup._screenshots); } - this.dispatchEventToListeners( - Animation.AnimationModel.Events.AnimationGroupStarted, matchedGroup || incomingGroup); + this.dispatchEventToListeners(Animation.AnimationModel.Events.AnimationGroupStarted, matchedGroup || incomingGroup); return !!matchedGroup; } @@ -799,8 +798,7 @@ this._target = target; /** @type {!Array<!Animation.AnimationModel.ScreenshotCapture.Request>} */ this._requests = []; - resourceTreeModel.addEventListener( - SDK.ResourceTreeModel.Events.ScreencastFrame, this._screencastFrame, this); + resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.ScreencastFrame, this._screencastFrame, this); this._model = model; this._model.addEventListener(Animation.AnimationModel.Events.ModelReset, this._stopScreencast, this); }
diff --git a/third_party/WebKit/Source/devtools/front_end/animation/AnimationTimeline.js b/third_party/WebKit/Source/devtools/front_end/animation/AnimationTimeline.js index a884d37..643e914 100644 --- a/third_party/WebKit/Source/devtools/front_end/animation/AnimationTimeline.js +++ b/third_party/WebKit/Source/devtools/front_end/animation/AnimationTimeline.js
@@ -32,8 +32,7 @@ this._symbol = Symbol('animationTimeline'); /** @type {!Map.<string, !Animation.AnimationModel.Animation>} */ this._animationsMap = new Map(); - SDK.targetManager.addModelListener( - SDK.DOMModel, SDK.DOMModel.Events.NodeRemoved, this._nodeRemoved, this); + SDK.targetManager.addModelListener(SDK.DOMModel, SDK.DOMModel.Events.NodeRemoved, this._nodeRemoved, this); SDK.targetManager.observeTargets(this, SDK.Target.Capability.DOM); UI.context.addFlavorChangeListener(SDK.DOMNode, this._nodeChanged, this); } @@ -125,8 +124,7 @@ this._playbackRateButtons = []; for (var playbackRate of Animation.AnimationTimeline.GlobalPlaybackRates) { var button = playbackRateControl.createChild('div', 'animation-playback-rate-button'); - button.textContent = - playbackRate ? Common.UIString(playbackRate * 100 + '%') : Common.UIString('Pause'); + button.textContent = playbackRate ? Common.UIString(playbackRate * 100 + '%') : Common.UIString('Pause'); button.playbackRate = playbackRate; button.addEventListener('click', this._setPlaybackRate.bind(this, playbackRate)); button.title = Common.UIString('Set speed to ') + button.textContent; @@ -146,8 +144,7 @@ this._currentTime = controls.createChild('div', 'animation-timeline-current-time monospace'); var toolbar = new UI.Toolbar('animation-controls-toolbar', controls); - this._controlButton = - new UI.ToolbarToggle(Common.UIString('Replay timeline'), 'largeicon-replay-animation'); + this._controlButton = new UI.ToolbarToggle(Common.UIString('Replay timeline'), 'largeicon-replay-animation'); this._controlState = Animation.AnimationTimeline._ControlState.Replay; this._controlButton.setToggled(true); this._controlButton.addEventListener('click', this._controlButtonToggle.bind(this)); @@ -213,8 +210,7 @@ this._allPaused = !this._allPaused; this._pauseButton.setToggled(this._allPaused); this._setPlaybackRate(this._playbackRate); - this._pauseButton.setTitle( - this._allPaused ? Common.UIString('Resume all') : Common.UIString('Pause all')); + this._pauseButton.setTitle(this._allPaused ? Common.UIString('Resume all') : Common.UIString('Pause all')); } /** @@ -596,11 +592,10 @@ if (!this._scrubberPlayer) return; this._currentTime.textContent = Common.UIString(Number.millisToString(this._scrubberPlayer.currentTime)); - if (this._scrubberPlayer.playState === 'pending' || this._scrubberPlayer.playState === 'running') { + if (this._scrubberPlayer.playState === 'pending' || this._scrubberPlayer.playState === 'running') this.element.window().requestAnimationFrame(this._updateScrubber.bind(this)); - } else if (this._scrubberPlayer.playState === 'finished') { + else if (this._scrubberPlayer.playState === 'finished') this._currentTime.textContent = ''; - } } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/animation/AnimationUI.js b/third_party/WebKit/Source/devtools/front_end/animation/AnimationUI.js index 7ccc3c3..45c161f 100644 --- a/third_party/WebKit/Source/devtools/front_end/animation/AnimationUI.js +++ b/third_party/WebKit/Source/devtools/front_end/animation/AnimationUI.js
@@ -43,8 +43,7 @@ */ static Color(animation) { var names = Object.keys(Animation.AnimationUI.Colors); - var color = - Animation.AnimationUI.Colors[names[String.hashCode(animation.name() || animation.id()) % names.length]]; + var color = Animation.AnimationUI.Colors[names[String.hashCode(animation.name() || animation.id()) % names.length]]; return color.asString(Common.Color.Format.RGB); } @@ -84,8 +83,8 @@ if (!cache.animationLine) cache.animationLine = this._createLine(parentElement, 'animation-line'); cache.animationLine.setAttribute( - 'x2', (this._duration() * this._timeline.pixelMsRatio() + Animation.AnimationUI.Options.AnimationMargin) - .toFixed(2)); + 'x2', + (this._duration() * this._timeline.pixelMsRatio() + Animation.AnimationUI.Options.AnimationMargin).toFixed(2)); } /** @@ -178,9 +177,10 @@ var bezier = Common.Geometry.CubicBezier.parse(easing); var cache = this._cachedElements[iteration].keyframeRender; - if (!cache[keyframeIndex]) + if (!cache[keyframeIndex]) { cache[keyframeIndex] = bezier ? parentElement.createSVGChild('path', 'animation-keyframe') : parentElement.createSVGChild('g', 'animation-keyframe-step'); + } var group = cache[keyframeIndex]; group.style.transform = 'translateX(' + leftDistance.toFixed(2) + 'px)'; @@ -252,9 +252,10 @@ * @param {number} iteration */ _renderIteration(parentElement, iteration) { - if (!this._cachedElements[iteration]) + if (!this._cachedElements[iteration]) { this._cachedElements[iteration] = {animationLine: null, keyframePoints: {}, keyframeRender: {}, group: parentElement.createSVGChild('g')}; + } var group = this._cachedElements[iteration].group; group.style.transform = 'translateX(' + (iteration * this._duration() * this._timeline.pixelMsRatio()).toFixed(2) + 'px)';
diff --git a/third_party/WebKit/Source/devtools/front_end/audits/AuditCategories.js b/third_party/WebKit/Source/devtools/front_end/audits/AuditCategories.js index f7aa7d2..a22396c 100644 --- a/third_party/WebKit/Source/devtools/front_end/audits/AuditCategories.js +++ b/third_party/WebKit/Source/devtools/front_end/audits/AuditCategories.js
@@ -61,8 +61,7 @@ this.addRule(new Audits.AuditRules.CombineJsResourcesRule(2), Audits.AuditRule.Severity.Severe); this.addRule(new Audits.AuditRules.CombineCssResourcesRule(2), Audits.AuditRule.Severity.Severe); this.addRule(new Audits.AuditRules.MinimizeDnsLookupsRule(4), Audits.AuditRule.Severity.Warning); - this.addRule( - new Audits.AuditRules.ParallelizeDownloadRule(4, 10, 0.5), Audits.AuditRule.Severity.Warning); + this.addRule(new Audits.AuditRules.ParallelizeDownloadRule(4, 10, 0.5), Audits.AuditRule.Severity.Warning); this.addRule(new Audits.AuditRules.BrowserCacheControlRule(), Audits.AuditRule.Severity.Severe); } };
diff --git a/third_party/WebKit/Source/devtools/front_end/audits/AuditController.js b/third_party/WebKit/Source/devtools/front_end/audits/AuditController.js index b98970d..d70484c 100644 --- a/third_party/WebKit/Source/devtools/front_end/audits/AuditController.js +++ b/third_party/WebKit/Source/devtools/front_end/audits/AuditController.js
@@ -38,8 +38,7 @@ */ constructor(auditsPanel) { this._auditsPanel = auditsPanel; - SDK.targetManager.addEventListener( - SDK.TargetManager.Events.Load, this._didMainResourceLoad, this); + SDK.targetManager.addEventListener(SDK.TargetManager.Events.Load, this._didMainResourceLoad, this); SDK.targetManager.addModelListener( SDK.NetworkManager, SDK.NetworkManager.Events.RequestFinished, this._didLoadResource, this); }
diff --git a/third_party/WebKit/Source/devtools/front_end/audits/AuditExtensionCategory.js b/third_party/WebKit/Source/devtools/front_end/audits/AuditExtensionCategory.js index 1b899f4e..9c78a1c 100644 --- a/third_party/WebKit/Source/devtools/front_end/audits/AuditExtensionCategory.js +++ b/third_party/WebKit/Source/devtools/front_end/audits/AuditExtensionCategory.js
@@ -129,8 +129,7 @@ } _addNode(parent, node) { - var contents = - Audits.auditFormatters.partiallyApply(Audits.AuditExtensionFormatters, this, node.contents); + var contents = Audits.auditFormatters.partiallyApply(Audits.AuditExtensionFormatters, this, node.contents); var addedNode = parent.addChild(contents, node.expanded); if (node.children) { for (var i = 0; i < node.children.length; ++i) @@ -216,9 +215,7 @@ * @param {!SDK.RemoteObject} remoteObject */ function onEvaluate(remoteObject) { - Common.Renderer.renderPromise(remoteObject) - .then(appendRenderer) - .then(remoteObject.release.bind(remoteObject)); + Common.Renderer.renderPromise(remoteObject).then(appendRenderer).then(remoteObject.release.bind(remoteObject)); /** * @param {!Element} element
diff --git a/third_party/WebKit/Source/devtools/front_end/audits/AuditLauncherView.js b/third_party/WebKit/Source/devtools/front_end/audits/AuditLauncherView.js index 135b123..35ef764 100644 --- a/third_party/WebKit/Source/devtools/front_end/audits/AuditLauncherView.js +++ b/third_party/WebKit/Source/devtools/front_end/audits/AuditLauncherView.js
@@ -266,9 +266,10 @@ } _updateResourceProgress() { - if (this._displayResourceLoadingProgress) + if (this._displayResourceLoadingProgress) { this._progressIndicator.setTitle( Common.UIString('Loading (%d of %d)', this._loadedResources, this._totalResources)); + } } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/audits/AuditResultView.js b/third_party/WebKit/Source/devtools/front_end/audits/AuditResultView.js index 85bf3fa..442feaf 100644 --- a/third_party/WebKit/Source/devtools/front_end/audits/AuditResultView.js +++ b/third_party/WebKit/Source/devtools/front_end/audits/AuditResultView.js
@@ -44,8 +44,7 @@ this._treeOutline.expandTreeElementsWhenArrowing = true; function ruleSorter(a, b) { - var result = - Audits.AuditRule.SeverityOrder[a.severity || 0] - Audits.AuditRule.SeverityOrder[b.severity || 0]; + var result = Audits.AuditRule.SeverityOrder[a.severity || 0] - Audits.AuditRule.SeverityOrder[b.severity || 0]; if (!result) result = (a.value || '').localeCompare(b.value || ''); return result;
diff --git a/third_party/WebKit/Source/devtools/front_end/audits/AuditRules.js b/third_party/WebKit/Source/devtools/front_end/audits/AuditRules.js index 1509b39..c5376ff0 100644 --- a/third_party/WebKit/Source/devtools/front_end/audits/AuditRules.js +++ b/third_party/WebKit/Source/devtools/front_end/audits/AuditRules.js
@@ -193,8 +193,8 @@ Audits.AuditRules.CombineJsResourcesRule = class extends Audits.AuditRules.CombineExternalResourcesRule { constructor(allowedPerDomain) { super( - 'page-externaljs', Common.UIString('Combine external JavaScript'), Common.resourceTypes.Script, - 'JavaScript', allowedPerDomain); + 'page-externaljs', Common.UIString('Combine external JavaScript'), Common.resourceTypes.Script, 'JavaScript', + allowedPerDomain); } }; @@ -628,9 +628,9 @@ var freshnessLifetimeMs; var maxAgeMatch = this.responseHeaderMatch(request, 'Cache-Control', 'max-age=(\\d+)'); - if (maxAgeMatch) + if (maxAgeMatch) { freshnessLifetimeMs = (maxAgeMatch[1]) ? 1000 * maxAgeMatch[1] : 0; - else { + } else { var expiresHeader = this.responseHeader(request, 'Expires'); if (expiresHeader) { var expDate = Date.parse(expiresHeader); @@ -1121,8 +1121,8 @@ var lateStyleUrls = []; for (var i = 0; i < lateStyleIds.length; ++i) { var lateStyleNode = domModel.nodeForId(lateStyleIds[i]); - var completeHref = Common.ParsedURL.completeURL( - lateStyleNode.ownerDocument.baseURL, lateStyleNode.getAttribute('href')); + var completeHref = + Common.ParsedURL.completeURL(lateStyleNode.ownerDocument.baseURL, lateStyleNode.getAttribute('href')); lateStyleUrls.push(completeHref || '<empty>'); } result = [lateStyleUrls, cssBeforeInlineCount]; @@ -1402,10 +1402,11 @@ for (var i = 0, len = sortedCookieSizes.length; i < len; ++i) { var maxCookieSize = sortedCookieSizes[i].maxCookieSize; - if (maxCookieSize > this._maxBytesThreshold) + if (maxCookieSize > this._maxBytesThreshold) { hugeCookieDomains.push( Audits.AuditRuleResult.resourceDomain(sortedCookieSizes[i].domain) + ': ' + Number.bytesToString(maxCookieSize)); + } } var bigAvgCookieDomains = []; @@ -1413,9 +1414,10 @@ for (var i = 0, len = sortedCookieSizes.length; i < len; ++i) { var domain = sortedCookieSizes[i].domain; var avgCookieSize = sortedCookieSizes[i].avgCookieSize; - if (avgCookieSize > this._avgBytesThreshold && avgCookieSize < this._maxBytesThreshold) + if (avgCookieSize > this._avgBytesThreshold && avgCookieSize < this._maxBytesThreshold) { bigAvgCookieDomains.push( Audits.AuditRuleResult.resourceDomain(domain) + ': ' + Number.bytesToString(avgCookieSize)); + } } result.addChild(Common.UIString( 'The average cookie size for all requests on this page is %s', Number.bytesToString(avgAllCookiesSize)));
diff --git a/third_party/WebKit/Source/devtools/front_end/bindings/BlackboxManager.js b/third_party/WebKit/Source/devtools/front_end/bindings/BlackboxManager.js index 0072787..6eabe87 100644 --- a/third_party/WebKit/Source/devtools/front_end/bindings/BlackboxManager.js +++ b/third_party/WebKit/Source/devtools/front_end/bindings/BlackboxManager.js
@@ -13,11 +13,9 @@ this._debuggerWorkspaceBinding = debuggerWorkspaceBinding; SDK.targetManager.addModelListener( - SDK.DebuggerModel, SDK.DebuggerModel.Events.ParsedScriptSource, this._parsedScriptSource, - this); + SDK.DebuggerModel, SDK.DebuggerModel.Events.ParsedScriptSource, this._parsedScriptSource, this); SDK.targetManager.addModelListener( - SDK.DebuggerModel, SDK.DebuggerModel.Events.GlobalObjectCleared, this._globalObjectCleared, - this); + SDK.DebuggerModel, SDK.DebuggerModel.Events.GlobalObjectCleared, this._globalObjectCleared, this); Common.moduleSetting('skipStackFramesPattern').addChangeListener(this._patternChanged.bind(this)); Common.moduleSetting('skipContentScripts').addChangeListener(this._patternChanged.bind(this)); @@ -362,9 +360,10 @@ if (previousScriptState) { var hasChanged = false; hasChanged = previousScriptState.length !== positions.length; - for (var i = 0; !hasChanged && i < positions.length; ++i) + for (var i = 0; !hasChanged && i < positions.length; ++i) { hasChanged = positions[i].lineNumber !== previousScriptState[i].lineNumber || positions[i].columnNumber !== previousScriptState[i].columnNumber; + } if (!hasChanged) return Promise.resolve(); } else {
diff --git a/third_party/WebKit/Source/devtools/front_end/bindings/BreakpointManager.js b/third_party/WebKit/Source/devtools/front_end/bindings/BreakpointManager.js index ce05b45..b6aaac23 100644 --- a/third_party/WebKit/Source/devtools/front_end/bindings/BreakpointManager.js +++ b/third_party/WebKit/Source/devtools/front_end/bindings/BreakpointManager.js
@@ -55,8 +55,7 @@ this._workspace.addEventListener(Workspace.Workspace.Events.ProjectRemoved, this._projectRemoved, this); this._workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded, this._uiSourceCodeAdded, this); - this._workspace.addEventListener( - Workspace.Workspace.Events.UISourceCodeRemoved, this._uiSourceCodeRemoved, this); + this._workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeRemoved, this._uiSourceCodeRemoved, this); targetManager.observeTargets(this, SDK.Target.Capability.JS); } @@ -278,10 +277,12 @@ if (!targets.length) return Promise.resolve([]); for (var target of targets) { - var startLocation = this._debuggerWorkspaceBinding.uiLocationToRawLocation(target, uiSourceCode, textRange.startLine, textRange.startColumn); + var startLocation = this._debuggerWorkspaceBinding.uiLocationToRawLocation( + target, uiSourceCode, textRange.startLine, textRange.startColumn); if (!startLocation) continue; - var endLocation = this._debuggerWorkspaceBinding.uiLocationToRawLocation(target, uiSourceCode, textRange.endLine, textRange.endColumn); + var endLocation = this._debuggerWorkspaceBinding.uiLocationToRawLocation( + target, uiSourceCode, textRange.endLine, textRange.endColumn); if (!endLocation) continue; var debuggerModel = SDK.DebuggerModel.fromTarget(target); @@ -300,7 +301,7 @@ sortedLocations.sort(Workspace.UILocation.comparator); if (!sortedLocations.length) return []; - var result = [ sortedLocations[0] ]; + var result = [sortedLocations[0]]; var lastLocation = sortedLocations[0]; for (var i = 1; i < sortedLocations.length; ++i) { if (sortedLocations[i].id() === lastLocation.id()) @@ -704,8 +705,7 @@ * @return {string} */ _breakpointStorageId() { - return Bindings.BreakpointManager._breakpointStorageId( - this._sourceFileId, this._lineNumber, this._columnNumber); + return Bindings.BreakpointManager._breakpointStorageId(this._sourceFileId, this._lineNumber, this._columnNumber); } _fakeBreakpointAtPrimaryLocation() { @@ -823,16 +823,17 @@ this._debuggerWorkspaceBinding.uiLocationToRawLocation(this.target(), uiSourceCode, lineNumber, columnNumber) : null; var newState; - if (this._breakpoint._isRemoved || !this._breakpoint.enabled() || this._scriptDiverged()) + if (this._breakpoint._isRemoved || !this._breakpoint.enabled() || this._scriptDiverged()) { newState = null; - else if (debuggerLocation) { + } else if (debuggerLocation) { var script = debuggerLocation.script(); - if (script.sourceURL) + if (script.sourceURL) { newState = new Bindings.BreakpointManager.Breakpoint.State( script.sourceURL, null, debuggerLocation.lineNumber, debuggerLocation.columnNumber, condition); - else + } else { newState = new Bindings.BreakpointManager.Breakpoint.State( null, debuggerLocation.scriptId, debuggerLocation.lineNumber, debuggerLocation.columnNumber, condition); + } } else if (this._breakpoint._currentState && this._breakpoint._currentState.url) { var position = this._breakpoint._currentState; newState = new Bindings.BreakpointManager.Breakpoint.State( @@ -862,12 +863,13 @@ } var updateCallback = this._didSetBreakpointInDebugger.bind(this, callback); - if (newState.url) + if (newState.url) { this._debuggerModel.setBreakpointByURL( newState.url, newState.lineNumber, newState.columnNumber, this._breakpoint.condition(), updateCallback); - else if (newState.scriptId) + } else if (newState.scriptId) { this._debuggerModel.setBreakpointBySourceId( /** @type {!SDK.DebuggerModel.Location} */ (debuggerLocation), condition, updateCallback); + } this._currentState = newState; }
diff --git a/third_party/WebKit/Source/devtools/front_end/bindings/CSSWorkspaceBinding.js b/third_party/WebKit/Source/devtools/front_end/bindings/CSSWorkspaceBinding.js index f563b5e..66bb99f 100644 --- a/third_party/WebKit/Source/devtools/front_end/bindings/CSSWorkspaceBinding.js +++ b/third_party/WebKit/Source/devtools/front_end/bindings/CSSWorkspaceBinding.js
@@ -26,9 +26,10 @@ */ targetAdded(target) { var cssModel = SDK.CSSModel.fromTarget(target); - if (cssModel) + if (cssModel) { this._modelToTargetInfo.set( cssModel, new Bindings.CSSWorkspaceBinding.TargetInfo(cssModel, this._workspace, this._networkMapping)); + } } /** @@ -153,8 +154,8 @@ constructor(cssModel, workspace, networkMapping) { this._cssModel = cssModel; this._stylesSourceMapping = new Bindings.StylesSourceMapping(cssModel, workspace, networkMapping); - this._sassSourceMapping = new Bindings.SASSSourceMapping( - cssModel, networkMapping, Bindings.NetworkProject.forTarget(cssModel.target())); + this._sassSourceMapping = + new Bindings.SASSSourceMapping(cssModel, networkMapping, Bindings.NetworkProject.forTarget(cssModel.target())); /** @type {!Multimap<!SDK.CSSStyleSheetHeader, !Bindings.LiveLocation>} */ this._locations = new Multimap();
diff --git a/third_party/WebKit/Source/devtools/front_end/bindings/CompilerScriptMapping.js b/third_party/WebKit/Source/devtools/front_end/bindings/CompilerScriptMapping.js index 23f0356..7247db9 100644 --- a/third_party/WebKit/Source/devtools/front_end/bindings/CompilerScriptMapping.js +++ b/third_party/WebKit/Source/devtools/front_end/bindings/CompilerScriptMapping.js
@@ -89,9 +89,9 @@ */ mapsToSourceCode(rawLocation) { var sourceMap = this._sourceMapForScriptId.get(rawLocation.scriptId); - if (!sourceMap) { + if (!sourceMap) return true; - } + return !!sourceMap.findEntry(rawLocation.lineNumber, rawLocation.columnNumber); } @@ -244,8 +244,7 @@ var embeddedContent = sourceMap.embeddedContentByURL(sourceURL); var embeddedContentLength = typeof embeddedContent === 'string' ? embeddedContent.length : null; uiSourceCode = this._networkProject.addFile( - contentProvider, SDK.ResourceTreeFrame.fromScript(script), script.isContentScript(), - embeddedContentLength); + contentProvider, SDK.ResourceTreeFrame.fromScript(script), script.isContentScript(), embeddedContentLength); uiSourceCode[Bindings.CompilerScriptMapping._originSymbol] = script.sourceURL; } if (uiSourceCode) { @@ -331,8 +330,7 @@ var loadingPromise = this._sourceMapLoadingPromises.get(sourceMapURL); if (!loadingPromise) { - loadingPromise = - SDK.TextSourceMap.load(sourceMapURL, scriptURL).then(sourceMapLoaded.bind(this, sourceMapURL)); + loadingPromise = SDK.TextSourceMap.load(sourceMapURL, scriptURL).then(sourceMapLoaded.bind(this, sourceMapURL)); this._sourceMapLoadingPromises.set(sourceMapURL, loadingPromise); } return loadingPromise;
diff --git a/third_party/WebKit/Source/devtools/front_end/bindings/DebuggerWorkspaceBinding.js b/third_party/WebKit/Source/devtools/front_end/bindings/DebuggerWorkspaceBinding.js index dbf9f63f..6b196e7 100644 --- a/third_party/WebKit/Source/devtools/front_end/bindings/DebuggerWorkspaceBinding.js +++ b/third_party/WebKit/Source/devtools/front_end/bindings/DebuggerWorkspaceBinding.js
@@ -21,11 +21,9 @@ targetManager.observeTargets(this); targetManager.addModelListener( - SDK.DebuggerModel, SDK.DebuggerModel.Events.GlobalObjectCleared, this._globalObjectCleared, - this); + SDK.DebuggerModel, SDK.DebuggerModel.Events.GlobalObjectCleared, this._globalObjectCleared, this); targetManager.addModelListener( - SDK.DebuggerModel, SDK.DebuggerModel.Events.BeforeDebuggerPaused, this._beforeDebuggerPaused, - this); + SDK.DebuggerModel, SDK.DebuggerModel.Events.BeforeDebuggerPaused, this._beforeDebuggerPaused, this); targetManager.addModelListener( SDK.DebuggerModel, SDK.DebuggerModel.Events.DebuggerResumed, this._debuggerResumed, this); workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeRemoved, this._uiSourceCodeRemoved, this); @@ -125,8 +123,8 @@ createLiveLocation(rawLocation, updateDelegate, locationPool) { var info = this._infoForScript(rawLocation.target(), rawLocation.scriptId); console.assert(info); - var location = new Bindings.DebuggerWorkspaceBinding.Location( - info._script, rawLocation, this, updateDelegate, locationPool); + var location = + new Bindings.DebuggerWorkspaceBinding.Location(info._script, rawLocation, this, updateDelegate, locationPool); info._addLocation(location); return location; } @@ -376,10 +374,8 @@ this._uiSourceCodeToSourceMapping = new Map(); this._eventListeners = [ - debuggerModel.addEventListener( - SDK.DebuggerModel.Events.ParsedScriptSource, this._parsedScriptSource, this), - debuggerModel.addEventListener( - SDK.DebuggerModel.Events.FailedToParseScriptSource, this._parsedScriptSource, this) + debuggerModel.addEventListener(SDK.DebuggerModel.Events.ParsedScriptSource, this._parsedScriptSource, this), + debuggerModel.addEventListener(SDK.DebuggerModel.Events.FailedToParseScriptSource, this._parsedScriptSource, this) ]; }
diff --git a/third_party/WebKit/Source/devtools/front_end/bindings/DefaultScriptMapping.js b/third_party/WebKit/Source/devtools/front_end/bindings/DefaultScriptMapping.js index 004fd11..8e8f028 100644 --- a/third_party/WebKit/Source/devtools/front_end/bindings/DefaultScriptMapping.js +++ b/third_party/WebKit/Source/devtools/front_end/bindings/DefaultScriptMapping.js
@@ -41,14 +41,13 @@ this._debuggerModel = debuggerModel; this._debuggerWorkspaceBinding = debuggerWorkspaceBinding; var projectId = Bindings.DefaultScriptMapping.projectIdForTarget(debuggerModel.target()); - this._project = - new Bindings.ContentProviderBasedProject(workspace, projectId, Workspace.projectTypes.Debugger, ''); + this._project = new Bindings.ContentProviderBasedProject(workspace, projectId, Workspace.projectTypes.Debugger, ''); /** @type {!Map.<string, !Workspace.UISourceCode>} */ this._uiSourceCodeForScriptId = new Map(); /** @type {!Map.<!Workspace.UISourceCode, string>} */ this._scriptIdForUISourceCode = new Map(); - this._eventListeners = [debuggerModel.addEventListener( - SDK.DebuggerModel.Events.GlobalObjectCleared, this._debuggerReset, this)]; + this._eventListeners = + [debuggerModel.addEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared, this._debuggerReset, this)]; } /** @@ -93,9 +92,10 @@ uiLocationToRawLocation(uiSourceCode, lineNumber, columnNumber) { var scriptId = this._scriptIdForUISourceCode.get(uiSourceCode); var script = this._debuggerModel.scriptForId(scriptId); - if (script.isInlineScriptWithSourceURL()) + if (script.isInlineScriptWithSourceURL()) { return this._debuggerModel.createRawLocation( script, lineNumber + script.lineOffset, lineNumber ? columnNumber : columnNumber + script.columnOffset); + } return this._debuggerModel.createRawLocation(script, lineNumber, columnNumber); }
diff --git a/third_party/WebKit/Source/devtools/front_end/bindings/FileSystemWorkspaceBinding.js b/third_party/WebKit/Source/devtools/front_end/bindings/FileSystemWorkspaceBinding.js index 3250515..4935d501 100644 --- a/third_party/WebKit/Source/devtools/front_end/bindings/FileSystemWorkspaceBinding.js +++ b/third_party/WebKit/Source/devtools/front_end/bindings/FileSystemWorkspaceBinding.js
@@ -258,8 +258,7 @@ */ requestFileContent(uiSourceCode, callback) { var filePath = this._filePathForUISourceCode(uiSourceCode); - var isImage = - Bindings.FileSystemWorkspaceBinding._imageExtensions.has(Common.ParsedURL.extractExtension(filePath)); + var isImage = Bindings.FileSystemWorkspaceBinding._imageExtensions.has(Common.ParsedURL.extractExtension(filePath)); this._fileSystem.requestFileContent(filePath, isImage ? base64CallbackWrapper : callback);
diff --git a/third_party/WebKit/Source/devtools/front_end/bindings/FileUtils.js b/third_party/WebKit/Source/devtools/front_end/bindings/FileUtils.js index 6f104c5..9b744ad8 100644 --- a/third_party/WebKit/Source/devtools/front_end/bindings/FileUtils.js +++ b/third_party/WebKit/Source/devtools/front_end/bindings/FileUtils.js
@@ -211,8 +211,7 @@ */ function callbackWrapper(accepted) { if (accepted) - Workspace.fileManager.addEventListener( - Workspace.FileManager.Events.AppendedToURL, this._onAppendDone, this); + Workspace.fileManager.addEventListener(Workspace.FileManager.Events.AppendedToURL, this._onAppendDone, this); callback(accepted); } Workspace.fileManager.save(this._fileName, '', true, callbackWrapper.bind(this)); @@ -235,8 +234,7 @@ this._closed = true; if (this._writeCallbacks.length) return; - Workspace.fileManager.removeEventListener( - Workspace.FileManager.Events.AppendedToURL, this._onAppendDone, this); + Workspace.fileManager.removeEventListener(Workspace.FileManager.Events.AppendedToURL, this._onAppendDone, this); Workspace.fileManager.close(this._fileName); } @@ -251,8 +249,7 @@ callback(this); if (!this._writeCallbacks.length) { if (this._closed) { - Workspace.fileManager.removeEventListener( - Workspace.FileManager.Events.AppendedToURL, this._onAppendDone, this); + Workspace.fileManager.removeEventListener(Workspace.FileManager.Events.AppendedToURL, this._onAppendDone, this); Workspace.fileManager.close(this._fileName); } }
diff --git a/third_party/WebKit/Source/devtools/front_end/bindings/NetworkProject.js b/third_party/WebKit/Source/devtools/front_end/bindings/NetworkProject.js index 728f81ec..cef71b0 100644 --- a/third_party/WebKit/Source/devtools/front_end/bindings/NetworkProject.js +++ b/third_party/WebKit/Source/devtools/front_end/bindings/NetworkProject.js
@@ -79,8 +79,7 @@ if (resourceTreeModel) { this._eventListeners.push( - resourceTreeModel.addEventListener( - SDK.ResourceTreeModel.Events.ResourceAdded, this._resourceAdded, this), + resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.ResourceAdded, this._resourceAdded, this), resourceTreeModel.addEventListener( SDK.ResourceTreeModel.Events.FrameWillNavigate, this._frameWillNavigate, this), resourceTreeModel.addEventListener( @@ -90,8 +89,7 @@ var debuggerModel = SDK.DebuggerModel.fromTarget(target); if (debuggerModel) { this._eventListeners.push( - debuggerModel.addEventListener( - SDK.DebuggerModel.Events.ParsedScriptSource, this._parsedScriptSource, this), + debuggerModel.addEventListener(SDK.DebuggerModel.Events.ParsedScriptSource, this._parsedScriptSource, this), debuggerModel.addEventListener( SDK.DebuggerModel.Events.FailedToParseScriptSource, this._parsedScriptSource, this)); } @@ -152,10 +150,9 @@ * @return {string} */ static uiSourceCodeMimeType(uiSourceCode) { - if (uiSourceCode[Bindings.NetworkProject._scriptSymbol] || - uiSourceCode[Bindings.NetworkProject._styleSheetSymbol]) { + if (uiSourceCode[Bindings.NetworkProject._scriptSymbol] || uiSourceCode[Bindings.NetworkProject._styleSheetSymbol]) return uiSourceCode.contentType().canonicalMimeType(); - } + var resource = uiSourceCode[Bindings.NetworkProject._resourceSymbol]; if (resource) return resource.mimeType; @@ -251,8 +248,7 @@ if (!parsedURL.isValid) return; } - var uiSourceCode = - this._createFile(script, SDK.ResourceTreeFrame.fromScript(script), script.isContentScript()); + var uiSourceCode = this._createFile(script, SDK.ResourceTreeFrame.fromScript(script), script.isContentScript()); uiSourceCode[Bindings.NetworkProject._scriptSymbol] = script; var resource = SDK.ResourceTreeModel.resourceForURL(uiSourceCode.url()); this._addUISourceCodeWithProvider(uiSourceCode, script, this._resourceMetadata(resource)); @@ -267,8 +263,7 @@ return; var originalContentProvider = header.originalContentProvider(); - var uiSourceCode = - this._createFile(originalContentProvider, SDK.ResourceTreeFrame.fromStyleSheet(header), false); + var uiSourceCode = this._createFile(originalContentProvider, SDK.ResourceTreeFrame.fromStyleSheet(header), false); uiSourceCode[Bindings.NetworkProject._styleSheetSymbol] = header; var resource = SDK.ResourceTreeModel.resourceForURL(uiSourceCode.url()); this._addUISourceCodeWithProvider(uiSourceCode, originalContentProvider, this._resourceMetadata(resource)); @@ -300,13 +295,12 @@ var resourceType = resource.resourceType(); // Only load selected resource types from resources. if (resourceType !== Common.resourceTypes.Image && resourceType !== Common.resourceTypes.Font && - resourceType !== Common.resourceTypes.Document && resourceType !== Common.resourceTypes.Manifest) { + resourceType !== Common.resourceTypes.Document && resourceType !== Common.resourceTypes.Manifest) return; - } + // Ignore non-images and non-fonts. - if (resourceType === Common.resourceTypes.Image && resource.mimeType && - !resource.mimeType.startsWith('image')) + if (resourceType === Common.resourceTypes.Image && resource.mimeType && !resource.mimeType.startsWith('image')) return; if (resourceType === Common.resourceTypes.Font && resource.mimeType && !resource.mimeType.includes('font')) return;
diff --git a/third_party/WebKit/Source/devtools/front_end/bindings/PresentationConsoleMessageHelper.js b/third_party/WebKit/Source/devtools/front_end/bindings/PresentationConsoleMessageHelper.js index f53aa60f..85639d1 100644 --- a/third_party/WebKit/Source/devtools/front_end/bindings/PresentationConsoleMessageHelper.js +++ b/third_party/WebKit/Source/devtools/front_end/bindings/PresentationConsoleMessageHelper.js
@@ -44,17 +44,14 @@ /** @type {!Array.<!Bindings.PresentationConsoleMessage>} */ this._presentationConsoleMessages = []; - SDK.multitargetConsoleModel.addEventListener( - SDK.ConsoleModel.Events.ConsoleCleared, this._consoleCleared, this); + SDK.multitargetConsoleModel.addEventListener(SDK.ConsoleModel.Events.ConsoleCleared, this._consoleCleared, this); SDK.multitargetConsoleModel.addEventListener( SDK.ConsoleModel.Events.MessageAdded, this._onConsoleMessageAdded, this); SDK.multitargetConsoleModel.messages().forEach(this._consoleMessageAdded, this); SDK.targetManager.addModelListener( - SDK.DebuggerModel, SDK.DebuggerModel.Events.ParsedScriptSource, this._parsedScriptSource, - this); + SDK.DebuggerModel, SDK.DebuggerModel.Events.ParsedScriptSource, this._parsedScriptSource, this); SDK.targetManager.addModelListener( - SDK.DebuggerModel, SDK.DebuggerModel.Events.FailedToParseScriptSource, - this._parsedScriptSource, this); + SDK.DebuggerModel, SDK.DebuggerModel.Events.FailedToParseScriptSource, this._parsedScriptSource, this); SDK.targetManager.addModelListener( SDK.DebuggerModel, SDK.DebuggerModel.Events.GlobalObjectCleared, this._debuggerReset, this); @@ -94,9 +91,10 @@ if (message.scriptId) return debuggerModel.createRawLocationByScriptId(message.scriptId, message.line, message.column); var callFrame = message.stackTrace && message.stackTrace.callFrames ? message.stackTrace.callFrames[0] : null; - if (callFrame) + if (callFrame) { return debuggerModel.createRawLocationByScriptId( callFrame.scriptId, callFrame.lineNumber, callFrame.columnNumber); + } if (message.url) return debuggerModel.createRawLocationByURL(message.url, message.line, message.column); return null; @@ -177,8 +175,7 @@ this._level = message.level === SDK.ConsoleMessage.MessageLevel.Error ? Workspace.UISourceCode.Message.Level.Error : Workspace.UISourceCode.Message.Level.Warning; - Bindings.debuggerWorkspaceBinding.createLiveLocation( - rawLocation, this._updateLocation.bind(this), locationPool); + Bindings.debuggerWorkspaceBinding.createLiveLocation(rawLocation, this._updateLocation.bind(this), locationPool); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/bindings/ResourceScriptMapping.js b/third_party/WebKit/Source/devtools/front_end/bindings/ResourceScriptMapping.js index 6acf340..8c878fe3 100644 --- a/third_party/WebKit/Source/devtools/front_end/bindings/ResourceScriptMapping.js +++ b/third_party/WebKit/Source/devtools/front_end/bindings/ResourceScriptMapping.js
@@ -91,9 +91,10 @@ var scripts = this._scriptsForUISourceCode(uiSourceCode); console.assert(scripts.length); var script = scripts[scripts.length - 1]; - if (script.isInlineScriptWithSourceURL()) + if (script.isInlineScriptWithSourceURL()) { return this._debuggerModel.createRawLocation( script, lineNumber + script.lineOffset, lineNumber ? columnNumber : columnNumber + script.columnOffset); + } return this._debuggerModel.createRawLocation(script, lineNumber, columnNumber); } @@ -333,8 +334,7 @@ if (!error && !exceptionDetails) return; if (!exceptionDetails) { - Common.console.addMessage( - Common.UIString('LiveEdit failed: %s', error), Common.Console.MessageLevel.Warning); + Common.console.addMessage(Common.UIString('LiveEdit failed: %s', error), Common.Console.MessageLevel.Warning); return; } var messageText = Common.UIString('LiveEdit compile failed: %s', exceptionDetails.text);
diff --git a/third_party/WebKit/Source/devtools/front_end/bindings/StylesSourceMapping.js b/third_party/WebKit/Source/devtools/front_end/bindings/StylesSourceMapping.js index f5469f58..4c44e053 100644 --- a/third_party/WebKit/Source/devtools/front_end/bindings/StylesSourceMapping.js +++ b/third_party/WebKit/Source/devtools/front_end/bindings/StylesSourceMapping.js
@@ -51,14 +51,12 @@ this._workspace.addEventListener(Workspace.Workspace.Events.ProjectRemoved, this._projectRemoved, this), this._workspace.addEventListener( Workspace.Workspace.Events.UISourceCodeAdded, this._uiSourceCodeAddedToWorkspace, this), - this._workspace.addEventListener( - Workspace.Workspace.Events.UISourceCodeRemoved, this._uiSourceCodeRemoved, this), + this._workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeRemoved, this._uiSourceCodeRemoved, this), this._cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetAdded, this._styleSheetAdded, this), this._cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetRemoved, this._styleSheetRemoved, this), this._cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetChanged, this._styleSheetChanged, this), SDK.ResourceTreeModel.fromTarget(cssModel.target()) - .addEventListener( - SDK.ResourceTreeModel.Events.MainFrameNavigated, this._unbindAllUISourceCodes, this) + .addEventListener(SDK.ResourceTreeModel.Events.MainFrameNavigated, this._unbindAllUISourceCodes, this) ]; }
diff --git a/third_party/WebKit/Source/devtools/front_end/common/Color.js b/third_party/WebKit/Source/devtools/front_end/common/Color.js index 2fffeac..ed25f69a 100644 --- a/third_party/WebKit/Source/devtools/front_end/common/Color.js +++ b/third_party/WebKit/Source/devtools/front_end/common/Color.js
@@ -73,8 +73,9 @@ if (hex.length === 3) { format = Common.Color.Format.ShortHEX; hex = hex.charAt(0) + hex.charAt(0) + hex.charAt(1) + hex.charAt(1) + hex.charAt(2) + hex.charAt(2); - } else + } else { format = Common.Color.Format.HEX; + } var r = parseInt(hex.substring(0, 2), 16); var g = parseInt(hex.substring(2, 4), 16); var b = parseInt(hex.substring(4, 6), 16); @@ -150,8 +151,7 @@ * @return {!Common.Color} */ static fromRGBA(rgba) { - return new Common.Color( - [rgba[0] / 255, rgba[1] / 255, rgba[2] / 255, rgba[3]], Common.Color.Format.RGBA); + return new Common.Color([rgba[0] / 255, rgba[1] / 255, rgba[2] / 255, rgba[3]], Common.Color.Format.RGBA); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/common/Console.js b/third_party/WebKit/Source/devtools/front_end/common/Console.js index e8d8ff6..442705d 100644 --- a/third_party/WebKit/Source/devtools/front_end/common/Console.js +++ b/third_party/WebKit/Source/devtools/front_end/common/Console.js
@@ -17,8 +17,7 @@ * @param {boolean=} show */ addMessage(text, level, show) { - var message = new Common.Console.Message( - text, level || Common.Console.MessageLevel.Log, Date.now(), show || false); + var message = new Common.Console.Message(text, level || Common.Console.MessageLevel.Log, Date.now(), show || false); this._messages.push(message); this.dispatchEventToListeners(Common.Console.Events.MessageAdded, message); }
diff --git a/third_party/WebKit/Source/devtools/front_end/common/ResourceType.js b/third_party/WebKit/Source/devtools/front_end/common/ResourceType.js index 2a0f75a..4124bdb 100644 --- a/third_party/WebKit/Source/devtools/front_end/common/ResourceType.js +++ b/third_party/WebKit/Source/devtools/front_end/common/ResourceType.js
@@ -50,9 +50,9 @@ */ static mimeFromURL(url) { var name = Common.ParsedURL.extractName(url); - if (Common.ResourceType._mimeTypeByName.has(name)) { + if (Common.ResourceType._mimeTypeByName.has(name)) return Common.ResourceType._mimeTypeByName.get(name); - } + var ext = Common.ParsedURL.extractExtension(url).toLowerCase(); return Common.ResourceType._mimeTypeByExtension.get(ext); } @@ -186,8 +186,7 @@ EventSource: new Common.ResourceType('eventsource', 'EventSource', Common.resourceCategories.XHR, true), Script: new Common.ResourceType('script', 'Script', Common.resourceCategories.Script, true), Snippet: new Common.ResourceType('snippet', 'Snippet', Common.resourceCategories.Script, true), - Stylesheet: - new Common.ResourceType('stylesheet', 'Stylesheet', Common.resourceCategories.Stylesheet, true), + Stylesheet: new Common.ResourceType('stylesheet', 'Stylesheet', Common.resourceCategories.Stylesheet, true), Image: new Common.ResourceType('image', 'Image', Common.resourceCategories.Image, false), Media: new Common.ResourceType('media', 'Media', Common.resourceCategories.Media, false), Font: new Common.ResourceType('font', 'Font', Common.resourceCategories.Font, false),
diff --git a/third_party/WebKit/Source/devtools/front_end/common/SegmentedRange.js b/third_party/WebKit/Source/devtools/front_end/common/SegmentedRange.js index 2960020..944d68a 100644 --- a/third_party/WebKit/Source/devtools/front_end/common/SegmentedRange.js +++ b/third_party/WebKit/Source/devtools/front_end/common/SegmentedRange.js
@@ -58,9 +58,10 @@ } else if (this._segments[startIndex - 1].end >= newSegment.begin) { // 2a. If merge failed and segments overlap, adjust preceding segment. // If an old segment entirely contains new one, split it in two. - if (newSegment.end < precedingSegment.end) + if (newSegment.end < precedingSegment.end) { this._segments.splice( startIndex, 0, new Common.Segment(newSegment.end, precedingSegment.end, precedingSegment.data)); + } precedingSegment.end = newSegment.begin; } } @@ -73,8 +74,9 @@ if (merged) { endIndex++; newSegment = merged; - } else if (newSegment.intersects(this._segments[endIndex])) + } else if (newSegment.intersects(this._segments[endIndex])) { this._segments[endIndex].begin = newSegment.end; + } } this._segments.splice(startIndex, endIndex - startIndex, newSegment); }
diff --git a/third_party/WebKit/Source/devtools/front_end/common/Settings.js b/third_party/WebKit/Source/devtools/front_end/common/Settings.js index 888ac91..4176ec8 100644 --- a/third_party/WebKit/Source/devtools/front_end/common/Settings.js +++ b/third_party/WebKit/Source/devtools/front_end/common/Settings.js
@@ -91,10 +91,11 @@ * @return {!Common.Setting} */ createSetting(key, defaultValue, isLocal) { - if (!this._registry.get(key)) + if (!this._registry.get(key)) { this._registry.set( key, new Common.Setting( this, key, defaultValue, this._eventSupport, isLocal ? this._localStorage : this._settingsStorage)); + } return /** @type {!Common.Setting} */ (this._registry.get(key)); } @@ -115,11 +116,12 @@ * @return {!Common.RegExpSetting} */ createRegExpSetting(key, defaultValue, regexFlags, isLocal) { - if (!this._registry.get(key)) + if (!this._registry.get(key)) { this._registry.set( key, new Common.RegExpSetting( this, key, defaultValue, this._eventSupport, isLocal ? this._localStorage : this._settingsStorage, regexFlags)); + } return /** @type {!Common.RegExpSetting} */ (this._registry.get(key)); } @@ -635,12 +637,13 @@ if (Array.isArray(oldValue)) { for (var preset of oldValue) { if (typeof preset.title === 'string' && typeof preset.value === 'object' && - typeof preset.value.throughput === 'number' && typeof preset.value.latency === 'number') + typeof preset.value.throughput === 'number' && typeof preset.value.latency === 'number') { newValue.push({ title: preset.title, value: {download: preset.value.throughput, upload: preset.value.throughput, latency: preset.value.latency} }); + } } } setting.set(newValue);
diff --git a/third_party/WebKit/Source/devtools/front_end/common/TextUtils.js b/third_party/WebKit/Source/devtools/front_end/common/TextUtils.js index ac042463..a7c2cf3 100644 --- a/third_party/WebKit/Source/devtools/front_end/common/TextUtils.js +++ b/third_party/WebKit/Source/devtools/front_end/common/TextUtils.js
@@ -101,8 +101,9 @@ if (startWord !== -1) wordCallback(text.substring(startWord, i)); startWord = -1; - } else if (startWord === -1) + } else if (startWord === -1) { startWord = i; + } } if (startWord !== -1) wordCallback(text.substring(startWord));
diff --git a/third_party/WebKit/Source/devtools/front_end/common/UIString.js b/third_party/WebKit/Source/devtools/front_end/common/UIString.js index dce656e..45f73639 100644 --- a/third_party/WebKit/Source/devtools/front_end/common/UIString.js +++ b/third_party/WebKit/Source/devtools/front_end/common/UIString.js
@@ -51,12 +51,13 @@ var localized = Common.localize(string); var capitalized; - if (Common._useLowerCaseMenuTitles) + if (Common._useLowerCaseMenuTitles) { capitalized = localized.replace(/\^(.)/g, '$1'); - else + } else { capitalized = localized.replace(/\^(.)/g, function(str, char) { return char.toUpperCase(); }); + } return String.vsprintf(capitalized, Array.prototype.slice.call(arguments, 1)); };
diff --git a/third_party/WebKit/Source/devtools/front_end/components/CustomPreviewSection.js b/third_party/WebKit/Source/devtools/front_end/components/CustomPreviewSection.js index 3f76412..5a7761f 100644 --- a/third_party/WebKit/Source/devtools/front_end/components/CustomPreviewSection.js +++ b/third_party/WebKit/Source/devtools/front_end/components/CustomPreviewSection.js
@@ -30,6 +30,8 @@ if (customPreview.hasBody) { this._header.classList.add('custom-expandable-section-header'); this._header.addEventListener('click', this._onClick.bind(this), false); + this._expandIcon = UI.Icon.create('smallicon-triangle-right', 'custom-expand-icon'); + this._header.insertBefore(this._expandIcon, this._header.firstChild); } this._sectionElement.appendChild(this._header); @@ -51,10 +53,7 @@ return createTextNode(jsonML + ''); var array = /** @type {!Array.<*>} */ (jsonML); - if (array[0] === 'object') - return this._layoutObjectTag(array); - else - return this._renderElement(array); + return array[0] === 'object' ? this._layoutObjectTag(array) : this._renderElement(array); } /** @@ -91,8 +90,8 @@ _layoutObjectTag(objectTag) { objectTag.shift(); var attributes = objectTag.shift(); - var remoteObject = - this._object.target().runtimeModel.createRemoteObject(/** @type {!Protocol.Runtime.RemoteObject} */ (attributes)); + var remoteObject = this._object.target().runtimeModel.createRemoteObject( + /** @type {!Protocol.Runtime.RemoteObject} */ (attributes)); if (remoteObject.customPreview()) return (new Components.CustomPreviewSection(remoteObject)).element(); @@ -125,6 +124,10 @@ this._expanded = !this._expanded; this._header.classList.toggle('expanded', this._expanded); this._cachedContent.classList.toggle('hidden', !this._expanded); + if (this._expanded) + this._expandIcon.setIconType('smallicon-triangle-bottom'); + else + this._expandIcon.setIconType('smallicon-triangle-right'); } _loadBody() { @@ -223,8 +226,7 @@ _contextMenuEventFired(event) { var contextMenu = new UI.ContextMenu(event); if (this._customPreviewSection) - contextMenu.appendItem( - Common.UIString.capitalize('Show as Javascript ^object'), this._disassemble.bind(this)); + contextMenu.appendItem(Common.UIString.capitalize('Show as Javascript ^object'), this._disassemble.bind(this)); contextMenu.appendApplicableItems(this._object); contextMenu.show(); }
diff --git a/third_party/WebKit/Source/devtools/front_end/components/DOMBreakpointsSidebarPane.js b/third_party/WebKit/Source/devtools/front_end/components/DOMBreakpointsSidebarPane.js index 25a4ea3..8aa4999 100644 --- a/third_party/WebKit/Source/devtools/front_end/components/DOMBreakpointsSidebarPane.js +++ b/third_party/WebKit/Source/devtools/front_end/components/DOMBreakpointsSidebarPane.js
@@ -40,8 +40,7 @@ /** @type {!Map<string, !Element>} */ this._breakpointElements = new Map(); - SDK.targetManager.addModelListener( - SDK.DOMModel, SDK.DOMModel.Events.NodeRemoved, this._nodeRemoved, this); + SDK.targetManager.addModelListener(SDK.DOMModel, SDK.DOMModel.Events.NodeRemoved, this._nodeRemoved, this); this._update(); } @@ -102,8 +101,7 @@ this._saveBreakpoints(); } - var breakpointsMenu = - createSubMenu ? contextMenu.appendSubMenuItem(Common.UIString('Break on...')) : contextMenu; + var breakpointsMenu = createSubMenu ? contextMenu.appendSubMenuItem(Common.UIString('Break on...')) : contextMenu; for (var key in Components.DOMBreakpointsSidebarPane.BreakpointTypes) { var type = Components.DOMBreakpointsSidebarPane.BreakpointTypes[key]; var label = Components.DOMBreakpointsSidebarPane.BreakpointTypeNouns[type]; @@ -316,13 +314,14 @@ if (breakpoint.url !== this._inspectedURL) breakpoints.push(breakpoint); } - for (var element of this._breakpointElements.values()) + for (var element of this._breakpointElements.values()) { breakpoints.push({ url: this._inspectedURL, path: element._node.path(), type: element._type, enabled: element._checkboxElement.checked }); + } this._domBreakpointsSetting.set(breakpoints); }
diff --git a/third_party/WebKit/Source/devtools/front_end/components/DOMPresentationUtils.js b/third_party/WebKit/Source/devtools/front_end/components/DOMPresentationUtils.js index a6a0fe6b..78b63896 100644 --- a/third_party/WebKit/Source/devtools/front_end/components/DOMPresentationUtils.js +++ b/third_party/WebKit/Source/devtools/front_end/components/DOMPresentationUtils.js
@@ -196,19 +196,21 @@ var offsetHeight = precomputedFeatures ? precomputedFeatures.offsetHeight : naturalHeight; var description; if (showDimensions) { - if (offsetHeight === naturalHeight && offsetWidth === naturalWidth) + if (offsetHeight === naturalHeight && offsetWidth === naturalWidth) { description = Common.UIString('%d \xd7 %d pixels', offsetWidth, offsetHeight); - else + } else { description = Common.UIString( '%d \xd7 %d pixels (Natural: %d \xd7 %d pixels)', offsetWidth, offsetHeight, naturalWidth, naturalHeight); + } } container.createChild('tr').createChild('td', 'image-container').appendChild(imageElement); if (description) container.createChild('tr').createChild('td').createChild('span', 'description').textContent = description; - if (imageURL !== originalImageURL) + if (imageURL !== originalImageURL) { container.createChild('tr').createChild('td').createChild('span', 'description').textContent = String.sprintf('currentSrc: %s', imageURL.trimMiddle(100)); + } userCallback(container); } }; @@ -289,9 +291,10 @@ return lowerCaseName + '[type="' + node.getAttribute('type') + '"]'; if (node.getAttribute('id')) return lowerCaseName + '#' + node.getAttribute('id'); - if (node.getAttribute('class')) + if (node.getAttribute('class')) { return (lowerCaseName === 'div' ? '' : lowerCaseName) + '.' + node.getAttribute('class').trim().replace(/\s+/g, '.'); + } return lowerCaseName; };
diff --git a/third_party/WebKit/Source/devtools/front_end/components/DataSaverInfobar.js b/third_party/WebKit/Source/devtools/front_end/components/DataSaverInfobar.js index 9b578c1..e9e90f3 100644 --- a/third_party/WebKit/Source/devtools/front_end/components/DataSaverInfobar.js +++ b/third_party/WebKit/Source/devtools/front_end/components/DataSaverInfobar.js
@@ -7,8 +7,7 @@ Components.DataSaverInfobar = class extends UI.Infobar { constructor() { super( - UI.Infobar.Type.Warning, - Common.UIString('Consider disabling Chrome Data Saver while debugging.'), + UI.Infobar.Type.Warning, Common.UIString('Consider disabling Chrome Data Saver while debugging.'), Common.settings.moduleSetting('disableDataSaverInfobar')); var message = this.createDetailsRowMessage(); message.createTextChild('More information about ');
diff --git a/third_party/WebKit/Source/devtools/front_end/components/EventListenersUtils.js b/third_party/WebKit/Source/devtools/front_end/components/EventListenersUtils.js index e243ad0..5d13d66 100644 --- a/third_party/WebKit/Source/devtools/front_end/components/EventListenersUtils.js +++ b/third_party/WebKit/Source/devtools/front_end/components/EventListenersUtils.js
@@ -58,9 +58,7 @@ * @return {!Promise<!Array<!SDK.EventListener>>} */ function convertToEventListeners(pageEventListenersObject) { - return SDK.RemoteArray.objectAsArray(pageEventListenersObject) - .map(toEventListener) - .then(filterOutEmptyObjects); + return SDK.RemoteArray.objectAsArray(pageEventListenersObject).map(toEventListener).then(filterOutEmptyObjects); /** * @param {!SDK.RemoteObject} listenerObject @@ -94,7 +92,7 @@ * @return {!{type:string, useCapture:boolean, passive:boolean, once:boolean}} */ function truncatePageEventListener() { - return {type: this.type, useCapture: this.useCapture, passive: this.passive, once: this.once}; + return {type: this.type, useCapture: this.useCapture, passive: this.passive, once: this.once}; } /** @@ -170,9 +168,7 @@ removeFunctionObject = functionObject; } - return Promise.all(promises) - .then(createEventListener) - .catchException(/** @type {?SDK.EventListener} */ (null)); + return Promise.all(promises).then(createEventListener).catchException(/** @type {?SDK.EventListener} */ (null)); /** * @return {!SDK.EventListener} @@ -308,9 +304,10 @@ eventListeners = eventListeners.concat(fetcherResult.eventListeners.map(checkEventListener).filter(nonEmptyObject)); } - if (fetcherResult.internalHandlers && isArrayLike(fetcherResult.internalHandlers)) + if (fetcherResult.internalHandlers && isArrayLike(fetcherResult.internalHandlers)) { internalHandlers = internalHandlers.concat(fetcherResult.internalHandlers.map(checkInternalHandler).filter(nonEmptyObject)); + } } catch (e) { errorLines.push('fetcher call produced error: ' + toString(e)); }
diff --git a/third_party/WebKit/Source/devtools/front_end/components/EventListenersView.js b/third_party/WebKit/Source/devtools/front_end/components/EventListenersView.js index 5cb1f80..8f57990 100644 --- a/third_party/WebKit/Source/devtools/front_end/components/EventListenersView.js +++ b/third_party/WebKit/Source/devtools/front_end/components/EventListenersView.js
@@ -331,9 +331,10 @@ return; } var allHidden = true; - for (var i = 0; i < parent.childCount(); ++i) + for (var i = 0; i < parent.childCount(); ++i) { if (!parent.childAt(i).hidden) allHidden = false; + } parent.hidden = allHidden; }
diff --git a/third_party/WebKit/Source/devtools/front_end/components/ExecutionContextSelector.js b/third_party/WebKit/Source/devtools/front_end/components/ExecutionContextSelector.js index 3fddc4d..e791e65 100644 --- a/third_party/WebKit/Source/devtools/front_end/components/ExecutionContextSelector.js +++ b/third_party/WebKit/Source/devtools/front_end/components/ExecutionContextSelector.js
@@ -16,14 +16,12 @@ context.addFlavorChangeListener(SDK.Target, this._targetChanged, this); targetManager.addModelListener( - SDK.RuntimeModel, SDK.RuntimeModel.Events.ExecutionContextCreated, - this._onExecutionContextCreated, this); + SDK.RuntimeModel, SDK.RuntimeModel.Events.ExecutionContextCreated, this._onExecutionContextCreated, this); targetManager.addModelListener( - SDK.RuntimeModel, SDK.RuntimeModel.Events.ExecutionContextDestroyed, - this._onExecutionContextDestroyed, this); + SDK.RuntimeModel, SDK.RuntimeModel.Events.ExecutionContextDestroyed, this._onExecutionContextDestroyed, this); targetManager.addModelListener( - SDK.RuntimeModel, SDK.RuntimeModel.Events.ExecutionContextOrderChanged, - this._onExecutionContextOrderChanged, this); + SDK.RuntimeModel, SDK.RuntimeModel.Events.ExecutionContextOrderChanged, this._onExecutionContextOrderChanged, + this); this._targetManager = targetManager; this._context = context; }
diff --git a/third_party/WebKit/Source/devtools/front_end/components/HandlerRegistry.js b/third_party/WebKit/Source/devtools/front_end/components/HandlerRegistry.js index ea4aa34..7c8b7e2 100644 --- a/third_party/WebKit/Source/devtools/front_end/components/HandlerRegistry.js +++ b/third_party/WebKit/Source/devtools/front_end/components/HandlerRegistry.js
@@ -100,8 +100,7 @@ if (!contentProvider.contentURL()) return; - contextMenu.appendItem( - UI.openLinkExternallyLabel(), this._openInNewTab.bind(this, contentProvider.contentURL())); + contextMenu.appendItem(UI.openLinkExternallyLabel(), this._openInNewTab.bind(this, contentProvider.contentURL())); // Skip 0th handler, as it's 'Use default panel' one. for (var i = 1; i < this.handlerNames.length; ++i) { var handler = this.handlerNames[i]; @@ -196,11 +195,10 @@ else InspectorFrontendHost.openInNewTab(resourceURL); } - if (!targetNode.enclosingNodeOrSelfWithClassList(['resources', 'panel']) && - Bindings.resourceForURL(resourceURL)) + if (!targetNode.enclosingNodeOrSelfWithClassList(['resources', 'panel']) && Bindings.resourceForURL(resourceURL)) { contextMenu.appendItem( - Common.UIString.capitalize('Open ^link in Application ^panel'), - openInResourcesPanel.bind(null, resourceURL)); + Common.UIString.capitalize('Open ^link in Application ^panel'), openInResourcesPanel.bind(null, resourceURL)); + } contextMenu.appendItem( UI.copyLinkAddressLabel(), InspectorFrontendHost.copyText.bind(InspectorFrontendHost, resourceURL)); @@ -221,8 +219,7 @@ this.element = createElementWithClass('select', 'chrome-select'); this.element.addEventListener('change', this._onChange.bind(this), false); this._update(); - this._handlerRegistry.addEventListener( - Components.HandlerRegistry.Events.HandlersUpdated, this._update.bind(this)); + this._handlerRegistry.addEventListener(Components.HandlerRegistry.Events.HandlersUpdated, this._update.bind(this)); } _update() { @@ -292,8 +289,7 @@ return null; var handlerSelector = new Components.HandlerSelector(Components.openAnchorLocationRegistry); - return UI.SettingsUI.createCustomSetting( - Common.UIString('Link handling:'), handlerSelector.element); + return UI.SettingsUI.createCustomSetting(Common.UIString('Link handling:'), handlerSelector.element); } };
diff --git a/third_party/WebKit/Source/devtools/front_end/components/JavaScriptAutocomplete.js b/third_party/WebKit/Source/devtools/front_end/components/JavaScriptAutocomplete.js index 5bea208..082dcf0 100644 --- a/third_party/WebKit/Source/devtools/front_end/components/JavaScriptAutocomplete.js +++ b/third_party/WebKit/Source/devtools/front_end/components/JavaScriptAutocomplete.js
@@ -10,12 +10,14 @@ * @param {boolean} force * @param {function(!Array.<string>, number=)} completionsReadyCallback */ -Components.JavaScriptAutocomplete.completionsForTextPromptInCurrentContext = function(proxyElement, wordRange, force, completionsReadyCallback) { +Components.JavaScriptAutocomplete.completionsForTextPromptInCurrentContext = function( + proxyElement, wordRange, force, completionsReadyCallback) { var expressionRange = wordRange.cloneRange(); expressionRange.collapse(true); expressionRange.setStartBefore(proxyElement); - Components.JavaScriptAutocomplete.completionsForTextInCurrentContext(expressionRange.toString(), wordRange.toString(), force) - .then(completionsReadyCallback); + Components.JavaScriptAutocomplete + .completionsForTextInCurrentContext(expressionRange.toString(), wordRange.toString(), force) + .then(completionsReadyCallback); }; /** @@ -54,7 +56,7 @@ }; - /** +/** * @param {string} expressionString * @param {string} query * @param {boolean=} force @@ -106,9 +108,9 @@ */ function extractTarget(object) { if (!object) - return Promise.resolve(/** @type {?SDK.RemoteObject} */(null)); + return Promise.resolve(/** @type {?SDK.RemoteObject} */ (null)); if (object.type !== 'object' || object.subtype !== 'proxy') - return Promise.resolve(/** @type {?SDK.RemoteObject} */(object)); + return Promise.resolve(/** @type {?SDK.RemoteObject} */ (object)); return object.getOwnPropertiesPromise().then(extractTargetFromProperties).then(extractTarget); } @@ -139,7 +141,7 @@ else object = this; - var resultSet = { __proto__: null }; + var resultSet = {__proto__: null}; try { for (var o = object; o; o = Object.getPrototypeOf(o)) { if ((type === 'array' || type === 'typedarray') && o === object && ArrayBuffer.isView(o) && o.length > 9999) @@ -162,16 +164,16 @@ * @param {?SDK.RemoteObject} object */ function completionsForObject(object) { - if (!object) + if (!object) { receivedPropertyNames(null); - else if (object.type === 'object' || object.type === 'function') + } else if (object.type === 'object' || object.type === 'function') { object.callFunctionJSON( - getCompletions, [SDK.RemoteObject.toCallArgument(object.subtype)], - receivedPropertyNames); - else if (object.type === 'string' || object.type === 'number' || object.type === 'boolean') + getCompletions, [SDK.RemoteObject.toCallArgument(object.subtype)], receivedPropertyNames); + } else if (object.type === 'string' || object.type === 'number' || object.type === 'boolean') { executionContext.evaluate( - '(' + getCompletions + ')("' + result.type + '")', 'completion', false, true, true, false, false, - receivedPropertyNamesFromEval); + '(' + getCompletions + ')("' + result.type + '")', 'completion', false, true, true, false, false, + receivedPropertyNamesFromEval); + } } extractTarget(result).then(completionsForObject); @@ -184,7 +186,7 @@ function receivedPropertyNamesFromEval(result, exceptionDetails) { executionContext.target().runtimeAgent().releaseObjectGroup('completion'); if (result && !exceptionDetails) - receivedPropertyNames(/** @type {!Object} */(result.value)); + receivedPropertyNames(/** @type {!Object} */ (result.value)); else fufill([]); } @@ -226,11 +228,11 @@ propertyNames[commandLineAPI[i]] = true; } fufill(Components.JavaScriptAutocomplete._completionsForQuery( - dotNotation, bracketNotation, expressionString, query, Object.keys(propertyNames))); + dotNotation, bracketNotation, expressionString, query, Object.keys(propertyNames))); } }; - /** +/** * @param {boolean} dotNotation * @param {boolean} bracketNotation * @param {string} expressionString @@ -238,7 +240,8 @@ * @param {!Array.<string>} properties * @return {!Array<string>} */ -Components.JavaScriptAutocomplete._completionsForQuery = function(dotNotation, bracketNotation, expressionString, query, properties) { +Components.JavaScriptAutocomplete._completionsForQuery = function( + dotNotation, bracketNotation, expressionString, query, properties) { if (bracketNotation) { if (query.length && query[0] === '\'') var quoteUsed = '\''; @@ -248,9 +251,9 @@ if (!expressionString) { const keywords = [ - 'break', 'case', 'catch', 'continue', 'default', 'delete', 'do', 'else', 'finally', - 'for', 'function', 'if', 'in', 'instanceof', 'new', 'return', 'switch', 'this', - 'throw', 'try', 'typeof', 'var', 'void', 'while', 'with' + 'break', 'case', 'catch', 'continue', 'default', 'delete', 'do', 'else', 'finally', + 'for', 'function', 'if', 'in', 'instanceof', 'new', 'return', 'switch', 'this', + 'throw', 'try', 'typeof', 'var', 'void', 'while', 'with' ]; properties = properties.concat(keywords); } @@ -290,5 +293,7 @@ else caseInsensitiveAnywhere.push(prop); } - return caseSensitivePrefix.concat(caseInsensitivePrefix).concat(caseSensitiveAnywhere).concat(caseInsensitiveAnywhere); + return caseSensitivePrefix.concat(caseInsensitivePrefix) + .concat(caseSensitiveAnywhere) + .concat(caseInsensitiveAnywhere); };
diff --git a/third_party/WebKit/Source/devtools/front_end/components/Linkifier.js b/third_party/WebKit/Source/devtools/front_end/components/Linkifier.js index be81f73..c62998aa2 100644 --- a/third_party/WebKit/Source/devtools/front_end/components/Linkifier.js +++ b/third_party/WebKit/Source/devtools/front_end/components/Linkifier.js
@@ -62,7 +62,7 @@ * @param {!Common.Event} event */ function onLinkIconChanged(event) { - var uiSourceCode = /** @type {!Workspace.UISourceCode} */(event.data); + var uiSourceCode = /** @type {!Workspace.UISourceCode} */ (event.data); var links = uiSourceCode[Components.Linkifier._sourceCodeAnchors] || []; for (var link of links) Components.Linkifier._updateLinkDecorations(link); @@ -184,8 +184,8 @@ return ''; var location = /** @type {!SDK.DebuggerModel.Location} */ ( debuggerModel.createRawLocation(script, lineNumber, columnNumber || 0)); - var uiLocation = /** @type {!Workspace.UILocation} */ ( - Bindings.debuggerWorkspaceBinding.rawLocationToUILocation(location)); + var uiLocation = + /** @type {!Workspace.UILocation} */ (Bindings.debuggerWorkspaceBinding.rawLocationToUILocation(location)); return uiLocation.linkText(); } @@ -551,8 +551,7 @@ * @return {!Node} */ function linkifier(title, url, lineNumber, columnNumber) { - var isExternal = - !Bindings.resourceForURL(url) && !Bindings.networkMapping.uiSourceCodeForURLForAnyTarget(url); + var isExternal = !Bindings.resourceForURL(url) && !Bindings.networkMapping.uiSourceCodeForURLForAnyTarget(url); var urlNode = UI.linkifyURLAsNode(url, title, undefined, isExternal); if (typeof lineNumber !== 'undefined') { urlNode.lineNumber = lineNumber;
diff --git a/third_party/WebKit/Source/devtools/front_end/components/NetworkConditionsSelector.js b/third_party/WebKit/Source/devtools/front_end/components/NetworkConditionsSelector.js index f096a83f..fc19d6e0 100644 --- a/third_party/WebKit/Source/devtools/front_end/components/NetworkConditionsSelector.js +++ b/third_party/WebKit/Source/devtools/front_end/components/NetworkConditionsSelector.js
@@ -132,12 +132,13 @@ function appendItems(contextMenu) { for (var index = 0; index < options.length; ++index) { var conditions = options[index]; - if (!conditions) + if (!conditions) { contextMenu.appendSeparator(); - else + } else { contextMenu.appendCheckboxItem( Components.NetworkConditionsSelector._conditionsTitle(conditions, true).text, selector.optionSelected.bind(selector, conditions), selectedIndex === index); + } } contextMenu.appendItem(Common.UIString('Edit\u2026'), selector.revealAndUpdate.bind(selector)); } @@ -170,12 +171,10 @@ */ static createOfflineToolbarCheckbox() { var checkbox = new UI.ToolbarCheckbox( - Common.UIString('Offline'), Common.UIString('Force disconnected from network'), undefined, - forceOffline); + Common.UIString('Offline'), Common.UIString('Force disconnected from network'), undefined, forceOffline); SDK.multitargetNetworkManager.addEventListener( SDK.MultitargetNetworkManager.Events.ConditionsChanged, networkConditionsChanged); - checkbox.setChecked( - SDK.multitargetNetworkManager.networkConditions() === SDK.NetworkManager.OfflineConditions); + checkbox.setChecked(SDK.multitargetNetworkManager.networkConditions() === SDK.NetworkManager.OfflineConditions); var lastNetworkConditions; @@ -199,14 +198,8 @@ _populateOptions() { var customGroup = {title: Common.UIString('Custom'), items: this._customSetting.get()}; - var presetsGroup = { - title: Common.UIString('Presets'), - items: Components.NetworkConditionsSelector._presets - }; - var disabledGroup = { - title: Common.UIString('Disabled'), - items: [SDK.NetworkManager.NoThrottlingConditions] - }; + var presetsGroup = {title: Common.UIString('Presets'), items: Components.NetworkConditionsSelector._presets}; + var disabledGroup = {title: Common.UIString('Disabled'), items: [SDK.NetworkManager.NoThrottlingConditions]}; this._options = this._populateCallback([customGroup, presetsGroup, disabledGroup]); if (!this._conditionsChanged()) { for (var i = this._options.length - 1; i >= 0; i--) { @@ -253,8 +246,7 @@ /** @type {!Array.<!SDK.NetworkManager.Conditions>} */ Components.NetworkConditionsSelector._presets = [ - SDK.NetworkManager.OfflineConditions, - {title: 'GPRS', download: 50 * 1024 / 8, upload: 20 * 1024 / 8, latency: 500}, + SDK.NetworkManager.OfflineConditions, {title: 'GPRS', download: 50 * 1024 / 8, upload: 20 * 1024 / 8, latency: 500}, {title: 'Regular 2G', download: 250 * 1024 / 8, upload: 50 * 1024 / 8, latency: 300}, {title: 'Good 2G', download: 450 * 1024 / 8, upload: 150 * 1024 / 8, latency: 150}, {title: 'Regular 3G', download: 750 * 1024 / 8, upload: 250 * 1024 / 8, latency: 100},
diff --git a/third_party/WebKit/Source/devtools/front_end/components/ObjectPopoverHelper.js b/third_party/WebKit/Source/devtools/front_end/components/ObjectPopoverHelper.js index d42700e..abbcb82 100644 --- a/third_party/WebKit/Source/devtools/front_end/components/ObjectPopoverHelper.js +++ b/third_party/WebKit/Source/devtools/front_end/components/ObjectPopoverHelper.js
@@ -97,8 +97,7 @@ var linkContainer = title.createChild('div', 'function-title-link-container'); if (rawLocation && Runtime.experiments.isEnabled('continueToFirstInvocation')) { var sectionToolbar = new UI.Toolbar('function-location-step-into', linkContainer); - var stepInto = new UI.ToolbarButton( - Common.UIString('Continue to first invocation'), 'largeicon-step-in'); + var stepInto = new UI.ToolbarButton(Common.UIString('Continue to first invocation'), 'largeicon-step-in'); stepInto.addEventListener('click', () => rawLocation.continueToLocation()); sectionToolbar.appendToolbarItem(stepInto); }
diff --git a/third_party/WebKit/Source/devtools/front_end/components/ObjectPropertiesSection.js b/third_party/WebKit/Source/devtools/front_end/components/ObjectPropertiesSection.js index 4bf242ac..73cba98 100644 --- a/third_party/WebKit/Source/devtools/front_end/components/ObjectPropertiesSection.js +++ b/third_party/WebKit/Source/devtools/front_end/components/ObjectPropertiesSection.js
@@ -280,8 +280,7 @@ var anchor = createElement('span'); element.classList.add('linkified'); element.appendChild(anchor); - element.addEventListener( - 'click', Common.Revealer.reveal.bind(Common.Revealer, response.location, undefined)); + element.addEventListener('click', Common.Revealer.reveal.bind(Common.Revealer, response.location, undefined)); element = anchor; } @@ -923,11 +922,12 @@ } _updateExpandable() { - if (this.property.value) + if (this.property.value) { this.setExpandable( !this.property.value.customPreview() && this.property.value.hasChildren && !this.property.wasThrown); - else + } else { this.setExpandable(false); + } } }; @@ -1076,13 +1076,13 @@ if (fromIndex === toIndex) Components.ArrayGroupingTreeElement._populateAsFragment(treeNode, object, fromIndex, toIndex, linkifier); else - treeNode.appendChild( - new Components.ArrayGroupingTreeElement(object, fromIndex, toIndex, count, linkifier)); + treeNode.appendChild(new Components.ArrayGroupingTreeElement(object, fromIndex, toIndex, count, linkifier)); } } - if (topLevel) + if (topLevel) { Components.ArrayGroupingTreeElement._populateNonIndexProperties( treeNode, object, result.skipGetOwnPropertyNames, linkifier); + } } } @@ -1097,10 +1097,7 @@ static _populateAsFragment(treeNode, object, fromIndex, toIndex, linkifier) { object.callFunction( buildArrayFragment, - [ - {value: fromIndex}, {value: toIndex}, - {value: Components.ArrayGroupingTreeElement._sparseIterationThreshold} - ], + [{value: fromIndex}, {value: toIndex}, {value: Components.ArrayGroupingTreeElement._sparseIterationThreshold}], processArrayFragment.bind(this)); /**
diff --git a/third_party/WebKit/Source/devtools/front_end/components/ShortcutsScreen.js b/third_party/WebKit/Source/devtools/front_end/components/ShortcutsScreen.js index b7ec5fe..987917e 100644 --- a/third_party/WebKit/Source/devtools/front_end/components/ShortcutsScreen.js +++ b/third_party/WebKit/Source/devtools/front_end/components/ShortcutsScreen.js
@@ -54,8 +54,7 @@ elementsSection.addAlternateKeys( Components.ShortcutsScreen.ElementsPanelShortcuts.HideElement, Common.UIString('Hide element')); elementsSection.addAlternateKeys( - Components.ShortcutsScreen.ElementsPanelShortcuts.ToggleEditAsHTML, - Common.UIString('Toggle edit as HTML')); + Components.ShortcutsScreen.ElementsPanelShortcuts.ToggleEditAsHTML, Common.UIString('Toggle edit as HTML')); var stylesPaneSection = Components.shortcutsScreen.section(Common.UIString('Styles Pane')); @@ -69,41 +68,31 @@ Components.ShortcutsScreen.ElementsPanelShortcuts.DecrementValue, Common.UIString('Decrement value')); stylesPaneSection.addAlternateKeys( - Components.ShortcutsScreen.ElementsPanelShortcuts.IncrementBy10, - Common.UIString('Increment by %f', 10)); + Components.ShortcutsScreen.ElementsPanelShortcuts.IncrementBy10, Common.UIString('Increment by %f', 10)); stylesPaneSection.addAlternateKeys( - Components.ShortcutsScreen.ElementsPanelShortcuts.DecrementBy10, - Common.UIString('Decrement by %f', 10)); + Components.ShortcutsScreen.ElementsPanelShortcuts.DecrementBy10, Common.UIString('Decrement by %f', 10)); stylesPaneSection.addAlternateKeys( - Components.ShortcutsScreen.ElementsPanelShortcuts.IncrementBy100, - Common.UIString('Increment by %f', 100)); + Components.ShortcutsScreen.ElementsPanelShortcuts.IncrementBy100, Common.UIString('Increment by %f', 100)); stylesPaneSection.addAlternateKeys( - Components.ShortcutsScreen.ElementsPanelShortcuts.DecrementBy100, - Common.UIString('Decrement by %f', 100)); + Components.ShortcutsScreen.ElementsPanelShortcuts.DecrementBy100, Common.UIString('Decrement by %f', 100)); stylesPaneSection.addAlternateKeys( - Components.ShortcutsScreen.ElementsPanelShortcuts.IncrementBy01, - Common.UIString('Increment by %f', 0.1)); + Components.ShortcutsScreen.ElementsPanelShortcuts.IncrementBy01, Common.UIString('Increment by %f', 0.1)); stylesPaneSection.addAlternateKeys( - Components.ShortcutsScreen.ElementsPanelShortcuts.DecrementBy01, - Common.UIString('Decrement by %f', 0.1)); + Components.ShortcutsScreen.ElementsPanelShortcuts.DecrementBy01, Common.UIString('Decrement by %f', 0.1)); // Debugger var section = Components.shortcutsScreen.section(Common.UIString('Debugger')); section.addAlternateKeys( - UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.toggle-pause'), - Common.UIString('Pause/ Continue')); + UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.toggle-pause'), Common.UIString('Pause/ Continue')); section.addAlternateKeys( - UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.step-over'), - Common.UIString('Step over')); + UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.step-over'), Common.UIString('Step over')); section.addAlternateKeys( - UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.step-into'), - Common.UIString('Step into')); + UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.step-into'), Common.UIString('Step into')); section.addAlternateKeys( - UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.step-out'), - Common.UIString('Step out')); + UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.step-out'), Common.UIString('Step out')); var nextAndPrevFrameKeys = Components.ShortcutsScreen.SourcesPanelShortcuts.NextCallFrame.concat( Components.ShortcutsScreen.SourcesPanelShortcuts.PrevCallFrame); @@ -116,8 +105,7 @@ Components.ShortcutsScreen.SourcesPanelShortcuts.AddSelectionToWatch, Common.UIString('Add selection to watch')); section.addAlternateKeys( - Components.ShortcutsScreen.SourcesPanelShortcuts.ToggleBreakpoint, - Common.UIString('Toggle breakpoint')); + Components.ShortcutsScreen.SourcesPanelShortcuts.ToggleBreakpoint, Common.UIString('Toggle breakpoint')); section.addAlternateKeys( UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.toggle-breakpoints-active'), Common.UIString('Toggle all breakpoints')); @@ -127,10 +115,8 @@ section.addAlternateKeys( Components.ShortcutsScreen.SourcesPanelShortcuts.GoToMember, Common.UIString('Go to member')); section.addAlternateKeys( - Components.ShortcutsScreen.SourcesPanelShortcuts.ToggleAutocompletion, - Common.UIString('Autocompletion')); - section.addAlternateKeys( - Components.ShortcutsScreen.SourcesPanelShortcuts.GoToLine, Common.UIString('Go to line')); + Components.ShortcutsScreen.SourcesPanelShortcuts.ToggleAutocompletion, Common.UIString('Autocompletion')); + section.addAlternateKeys(Components.ShortcutsScreen.SourcesPanelShortcuts.GoToLine, Common.UIString('Go to line')); section.addAlternateKeys( Components.ShortcutsScreen.SourcesPanelShortcuts.JumpToPreviousLocation, Common.UIString('Jump to previous editing location')); @@ -154,8 +140,7 @@ section.addAlternateKeys( Components.ShortcutsScreen.SourcesPanelShortcuts.SelectNextOccurrence, Common.UIString('Select next occurrence')); - section.addAlternateKeys( - Components.ShortcutsScreen.SourcesPanelShortcuts.SoftUndo, Common.UIString('Soft undo')); + section.addAlternateKeys(Components.ShortcutsScreen.SourcesPanelShortcuts.SoftUndo, Common.UIString('Soft undo')); section.addAlternateKeys( Components.ShortcutsScreen.SourcesPanelShortcuts.GotoMatchingBracket, Common.UIString('Go to matching bracket')); @@ -171,8 +156,7 @@ UI.shortcutRegistry.shortcutDescriptorsForAction('timeline.toggle-recording'), Common.UIString('Start/stop recording')); section.addAlternateKeys( - UI.shortcutRegistry.shortcutDescriptorsForAction('main.reload'), - Common.UIString('Record page reload')); + UI.shortcutRegistry.shortcutDescriptorsForAction('main.reload'), Common.UIString('Record page reload')); section.addAlternateKeys( UI.shortcutRegistry.shortcutDescriptorsForAction('timeline.save-to-file'), Common.UIString('Save timeline data')); @@ -202,10 +186,8 @@ section.addAlternateKeys( Components.ShortcutsScreen.LayersPanelShortcuts.TogglePanRotate, Common.UIString('Temporarily toggle pan/rotate mode while held')); - section.addAlternateKeys( - Components.ShortcutsScreen.LayersPanelShortcuts.ZoomIn, Common.UIString('Zoom in')); - section.addAlternateKeys( - Components.ShortcutsScreen.LayersPanelShortcuts.ZoomOut, Common.UIString('Zoom out')); + section.addAlternateKeys(Components.ShortcutsScreen.LayersPanelShortcuts.ZoomIn, Common.UIString('Zoom in')); + section.addAlternateKeys(Components.ShortcutsScreen.LayersPanelShortcuts.ZoomOut, Common.UIString('Zoom out')); section.addRelatedKeys( Components.ShortcutsScreen.LayersPanelShortcuts.Up.concat( Components.ShortcutsScreen.LayersPanelShortcuts.Down), @@ -252,8 +234,7 @@ var note = scrollPane.createChild('p', 'help-footnote'); note.appendChild(UI.linkifyDocumentationURLAsNode( - 'iterate/inspect-styles/shortcuts', - Common.UIString('Full list of DevTools keyboard shortcuts and gestures'))); + 'iterate/inspect-styles/shortcuts', Common.UIString('Full list of DevTools keyboard shortcuts and gestures'))); return widget; } @@ -397,8 +378,8 @@ NextProperty: [UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Tab)], - PreviousProperty: [UI.KeyboardShortcut.makeDescriptor( - UI.KeyboardShortcut.Keys.Tab, UI.KeyboardShortcut.Modifiers.Shift)], + PreviousProperty: + [UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Tab, UI.KeyboardShortcut.Modifiers.Shift)], IncrementValue: [UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Up)], @@ -406,52 +387,46 @@ IncrementBy10: [ UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.PageUp), - UI.KeyboardShortcut.makeDescriptor( - UI.KeyboardShortcut.Keys.Up, UI.KeyboardShortcut.Modifiers.Shift) + UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Up, UI.KeyboardShortcut.Modifiers.Shift) ], DecrementBy10: [ UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.PageDown), - UI.KeyboardShortcut.makeDescriptor( - UI.KeyboardShortcut.Keys.Down, UI.KeyboardShortcut.Modifiers.Shift) + UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Down, UI.KeyboardShortcut.Modifiers.Shift) ], - IncrementBy100: [UI.KeyboardShortcut.makeDescriptor( - UI.KeyboardShortcut.Keys.PageUp, UI.KeyboardShortcut.Modifiers.Shift)], + IncrementBy100: + [UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.PageUp, UI.KeyboardShortcut.Modifiers.Shift)], - DecrementBy100: [UI.KeyboardShortcut.makeDescriptor( - UI.KeyboardShortcut.Keys.PageDown, UI.KeyboardShortcut.Modifiers.Shift)], + DecrementBy100: + [UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.PageDown, UI.KeyboardShortcut.Modifiers.Shift)], - IncrementBy01: [UI.KeyboardShortcut.makeDescriptor( - UI.KeyboardShortcut.Keys.Up, UI.KeyboardShortcut.Modifiers.Alt)], + IncrementBy01: [UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Up, UI.KeyboardShortcut.Modifiers.Alt)], - DecrementBy01: [UI.KeyboardShortcut.makeDescriptor( - UI.KeyboardShortcut.Keys.Down, UI.KeyboardShortcut.Modifiers.Alt)] + DecrementBy01: [UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Down, UI.KeyboardShortcut.Modifiers.Alt)] }; Components.ShortcutsScreen.SourcesPanelShortcuts = { - SelectNextOccurrence: - [UI.KeyboardShortcut.makeDescriptor('d', UI.KeyboardShortcut.Modifiers.CtrlOrMeta)], + SelectNextOccurrence: [UI.KeyboardShortcut.makeDescriptor('d', UI.KeyboardShortcut.Modifiers.CtrlOrMeta)], SoftUndo: [UI.KeyboardShortcut.makeDescriptor('u', UI.KeyboardShortcut.Modifiers.CtrlOrMeta)], - GotoMatchingBracket: - [UI.KeyboardShortcut.makeDescriptor('m', UI.KeyboardShortcut.Modifiers.Ctrl)], + GotoMatchingBracket: [UI.KeyboardShortcut.makeDescriptor('m', UI.KeyboardShortcut.Modifiers.Ctrl)], - ToggleAutocompletion: [UI.KeyboardShortcut.makeDescriptor( - UI.KeyboardShortcut.Keys.Space, UI.KeyboardShortcut.Modifiers.Ctrl)], + ToggleAutocompletion: + [UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Space, UI.KeyboardShortcut.Modifiers.Ctrl)], - IncreaseCSSUnitByOne: [UI.KeyboardShortcut.makeDescriptor( - UI.KeyboardShortcut.Keys.Up, UI.KeyboardShortcut.Modifiers.Alt)], + IncreaseCSSUnitByOne: + [UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Up, UI.KeyboardShortcut.Modifiers.Alt)], - DecreaseCSSUnitByOne: [UI.KeyboardShortcut.makeDescriptor( - UI.KeyboardShortcut.Keys.Down, UI.KeyboardShortcut.Modifiers.Alt)], + DecreaseCSSUnitByOne: + [UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Down, UI.KeyboardShortcut.Modifiers.Alt)], - IncreaseCSSUnitByTen: [UI.KeyboardShortcut.makeDescriptor( - UI.KeyboardShortcut.Keys.PageUp, UI.KeyboardShortcut.Modifiers.Alt)], + IncreaseCSSUnitByTen: + [UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.PageUp, UI.KeyboardShortcut.Modifiers.Alt)], - DecreaseCSSUnitByTen: [UI.KeyboardShortcut.makeDescriptor( - UI.KeyboardShortcut.Keys.PageDown, UI.KeyboardShortcut.Modifiers.Alt)], + DecreaseCSSUnitByTen: + [UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.PageDown, UI.KeyboardShortcut.Modifiers.Alt)], EvaluateSelectionInConsole: [UI.KeyboardShortcut.makeDescriptor( 'e', UI.KeyboardShortcut.Modifiers.Shift | UI.KeyboardShortcut.Modifiers.Ctrl)], @@ -463,23 +438,22 @@ GoToLine: [UI.KeyboardShortcut.makeDescriptor('g', UI.KeyboardShortcut.Modifiers.Ctrl)], - ToggleBreakpoint: - [UI.KeyboardShortcut.makeDescriptor('b', UI.KeyboardShortcut.Modifiers.CtrlOrMeta)], + ToggleBreakpoint: [UI.KeyboardShortcut.makeDescriptor('b', UI.KeyboardShortcut.Modifiers.CtrlOrMeta)], - NextCallFrame: [UI.KeyboardShortcut.makeDescriptor( - UI.KeyboardShortcut.Keys.Period, UI.KeyboardShortcut.Modifiers.Ctrl)], + NextCallFrame: + [UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Period, UI.KeyboardShortcut.Modifiers.Ctrl)], - PrevCallFrame: [UI.KeyboardShortcut.makeDescriptor( - UI.KeyboardShortcut.Keys.Comma, UI.KeyboardShortcut.Modifiers.Ctrl)], + PrevCallFrame: + [UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Comma, UI.KeyboardShortcut.Modifiers.Ctrl)], - ToggleComment: [UI.KeyboardShortcut.makeDescriptor( - UI.KeyboardShortcut.Keys.Slash, UI.KeyboardShortcut.Modifiers.CtrlOrMeta)], + ToggleComment: + [UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Slash, UI.KeyboardShortcut.Modifiers.CtrlOrMeta)], - JumpToPreviousLocation: [UI.KeyboardShortcut.makeDescriptor( - UI.KeyboardShortcut.Keys.Minus, UI.KeyboardShortcut.Modifiers.Alt)], + JumpToPreviousLocation: + [UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Minus, UI.KeyboardShortcut.Modifiers.Alt)], - JumpToNextLocation: [UI.KeyboardShortcut.makeDescriptor( - UI.KeyboardShortcut.Keys.Plus, UI.KeyboardShortcut.Modifiers.Alt)], + JumpToNextLocation: + [UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Plus, UI.KeyboardShortcut.Modifiers.Alt)], CloseEditorTab: [UI.KeyboardShortcut.makeDescriptor('w', UI.KeyboardShortcut.Modifiers.Alt)], @@ -499,34 +473,20 @@ TogglePanRotate: [UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Shift)], ZoomIn: [ - UI.KeyboardShortcut.makeDescriptor( - UI.KeyboardShortcut.Keys.Plus, UI.KeyboardShortcut.Modifiers.Shift), + UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Plus, UI.KeyboardShortcut.Modifiers.Shift), UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.NumpadPlus) ], ZoomOut: [ - UI.KeyboardShortcut.makeDescriptor( - UI.KeyboardShortcut.Keys.Minus, UI.KeyboardShortcut.Modifiers.Shift), + UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Minus, UI.KeyboardShortcut.Modifiers.Shift), UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.NumpadMinus) ], - Up: [ - UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Up), - UI.KeyboardShortcut.makeDescriptor('w') - ], + Up: [UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Up), UI.KeyboardShortcut.makeDescriptor('w')], - Down: [ - UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Down), - UI.KeyboardShortcut.makeDescriptor('s') - ], + Down: [UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Down), UI.KeyboardShortcut.makeDescriptor('s')], - Left: [ - UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Left), - UI.KeyboardShortcut.makeDescriptor('a') - ], + Left: [UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Left), UI.KeyboardShortcut.makeDescriptor('a')], - Right: [ - UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Right), - UI.KeyboardShortcut.makeDescriptor('d') - ] + Right: [UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Right), UI.KeyboardShortcut.makeDescriptor('d')] };
diff --git a/third_party/WebKit/Source/devtools/front_end/components/Spectrum.js b/third_party/WebKit/Source/devtools/front_end/components/Spectrum.js index ee5e40b..65286b4 100644 --- a/third_party/WebKit/Source/devtools/front_end/components/Spectrum.js +++ b/third_party/WebKit/Source/devtools/front_end/components/Spectrum.js
@@ -56,8 +56,7 @@ this._contrastRatioLine = contrastRatioSVG.createSVGChild('path', 'spectrum-contrast-line'); var toolbar = new UI.Toolbar('spectrum-eye-dropper', this.contentElement); - this._colorPickerButton = - new UI.ToolbarToggle(Common.UIString('Toggle color picker'), 'largeicon-eyedropper'); + this._colorPickerButton = new UI.ToolbarToggle(Common.UIString('Toggle color picker'), 'largeicon-eyedropper'); this._colorPickerButton.setToggled(true); this._colorPickerButton.addEventListener('click', this._toggleColorPicker.bind(this, undefined)); toolbar.appendToolbarItem(this._colorPickerButton); @@ -169,9 +168,9 @@ var hsva = this._hsv.slice(); hsva[3] = Number.constrain(newAlpha, 0, 1); var colorFormat = undefined; - if (hsva[3] !== 1 && (this._colorFormat === Common.Color.Format.ShortHEX || - this._colorFormat === Common.Color.Format.HEX || - this._colorFormat === Common.Color.Format.Nickname)) + if (hsva[3] !== 1 && + (this._colorFormat === Common.Color.Format.ShortHEX || this._colorFormat === Common.Color.Format.HEX || + this._colorFormat === Common.Color.Format.Nickname)) colorFormat = Common.Color.Format.RGB; this._innerSetColor(hsva, '', colorFormat, Components.Spectrum._ChangeSource.Other); } @@ -256,8 +255,7 @@ shadow = colorElement.createChild('div', 'spectrum-palette-color spectrum-palette-color-shadow'); shadow.style.background = palette.colors[i]; colorElement.title = Common.UIString(palette.colors[i] + '. Long-click to show alternate shades.'); - new UI.LongClickController( - colorElement, this._showLightnessShades.bind(this, colorElement, palette.colors[i])); + new UI.LongClickController(colorElement, this._showLightnessShades.bind(this, colorElement, palette.colors[i])); } this._paletteContainer.appendChild(colorElement); } @@ -326,8 +324,7 @@ _slotIndexForEvent(e) { var localX = e.pageX - this._paletteContainer.totalOffsetLeft(); var localY = e.pageY - this._paletteContainer.totalOffsetTop(); - var col = - Math.min(localX / Components.Spectrum._colorChipSize | 0, Components.Spectrum._itemsPerPaletteRow - 1); + var col = Math.min(localX / Components.Spectrum._colorChipSize | 0, Components.Spectrum._itemsPerPaletteRow - 1); var row = (localY / Components.Spectrum._colorChipSize) | 0; return Math.min( row * Components.Spectrum._itemsPerPaletteRow + col, this._customPaletteSetting.get().colors.length - 1); @@ -366,8 +363,7 @@ if (e.pageX < this._paletteContainer.totalOffsetLeft() || e.pageY < this._paletteContainer.totalOffsetTop()) return; var newIndex = this._slotIndexForEvent(e); - var offsetX = - e.pageX - (newIndex % Components.Spectrum._itemsPerPaletteRow) * Components.Spectrum._colorChipSize; + var offsetX = e.pageX - (newIndex % Components.Spectrum._itemsPerPaletteRow) * Components.Spectrum._colorChipSize; var offsetY = e.pageY - (newIndex / Components.Spectrum._itemsPerPaletteRow | 0) * Components.Spectrum._colorChipSize; @@ -529,8 +525,7 @@ return; var contextMenu = new UI.ContextMenu(event); if (colorIndex !== -1) { - contextMenu.appendItem( - Common.UIString('Remove color'), this._deletePaletteColors.bind(this, colorIndex, false)); + contextMenu.appendItem(Common.UIString('Remove color'), this._deletePaletteColors.bind(this, colorIndex, false)); contextMenu.appendItem( Common.UIString('Remove all to the right'), this._deletePaletteColors.bind(this, colorIndex, true)); }
diff --git a/third_party/WebKit/Source/devtools/front_end/components/breakpointsList.css b/third_party/WebKit/Source/devtools/front_end/components/breakpointsList.css index 584a268..5910b47d 100644 --- a/third_party/WebKit/Source/devtools/front_end/components/breakpointsList.css +++ b/third_party/WebKit/Source/devtools/front_end/components/breakpointsList.css
@@ -27,6 +27,34 @@ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +.breakpoint-entry { + padding: 3px 8px 3px 8px; + min-height: 18px; + line-height: 15px; + border-top: 1px solid #efefef; +} + +.breakpoint-entry [is=dt-checkbox] { + max-width: 100%; +} + +.breakpoint-entry .dt-checkbox-text { + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; +} + +:not(.breakpoints-list-deactivated) > .breakpoint-entry:hover { + background-color: #eee; +} + +.breakpoint-entry > .source-text { + cursor: pointer; + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; +} + .breakpoint-condition { display: block; margin-top: 4px;
diff --git a/third_party/WebKit/Source/devtools/front_end/components/customPreviewSection.css b/third_party/WebKit/Source/devtools/front_end/components/customPreviewSection.css index bfe65b5..e9bba4ab 100644 --- a/third_party/WebKit/Source/devtools/front_end/components/customPreviewSection.css +++ b/third_party/WebKit/Source/devtools/front_end/components/customPreviewSection.css
@@ -9,32 +9,11 @@ flex-direction: column; } -.custom-expandable-section-header::before { +.custom-expand-icon { -webkit-user-select: none; - background-image: url(Images/toolbarButtonGlyphs.png); - background-size: 352px 168px; opacity: 0.5; - content: "a"; - width: 8px; margin-right: 4px; - padding-right: 2px; - color: transparent; - text-shadow: none; -} - -@media (-webkit-min-device-pixel-ratio: 1.1) { - .custom-expandable-section-header::before { - background-image: url(Images/toolbarButtonGlyphs_2x.png); - } -} /* media */ - - -.custom-expandable-section-header::before { - background-position: -4px -96px; -} - -.custom-expandable-section-header.expanded::before { - background-position: -20px -96px; + background: black; } .custom-expandable-section-standard-section {
diff --git a/third_party/WebKit/Source/devtools/front_end/components_lazy/CookiesTable.js b/third_party/WebKit/Source/devtools/front_end/components_lazy/CookiesTable.js index 842eee7c..efa8d8f 100644 --- a/third_party/WebKit/Source/devtools/front_end/components_lazy/CookiesTable.js +++ b/third_party/WebKit/Source/devtools/front_end/components_lazy/CookiesTable.js
@@ -56,28 +56,10 @@ {id: 'value', title: Common.UIString('Value'), sortable: true, longText: true, weight: 34}, {id: 'domain', title: Common.UIString('Domain'), sortable: true, weight: 7}, {id: 'path', title: Common.UIString('Path'), sortable: true, weight: 7}, - {id: 'expires', title: Common.UIString('Expires / Max-Age'), sortable: true, weight: 7}, { - id: 'size', - title: Common.UIString('Size'), - sortable: true, - align: UI.DataGrid.Align.Right, - weight: 7 - }, - { - id: 'httpOnly', - title: Common.UIString('HTTP'), - sortable: true, - align: UI.DataGrid.Align.Center, - weight: 7 - }, - { - id: 'secure', - title: Common.UIString('Secure'), - sortable: true, - align: UI.DataGrid.Align.Center, - weight: 7 - }, - { + {id: 'expires', title: Common.UIString('Expires / Max-Age'), sortable: true, weight: 7}, + {id: 'size', title: Common.UIString('Size'), sortable: true, align: UI.DataGrid.Align.Right, weight: 7}, + {id: 'httpOnly', title: Common.UIString('HTTP'), sortable: true, align: UI.DataGrid.Align.Center, weight: 7}, + {id: 'secure', title: Common.UIString('Secure'), sortable: true, align: UI.DataGrid.Align.Center, weight: 7}, { id: 'sameSite', title: Common.UIString('SameSite'), sortable: true, @@ -121,9 +103,10 @@ if (node === this._dataGrid.creationNode) return; var domain = node.cookie.domain(); - if (domain) + if (domain) { contextMenu.appendItem( Common.UIString.capitalize('Clear ^all from "%s"', domain), this._clearAndRefresh.bind(this, domain)); + } contextMenu.appendItem(Common.UIString.capitalize('Clear ^all'), this._clearAndRefresh.bind(this, null)); } @@ -187,8 +170,9 @@ groupNode.element().classList.add('row-group'); this._populateNode(groupNode, item.cookies, selectedCookie); groupNode.expand(); - } else + } else { this._populateNode(this._dataGrid.rootNode(), item.cookies, selectedCookie); + } } }
diff --git a/third_party/WebKit/Source/devtools/front_end/components_lazy/FilmStripView.js b/third_party/WebKit/Source/devtools/front_end/components_lazy/FilmStripView.js index 7ed53b6..6318a74a1 100644 --- a/third_party/WebKit/Source/devtools/front_end/components_lazy/FilmStripView.js +++ b/third_party/WebKit/Source/devtools/front_end/components_lazy/FilmStripView.js
@@ -227,8 +227,7 @@ createTextButton('\u25C0', this._onPrevFrame.bind(this), undefined, Common.UIString('Previous frame')); footerElement.appendChild(prevButton); this._timeLabel = footerElement.createChild('div', 'filmstrip-dialog-label'); - var nextButton = - createTextButton('\u25B6', this._onNextFrame.bind(this), undefined, Common.UIString('Next frame')); + var nextButton = createTextButton('\u25B6', this._onNextFrame.bind(this), undefined, Common.UIString('Next frame')); footerElement.appendChild(nextButton); footerElement.createChild('div', 'flex-auto');
diff --git a/third_party/WebKit/Source/devtools/front_end/components_lazy/LineLevelProfile.js b/third_party/WebKit/Source/devtools/front_end/components_lazy/LineLevelProfile.js index e0808e0..bdcaeeb 100644 --- a/third_party/WebKit/Source/devtools/front_end/components_lazy/LineLevelProfile.js +++ b/third_party/WebKit/Source/devtools/front_end/components_lazy/LineLevelProfile.js
@@ -73,8 +73,7 @@ var uiSourceCode = Workspace.workspace.uiSourceCodeForURL(url); if (!uiSourceCode) continue; - var target = - Bindings.NetworkProject.targetForUISourceCode(uiSourceCode) || SDK.targetManager.mainTarget(); + var target = Bindings.NetworkProject.targetForUISourceCode(uiSourceCode) || SDK.targetManager.mainTarget(); var debuggerModel = target ? SDK.DebuggerModel.fromTarget(target) : null; if (!debuggerModel) continue; @@ -110,13 +109,15 @@ * @param {!Bindings.LiveLocation} liveLocation */ updateLocation(liveLocation) { - if (this._uiLocation) + if (this._uiLocation) { this._uiLocation.uiSourceCode.removeLineDecoration( this._uiLocation.lineNumber, Components.LineLevelProfile.LineDecorator.type); + } this._uiLocation = liveLocation.uiLocation(); - if (this._uiLocation) + if (this._uiLocation) { this._uiLocation.uiSourceCode.addLineDecoration( this._uiLocation.lineNumber, Components.LineLevelProfile.LineDecorator.type, this._time); + } } };
diff --git a/third_party/WebKit/Source/devtools/front_end/console/ConsoleContextSelector.js b/third_party/WebKit/Source/devtools/front_end/console/ConsoleContextSelector.js index f81805e0..a7436d5 100644 --- a/third_party/WebKit/Source/devtools/front_end/console/ConsoleContextSelector.js +++ b/third_party/WebKit/Source/devtools/front_end/console/ConsoleContextSelector.js
@@ -18,18 +18,14 @@ SDK.targetManager.observeTargets(this); SDK.targetManager.addModelListener( - SDK.RuntimeModel, SDK.RuntimeModel.Events.ExecutionContextCreated, - this._onExecutionContextCreated, this); + SDK.RuntimeModel, SDK.RuntimeModel.Events.ExecutionContextCreated, this._onExecutionContextCreated, this); SDK.targetManager.addModelListener( - SDK.RuntimeModel, SDK.RuntimeModel.Events.ExecutionContextChanged, - this._onExecutionContextChanged, this); + SDK.RuntimeModel, SDK.RuntimeModel.Events.ExecutionContextChanged, this._onExecutionContextChanged, this); SDK.targetManager.addModelListener( - SDK.RuntimeModel, SDK.RuntimeModel.Events.ExecutionContextDestroyed, - this._onExecutionContextDestroyed, this); + SDK.RuntimeModel, SDK.RuntimeModel.Events.ExecutionContextDestroyed, this._onExecutionContextDestroyed, this); this._selectElement.addEventListener('change', this._executionContextChanged.bind(this), false); - UI.context.addFlavorChangeListener( - SDK.ExecutionContext, this._executionContextChangedExternally, this); + UI.context.addFlavorChangeListener(SDK.ExecutionContext, this._executionContextChangedExternally, this); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/console/ConsoleView.js b/third_party/WebKit/Source/devtools/front_end/console/ConsoleView.js index 079e1e6..d0f9972 100644 --- a/third_party/WebKit/Source/devtools/front_end/console/ConsoleView.js +++ b/third_party/WebKit/Source/devtools/front_end/console/ConsoleView.js
@@ -57,12 +57,10 @@ this._executionContextComboBox = new UI.ToolbarComboBox(null, 'console-context'); this._executionContextComboBox.setMaxWidth(200); - this._consoleContextSelector = - new Console.ConsoleContextSelector(this._executionContextComboBox.selectElement()); + this._consoleContextSelector = new Console.ConsoleContextSelector(this._executionContextComboBox.selectElement()); this._filter = new Console.ConsoleViewFilter(this); - this._filter.addEventListener( - Console.ConsoleViewFilter.Events.FilterChanged, this._updateMessageList.bind(this)); + this._filter.addEventListener(Console.ConsoleViewFilter.Events.FilterChanged, this._updateMessageList.bind(this)); this._filterBar = new UI.FilterBar('consoleView'); @@ -123,8 +121,7 @@ this._registerShortcuts(); this._messagesElement.addEventListener('contextmenu', this._handleContextMenuEvent.bind(this), false); - Common.moduleSetting('monitoringXHREnabled') - .addChangeListener(this._monitoringXHREnabledSettingChanged, this); + Common.moduleSetting('monitoringXHREnabled').addChangeListener(this._monitoringXHREnabledSettingChanged, this); this._linkifier = new Components.Linkifier(); @@ -146,8 +143,7 @@ this._consoleHistoryAutocompleteChanged(); this._updateFilterStatus(); - Common.moduleSetting('consoleTimestampsEnabled') - .addChangeListener(this._consoleTimestampsSettingChanged, this); + Common.moduleSetting('consoleTimestampsEnabled').addChangeListener(this._consoleTimestampsSettingChanged, this); this._registerWithMessageSink(); SDK.targetManager.observeTargets(this); @@ -200,8 +196,8 @@ var resourcesLoaded = !resourceTreeModel || resourceTreeModel.cachedResourcesLoaded(); if (!mainTarget || !resourcesLoaded) { SDK.targetManager.addModelListener( - SDK.ResourceTreeModel, SDK.ResourceTreeModel.Events.CachedResourcesLoaded, - this._onResourceTreeModelLoaded, this); + SDK.ResourceTreeModel, SDK.ResourceTreeModel.Events.CachedResourcesLoaded, this._onResourceTreeModelLoaded, + this); return; } this._fetchMultitargetMessages(); @@ -215,14 +211,13 @@ if (resourceTreeModel.target() !== SDK.targetManager.mainTarget()) return; SDK.targetManager.removeModelListener( - SDK.ResourceTreeModel, SDK.ResourceTreeModel.Events.CachedResourcesLoaded, - this._onResourceTreeModelLoaded, this); + SDK.ResourceTreeModel, SDK.ResourceTreeModel.Events.CachedResourcesLoaded, this._onResourceTreeModelLoaded, + this); this._fetchMultitargetMessages(); } _fetchMultitargetMessages() { - SDK.multitargetConsoleModel.addEventListener( - SDK.ConsoleModel.Events.ConsoleCleared, this._consoleCleared, this); + SDK.multitargetConsoleModel.addEventListener(SDK.ConsoleModel.Events.ConsoleCleared, this._consoleCleared, this); SDK.multitargetConsoleModel.addEventListener( SDK.ConsoleModel.Events.MessageAdded, this._onConsoleMessageAdded, this); SDK.multitargetConsoleModel.addEventListener( @@ -317,8 +312,8 @@ } var consoleMessage = new SDK.ConsoleMessage( - null, SDK.ConsoleMessage.MessageSource.Other, level, message.text, undefined, undefined, undefined, - undefined, undefined, undefined, undefined, message.timestamp); + null, SDK.ConsoleMessage.MessageSource.Other, level, message.text, undefined, undefined, undefined, undefined, + undefined, undefined, undefined, message.timestamp); this._addConsoleMessage(consoleMessage); } @@ -457,14 +452,14 @@ * @return {number} */ function compareTimestamps(viewMessage1, viewMessage2) { - return SDK.ConsoleMessage.timestampComparator( - viewMessage1.consoleMessage(), viewMessage2.consoleMessage()); + return SDK.ConsoleMessage.timestampComparator(viewMessage1.consoleMessage(), viewMessage2.consoleMessage()); } if (message.type === SDK.ConsoleMessage.MessageType.Command || - message.type === SDK.ConsoleMessage.MessageType.Result) + message.type === SDK.ConsoleMessage.MessageType.Result) { message.timestamp = this._consoleMessages.length ? this._consoleMessages.peekLast().consoleMessage().timestamp : 0; + } var viewMessage = this._createViewMessage(message); message[this._viewMessageSymbol] = viewMessage; var insertAt = this._consoleMessages.upperBound(viewMessage, compareTimestamps); @@ -596,8 +591,8 @@ var filterSubMenu = contextMenu.appendSubMenuItem(Common.UIString('Filter')); if (consoleMessage && consoleMessage.url) { - var menuTitle = Common.UIString.capitalize( - 'Hide ^messages from %s', new Common.ParsedURL(consoleMessage.url).displayName); + var menuTitle = + Common.UIString.capitalize('Hide ^messages from %s', new Common.ParsedURL(consoleMessage.url).displayName); filterSubMenu.appendItem(menuTitle, this._filter.addMessageURLFilter.bind(this._filter, consoleMessage.url)); } @@ -755,10 +750,7 @@ } section.addAlternateKeys(keys, Common.UIString('Clear console')); - keys = [ - shortcut.makeDescriptor(shortcut.Keys.Tab), - shortcut.makeDescriptor(shortcut.Keys.Right) - ]; + keys = [shortcut.makeDescriptor(shortcut.Keys.Tab), shortcut.makeDescriptor(shortcut.Keys.Right)]; section.addRelatedKeys(keys, Common.UIString('Accept suggestion')); var shortcutU = shortcut.makeDescriptor('u', UI.KeyboardShortcut.Modifiers.Ctrl); @@ -808,16 +800,16 @@ if (!result) return; - var level = !!exceptionDetails ? SDK.ConsoleMessage.MessageLevel.Error : - SDK.ConsoleMessage.MessageLevel.Log; + var level = !!exceptionDetails ? SDK.ConsoleMessage.MessageLevel.Error : SDK.ConsoleMessage.MessageLevel.Log; var message; - if (!exceptionDetails) + if (!exceptionDetails) { message = new SDK.ConsoleMessage( - result.target(), SDK.ConsoleMessage.MessageSource.JS, level, '', - SDK.ConsoleMessage.MessageType.Result, undefined, undefined, undefined, undefined, [result]); - else + result.target(), SDK.ConsoleMessage.MessageSource.JS, level, '', SDK.ConsoleMessage.MessageType.Result, + undefined, undefined, undefined, undefined, [result]); + } else { message = SDK.ConsoleMessage.fromException( result.target(), exceptionDetails, SDK.ConsoleMessage.MessageType.Result, undefined, undefined); + } message.setOriginatingMessage(originatingConsoleMessage); result.target().consoleModel.addMessage(message); } @@ -936,9 +928,8 @@ _searchMessage(index) { var message = this._visibleViewMessages[index]; message.setSearchRegex(this._searchRegex); - for (var i = 0; i < message.searchCount(); ++i) { + for (var i = 0; i < message.searchCount(); ++i) this._regexMatchRanges.push({messageIndex: index, matchIndex: i}); - } } /** @@ -982,8 +973,7 @@ if (this._currentMatchRangeIndex >= 0) { matchRange = this._regexMatchRanges[this._currentMatchRangeIndex]; var message = this._visibleViewMessages[matchRange.messageIndex]; - message.searchHighlightNode(matchRange.matchIndex) - .classList.remove(UI.highlightedCurrentSearchResultClassName); + message.searchHighlightNode(matchRange.matchIndex).classList.remove(UI.highlightedCurrentSearchResultClassName); } index = mod(index, this._regexMatchRanges.length); @@ -1070,12 +1060,10 @@ this._textFilterUI.addEventListener(UI.FilterUI.Events.FilterChanged, this._textFilterChanged, this); filterBar.addFilter(this._textFilterUI); - this._hideNetworkMessagesCheckbox = new UI.CheckboxFilterUI( - '', Common.UIString('Hide network'), true, - Common.moduleSetting('hideNetworkMessages')); + this._hideNetworkMessagesCheckbox = + new UI.CheckboxFilterUI('', Common.UIString('Hide network'), true, Common.moduleSetting('hideNetworkMessages')); this._hideViolationMessagesCheckbox = new UI.CheckboxFilterUI( - '', Common.UIString('Hide violations'), false, - Common.moduleSetting('hideViolationMessages')); + '', Common.UIString('Hide violations'), false, Common.moduleSetting('hideViolationMessages')); Common.moduleSetting('hideNetworkMessages').addChangeListener(this._filterChanged, this); Common.moduleSetting('hideViolationMessages').addChangeListener(this._filterChanged, this); filterBar.addFilter(this._hideNetworkMessagesCheckbox); @@ -1142,9 +1130,8 @@ if (!this._view._showAllMessagesCheckbox.checked() && executionContext) { if (message.target() !== executionContext.target()) return false; - if (message.executionContextId && message.executionContextId !== executionContext.id) { + if (message.executionContextId && message.executionContextId !== executionContext.id) return false; - } } if (Common.moduleSetting('hideNetworkMessages').get() && @@ -1181,8 +1168,7 @@ * @return {boolean} */ shouldBeVisibleByDefault(viewMessage) { - return viewMessage.consoleMessage().source !== - SDK.ConsoleMessage.MessageSource.Violation; + return viewMessage.consoleMessage().source !== SDK.ConsoleMessage.MessageSource.Violation; } reset() {
diff --git a/third_party/WebKit/Source/devtools/front_end/console/ConsoleViewMessage.js b/third_party/WebKit/Source/devtools/front_end/console/ConsoleViewMessage.js index 567fd3aa..ad09cfa 100644 --- a/third_party/WebKit/Source/devtools/front_end/console/ConsoleViewMessage.js +++ b/third_party/WebKit/Source/devtools/front_end/console/ConsoleViewMessage.js
@@ -231,14 +231,15 @@ messageElement.createTextChild(consoleMessage.request.requestMethod + ' '); messageElement.appendChild(Components.Linkifier.linkifyUsingRevealer( consoleMessage.request, consoleMessage.request.url, consoleMessage.request.url)); - if (consoleMessage.request.failed) + if (consoleMessage.request.failed) { messageElement.createTextChildren(' ', consoleMessage.request.localizedFailDescription); - else + } else { messageElement.createTextChildren( ' ', String(consoleMessage.request.statusCode), ' (', consoleMessage.request.statusText, ')'); + } } else { - var fragment = Components.linkifyStringAsFragmentWithCustomLinkifier( - messageText, linkifyRequest.bind(consoleMessage)); + var fragment = + Components.linkifyStringAsFragmentWithCustomLinkifier(messageText, linkifyRequest.bind(consoleMessage)); messageElement.appendChild(fragment); } } else { @@ -280,17 +281,17 @@ _buildMessageAnchor(consoleMessage) { var anchorElement = null; if (consoleMessage.source !== SDK.ConsoleMessage.MessageSource.Network || consoleMessage.request) { - if (consoleMessage.scriptId) + if (consoleMessage.scriptId) { anchorElement = this._linkifyScriptId( consoleMessage.scriptId, consoleMessage.url || '', consoleMessage.line, consoleMessage.column); - else if (consoleMessage.stackTrace && consoleMessage.stackTrace.callFrames.length) + } else if (consoleMessage.stackTrace && consoleMessage.stackTrace.callFrames.length) { anchorElement = this._linkifyStackTraceTopFrame(consoleMessage.stackTrace); - else if (consoleMessage.url && consoleMessage.url !== 'undefined') + } else if (consoleMessage.url && consoleMessage.url !== 'undefined') { anchorElement = this._linkifyLocation(consoleMessage.url, consoleMessage.line, consoleMessage.column); + } } else if (consoleMessage.url) { var url = consoleMessage.url; - var isExternal = - !Bindings.resourceForURL(url) && !Bindings.networkMapping.uiSourceCodeForURLForAnyTarget(url); + var isExternal = !Bindings.resourceForURL(url) && !Bindings.networkMapping.uiSourceCodeForURLForAnyTarget(url); anchorElement = UI.linkifyURLAsNode(url, url, 'console-message-url', isExternal); } @@ -417,8 +418,8 @@ parameters[i] = this._parameterToRemoteObject(parameters[i], this._target()); // There can be string log and string eval result. We distinguish between them based on message type. - var shouldFormatMessage = SDK.RemoteObject.type( - (/** @type {!Array.<!SDK.RemoteObject>} **/ (parameters))[0]) === 'string' && + var shouldFormatMessage = + SDK.RemoteObject.type((/** @type {!Array.<!SDK.RemoteObject>} **/ (parameters))[0]) === 'string' && (this._message.type !== SDK.ConsoleMessage.MessageType.Result || this._message.level === SDK.ConsoleMessage.MessageLevel.Error || this._message.level === SDK.ConsoleMessage.MessageLevel.RevokedError); @@ -552,8 +553,7 @@ */ function formatTargetFunction(targetFunction) { var functionElement = createElement('span'); - Components.ObjectPropertiesSection.formatObjectAsFunction( - targetFunction, functionElement, true, includePreview); + Components.ObjectPropertiesSection.formatObjectAsFunction(targetFunction, functionElement, true, includePreview); result.appendChild(functionElement); if (targetFunction !== func) { var note = result.createChild('span', 'object-info-state-note'); @@ -846,9 +846,9 @@ formatters._ = bypassFormatter; function append(a, b) { - if (b instanceof Node) + if (b instanceof Node) { a.appendChild(b); - else if (typeof b !== 'undefined') { + } else if (typeof b !== 'undefined') { var toAppend = Components.linkifyStringAsFragment(String(b)); if (currentStyle) { var wrapper = createElement('span'); @@ -948,12 +948,12 @@ var formattedMessage; var consoleMessage = this._message; var target = consoleMessage.target(); - var shouldIncludeTrace = !!consoleMessage.stackTrace && - (consoleMessage.source === SDK.ConsoleMessage.MessageSource.Network || - consoleMessage.level === SDK.ConsoleMessage.MessageLevel.Error || - consoleMessage.level === SDK.ConsoleMessage.MessageLevel.RevokedError || - consoleMessage.type === SDK.ConsoleMessage.MessageType.Trace || - consoleMessage.level === SDK.ConsoleMessage.MessageLevel.Warning); + var shouldIncludeTrace = + !!consoleMessage.stackTrace && (consoleMessage.source === SDK.ConsoleMessage.MessageSource.Network || + consoleMessage.level === SDK.ConsoleMessage.MessageLevel.Error || + consoleMessage.level === SDK.ConsoleMessage.MessageLevel.RevokedError || + consoleMessage.type === SDK.ConsoleMessage.MessageType.Trace || + consoleMessage.level === SDK.ConsoleMessage.MessageLevel.Warning); if (target && shouldIncludeTrace) formattedMessage = this._buildMessageWithStackTrace(consoleMessage, target, this._linkifier); else if (this._message.type === SDK.ConsoleMessage.MessageType.Table) @@ -1086,9 +1086,10 @@ while ((match = this._searchRegex.exec(text)) && match[0]) sourceRanges.push(new Common.SourceRange(match.index, match[0].length)); - if (sourceRanges.length) + if (sourceRanges.length) { this._searchHighlightNodes = UI.highlightSearchResults(this.contentElement(), sourceRanges, this._searchHiglightNodeChanges); + } } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/devices/DevicesView.js b/third_party/WebKit/Source/devtools/front_end/devices/DevicesView.js index 4c13324..f22505f 100644 --- a/third_party/WebKit/Source/devtools/front_end/devices/DevicesView.js +++ b/third_party/WebKit/Source/devtools/front_end/devices/DevicesView.js
@@ -233,8 +233,8 @@ portForwardingFooter.createChild('span').textContent = Common.UIString( 'Define the listening port on your device that maps to a port accessible from your development machine. '); portForwardingFooter.appendChild(UI.linkifyURLAsNode( - 'https://developer.chrome.com/devtools/docs/remote-debugging#port-forwarding', - Common.UIString('Learn more'), undefined, true)); + 'https://developer.chrome.com/devtools/docs/remote-debugging#port-forwarding', Common.UIString('Learn more'), + undefined, true)); this._list = new UI.ListWidget(this); this._list.registerRequiredCSS('devices/devicesView.css'); @@ -576,8 +576,7 @@ var titleRow = element.createChild('div', 'device-page-title-row'); var title = titleRow.createChild('div', 'device-page-title'); - var inspect = - createTextButton(Common.UIString('Inspect'), doAction.bind(null, 'inspect'), 'device-inspect-button'); + var inspect = createTextButton(Common.UIString('Inspect'), doAction.bind(null, 'inspect'), 'device-inspect-button'); titleRow.appendChild(inspect); var toolbar = new UI.Toolbar(''); @@ -634,8 +633,7 @@ this._cachedPortStatus = json; this._portStatus.removeChildren(); - this._portStatus.createChild('div', 'device-port-status-text').textContent = - Common.UIString('Port Forwarding:'); + this._portStatus.createChild('div', 'device-port-status-text').textContent = Common.UIString('Port Forwarding:'); var connected = []; var transient = []; var error = [];
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/ClassesPaneWidget.js b/third_party/WebKit/Source/devtools/front_end/elements/ClassesPaneWidget.js index 819e4cd..5e92aa9 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/ClassesPaneWidget.js +++ b/third_party/WebKit/Source/devtools/front_end/elements/ClassesPaneWidget.js
@@ -21,8 +21,7 @@ var proxyElement = this._prompt.attach(this._input); proxyElement.addEventListener('keydown', this._onKeyDown.bind(this), false); - SDK.targetManager.addModelListener( - SDK.DOMModel, SDK.DOMModel.Events.DOMMutated, this._onDOMMutated, this); + SDK.targetManager.addModelListener(SDK.DOMModel, SDK.DOMModel.Events.DOMMutated, this._onDOMMutated, this); /** @type {!Set<!SDK.DOMNode>} */ this._mutatingNodes = new Set(); UI.context.addFlavorChangeListener(SDK.DOMNode, this._update, this);
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/ColorSwatchPopoverIcon.js b/third_party/WebKit/Source/devtools/front_end/elements/ColorSwatchPopoverIcon.js index c5443c50..a2557e9 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/ColorSwatchPopoverIcon.js +++ b/third_party/WebKit/Source/devtools/front_end/elements/ColorSwatchPopoverIcon.js
@@ -34,9 +34,10 @@ this._bezierEditor = new UI.BezierEditor(); var cubicBezier = Common.Geometry.CubicBezier.parse(this._swatch.bezierText()); - if (!cubicBezier) + if (!cubicBezier) { cubicBezier = /** @type {!Common.Geometry.CubicBezier} */ (Common.Geometry.CubicBezier.parse('linear')); + } this._bezierEditor.setBezier(cubicBezier); this._bezierEditor.addEventListener(UI.BezierEditor.Events.BezierChanged, this._boundBezierChanged); this._swatchPopoverHelper.show(this._bezierEditor, this._swatch.iconElement(), this._onPopoverHidden.bind(this)); @@ -46,8 +47,7 @@ this._originalPropertyText = this._treeElement.property.propertyText; this._treeElement.parentPane().setEditingStyle(true); - var uiLocation = - Bindings.cssWorkspaceBinding.propertyUILocation(this._treeElement.property, false /* forName */); + var uiLocation = Bindings.cssWorkspaceBinding.propertyUILocation(this._treeElement.property, false /* forName */); if (uiLocation) Common.Revealer.reveal(uiLocation, true /* omitFocus */); } @@ -157,8 +157,7 @@ this._originalPropertyText = this._treeElement.property.propertyText; this._treeElement.parentPane().setEditingStyle(true); - var uiLocation = - Bindings.cssWorkspaceBinding.propertyUILocation(this._treeElement.property, false /* forName */); + var uiLocation = Bindings.cssWorkspaceBinding.propertyUILocation(this._treeElement.property, false /* forName */); if (uiLocation) Common.Revealer.reveal(uiLocation, true /* omitFocus */); } @@ -205,8 +204,7 @@ } }; -Elements.ColorSwatchPopoverIcon._treeElementSymbol = - Symbol('Elements.ColorSwatchPopoverIcon._treeElementSymbol'); +Elements.ColorSwatchPopoverIcon._treeElementSymbol = Symbol('Elements.ColorSwatchPopoverIcon._treeElementSymbol'); /** @@ -264,8 +262,7 @@ this._originalPropertyText = this._treeElement.property.propertyText; this._treeElement.parentPane().setEditingStyle(true); - var uiLocation = - Bindings.cssWorkspaceBinding.propertyUILocation(this._treeElement.property, false /* forName */); + var uiLocation = Bindings.cssWorkspaceBinding.propertyUILocation(this._treeElement.property, false /* forName */); if (uiLocation) Common.Revealer.reveal(uiLocation, true /* omitFocus */); } @@ -292,8 +289,7 @@ if (this._scrollerElement) this._scrollerElement.removeEventListener('scroll', this._boundOnScroll, false); - this._cssShadowEditor.removeEventListener( - UI.CSSShadowEditor.Events.ShadowChanged, this._boundShadowChanged); + this._cssShadowEditor.removeEventListener(UI.CSSShadowEditor.Events.ShadowChanged, this._boundShadowChanged); delete this._cssShadowEditor; var propertyText = commitEdit ? this._treeElement.renderedPropertyText() : this._originalPropertyText; @@ -303,5 +299,4 @@ } }; -Elements.ShadowSwatchPopoverHelper._treeElementSymbol = - Symbol('Elements.ShadowSwatchPopoverHelper._treeElementSymbol'); +Elements.ShadowSwatchPopoverHelper._treeElementSymbol = Symbol('Elements.ShadowSwatchPopoverHelper._treeElementSymbol');
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/ComputedStyleModel.js b/third_party/WebKit/Source/devtools/front_end/elements/ComputedStyleModel.js index 969bb99..1315b0db 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/ComputedStyleModel.js +++ b/third_party/WebKit/Source/devtools/front_end/elements/ComputedStyleModel.js
@@ -54,22 +54,16 @@ if (this._cssModel && domModel && resourceTreeModel) { this._targetEvents = [ - this._cssModel.addEventListener( - SDK.CSSModel.Events.StyleSheetAdded, this._onComputedStyleChanged, this), - this._cssModel.addEventListener( - SDK.CSSModel.Events.StyleSheetRemoved, this._onComputedStyleChanged, this), - this._cssModel.addEventListener( - SDK.CSSModel.Events.StyleSheetChanged, this._onComputedStyleChanged, this), + this._cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetAdded, this._onComputedStyleChanged, this), + this._cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetRemoved, this._onComputedStyleChanged, this), + this._cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetChanged, this._onComputedStyleChanged, this), this._cssModel.addEventListener(SDK.CSSModel.Events.FontsUpdated, this._onComputedStyleChanged, this), this._cssModel.addEventListener( SDK.CSSModel.Events.MediaQueryResultChanged, this._onComputedStyleChanged, this), - this._cssModel.addEventListener( - SDK.CSSModel.Events.PseudoStateForced, this._onComputedStyleChanged, this), - this._cssModel.addEventListener( - SDK.CSSModel.Events.ModelWasEnabled, this._onComputedStyleChanged, this), + this._cssModel.addEventListener(SDK.CSSModel.Events.PseudoStateForced, this._onComputedStyleChanged, this), + this._cssModel.addEventListener(SDK.CSSModel.Events.ModelWasEnabled, this._onComputedStyleChanged, this), domModel.addEventListener(SDK.DOMModel.Events.DOMMutated, this._onDOMModelChanged, this), - resourceTreeModel.addEventListener( - SDK.ResourceTreeModel.Events.FrameResized, this._onFrameResized, this), + resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.FrameResized, this._onFrameResized, this), ]; } } @@ -79,8 +73,7 @@ */ _onComputedStyleChanged(event) { delete this._computedStylePromise; - this.dispatchEventToListeners( - Elements.ComputedStyleModel.Events.ComputedStyleChanged, event ? event.data : null); + this.dispatchEventToListeners(Elements.ComputedStyleModel.Events.ComputedStyleChanged, event ? event.data : null); } /** @@ -128,9 +121,10 @@ if (!elementNode || !cssModel) return Promise.resolve(/** @type {?Elements.ComputedStyleModel.ComputedStyle} */ (null)); - if (!this._computedStylePromise) + if (!this._computedStylePromise) { this._computedStylePromise = cssModel.computedStylePromise(elementNode.id).then(verifyOutdated.bind(this, elementNode)); + } return this._computedStylePromise;
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/ComputedStyleWidget.js b/third_party/WebKit/Source/devtools/front_end/elements/ComputedStyleWidget.js index d9446b7..767b3c3 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/ComputedStyleWidget.js +++ b/third_party/WebKit/Source/devtools/front_end/elements/ComputedStyleWidget.js
@@ -198,8 +198,9 @@ treeElement.listItemElement.addEventListener('mousedown', (e) => e.consume(), false); treeElement.listItemElement.addEventListener('dblclick', (e) => e.consume(), false); treeElement.listItemElement.addEventListener('click', handleClick.bind(null, treeElement), false); - var gotoSourceElement = propertyValueElement.createChild('div', 'goto-source-icon'); + var gotoSourceElement = UI.Icon.create('smallicon-arrow-in-circle', 'goto-source-icon'); gotoSourceElement.addEventListener('click', this._navigateToSource.bind(this, activeProperty)); + propertyValueElement.appendChild(gotoSourceElement); if (expandedProperties.has(propertyName)) treeElement.expand(); } @@ -260,14 +261,13 @@ else activeProperty = property; - var renderer = new Elements.StylesSidebarPropertyRenderer( - null, node, property.name, /** @type {string} */ (property.value)); + var renderer = + new Elements.StylesSidebarPropertyRenderer(null, node, property.name, /** @type {string} */ (property.value)); renderer.setColorHandler(this._processColor.bind(this)); var valueElement = renderer.renderValue(); valueElement.classList.add('property-trace-value'); valueElement.addEventListener('click', this._navigateToSource.bind(this, property), false); - var gotoSourceElement = createElement('div'); - gotoSourceElement.classList.add('goto-source-icon'); + var gotoSourceElement = UI.Icon.create('smallicon-arrow-in-circle', 'goto-source-icon'); gotoSourceElement.addEventListener('click', this._navigateToSource.bind(this, property)); valueElement.insertBefore(gotoSourceElement, valueElement.firstChild);
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/ElementStatePaneWidget.js b/third_party/WebKit/Source/devtools/front_end/elements/ElementStatePaneWidget.js index 456799f1..77efe65 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/ElementStatePaneWidget.js +++ b/third_party/WebKit/Source/devtools/front_end/elements/ElementStatePaneWidget.js
@@ -106,8 +106,7 @@ */ Elements.ElementStatePaneWidget.ButtonProvider = class { constructor() { - this._button = new UI.ToolbarToggle( - Common.UIString('Toggle Element State'), ''); + this._button = new UI.ToolbarToggle(Common.UIString('Toggle Element State'), ''); this._button.setText(Common.UIString(':hov')); this._button.addEventListener('click', this._clicked, this); this._button.element.classList.add('monospace');
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/ElementsPanel.js b/third_party/WebKit/Source/devtools/front_end/elements/ElementsPanel.js index 355f3e20..2b6bd43 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/ElementsPanel.js +++ b/third_party/WebKit/Source/devtools/front_end/elements/ElementsPanel.js
@@ -64,8 +64,7 @@ crumbsContainer.id = 'elements-crumbs'; this._breadcrumbs = new Elements.ElementsBreadcrumbs(); this._breadcrumbs.show(crumbsContainer); - this._breadcrumbs.addEventListener( - Elements.ElementsBreadcrumbs.Events.NodeSelected, this._crumbNodeSelected, this); + this._breadcrumbs.addEventListener(Elements.ElementsBreadcrumbs.Events.NodeSelected, this._crumbNodeSelected, this); this._currentToolbarPane = null; @@ -244,9 +243,9 @@ var width = this._splitWidget.element.offsetWidth; if (this._splitWidget.isVertical()) width -= this._splitWidget.sidebarSize(); - for (var i = 0; i < this._treeOutlines.length; ++i) { + for (var i = 0; i < this._treeOutlines.length; ++i) this._treeOutlines[i].setVisibleWidth(width); - } + this._breadcrumbs.updateSizes(); } @@ -285,11 +284,12 @@ var treeOutline = this._treeOutlines[i]; treeOutline.setVisible(true); - if (!treeOutline.rootDOMNode) + if (!treeOutline.rootDOMNode) { if (treeOutline.domModel().existingDocument()) this._documentUpdated(treeOutline.domModel(), treeOutline.domModel().existingDocument()); else treeOutline.domModel().requestDocument(); + } } this.focus(); } @@ -474,9 +474,10 @@ var promises = []; var domModels = SDK.DOMModel.instances(); - for (var domModel of domModels) + for (var domModel of domModels) { promises.push( domModel.performSearchPromise(whitespaceTrimmedQuery, Common.moduleSetting('showUAShadowDOM').get())); + } Promise.all(promises).then(resultCountCallback.bind(this)); /** @@ -854,8 +855,7 @@ showMetrics.call(this, false); } - this.sidebarPaneView = - UI.viewManager.createTabbedLocation(() => UI.viewManager.showView('elements')); + this.sidebarPaneView = UI.viewManager.createTabbedLocation(() => UI.viewManager.showView('elements')); var tabbedPane = this.sidebarPaneView.tabbedPane(); tabbedPane.element.addEventListener('contextmenu', this._sidebarContextMenuEventFired.bind(this), false); if (this._popoverHelper) @@ -935,11 +935,10 @@ * @param {!Object} object */ appendApplicableItems(event, contextMenu, object) { - if (!(object instanceof SDK.RemoteObject && - (/** @type {!SDK.RemoteObject} */ (object)).isNode()) && - !(object instanceof SDK.DOMNode) && !(object instanceof SDK.DeferredDOMNode)) { + if (!(object instanceof SDK.RemoteObject && (/** @type {!SDK.RemoteObject} */ (object)).isNode()) && + !(object instanceof SDK.DOMNode) && !(object instanceof SDK.DeferredDOMNode)) return; - } + // Add debbuging-related actions if (object instanceof SDK.DOMNode) { @@ -1068,8 +1067,7 @@ decorate(node) { return { color: 'orange', - title: Common.UIString( - 'Element state: %s', ':' + SDK.CSSModel.fromNode(node).pseudoState(node).join(', :')) + title: Common.UIString('Element state: %s', ':' + SDK.CSSModel.fromNode(node).pseudoState(node).join(', :')) }; } };
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/ElementsTreeElement.js b/third_party/WebKit/Source/devtools/front_end/elements/ElementsTreeElement.js index a18fc198..ccd29d4 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/ElementsTreeElement.js +++ b/third_party/WebKit/Source/devtools/front_end/elements/ElementsTreeElement.js
@@ -403,9 +403,9 @@ } _insertInLastAttributePosition(tag, node) { - if (tag.getElementsByClassName('webkit-html-attribute').length > 0) + if (tag.getElementsByClassName('webkit-html-attribute').length > 0) { tag.insertBefore(node, tag.lastChild); - else { + } else { var nodeName = tag.textContent.match(/^<(.*?)>$/)[1]; tag.textContent = ''; tag.createTextChild('<' + nodeName); @@ -463,10 +463,11 @@ var attribute = event.target.enclosingNodeOrSelfWithClass('webkit-html-attribute'); var newAttribute = event.target.enclosingNodeOrSelfWithClass('add-attribute'); - if (attribute && !newAttribute) + if (attribute && !newAttribute) { contextMenu.appendItem( Common.UIString.capitalize('Edit ^attribute'), this._startEditingAttribute.bind(this, attribute, event.target)); + } this.populateNodeContextMenu(contextMenu); Elements.ElementsTreeElement.populateForcedPseudoStateItems(contextMenu, treeElement.node()); contextMenu.appendSeparator(); @@ -482,8 +483,7 @@ populateTextContextMenu(contextMenu, textNode) { if (!this._editing) - contextMenu.appendItem( - Common.UIString.capitalize('Edit ^text'), this._startEditingTextNode.bind(this, textNode)); + contextMenu.appendItem(Common.UIString.capitalize('Edit ^text'), this._startEditingTextNode.bind(this, textNode)); this.populateNodeContextMenu(contextMenu); } @@ -547,9 +547,10 @@ if (this._canAddAttributes) { var attribute = listItem.getElementsByClassName('webkit-html-attribute')[0]; - if (attribute) + if (attribute) { return this._startEditingAttribute( attribute, attribute.getElementsByClassName('webkit-html-attribute-value')[0]); + } return this._addNewAttribute(); } @@ -623,9 +624,10 @@ } var attributeValue = attributeName && attributeValueElement ? this._node.getAttribute(attributeName) : undefined; - if (attributeValue !== undefined) + if (attributeValue !== undefined) { attributeValueElement.setTextContentTruncatedIfNeeded( attributeValue, Common.UIString('<value is too large to edit>')); + } // Remove zero-width spaces that were added by nodeTitleInfo. removeZeroWidthSpaceRecursive(attribute); @@ -723,8 +725,7 @@ tagNameElement.addEventListener('keyup', keyupListener, false); - var config = - new UI.InplaceEditor.Config(editingComitted.bind(this), editingCancelled.bind(this), tagName); + var config = new UI.InplaceEditor.Config(editingComitted.bind(this), editingCancelled.bind(this), tagName); this._editing = UI.InplaceEditor.startEditing(tagNameElement, config); this.listItemElement.getComponentSelection().setBaseAndExtent(tagNameElement, 0, tagNameElement, 1); return true; @@ -804,8 +805,8 @@ var config = new UI.InplaceEditor.Config(commit.bind(this), dispose.bind(this)); config.setMultilineOptions( - initialValue, {name: 'xml', htmlMode: true}, 'web-inspector-html', - Common.moduleSetting('domWordWrap').get(), true); + initialValue, {name: 'xml', htmlMode: true}, 'web-inspector-html', Common.moduleSetting('domWordWrap').get(), + true); UI.InplaceEditor.startMultilineEditing(this._htmlEditElement, config).then(markAsBeingEdited.bind(this)); /** @@ -1055,9 +1056,10 @@ this.treeOutline._decoratorExtensions = runtime.extensions(Components.DOMPresentationUtils.MarkerDecorator); var markerToExtension = new Map(); - for (var i = 0; i < this.treeOutline._decoratorExtensions.length; ++i) + for (var i = 0; i < this.treeOutline._decoratorExtensions.length; ++i) { markerToExtension.set( this.treeOutline._decoratorExtensions[i].descriptor()['marker'], this.treeOutline._decoratorExtensions[i]); + } var promises = []; var decorations = []; @@ -1384,8 +1386,7 @@ break; } - if (this.treeOutline.isXMLMimeType || - !Elements.ElementsTreeElement.ForbiddenClosingTagElements.has(tagName)) + if (this.treeOutline.isXMLMimeType || !Elements.ElementsTreeElement.ForbiddenClosingTagElements.has(tagName)) this._buildTagDOM(titleDOM, tagName, true, false, updateRecord); break; @@ -1428,8 +1429,9 @@ docTypeElement.createTextChild(' PUBLIC "' + node.publicId + '"'); if (node.systemId) docTypeElement.createTextChild(' "' + node.systemId + '"'); - } else if (node.systemId) + } else if (node.systemId) { docTypeElement.createTextChild(' SYSTEM "' + node.systemId + '"'); + } if (node.internalSubset) docTypeElement.createTextChild(' [' + node.internalSubset + ']');
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/ElementsTreeElementHighlighter.js b/third_party/WebKit/Source/devtools/front_end/elements/ElementsTreeElementHighlighter.js index 69135b7..4452935d 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/ElementsTreeElementHighlighter.js +++ b/third_party/WebKit/Source/devtools/front_end/elements/ElementsTreeElementHighlighter.js
@@ -13,12 +13,10 @@ this._treeOutline = treeOutline; this._treeOutline.addEventListener(TreeOutline.Events.ElementExpanded, this._clearState, this); this._treeOutline.addEventListener(TreeOutline.Events.ElementCollapsed, this._clearState, this); - this._treeOutline.addEventListener( - Elements.ElementsTreeOutline.Events.SelectedNodeChanged, this._clearState, this); + this._treeOutline.addEventListener(Elements.ElementsTreeOutline.Events.SelectedNodeChanged, this._clearState, this); SDK.targetManager.addModelListener( SDK.DOMModel, SDK.DOMModel.Events.NodeHighlightedInOverlay, this._highlightNode, this); - this._treeOutline.domModel().addEventListener( - SDK.DOMModel.Events.InspectModeWillBeToggled, this._clearState, this); + this._treeOutline.domModel().addEventListener(SDK.DOMModel.Events.InspectModeWillBeToggled, this._clearState, this); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/ElementsTreeOutline.js b/third_party/WebKit/Source/devtools/front_end/elements/ElementsTreeOutline.js index 28f8897d..6faef61b 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/ElementsTreeOutline.js +++ b/third_party/WebKit/Source/devtools/front_end/elements/ElementsTreeOutline.js
@@ -638,10 +638,10 @@ return; } - if (element instanceof Elements.ElementsTreeOutline.ShortcutTreeElement) + if (element instanceof Elements.ElementsTreeOutline.ShortcutTreeElement) { this._domModel.highlightDOMNodeWithConfig( - undefined, {mode: 'all', showInfo: !UI.KeyboardShortcut.eventHasCtrlOrMeta(event)}, - element.backendNodeId()); + undefined, {mode: 'all', showInfo: !UI.KeyboardShortcut.eventHasCtrlOrMeta(event)}, element.backendNodeId()); + } } _onmouseleave(event) { @@ -995,13 +995,10 @@ this._domModel.addEventListener(SDK.DOMModel.Events.NodeRemoved, this._nodeRemoved, this); this._domModel.addEventListener(SDK.DOMModel.Events.AttrModified, this._attributeModified, this); this._domModel.addEventListener(SDK.DOMModel.Events.AttrRemoved, this._attributeRemoved, this); - this._domModel.addEventListener( - SDK.DOMModel.Events.CharacterDataModified, this._characterDataModified, this); + this._domModel.addEventListener(SDK.DOMModel.Events.CharacterDataModified, this._characterDataModified, this); this._domModel.addEventListener(SDK.DOMModel.Events.DocumentUpdated, this._documentUpdated, this); - this._domModel.addEventListener( - SDK.DOMModel.Events.ChildNodeCountUpdated, this._childNodeCountUpdated, this); - this._domModel.addEventListener( - SDK.DOMModel.Events.DistributedNodesChanged, this._distributedNodesChanged, this); + this._domModel.addEventListener(SDK.DOMModel.Events.ChildNodeCountUpdated, this._childNodeCountUpdated, this); + this._domModel.addEventListener(SDK.DOMModel.Events.DistributedNodesChanged, this._distributedNodesChanged, this); } unwireFromDOMModel() { @@ -1009,11 +1006,9 @@ this._domModel.removeEventListener(SDK.DOMModel.Events.NodeRemoved, this._nodeRemoved, this); this._domModel.removeEventListener(SDK.DOMModel.Events.AttrModified, this._attributeModified, this); this._domModel.removeEventListener(SDK.DOMModel.Events.AttrRemoved, this._attributeRemoved, this); - this._domModel.removeEventListener( - SDK.DOMModel.Events.CharacterDataModified, this._characterDataModified, this); + this._domModel.removeEventListener(SDK.DOMModel.Events.CharacterDataModified, this._characterDataModified, this); this._domModel.removeEventListener(SDK.DOMModel.Events.DocumentUpdated, this._documentUpdated, this); - this._domModel.removeEventListener( - SDK.DOMModel.Events.ChildNodeCountUpdated, this._childNodeCountUpdated, this); + this._domModel.removeEventListener(SDK.DOMModel.Events.ChildNodeCountUpdated, this._childNodeCountUpdated, this); this._domModel.removeEventListener( SDK.DOMModel.Events.DistributedNodesChanged, this._distributedNodesChanged, this); delete this._domModel[Elements.ElementsTreeOutline._treeOutlineSymbol]; @@ -1299,8 +1294,8 @@ var visibleChildCount = this._visibleChildren(treeElement.node()).length; this.setExpandedChildrenLimit( treeElement, Math.max( - visibleChildCount, treeElement.expandedChildrenLimit() + - Elements.ElementsTreeElement.InitialChildrenLimit)); + visibleChildCount, + treeElement.expandedChildrenLimit() + Elements.ElementsTreeElement.InitialChildrenLimit)); event.consume(); } }
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/EventListenersWidget.js b/third_party/WebKit/Source/devtools/front_end/elements/EventListenersWidget.js index 6fbe037..464cab1d 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/EventListenersWidget.js +++ b/third_party/WebKit/Source/devtools/front_end/elements/EventListenersWidget.js
@@ -65,8 +65,7 @@ if (value === this._dispatchFilterBySetting.get()) dispatchFilter.select(option); } - addDispatchFilterOption.call( - this, Common.UIString('All'), Elements.EventListenersWidget.DispatchFilterBy.All); + addDispatchFilterOption.call(this, Common.UIString('All'), Elements.EventListenersWidget.DispatchFilterBy.All); addDispatchFilterOption.call( this, Common.UIString('Passive'), Elements.EventListenersWidget.DispatchFilterBy.Passive); addDispatchFilterOption.call( @@ -74,8 +73,8 @@ dispatchFilter.setMaxWidth(200); this._toolbarItems.push(dispatchFilter); this._toolbarItems.push(new UI.ToolbarCheckbox( - Common.UIString('Framework listeners'), - Common.UIString('Resolve event listeners bound with framework'), this._showFrameworkListenersSetting)); + Common.UIString('Framework listeners'), Common.UIString('Resolve event listeners bound with framework'), + this._showFrameworkListenersSetting)); UI.context.addFlavorChangeListener(SDK.DOMNode, this.update, this); this.update();
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/InspectElementModeController.js b/third_party/WebKit/Source/devtools/front_end/elements/InspectElementModeController.js index 92a078d9..719033b 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/InspectElementModeController.js +++ b/third_party/WebKit/Source/devtools/front_end/elements/InspectElementModeController.js
@@ -39,8 +39,7 @@ } this._mode = Protocol.DOM.InspectMode.None; - SDK.targetManager.addEventListener( - SDK.TargetManager.Events.SuspendStateChanged, this._suspendStateChanged, this); + SDK.targetManager.addEventListener(SDK.TargetManager.Events.SuspendStateChanged, this._suspendStateChanged, this); SDK.targetManager.observeTargets(this, SDK.Target.Capability.DOM); } @@ -94,11 +93,12 @@ return; var mode; - if (this.isInInspectElementMode()) + if (this.isInInspectElementMode()) { mode = Protocol.DOM.InspectMode.None; - else + } else { mode = Common.moduleSetting('showUAShadowDOM').get() ? Protocol.DOM.InspectMode.SearchForUAShadowDOM : - Protocol.DOM.InspectMode.SearchForNode; + Protocol.DOM.InspectMode.SearchForNode; + } this._setMode(mode); }
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/MetricsSidebarPane.js b/third_party/WebKit/Source/devtools/front_end/elements/MetricsSidebarPane.js index ab5aab4d..8d2d6886 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/MetricsSidebarPane.js +++ b/third_party/WebKit/Source/devtools/front_end/elements/MetricsSidebarPane.js
@@ -224,13 +224,12 @@ var boxes = ['content', 'padding', 'border', 'margin', 'position']; var boxColors = [ - Common.Color.PageHighlight.Content, Common.Color.PageHighlight.Padding, - Common.Color.PageHighlight.Border, Common.Color.PageHighlight.Margin, - Common.Color.fromRGBA([0, 0, 0, 0]) + Common.Color.PageHighlight.Content, Common.Color.PageHighlight.Padding, Common.Color.PageHighlight.Border, + Common.Color.PageHighlight.Margin, Common.Color.fromRGBA([0, 0, 0, 0]) ]; var boxLabels = [ - Common.UIString('content'), Common.UIString('padding'), Common.UIString('border'), - Common.UIString('margin'), Common.UIString('position') + Common.UIString('content'), Common.UIString('padding'), Common.UIString('border'), Common.UIString('margin'), + Common.UIString('position') ]; var previousBox = null; this._boxElements = []; @@ -313,8 +312,8 @@ this._isEditingMetrics = true; - var config = new UI.InplaceEditor.Config( - this._editingCommitted.bind(this), this.editingCancelled.bind(this), context); + var config = + new UI.InplaceEditor.Config(this._editingCommitted.bind(this), this.editingCancelled.bind(this), context); UI.InplaceEditor.startEditing(targetElement, config); targetElement.getComponentSelection().setBaseAndExtent(targetElement, 0, targetElement, 1); @@ -344,8 +343,7 @@ return prefix + number + suffix; } - UI.handleElementValueModifications( - event, element, finishHandler.bind(this), undefined, customNumberHandler); + UI.handleElementValueModifications(event, element, finishHandler.bind(this), undefined, customNumberHandler); } editingEnded(element, context) { @@ -362,9 +360,10 @@ var pastLastSourcePropertyIndex = this.inlineStyle.pastLastSourcePropertyIndex(); if (pastLastSourcePropertyIndex) this.inlineStyle.allProperties[pastLastSourcePropertyIndex - 1].setText('', false); - } else + } else { this.inlineStyle.allProperties[this.originalPropertyData.index].setText( this.originalPropertyData.propertyText, false); + } } this.editingEnded(element, context); this.update();
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/PlatformFontsWidget.js b/third_party/WebKit/Source/devtools/front_end/elements/PlatformFontsWidget.js index b50738b..3e49875a 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/PlatformFontsWidget.js +++ b/third_party/WebKit/Source/devtools/front_end/elements/PlatformFontsWidget.js
@@ -91,8 +91,8 @@ fontDelimeterElement.textContent = '\u2014'; var fontOrigin = fontStatElement.createChild('span'); - fontOrigin.textContent = platformFonts[i].isCustomFont ? Common.UIString('Network resource') : - Common.UIString('Local file'); + fontOrigin.textContent = + platformFonts[i].isCustomFont ? Common.UIString('Network resource') : Common.UIString('Local file'); var fontUsageElement = fontStatElement.createChild('span', 'font-usage'); var usage = platformFonts[i].glyphCount;
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/PropertiesWidget.js b/third_party/WebKit/Source/devtools/front_end/elements/PropertiesWidget.js index abc6b23..d9389b7 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/PropertiesWidget.js +++ b/third_party/WebKit/Source/devtools/front_end/elements/PropertiesWidget.js
@@ -34,10 +34,8 @@ constructor() { super(); - SDK.targetManager.addModelListener( - SDK.DOMModel, SDK.DOMModel.Events.AttrModified, this._onNodeChange, this); - SDK.targetManager.addModelListener( - SDK.DOMModel, SDK.DOMModel.Events.AttrRemoved, this._onNodeChange, this); + SDK.targetManager.addModelListener(SDK.DOMModel, SDK.DOMModel.Events.AttrModified, this._onNodeChange, this); + SDK.targetManager.addModelListener(SDK.DOMModel, SDK.DOMModel.Events.AttrRemoved, this._onNodeChange, this); SDK.targetManager.addModelListener( SDK.DOMModel, SDK.DOMModel.Events.CharacterDataModified, this._onNodeChange, this); SDK.targetManager.addModelListener( @@ -62,8 +60,7 @@ */ doUpdate() { if (this._lastRequestedNode) { - this._lastRequestedNode.target().runtimeAgent().releaseObjectGroup( - Elements.PropertiesWidget._objectGroupName); + this._lastRequestedNode.target().runtimeAgent().releaseObjectGroup(Elements.PropertiesWidget._objectGroupName); delete this._lastRequestedNode; } @@ -74,8 +71,7 @@ } this._lastRequestedNode = this._node; - return this._node.resolveToObjectPromise(Elements.PropertiesWidget._objectGroupName) - .then(nodeResolved.bind(this)); + return this._node.resolveToObjectPromise(Elements.PropertiesWidget._objectGroupName).then(nodeResolved.bind(this)); /** * @param {?SDK.RemoteObject} object @@ -157,9 +153,8 @@ */ _propertyExpanded(event) { Host.userMetrics.actionTaken(Host.UserMetrics.Action.DOMPropertiesExpanded); - for (var section of this.sections) { + for (var section of this.sections) section.removeEventListener(TreeOutline.Events.ElementExpanded, this._propertyExpanded, this); - } } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/StylesSidebarPane.js b/third_party/WebKit/Source/devtools/front_end/elements/StylesSidebarPane.js index 5355cf2b..dda1f86 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/StylesSidebarPane.js +++ b/third_party/WebKit/Source/devtools/front_end/elements/StylesSidebarPane.js
@@ -670,9 +670,10 @@ } var header = rule.styleSheetId ? matchedStyles.cssModel().styleSheetHeaderForId(rule.styleSheetId) : null; - if (ruleLocation && rule.styleSheetId && header && header.resourceURL()) + if (ruleLocation && rule.styleSheetId && header && header.resourceURL()) { return Elements.StylePropertiesSection._linkifyRuleLocation( matchedStyles.cssModel(), linkifier, rule.styleSheetId, ruleLocation); + } if (rule.isUserAgent()) return createTextNode(Common.UIString('user agent stylesheet')); @@ -733,30 +734,25 @@ return; var items = []; - var textShadowButton = - new UI.ToolbarButton(Common.UIString('Add text-shadow'), 'largeicon-text-shadow'); + var textShadowButton = new UI.ToolbarButton(Common.UIString('Add text-shadow'), 'largeicon-text-shadow'); textShadowButton.addEventListener('click', this._onInsertShadowPropertyClick.bind(this, 'text-shadow')); items.push(textShadowButton); - var boxShadowButton = - new UI.ToolbarButton(Common.UIString('Add box-shadow'), 'largeicon-box-shadow'); + var boxShadowButton = new UI.ToolbarButton(Common.UIString('Add box-shadow'), 'largeicon-box-shadow'); boxShadowButton.addEventListener('click', this._onInsertShadowPropertyClick.bind(this, 'box-shadow')); items.push(boxShadowButton); - var colorButton = - new UI.ToolbarButton(Common.UIString('Add color'), 'largeicon-foreground-color'); + var colorButton = new UI.ToolbarButton(Common.UIString('Add color'), 'largeicon-foreground-color'); colorButton.addEventListener('click', this._onInsertColorPropertyClick.bind(this)); items.push(colorButton); - var backgroundButton = - new UI.ToolbarButton(Common.UIString('Add background-color'), 'largeicon-background-color'); + var backgroundButton = new UI.ToolbarButton(Common.UIString('Add background-color'), 'largeicon-background-color'); backgroundButton.addEventListener('click', this._onInsertBackgroundColorPropertyClick.bind(this)); items.push(backgroundButton); var newRuleButton = null; if (this._style.parentRule) { - newRuleButton = - new UI.ToolbarButton(Common.UIString('Insert Style Rule Below'), 'largeicon-add'); + newRuleButton = new UI.ToolbarButton(Common.UIString('Insert Style Rule Below'), 'largeicon-add'); newRuleButton.addEventListener('click', this._onNewRuleClick.bind(this)); items.push(newRuleButton); } @@ -877,9 +873,9 @@ */ nextSibling() { var curElement = this.element; - do { + do curElement = curElement.nextSibling; - } while (curElement && !curElement._section); + while (curElement && !curElement._section); return curElement ? curElement._section : null; } @@ -889,9 +885,9 @@ */ previousSibling() { var curElement = this.element; - do { + do curElement = curElement.previousSibling; - } while (curElement && !curElement._section); + while (curElement && !curElement._section); return curElement ? curElement._section : null; } @@ -1022,9 +1018,9 @@ */ nextEditableSibling() { var curSection = this; - do { + do curSection = curSection.nextSibling(); - } while (curSection && !curSection.editable); + while (curSection && !curSection.editable); if (!curSection) { curSection = this.firstSibling(); @@ -1040,9 +1036,9 @@ */ previousEditableSibling() { var curSection = this; - do { + do curSection = curSection.previousSibling(); - } while (curSection && !curSection.editable); + while (curSection && !curSection.editable); if (!curSection) { curSection = this.lastSibling(); @@ -1127,8 +1123,7 @@ this._mediaListElement.classList.toggle('media-matches', this._matchedStyles.mediaMatches(this._style)); var selectorTexts = rule.selectors.map(selector => selector.text); - var matchingSelectorIndexes = - this._matchedStyles.matchingSelectors(/** @type {!SDK.CSSStyleRule} */ (rule)); + var matchingSelectorIndexes = this._matchedStyles.matchingSelectors(/** @type {!SDK.CSSStyleRule} */ (rule)); var matchingSelectors = new Array(selectorTexts.length).fill(false); for (var matchingIndex of matchingSelectorIndexes) matchingSelectors[matchingIndex] = true; @@ -1398,8 +1393,7 @@ var header = cssModel.styleSheetHeaderForId(/** @type {string} */ (rule.styleSheetId)); if (!header) return; - var rawLocation = - new SDK.CSSLocation(header, rule.lineNumberInSource(index), rule.columnNumberInSource(index)); + var rawLocation = new SDK.CSSLocation(header, rule.lineNumberInSource(index), rule.columnNumberInSource(index)); var uiLocation = Bindings.cssWorkspaceBinding.rawLocationToUILocation(rawLocation); if (uiLocation) Common.Revealer.reveal(uiLocation, !focus); @@ -1429,8 +1423,8 @@ element.scrollIntoViewIfNeeded(false); element.textContent = element.textContent; // Reset selector marks in group. - var config = new UI.InplaceEditor.Config( - this.editingSelectorCommitted.bind(this), this.editingSelectorCancelled.bind(this)); + var config = + new UI.InplaceEditor.Config(this.editingSelectorCommitted.bind(this), this.editingSelectorCancelled.bind(this)); UI.InplaceEditor.startEditing(this._selectorElement, config); element.getComponentSelection().setBaseAndExtent(element, 0, element, 1); @@ -2087,8 +2081,8 @@ var section = this.section(); if (section) { inherited = section.isPropertyInherited(name); - overloaded = this._matchedStyles.propertyState(longhandProperties[i]) === - SDK.CSSMatchedStyles.PropertyState.Overloaded; + overloaded = + this._matchedStyles.propertyState(longhandProperties[i]) === SDK.CSSMatchedStyles.PropertyState.Overloaded; } var item = new Elements.StylePropertyTreeElement( @@ -2201,8 +2195,7 @@ return; } - if (UI.KeyboardShortcut.eventHasCtrlOrMeta(/** @type {!MouseEvent} */ (event)) && - this.section().navigable) { + if (UI.KeyboardShortcut.eventHasCtrlOrMeta(/** @type {!MouseEvent} */ (event)) && this.section().navigable) { this._navigateToSource(/** @type {!Element} */ (event.target)); return; } @@ -2238,9 +2231,10 @@ if (section && !section.editable) return; - if (selectElement) + if (selectElement) { selectElement = selectElement.enclosingNodeOrSelfWithClass('webkit-css-property') || selectElement.enclosingNodeOrSelfWithClass('value'); + } if (!selectElement) selectElement = this.nameElement; @@ -2376,11 +2370,10 @@ if (isEnterKey(event)) { event.preventDefault(); result = 'forward'; - } else if (event.keyCode === UI.KeyboardShortcut.Keys.Esc.code || event.key === 'Escape') + } else if (event.keyCode === UI.KeyboardShortcut.Keys.Esc.code || event.key === 'Escape') { result = 'cancel'; - else if ( - !context.isEditingName && this._newProperty && - event.keyCode === UI.KeyboardShortcut.Keys.Backspace.code) { + } else if ( + !context.isEditingName && this._newProperty && event.keyCode === UI.KeyboardShortcut.Keys.Backspace.code) { // For a new property, when Backspace is pressed at the beginning of new property value, move back to the property name. var selection = event.target.getComponentSelection(); if (selection.isCollapsed && !selection.focusOffset) { @@ -2511,9 +2504,9 @@ */ _findSibling(moveDirection) { var target = this; - do { + do target = (moveDirection === 'forward' ? target.nextSibling : target.previousSibling); - } while (target && target.inherited()); + while (target && target.inherited()); return target; } @@ -2557,9 +2550,9 @@ if (((userInput !== context.previousContent || isDirtyViaPaste) && !this._newProperty) || shouldCommitNewProperty) { section._afterUpdate = moveToNextCallback.bind(this, this._newProperty, !blankInput, section); var propertyText; - if (blankInput || (this._newProperty && this.valueElement.textContent.isWhitespace())) + if (blankInput || (this._newProperty && this.valueElement.textContent.isWhitespace())) { propertyText = ''; - else { + } else { if (isEditingName) propertyText = userInput + ': ' + this.property.value; else @@ -2599,9 +2592,9 @@ var rootElement = section.propertiesTreeOutline.rootElement(); if (moveDirection === 'forward' && blankInput && !isEditingName) --moveToIndex; - if (moveToIndex >= rootElement.childCount() && !this._newProperty) + if (moveToIndex >= rootElement.childCount() && !this._newProperty) { createNewProperty = true; - else { + } else { var treeElement = moveToIndex >= 0 ? rootElement.childAt(moveToIndex) : null; if (treeElement) { var elementToEdit = @@ -2610,8 +2603,9 @@ elementToEdit = moveDirection === 'forward' ? treeElement.nameElement : treeElement.valueElement; treeElement.startEditing(elementToEdit); return; - } else if (!alreadyNew) + } else if (!alreadyNew) { moveToSelector = true; + } } } @@ -2769,14 +2763,15 @@ // If a CSS value is being edited that has a numeric or hex substring, hint that precision modifier shortcuts are available. if (treeElement && treeElement.valueElement) { var cssValueText = treeElement.valueElement.textContent; - if (cssValueText.match(/#[\da-f]{3,6}$/i)) + if (cssValueText.match(/#[\da-f]{3,6}$/i)) { this.setTitle(Common.UIString( 'Increment/decrement with mousewheel or up/down keys. %s: R ±1, Shift: G ±1, Alt: B ±1', Host.isMac() ? 'Cmd' : 'Ctrl')); - else if (cssValueText.match(/\d+/)) + } else if (cssValueText.match(/\d+/)) { this.setTitle(Common.UIString( 'Increment/decrement with mousewheel or up/down keys. %s: ±100, Shift: ±10, Alt: ±0.1', Host.isMac() ? 'Cmd' : 'Ctrl')); + } } } } @@ -2855,8 +2850,7 @@ * @this {Elements.StylesSidebarPane.CSSPropertyPrompt} */ function customNumberHandler(prefix, number, suffix) { - if (number !== 0 && !suffix.length && - SDK.cssMetadata().isLengthProperty(this._treeElement.property.name)) + if (number !== 0 && !suffix.length && SDK.cssMetadata().isLengthProperty(this._treeElement.property.name)) suffix = 'px'; return prefix + number + suffix; }
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/computedStyleSidebarPane.css b/third_party/WebKit/Source/devtools/front_end/elements/computedStyleSidebarPane.css index 4265c68b..0a8ac3c 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/computedStyleSidebarPane.css +++ b/third_party/WebKit/Source/devtools/front_end/elements/computedStyleSidebarPane.css
@@ -43,15 +43,10 @@ } .goto-source-icon { - -webkit-mask-image: url(Images/toolbarButtonGlyphs.png); - -webkit-mask-position: 0 -120px; background-color: #5a5a5a; - width: 28px; - height: 24px; display: none; position: absolute; - top: -6px; - left: -27px; + left: -16px; } .goto-source-icon:hover {
diff --git a/third_party/WebKit/Source/devtools/front_end/emulation/DeviceModeModel.js b/third_party/WebKit/Source/devtools/front_end/emulation/DeviceModeModel.js index 2fe860e..acea052b 100644 --- a/third_party/WebKit/Source/devtools/front_end/emulation/DeviceModeModel.js +++ b/third_party/WebKit/Source/devtools/front_end/emulation/DeviceModeModel.js
@@ -404,12 +404,13 @@ var outline = this._currentOutline(); var insets = this._currentInsets(); this._fitScale = this._calculateFitScale(orientation.width, orientation.height, outline, insets); - if (this._device.mobile()) - this._appliedUserAgentType = this._device.touch() ? Emulation.DeviceModeModel.UA.Mobile : - Emulation.DeviceModeModel.UA.MobileNoTouch; - else - this._appliedUserAgentType = this._device.touch() ? Emulation.DeviceModeModel.UA.DesktopTouch : - Emulation.DeviceModeModel.UA.Desktop; + if (this._device.mobile()) { + this._appliedUserAgentType = + this._device.touch() ? Emulation.DeviceModeModel.UA.Mobile : Emulation.DeviceModeModel.UA.MobileNoTouch; + } else { + this._appliedUserAgentType = + this._device.touch() ? Emulation.DeviceModeModel.UA.DesktopTouch : Emulation.DeviceModeModel.UA.Desktop; + } this._applyDeviceMetrics( new Size(orientation.width, orientation.height), insets, outline, this._scaleSetting.get(), this._device.deviceScaleFactor, this._device.mobile(), @@ -630,6 +631,5 @@ Emulation.DeviceModeModel._defaultMobileUserAgent = 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36'; Emulation.DeviceModeModel._defaultMobileUserAgent = - SDK.MultitargetNetworkManager.patchUserAgentWithChromeVersion( - Emulation.DeviceModeModel._defaultMobileUserAgent); + SDK.MultitargetNetworkManager.patchUserAgentWithChromeVersion(Emulation.DeviceModeModel._defaultMobileUserAgent); Emulation.DeviceModeModel.defaultMobileScaleFactor = 2;
diff --git a/third_party/WebKit/Source/devtools/front_end/emulation/DeviceModeToolbar.js b/third_party/WebKit/Source/devtools/front_end/emulation/DeviceModeToolbar.js index 3d97de2..a658424 100644 --- a/third_party/WebKit/Source/devtools/front_end/emulation/DeviceModeToolbar.js +++ b/third_party/WebKit/Source/devtools/front_end/emulation/DeviceModeToolbar.js
@@ -85,8 +85,8 @@ widthInput.maxLength = 4; widthInput.type = 'text'; widthInput.title = Common.UIString('Width'); - this._updateWidthInput = UI.bindInput( - widthInput, this._applyWidth.bind(this), Emulation.DeviceModeModel.deviceSizeValidator, true); + this._updateWidthInput = + UI.bindInput(widthInput, this._applyWidth.bind(this), Emulation.DeviceModeModel.deviceSizeValidator, true); this._widthInput = widthInput; this._widthItem = this._wrapToolbarItem(widthInput); toolbar.appendToolbarItem(this._widthItem); @@ -282,20 +282,17 @@ _appendOptionsMenuItems(contextMenu) { var model = this._model; appendToggleItem( - this._deviceOutlineSetting, Common.UIString('Hide device frame'), - Common.UIString('Show device frame'), model.type() !== Emulation.DeviceModeModel.Type.Device); + this._deviceOutlineSetting, Common.UIString('Hide device frame'), Common.UIString('Show device frame'), + model.type() !== Emulation.DeviceModeModel.Type.Device); appendToggleItem( - this._showMediaInspectorSetting, Common.UIString('Hide media queries'), - Common.UIString('Show media queries')); - appendToggleItem( - this._showRulersSetting, Common.UIString('Hide rulers'), Common.UIString('Show rulers')); + this._showMediaInspectorSetting, Common.UIString('Hide media queries'), Common.UIString('Show media queries')); + appendToggleItem(this._showRulersSetting, Common.UIString('Hide rulers'), Common.UIString('Show rulers')); contextMenu.appendSeparator(); appendToggleItem( this._showDeviceScaleFactorSetting, Common.UIString('Remove device pixel ratio'), Common.UIString('Add device pixel ratio')); appendToggleItem( - this._showUserAgentTypeSetting, Common.UIString('Remove device type'), - Common.UIString('Add device type')); + this._showUserAgentTypeSetting, Common.UIString('Remove device type'), Common.UIString('Add device type')); appendToggleItem( this._showNetworkConditionsSetting, Common.UIString('Remove network throttling'), Common.UIString('Add network throttling')); @@ -395,8 +392,8 @@ appendGroup.call(this, this._customDevices()); contextMenu.appendSeparator(); contextMenu.appendItem( - Common.UIString('Edit\u2026'), - this._emulatedDevicesList.revealCustomSetting.bind(this._emulatedDevicesList), false); + Common.UIString('Edit\u2026'), this._emulatedDevicesList.revealCustomSetting.bind(this._emulatedDevicesList), + false); /** * @param {!Array<!Emulation.EmulatedDevice>} devices @@ -406,9 +403,10 @@ if (!devices.length) return; contextMenu.appendSeparator(); - for (var device of devices) + for (var device of devices) { contextMenu.appendCheckboxItem( device.title, this._emulateDevice.bind(this, device), this._model.device() === device, false); + } } } @@ -546,16 +544,16 @@ if (device) { var modeCount = device ? device.modes.length : 0; this._modeButton.setEnabled(modeCount >= 2); - this._modeButton.setTitle( - modeCount === 2 ? Common.UIString('Rotate') : Common.UIString('Screen options')); + this._modeButton.setTitle(modeCount === 2 ? Common.UIString('Rotate') : Common.UIString('Screen options')); } this._cachedModelDevice = device; } - if (this._model.type() === Emulation.DeviceModeModel.Type.Device) + if (this._model.type() === Emulation.DeviceModeModel.Type.Device) { this._lastMode.set( /** @type {!Emulation.EmulatedDevice} */ (this._model.device()), /** @type {!Emulation.EmulatedDevice.Mode} */ (this._model.mode())); + } if (this._model.mode() !== this._cachedModelMode && this._model.type() !== Emulation.DeviceModeModel.Type.None) { this._cachedModelMode = this._model.mode();
diff --git a/third_party/WebKit/Source/devtools/front_end/emulation/DeviceModeView.js b/third_party/WebKit/Source/devtools/front_end/emulation/DeviceModeView.js index 411b20b..e79a21f 100644 --- a/third_party/WebKit/Source/devtools/front_end/emulation/DeviceModeView.js +++ b/third_party/WebKit/Source/devtools/front_end/emulation/DeviceModeView.js
@@ -22,8 +22,7 @@ this._topRuler = new Emulation.DeviceModeView.Ruler(true, this._model.setWidthAndScaleToFit.bind(this._model)); this._topRuler.element.classList.add('device-mode-ruler-top'); - this._leftRuler = - new Emulation.DeviceModeView.Ruler(false, this._model.setHeightAndScaleToFit.bind(this._model)); + this._leftRuler = new Emulation.DeviceModeView.Ruler(false, this._model.setHeightAndScaleToFit.bind(this._model)); this._leftRuler.element.classList.add('device-mode-ruler-left'); this._createUI(); UI.zoomManager.addEventListener(UI.ZoomManager.Events.ZoomChanged, this._zoomChanged, this); @@ -80,9 +79,8 @@ _populatePresetsContainer() { var sizes = [320, 375, 425, 768, 1024, 1440, 2560]; var titles = [ - Common.UIString('Mobile S'), Common.UIString('Mobile M'), Common.UIString('Mobile L'), - Common.UIString('Tablet'), Common.UIString('Laptop'), Common.UIString('Laptop L'), - Common.UIString('4K') + Common.UIString('Mobile S'), Common.UIString('Mobile M'), Common.UIString('Mobile L'), Common.UIString('Tablet'), + Common.UIString('Laptop'), Common.UIString('Laptop L'), Common.UIString('4K') ]; this._presetBlocks = []; var inner = this._responsivePresetsContainer.createChild('div', 'device-mode-presets-container-inner'); @@ -160,8 +158,7 @@ var dipOffsetX = cssOffsetX * UI.zoomManager.zoomFactor(); var newWidth = this._resizeStart.width + dipOffsetX * widthFactor; newWidth = Math.round(newWidth / this._model.scale()); - if (newWidth >= Emulation.DeviceModeModel.MinDeviceSize && - newWidth <= Emulation.DeviceModeModel.MaxDeviceSize) + if (newWidth >= Emulation.DeviceModeModel.MinDeviceSize && newWidth <= Emulation.DeviceModeModel.MaxDeviceSize) this._model.setWidth(newWidth); } @@ -169,8 +166,7 @@ var dipOffsetY = cssOffsetY * UI.zoomManager.zoomFactor(); var newHeight = this._resizeStart.height + dipOffsetY * heightFactor; newHeight = Math.round(newHeight / this._model.scale()); - if (newHeight >= Emulation.DeviceModeModel.MinDeviceSize && - newHeight <= Emulation.DeviceModeModel.MaxDeviceSize) + if (newHeight >= Emulation.DeviceModeModel.MinDeviceSize && newHeight <= Emulation.DeviceModeModel.MaxDeviceSize) this._model.setHeight(newHeight); } }
diff --git a/third_party/WebKit/Source/devtools/front_end/emulation/DevicesSettingsTab.js b/third_party/WebKit/Source/devtools/front_end/emulation/DevicesSettingsTab.js index 945fac6..7ab55da 100644 --- a/third_party/WebKit/Source/devtools/front_end/emulation/DevicesSettingsTab.js +++ b/third_party/WebKit/Source/devtools/front_end/emulation/DevicesSettingsTab.js
@@ -18,8 +18,7 @@ .createChild('div', 'settings-tab help-content help-container'); var buttonsRow = this.containerElement.createChild('div', 'devices-button-row'); - this._addCustomButton = - createTextButton(Common.UIString('Add custom device...'), this._addCustomDevice.bind(this)); + this._addCustomButton = createTextButton(Common.UIString('Add custom device...'), this._addCustomDevice.bind(this)); buttonsRow.appendChild(this._addCustomButton); this._list = new UI.ListWidget(this);
diff --git a/third_party/WebKit/Source/devtools/front_end/emulation/EmulatedDevices.js b/third_party/WebKit/Source/devtools/front_end/emulation/EmulatedDevices.js index 397be0be..9178966 100644 --- a/third_party/WebKit/Source/devtools/front_end/emulation/EmulatedDevices.js +++ b/third_party/WebKit/Source/devtools/front_end/emulation/EmulatedDevices.js
@@ -144,9 +144,9 @@ mode.insets = parseInsets(parseValue(modes[i], 'insets', 'object')); if (mode.insets.top < 0 || mode.insets.left < 0 || mode.insets.right < 0 || mode.insets.bottom < 0 || mode.insets.top + mode.insets.bottom > orientation.height || - mode.insets.left + mode.insets.right > orientation.width) { + mode.insets.left + mode.insets.right > orientation.width) throw new Error('Emulated device mode \'' + mode.title + '\'has wrong mode insets'); - } + mode.image = /** @type {string} */ (parseValue(modes[i], 'image', 'string', null)); result.modes.push(mode); } @@ -423,12 +423,8 @@ insets: new Insets(0, 0, 0, 0), image: null }); - device.modes.push({ - title: '', - orientation: Emulation.EmulatedDevice.Vertical, - insets: new Insets(0, 0, 0, 0), - image: null - }); + device.modes.push( + {title: '', orientation: Emulation.EmulatedDevice.Vertical, insets: new Insets(0, 0, 0, 0), image: null}); } } else { success = false;
diff --git a/third_party/WebKit/Source/devtools/front_end/emulation/Geolocation.js b/third_party/WebKit/Source/devtools/front_end/emulation/Geolocation.js index e977fd5..c3612403 100644 --- a/third_party/WebKit/Source/devtools/front_end/emulation/Geolocation.js +++ b/third_party/WebKit/Source/devtools/front_end/emulation/Geolocation.js
@@ -25,8 +25,7 @@ if (splitError.length === 2) { var splitPosition = splitError[0].split('@'); if (splitPosition.length === 2) - return new Emulation.Geolocation( - parseFloat(splitPosition[0]), parseFloat(splitPosition[1]), splitError[1]); + return new Emulation.Geolocation(parseFloat(splitPosition[0]), parseFloat(splitPosition[1]), splitError[1]); } } return new Emulation.Geolocation(0, 0, false); @@ -82,11 +81,12 @@ apply() { for (var target of SDK.targetManager.targets(SDK.Target.Capability.Browser)) { - if (this.error) + if (this.error) { target.emulationAgent().setGeolocationOverride(); - else + } else { target.emulationAgent().setGeolocationOverride( this.latitude, this.longitude, Emulation.Geolocation.DefaultMockAccuracy); + } } }
diff --git a/third_party/WebKit/Source/devtools/front_end/emulation/MediaQueryInspector.js b/third_party/WebKit/Source/devtools/front_end/emulation/MediaQueryInspector.js index 04a2cfb..8692e9d 100644 --- a/third_party/WebKit/Source/devtools/front_end/emulation/MediaQueryInspector.js +++ b/third_party/WebKit/Source/devtools/front_end/emulation/MediaQueryInspector.js
@@ -23,8 +23,7 @@ this._scale = 1; SDK.targetManager.observeTargets(this); - UI.zoomManager.addEventListener( - UI.ZoomManager.Events.ZoomChanged, this._renderMediaQueries.bind(this), this); + UI.zoomManager.addEventListener(UI.ZoomManager.Events.ZoomChanged, this._renderMediaQueries.bind(this), this); } /** @@ -38,12 +37,9 @@ this._cssModel = SDK.CSSModel.fromTarget(target); if (!this._cssModel) return; - this._cssModel.addEventListener( - SDK.CSSModel.Events.StyleSheetAdded, this._scheduleMediaQueriesUpdate, this); - this._cssModel.addEventListener( - SDK.CSSModel.Events.StyleSheetRemoved, this._scheduleMediaQueriesUpdate, this); - this._cssModel.addEventListener( - SDK.CSSModel.Events.StyleSheetChanged, this._scheduleMediaQueriesUpdate, this); + this._cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetAdded, this._scheduleMediaQueriesUpdate, this); + this._cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetRemoved, this._scheduleMediaQueriesUpdate, this); + this._cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetChanged, this._scheduleMediaQueriesUpdate, this); this._cssModel.addEventListener( SDK.CSSModel.Events.MediaQueryResultChanged, this._scheduleMediaQueriesUpdate, this); } @@ -55,12 +51,9 @@ targetRemoved(target) { if (SDK.CSSModel.fromTarget(target) !== this._cssModel) return; - this._cssModel.removeEventListener( - SDK.CSSModel.Events.StyleSheetAdded, this._scheduleMediaQueriesUpdate, this); - this._cssModel.removeEventListener( - SDK.CSSModel.Events.StyleSheetRemoved, this._scheduleMediaQueriesUpdate, this); - this._cssModel.removeEventListener( - SDK.CSSModel.Events.StyleSheetChanged, this._scheduleMediaQueriesUpdate, this); + this._cssModel.removeEventListener(SDK.CSSModel.Events.StyleSheetAdded, this._scheduleMediaQueriesUpdate, this); + this._cssModel.removeEventListener(SDK.CSSModel.Events.StyleSheetRemoved, this._scheduleMediaQueriesUpdate, this); + this._cssModel.removeEventListener(SDK.CSSModel.Events.StyleSheetChanged, this._scheduleMediaQueriesUpdate, this); this._cssModel.removeEventListener( SDK.CSSModel.Events.MediaQueryResultChanged, this._scheduleMediaQueriesUpdate, this); delete this._cssModel; @@ -128,8 +121,7 @@ for (var i = 0; i < contextMenuItems.length; ++i) { var title = contextMenuItems[i]; subMenuItem.appendItem( - title, - this._revealSourceLocation.bind(this, /** @type {!Workspace.UILocation} */ (uiLocations.get(title)))); + title, this._revealSourceLocation.bind(this, /** @type {!Workspace.UILocation} */ (uiLocations.get(title)))); } contextMenu.show(); }
diff --git a/third_party/WebKit/Source/devtools/front_end/emulation/SensorsView.js b/third_party/WebKit/Source/devtools/front_end/emulation/SensorsView.js index 73e1821..416ba44 100644 --- a/third_party/WebKit/Source/devtools/front_end/emulation/SensorsView.js +++ b/third_party/WebKit/Source/devtools/front_end/emulation/SensorsView.js
@@ -80,8 +80,7 @@ this._latitudeInput.setAttribute('type', 'number'); this._latitudeInput.value = 0; this._latitudeSetter = UI.bindInput( - this._latitudeInput, this._applyGeolocationUserInput.bind(this), Emulation.Geolocation.latitudeValidator, - true); + this._latitudeInput, this._applyGeolocationUserInput.bind(this), Emulation.Geolocation.latitudeValidator, true); this._latitudeSetter(String(geolocation.latitude)); this._longitudeInput = longitudeGroup.createChild('input'); @@ -121,8 +120,8 @@ } _applyGeolocationUserInput() { - var geolocation = Emulation.Geolocation.parseUserInput( - this._latitudeInput.value.trim(), this._longitudeInput.value.trim(), ''); + var geolocation = + Emulation.Geolocation.parseUserInput(this._latitudeInput.value.trim(), this._longitudeInput.value.trim(), ''); if (!geolocation) return; @@ -467,10 +466,9 @@ }, { title: 'Error', - value: [{ - title: Common.UIString('Location unavailable'), - location: Emulation.SensorsView.NonPresetOptions.Unavailable - }] + value: [ + {title: Common.UIString('Location unavailable'), location: Emulation.SensorsView.NonPresetOptions.Unavailable} + ] } ];
diff --git a/third_party/WebKit/Source/devtools/front_end/emulation/TouchModel.js b/third_party/WebKit/Source/devtools/front_end/emulation/TouchModel.js index 6fbeeb7..0cd5d3b 100644 --- a/third_party/WebKit/Source/devtools/front_end/emulation/TouchModel.js +++ b/third_party/WebKit/Source/devtools/front_end/emulation/TouchModel.js
@@ -67,9 +67,10 @@ var recepients = [window.__proto__, document.__proto__]; for (var i = 0; i < touchEvents.length; ++i) { for (var j = 0; j < recepients.length; ++j) { - if (!(touchEvents[i] in recepients[j])) + if (!(touchEvents[i] in recepients[j])) { Object.defineProperty( recepients[j], touchEvents[i], {value: null, writable: true, configurable: true, enumerable: true}); + } } } }; @@ -128,8 +129,7 @@ targetRemoved(target) { var domModel = SDK.DOMModel.fromTarget(target); if (domModel) - domModel.removeEventListener( - SDK.DOMModel.Events.InspectModeWillBeToggled, this._inspectModeToggled, this); + domModel.removeEventListener(SDK.DOMModel.Events.InspectModeWillBeToggled, this._inspectModeToggled, this); } };
diff --git a/third_party/WebKit/Source/devtools/front_end/extensions/ExtensionAPI.js b/third_party/WebKit/Source/devtools/front_end/extensions/ExtensionAPI.js index c8dc978b..12251be 100644 --- a/third_party/WebKit/Source/devtools/front_end/extensions/ExtensionAPI.js +++ b/third_party/WebKit/Source/devtools/front_end/extensions/ExtensionAPI.js
@@ -522,9 +522,10 @@ */ addCategory: function(displayName, resultCount) { var id = 'extension-audit-category-' + extensionServer.nextObjectId(); - if (typeof resultCount !== 'undefined') + if (typeof resultCount !== 'undefined') { console.warn( 'Passing resultCount to audits.addCategory() is deprecated. Use AuditResult.updateProgress() instead.'); + } extensionServer.sendRequest( {command: commands.AddAuditCategory, id: id, displayName: displayName, resultCount: resultCount}); return new AuditCategory(id);
diff --git a/third_party/WebKit/Source/devtools/front_end/extensions/ExtensionServer.js b/third_party/WebKit/Source/devtools/front_end/extensions/ExtensionServer.js index cc63880..4b6bcc63 100644 --- a/third_party/WebKit/Source/devtools/front_end/extensions/ExtensionServer.js +++ b/third_party/WebKit/Source/devtools/front_end/extensions/ExtensionServer.js
@@ -200,9 +200,9 @@ _onSubscribe(message, port) { var subscribers = this._subscribers[message.type]; - if (subscribers) + if (subscribers) { subscribers.push(port); - else { + } else { this._subscribers[message.type] = [port]; if (this._subscriptionStartHandlers[message.type]) this._subscriptionStartHandlers[message.type](); @@ -349,9 +349,10 @@ var result = error ? this._status.E_FAILED(error) : this._status.OK(); this._dispatchCallback(message.requestId, port, result); } - if (message.evaluateOnPage) + if (message.evaluateOnPage) { return sidebar.setExpression( message.expression, message.rootTitle, message.evaluateOptions, port._extensionOrigin, callback.bind(this)); + } sidebar.setObject(message.expression, message.rootTitle, callback.bind(this)); } @@ -408,8 +409,7 @@ _onReload(message) { var options = /** @type {!ExtensionReloadOptions} */ (message.options || {}); - SDK.multitargetNetworkManager.setUserAgentOverride( - typeof options.userAgent === 'string' ? options.userAgent : ''); + SDK.multitargetNetworkManager.setUserAgentOverride(typeof options.userAgent === 'string' ? options.userAgent : ''); var injectedScript; if (options.injectedScript) injectedScript = '(function(){' + options.injectedScript + '})()'; @@ -469,8 +469,8 @@ resources.set(contentProvider.contentURL(), this._makeResource(contentProvider)); } var uiSourceCodes = Workspace.workspace.uiSourceCodesForProjectType(Workspace.projectTypes.Network); - uiSourceCodes = uiSourceCodes.concat( - Workspace.workspace.uiSourceCodesForProjectType(Workspace.projectTypes.ContentScripts)); + uiSourceCodes = + uiSourceCodes.concat(Workspace.workspace.uiSourceCodesForProjectType(Workspace.projectTypes.ContentScripts)); uiSourceCodes.forEach(pushResourceData.bind(this)); for (var target of SDK.targetManager.targets(SDK.Target.Capability.DOM)) SDK.ResourceTreeModel.fromTarget(target).forAllResources(pushResourceData.bind(this)); @@ -654,8 +654,8 @@ _initExtensions() { this._registerAutosubscriptionHandler( - Extensions.extensionAPI.Events.ResourceAdded, Workspace.workspace, - Workspace.Workspace.Events.UISourceCodeAdded, this._notifyResourceAdded); + Extensions.extensionAPI.Events.ResourceAdded, Workspace.workspace, Workspace.Workspace.Events.UISourceCodeAdded, + this._notifyResourceAdded); this._registerAutosubscriptionTargetManagerHandler( Extensions.extensionAPI.Events.NetworkRequestFinished, SDK.NetworkManager, SDK.NetworkManager.Events.RequestFinished, this._notifyRequestFinished); @@ -679,8 +679,7 @@ onElementsSubscriptionStopped.bind(this)); this._registerResourceContentCommittedHandler(this._notifyUISourceCodeContentCommitted); - SDK.targetManager.addEventListener( - SDK.TargetManager.Events.InspectedURLChanged, this._inspectedURLChanged, this); + SDK.targetManager.addEventListener(SDK.TargetManager.Events.InspectedURLChanged, this._inspectedURLChanged, this); InspectorExtensionRegistry.getExtensionsAsync(); } @@ -823,10 +822,9 @@ */ _registerAutosubscriptionTargetManagerHandler(eventTopic, modelClass, frontendEventType, handler) { this._registerSubscriptionHandler( - eventTopic, SDK.targetManager.addModelListener.bind( - SDK.targetManager, modelClass, frontendEventType, handler, this), - SDK.targetManager.removeModelListener.bind( - SDK.targetManager, modelClass, frontendEventType, handler, this)); + eventTopic, + SDK.targetManager.addModelListener.bind(SDK.targetManager, modelClass, frontendEventType, handler, this), + SDK.targetManager.removeModelListener.bind(SDK.targetManager, modelClass, frontendEventType, handler, this)); } _registerResourceContentCommittedHandler(handler) { @@ -843,8 +841,7 @@ */ function removeLastEventListener() { Workspace.workspace.setHasResourceContentTrackingExtensions(false); - Workspace.workspace.removeEventListener( - Workspace.Workspace.Events.WorkingCopyCommittedByUser, handler, this); + Workspace.workspace.removeEventListener(Workspace.Workspace.Events.WorkingCopyCommittedByUser, handler, this); } this._registerSubscriptionHandler(
diff --git a/third_party/WebKit/Source/devtools/front_end/formatter_worker/HTMLFormatter.js b/third_party/WebKit/Source/devtools/front_end/formatter_worker/HTMLFormatter.js index 8a34442..f9441f6 100644 --- a/third_party/WebKit/Source/devtools/front_end/formatter_worker/HTMLFormatter.js +++ b/third_party/WebKit/Source/devtools/front_end/formatter_worker/HTMLFormatter.js
@@ -183,7 +183,8 @@ while (this._stack.length > 1) { var element = this._stack.peekLast(); - this._popElement(new FormatterWorker.HTMLModel.Tag(element.name, text.length, text.length, new Map(), false, false)); + this._popElement( + new FormatterWorker.HTMLModel.Tag(element.name, text.length, text.length, new Map(), false, false)); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/formatter_worker/JavaScriptOutline.js b/third_party/WebKit/Source/devtools/front_end/formatter_worker/JavaScriptOutline.js index f4f1d70..f3a6c1b 100644 --- a/third_party/WebKit/Source/devtools/front_end/formatter_worker/JavaScriptOutline.js +++ b/third_party/WebKit/Source/devtools/front_end/formatter_worker/JavaScriptOutline.js
@@ -52,10 +52,11 @@ }; addedFunction = true; previousIdentifier = null; - } else if (AT.punctuator(token, '.') && previousToken && AT.identifier(previousToken)) + } else if (AT.punctuator(token, '.') && previousToken && AT.identifier(previousToken)) { previousIdentifier += '.'; - else if (AT.punctuator(token, '(') && addedFunction) + } else if (AT.punctuator(token, '(') && addedFunction) { isReadingArguments = true; + } if (isReadingArguments && tokenValue) argumentsText += tokenValue;
diff --git a/third_party/WebKit/Source/devtools/front_end/heap_snapshot_worker/AllocationProfile.js b/third_party/WebKit/Source/devtools/front_end/heap_snapshot_worker/AllocationProfile.js index f7e543a2..f088fed 100644 --- a/third_party/WebKit/Source/devtools/front_end/heap_snapshot_worker/AllocationProfile.js +++ b/third_party/WebKit/Source/devtools/front_end/heap_snapshot_worker/AllocationProfile.js
@@ -96,9 +96,9 @@ functionInfo.addTraceTopNode(result); var rawChildren = rawNodeArray[nodeOffset + childrenOffset]; - for (var i = 0; i < rawChildren.length; i += nodeFieldCount) { + for (var i = 0; i < rawChildren.length; i += nodeFieldCount) result.children.push(traverseNode(rawChildren, i, result)); - } + return result; } @@ -143,9 +143,9 @@ var branchingCallers = []; var callers = node.callers(); - for (var i = 0; i < callers.length; i++) { + for (var i = 0; i < callers.length; i++) branchingCallers.push(this._serializeCaller(callers[i])); - } + return new Profiler.HeapSnapshotCommon.AllocationNodeCallers(nodesWithSingleCaller, branchingCallers); } @@ -362,9 +362,9 @@ bottomUpNode.liveSize += liveSize; bottomUpNode.traceTopIds.push(traceId); node = node.parent; - if (node === null) { + if (node === null) break; - } + bottomUpNode = bottomUpNode.addCaller(node); } }
diff --git a/third_party/WebKit/Source/devtools/front_end/heap_snapshot_worker/HeapSnapshot.js b/third_party/WebKit/Source/devtools/front_end/heap_snapshot_worker/HeapSnapshot.js index 38b0cacc..f809a427 100644 --- a/third_party/WebKit/Source/devtools/front_end/heap_snapshot_worker/HeapSnapshot.js +++ b/third_party/WebKit/Source/devtools/front_end/heap_snapshot_worker/HeapSnapshot.js
@@ -737,9 +737,8 @@ } _skipFilteredItems() { - while (this._iterator.hasNext() && !this._filter(this._iterator.item())) { + while (this._iterator.hasNext() && !this._filter(this._iterator.item())) this._iterator.next(); - } } }; @@ -1347,9 +1346,10 @@ nodesToVisit[nodesToVisitLength++] = childNodeIndex; } } - if (nodesToVisitLength > nodeCount) + if (nodesToVisitLength > nodeCount) { throw new Error( 'BFS failed. Nodes to visit (' + nodesToVisitLength + ') is more than nodes count (' + nodeCount + ')'); + } } _buildAggregates(filter) { @@ -1461,12 +1461,13 @@ _sortAggregateIndexes(aggregates) { var nodeA = this.createNode(); var nodeB = this.createNode(); - for (var clss in aggregates) + for (var clss in aggregates) { aggregates[clss].idxs.sort(function(idxA, idxB) { nodeA.nodeIndex = idxA; nodeB.nodeIndex = idxB; return nodeA.id() < nodeB.id() ? -1 : 1; }); + } } /** @@ -1704,9 +1705,9 @@ continue; var retanerPostOrderIndex = nodeOrdinal2PostOrderIndex[retainerNodeOrdinal]; if (dominators[retanerPostOrderIndex] !== noEntry) { - if (newDominatorIndex === noEntry) + if (newDominatorIndex === noEntry) { newDominatorIndex = retanerPostOrderIndex; - else { + } else { while (retanerPostOrderIndex !== newDominatorIndex) { while (retanerPostOrderIndex < newDominatorIndex) retanerPostOrderIndex = dominators[retanerPostOrderIndex]; @@ -2315,9 +2316,10 @@ var indexProvider = new HeapSnapshotWorker.HeapSnapshotNodeIndexProvider(snapshot); var it = new HeapSnapshotWorker.HeapSnapshotIndexRangeIterator(indexProvider, nodeIndexes); - if (filter) + if (filter) { it = new HeapSnapshotWorker.HeapSnapshotFilteredIterator( it, /** @type {function(!HeapSnapshotWorker.HeapSnapshotItem):boolean} */ (filter)); + } super(it, indexProvider); this.snapshot = snapshot; }
diff --git a/third_party/WebKit/Source/devtools/front_end/heap_snapshot_worker/HeapSnapshotLoader.js b/third_party/WebKit/Source/devtools/front_end/heap_snapshot_worker/HeapSnapshotLoader.js index a244d2cc..294e5375 100644 --- a/third_party/WebKit/Source/devtools/front_end/heap_snapshot_worker/HeapSnapshotLoader.js +++ b/third_party/WebKit/Source/devtools/front_end/heap_snapshot_worker/HeapSnapshotLoader.js
@@ -72,9 +72,9 @@ while (true) { while (index < length) { var code = this._json.charCodeAt(index); - if (char0 <= code && code <= char9) + if (char0 <= code && code <= char9) { break; - else if (code === closingBracket) { + } else if (code === closingBracket) { this._json = this._json.slice(index + 1); return false; }
diff --git a/third_party/WebKit/Source/devtools/front_end/heap_snapshot_worker/JSHeapSnapshot.js b/third_party/WebKit/Source/devtools/front_end/heap_snapshot_worker/JSHeapSnapshot.js index c4b0e547..b957343 100644 --- a/third_party/WebKit/Source/devtools/front_end/heap_snapshot_worker/JSHeapSnapshot.js +++ b/third_party/WebKit/Source/devtools/front_end/heap_snapshot_worker/JSHeapSnapshot.js
@@ -339,8 +339,9 @@ node.nodeIndex = nodeIndex; if (!node.isDocumentDOMTreesRoot()) continue; - } else if (edgeType !== edgeShortcutType) + } else if (edgeType !== edgeShortcutType) { continue; + } var nodeOrdinal = nodeIndex / nodeFieldCount; nodesToVisit[nodesToVisitLength++] = nodeOrdinal; flags[nodeOrdinal] |= pageObjectFlag;
diff --git a/third_party/WebKit/Source/devtools/front_end/layer_viewer/LayerDetailsView.js b/third_party/WebKit/Source/devtools/front_end/layer_viewer/LayerDetailsView.js index 43892b3..291035d 100644 --- a/third_party/WebKit/Source/devtools/front_end/layer_viewer/LayerDetailsView.js +++ b/third_party/WebKit/Source/devtools/front_end/layer_viewer/LayerDetailsView.js
@@ -192,8 +192,8 @@ 'canvas': Common.UIString('Composition due to the element being a <canvas> element.'), 'plugin': Common.UIString('Composition due to association with a plugin.'), 'iFrame': Common.UIString('Composition due to association with an <iframe> element.'), - 'backfaceVisibilityHidden': Common.UIString( - 'Composition due to association with an element with a "backface-visibility: hidden" style.'), + 'backfaceVisibilityHidden': + Common.UIString('Composition due to association with an element with a "backface-visibility: hidden" style.'), 'animation': Common.UIString('Composition due to association with an animated element.'), 'filters': Common.UIString('Composition due to association with an element with CSS filters applied.'), 'scrollDependentPosition': Common.UIString( @@ -202,20 +202,19 @@ Common.UIString('Composition due to association with an element with a "overflow-scrolling: touch" style.'), 'blending': Common.UIString('Composition due to association with an element that has blend mode other than "normal".'), - 'assumedOverlap': Common.UIString( - 'Composition due to association with an element that may overlap other composited elements.'), - 'overlap': - Common.UIString('Composition due to association with an element overlapping other composited elements.'), - 'negativeZIndexChildren': Common.UIString( - 'Composition due to association with an element with descendants that have a negative z-index.'), + 'assumedOverlap': + Common.UIString('Composition due to association with an element that may overlap other composited elements.'), + 'overlap': Common.UIString('Composition due to association with an element overlapping other composited elements.'), + 'negativeZIndexChildren': + Common.UIString('Composition due to association with an element with descendants that have a negative z-index.'), 'transformWithCompositedDescendants': Common.UIString('Composition due to association with an element with composited descendants.'), 'opacityWithCompositedDescendants': Common.UIString( 'Composition due to association with an element with opacity applied and composited descendants.'), 'maskWithCompositedDescendants': Common.UIString('Composition due to association with a masked element and composited descendants.'), - 'reflectionWithCompositedDescendants': Common.UIString( - 'Composition due to association with an element with a reflection and composited descendants.'), + 'reflectionWithCompositedDescendants': + Common.UIString('Composition due to association with an element with a reflection and composited descendants.'), 'filterWithCompositedDescendants': Common.UIString( 'Composition due to association with an element with CSS filters applied and composited descendants.'), 'blendingWithCompositedDescendants': Common.UIString( @@ -223,8 +222,8 @@ 'clipsCompositingDescendants': Common.UIString('Composition due to association with an element clipping compositing descendants.'), 'perspective': Common.UIString('Composition due to association with an element with perspective applied.'), - 'preserve3D': Common.UIString( - 'Composition due to association with an element with a "transform-style: preserve-3d" style.'), + 'preserve3D': + Common.UIString('Composition due to association with an element with a "transform-style: preserve-3d" style.'), 'root': Common.UIString('Root layer.'), 'layerForClip': Common.UIString('Layer for clip.'), 'layerForScrollbar': Common.UIString('Layer for scrollbar.'),
diff --git a/third_party/WebKit/Source/devtools/front_end/layer_viewer/LayerTreeOutline.js b/third_party/WebKit/Source/devtools/front_end/layer_viewer/LayerTreeOutline.js index eefff7a..8a650cb 100644 --- a/third_party/WebKit/Source/devtools/front_end/layer_viewer/LayerTreeOutline.js +++ b/third_party/WebKit/Source/devtools/front_end/layer_viewer/LayerTreeOutline.js
@@ -120,8 +120,7 @@ // Skip till nearest visible ancestor. while (parentLayer && parentLayer !== root && !parentLayer.drawsContent() && !showInternalLayers) parentLayer = parentLayer.parent(); - var parent = - layer === root ? this._treeOutline.rootElement() : parentLayer[LayerViewer.LayerTreeElement._symbol]; + var parent = layer === root ? this._treeOutline.rootElement() : parentLayer[LayerViewer.LayerTreeElement._symbol]; if (!parent) { console.assert(false, 'Parent is not in the tree'); return;
diff --git a/third_party/WebKit/Source/devtools/front_end/layer_viewer/Layers3DView.js b/third_party/WebKit/Source/devtools/front_end/layer_viewer/Layers3DView.js index fd7610d..90369d0 100644 --- a/third_party/WebKit/Source/devtools/front_end/layer_viewer/Layers3DView.js +++ b/third_party/WebKit/Source/devtools/front_end/layer_viewer/Layers3DView.js
@@ -266,8 +266,7 @@ var bounds; for (var i = 0; i < this._rects.length; ++i) - bounds = - Common.Geometry.boundsForTransformedPoints(scaleAndRotationMatrix, this._rects[i].vertices, bounds); + bounds = Common.Geometry.boundsForTransformedPoints(scaleAndRotationMatrix, this._rects[i].vertices, bounds); this._transformController.clampOffsets( (paddingX - bounds.maxX) / window.devicePixelRatio, @@ -544,8 +543,8 @@ if (!viewport) return; - var drawChrome = !Common.moduleSetting('frameViewerHideChromeWindow').get() && - this._chromeTextures.length >= 3 && this._chromeTextures.indexOf(undefined) < 0; + var drawChrome = !Common.moduleSetting('frameViewerHideChromeWindow').get() && this._chromeTextures.length >= 3 && + this._chromeTextures.indexOf(undefined) < 0; var z = (this._maxDepth + 1) * LayerViewer.Layers3DView.LayerSpacing; var borderWidth = Math.ceil(LayerViewer.Layers3DView.ViewportBorderWidth * this._scale); var vertices = [viewport.width, 0, z, viewport.width, viewport.height, z, 0, viewport.height, z, 0, 0, z]; @@ -565,7 +564,7 @@ var y = -chromeHeight; for (var i = 0; i < this._chromeTextures.length; ++i) { var width = i === LayerViewer.Layers3DView.ChromeTexture.Middle ? middleFragmentWidth : - this._chromeTextures[i].image.naturalWidth; + this._chromeTextures[i].image.naturalWidth; if (width < 0 || x + width > viewportWidth) break; vertices = [x, y, z, x + width, y, z, x + width, y + chromeHeight, z, x, y + chromeHeight, z]; @@ -694,15 +693,15 @@ _onContextMenu(event) { var contextMenu = new UI.ContextMenu(event); contextMenu.appendItem( - Common.UIString('Reset View'), this._transformController.resetAndNotify.bind(this._transformController), - false); + Common.UIString('Reset View'), this._transformController.resetAndNotify.bind(this._transformController), false); var selection = this._selectionFromEventPoint(event); - if (selection && selection.type() === LayerViewer.LayerView.Selection.Type.Snapshot) + if (selection && selection.type() === LayerViewer.LayerView.Selection.Type.Snapshot) { contextMenu.appendItem( Common.UIString('Show Paint Profiler'), this.dispatchEventToListeners.bind( this, LayerViewer.Layers3DView.Events.PaintProfilerRequested, selection.snapshot()), false); + } this._layerViewHost.showContextMenu(contextMenu, selection); } @@ -1109,10 +1108,10 @@ var i; // Vertices of the quad with transform matrix applied var points = []; - for (i = 0; i < 4; ++i) + for (i = 0; i < 4; ++i) { points[i] = Common.Geometry.multiplyVectorByMatrixAndNormalize( - new Common.Geometry.Vector(this.vertices[i * 3], this.vertices[i * 3 + 1], this.vertices[i * 3 + 2]), - matrix); + new Common.Geometry.Vector(this.vertices[i * 3], this.vertices[i * 3 + 1], this.vertices[i * 3 + 2]), matrix); + } // Calculating quad plane normal var normal = Common.Geometry.crossProduct( Common.Geometry.subtract(points[1], points[0]), Common.Geometry.subtract(points[2], points[1])); @@ -1182,10 +1181,8 @@ update(glContext, scale) { this._gl = glContext; this.scale = scale; - return this.snapshot.replay(null, null, scale) - .then(imageURL => imageURL && UI.loadImage(imageURL)) - .then(image => { - this.texture = image && LayerViewer.LayerTextureManager._createTextureForImage(glContext, image); - }); + return this.snapshot.replay(null, null, scale).then(imageURL => imageURL && UI.loadImage(imageURL)).then(image => { + this.texture = image && LayerViewer.LayerTextureManager._createTextureForImage(glContext, image); + }); } };
diff --git a/third_party/WebKit/Source/devtools/front_end/layer_viewer/TransformController.js b/third_party/WebKit/Source/devtools/front_end/layer_viewer/TransformController.js index f4125cf..821e50a 100644 --- a/third_party/WebKit/Source/devtools/front_end/layer_viewer/TransformController.js +++ b/third_party/WebKit/Source/devtools/front_end/layer_viewer/TransformController.js
@@ -36,8 +36,7 @@ panModeButton.addEventListener('click', this._setMode.bind(this, LayerViewer.TransformController.Modes.Pan)); this._modeButtons[LayerViewer.TransformController.Modes.Pan] = panModeButton; this._controlPanelToolbar.appendToolbarItem(panModeButton); - var rotateModeButton = - new UI.ToolbarToggle(Common.UIString('Rotate mode (V)'), 'largeicon-rotate'); + var rotateModeButton = new UI.ToolbarToggle(Common.UIString('Rotate mode (V)'), 'largeicon-rotate'); rotateModeButton.addEventListener( 'click', this._setMode.bind(this, LayerViewer.TransformController.Modes.Rotate)); this._modeButtons[LayerViewer.TransformController.Modes.Rotate] = rotateModeButton; @@ -45,8 +44,7 @@ } this._setMode(LayerViewer.TransformController.Modes.Pan); - var resetButton = - new UI.ToolbarButton(Common.UIString('Reset transform (0)'), 'largeicon-center'); + var resetButton = new UI.ToolbarButton(Common.UIString('Reset transform (0)'), 'largeicon-center'); resetButton.addEventListener('click', this.resetAndNotify.bind(this, undefined)); this._controlPanelToolbar.appendToolbarItem(resetButton); @@ -120,7 +118,7 @@ _toggleMode() { this._setMode( this._mode === LayerViewer.TransformController.Modes.Pan ? LayerViewer.TransformController.Modes.Rotate : - LayerViewer.TransformController.Modes.Pan); + LayerViewer.TransformController.Modes.Pan); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/layers/LayerTreeModel.js b/third_party/WebKit/Source/devtools/front_end/layers/LayerTreeModel.js index 38f5c91c..33b83c6 100644 --- a/third_party/WebKit/Source/devtools/front_end/layers/LayerTreeModel.js +++ b/third_party/WebKit/Source/devtools/front_end/layers/LayerTreeModel.js
@@ -35,8 +35,7 @@ constructor(target) { super(Layers.LayerTreeModel, target); target.registerLayerTreeDispatcher(new Layers.LayerTreeDispatcher(this)); - SDK.targetManager.addEventListener( - SDK.TargetManager.Events.MainFrameNavigated, this._onMainFrameNavigated, this); + SDK.targetManager.addEventListener(SDK.TargetManager.Events.MainFrameNavigated, this._onMainFrameNavigated, this); /** @type {?SDK.LayerTreeBase} */ this._layerTree = null; } @@ -415,8 +414,8 @@ return; } - var wrappedCallback = - InspectorBackend.wrapClientCallback(callback, 'Protocol.LayerTree.reasonsForCompositingLayer(): ', undefined, []); + var wrappedCallback = InspectorBackend.wrapClientCallback( + callback, 'Protocol.LayerTree.reasonsForCompositingLayer(): ', undefined, []); this._target.layerTreeAgent().compositingReasons(this.id(), wrappedCallback); }
diff --git a/third_party/WebKit/Source/devtools/front_end/layers/LayersPanel.js b/third_party/WebKit/Source/devtools/front_end/layers/LayersPanel.js index 2fa6a56a..0986e54 100644 --- a/third_party/WebKit/Source/devtools/front_end/layers/LayersPanel.js +++ b/third_party/WebKit/Source/devtools/front_end/layers/LayersPanel.js
@@ -116,8 +116,7 @@ targetRemoved(target) { if (!this._model || this._model.target() !== target) return; - this._model.removeEventListener( - Layers.LayerTreeModel.Events.LayerTreeChanged, this._onLayerTreeUpdated, this); + this._model.removeEventListener(Layers.LayerTreeModel.Events.LayerTreeChanged, this._onLayerTreeUpdated, this); this._model.removeEventListener(Layers.LayerTreeModel.Events.LayerPainted, this._onLayerPainted, this); this._model.disable(); this._model = null; @@ -158,8 +157,8 @@ return; this._layerBeingProfiled = selection.layer(); this._tabbedPane.appendTab( - Layers.LayersPanel.DetailsViewTabs.Profiler, Common.UIString('Profiler'), this._paintProfilerView, - undefined, true, true); + Layers.LayersPanel.DetailsViewTabs.Profiler, Common.UIString('Profiler'), this._paintProfilerView, undefined, + true, true); this._tabbedPane.selectTab(Layers.LayersPanel.DetailsViewTabs.Profiler); this._paintProfilerView.profile(snapshotWithRect.snapshot); });
diff --git a/third_party/WebKit/Source/devtools/front_end/main/Main.js b/third_party/WebKit/Source/devtools/front_end/main/Main.js index 3d7cac6..f1a7dd0 100644 --- a/third_party/WebKit/Source/devtools/front_end/main/Main.js +++ b/third_party/WebKit/Source/devtools/front_end/main/Main.js
@@ -73,7 +73,11 @@ */ _createSettings(prefs) { this._initializeExperiments(prefs); - var storagePrefix = Host.isCustomDevtoolsFrontend() ? '__custom__' : ''; + var storagePrefix = ''; + if (Host.isCustomDevtoolsFrontend()) + storagePrefix = '__custom__'; + else if (!Runtime.queryParam('can_dock') && !!Runtime.queryParam('debugFrontend')) + storagePrefix = '__bundled__'; var clearLocalStorage = window.localStorage ? window.localStorage.clear.bind(window.localStorage) : undefined; var localStorage = new Common.SettingsStorage(window.localStorage || {}, undefined, undefined, clearLocalStorage, storagePrefix); @@ -186,20 +190,18 @@ new Bindings.FileSystemWorkspaceBinding(Workspace.isolatedFileSystemManager, Workspace.workspace); Bindings.networkMapping = new Bindings.NetworkMapping( SDK.targetManager, Workspace.workspace, fileSystemWorkspaceBinding, Workspace.fileSystemMapping); - Main.networkProjectManager = - new Bindings.NetworkProjectManager(SDK.targetManager, Workspace.workspace); - Bindings.presentationConsoleMessageHelper = - new Bindings.PresentationConsoleMessageHelper(Workspace.workspace); - Bindings.cssWorkspaceBinding = new Bindings.CSSWorkspaceBinding( - SDK.targetManager, Workspace.workspace, Bindings.networkMapping); - Bindings.debuggerWorkspaceBinding = new Bindings.DebuggerWorkspaceBinding( - SDK.targetManager, Workspace.workspace, Bindings.networkMapping); - Bindings.breakpointManager = new Bindings.BreakpointManager( - null, Workspace.workspace, SDK.targetManager, Bindings.debuggerWorkspaceBinding); + Main.networkProjectManager = new Bindings.NetworkProjectManager(SDK.targetManager, Workspace.workspace); + Bindings.presentationConsoleMessageHelper = new Bindings.PresentationConsoleMessageHelper(Workspace.workspace); + Bindings.cssWorkspaceBinding = + new Bindings.CSSWorkspaceBinding(SDK.targetManager, Workspace.workspace, Bindings.networkMapping); + Bindings.debuggerWorkspaceBinding = + new Bindings.DebuggerWorkspaceBinding(SDK.targetManager, Workspace.workspace, Bindings.networkMapping); + Bindings.breakpointManager = + new Bindings.BreakpointManager(null, Workspace.workspace, SDK.targetManager, Bindings.debuggerWorkspaceBinding); Extensions.extensionServer = new Extensions.ExtensionServer(); - Persistence.persistence = new Persistence.Persistence( - Workspace.workspace, Bindings.breakpointManager, Workspace.fileSystemMapping); + Persistence.persistence = + new Persistence.Persistence(Workspace.workspace, Bindings.breakpointManager, Workspace.fileSystemMapping); new Main.OverlayController(); new Components.ExecutionContextSelector(SDK.targetManager, UI.context); @@ -244,10 +246,11 @@ var toggleSearchNodeAction = UI.actionRegistry.action('elements.toggle-element-search'); // TODO: we should not access actions from other modules. - if (toggleSearchNodeAction) + if (toggleSearchNodeAction) { InspectorFrontendHost.events.addEventListener( InspectorFrontendHostAPI.Events.EnterInspectElementMode, toggleSearchNodeAction.execute.bind(toggleSearchNodeAction), this); + } UI.inspectorView.createToolbars(); InspectorFrontendHost.loadCompleted(); @@ -298,8 +301,8 @@ _registerForwardedShortcuts() { /** @const */ var forwardedActions = ['main.toggle-dock', 'debugger.toggle-breakpoints-active', 'debugger.toggle-pause', 'commandMenu.show']; - var actionKeys = UI.shortcutRegistry.keysForActions(forwardedActions) - .map(UI.KeyboardShortcut.keyCodeAndModifiersFromKey); + var actionKeys = + UI.shortcutRegistry.keysForActions(forwardedActions).map(UI.KeyboardShortcut.keyCodeAndModifiersFromKey); InspectorFrontendHost.setWhitelistedShortcuts(JSON.stringify(actionKeys)); } @@ -415,8 +418,7 @@ if (inspectElementModeShortcuts.length) section.addKey(inspectElementModeShortcuts[0], Common.UIString('Select node to inspect')); - var openResourceShortcut = - UI.KeyboardShortcut.makeDescriptor('p', UI.KeyboardShortcut.Modifiers.CtrlOrMeta); + var openResourceShortcut = UI.KeyboardShortcut.makeDescriptor('p', UI.KeyboardShortcut.Modifiers.CtrlOrMeta); section.addKey(openResourceShortcut, Common.UIString('Go to source')); if (Host.isMac()) { @@ -661,12 +663,9 @@ this._warnings = this._createItem(shadowRoot, 'smallicon-warning'); this._titles = []; - SDK.multitargetConsoleModel.addEventListener( - SDK.ConsoleModel.Events.ConsoleCleared, this._update, this); - SDK.multitargetConsoleModel.addEventListener( - SDK.ConsoleModel.Events.MessageAdded, this._update, this); - SDK.multitargetConsoleModel.addEventListener( - SDK.ConsoleModel.Events.MessageUpdated, this._update, this); + SDK.multitargetConsoleModel.addEventListener(SDK.ConsoleModel.Events.ConsoleCleared, this._update, this); + SDK.multitargetConsoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, this._update, this); + SDK.multitargetConsoleModel.addEventListener(SDK.ConsoleModel.Events.MessageUpdated, this._update, this); this._update(); } @@ -711,8 +710,7 @@ this._titles = []; this._toolbarItem.setVisible(!!(errors || revokedErrors || warnings)); - this._updateItem( - this._errors, errors, false, Common.UIString(errors === 1 ? '%d error' : '%d errors', errors)); + this._updateItem(this._errors, errors, false, Common.UIString(errors === 1 ? '%d error' : '%d errors', errors)); this._updateItem( this._revokedErrors, revokedErrors, !errors, Common.UIString( @@ -739,8 +737,7 @@ */ Main.Main.MainMenuItem = class { constructor() { - this._item = - new UI.ToolbarButton(Common.UIString('Customize and control DevTools'), 'largeicon-menu'); + this._item = new UI.ToolbarButton(Common.UIString('Customize and control DevTools'), 'largeicon-menu'); this._item.addEventListener('mousedown', this._mouseDown, this); } @@ -770,8 +767,7 @@ dockItemElement.appendChild(titleElement); var dockItemToolbar = new UI.Toolbar('', dockItemElement); dockItemToolbar.makeBlueOnHover(); - var undock = new UI.ToolbarToggle( - Common.UIString('Undock into separate window'), 'largeicon-undock'); + var undock = new UI.ToolbarToggle(Common.UIString('Undock into separate window'), 'largeicon-undock'); var bottom = new UI.ToolbarToggle(Common.UIString('Dock to bottom'), 'largeicon-dock-to-bottom'); var right = new UI.ToolbarToggle(Common.UIString('Dock to right'), 'largeicon-dock-to-right'); undock.addEventListener('mouseup', setDockSide.bind(null, Components.DockController.State.Undocked)); @@ -796,9 +792,8 @@ } contextMenu.appendAction( - 'main.toggle-drawer', UI.inspectorView.drawerVisible() ? - Common.UIString('Hide console drawer') : - Common.UIString('Show console drawer')); + 'main.toggle-drawer', UI.inspectorView.drawerVisible() ? Common.UIString('Hide console drawer') : + Common.UIString('Show console drawer')); contextMenu.appendItemsAtLocation('mainMenu'); var moreTools = contextMenu.namedSubMenu('mainMenuMoreTools'); var extensions = self.runtime.extensions('view', undefined, true); @@ -808,8 +803,7 @@ continue; if (descriptor['location'] !== 'drawer-view' && descriptor['location'] !== 'panel') continue; - moreTools.appendItem( - extension.title(), UI.viewManager.showView.bind(UI.viewManager, descriptor['id'])); + moreTools.appendItem(extension.title(), UI.viewManager.showView.bind(UI.viewManager, descriptor['id'])); } contextMenu.show(); @@ -831,15 +825,12 @@ updateVisibility(); function updateVisibility() { - if (manager.isThrottling()) { - UI.inspectorView.setPanelIcon( - 'network', 'smallicon-warning', Common.UIString('Network throttling is enabled')); - } else if (blockedURLsSetting.get().length) { - UI.inspectorView.setPanelIcon( - 'network', 'smallicon-warning', Common.UIString('Requests may be blocked')); - } else { + if (manager.isThrottling()) + UI.inspectorView.setPanelIcon('network', 'smallicon-warning', Common.UIString('Network throttling is enabled')); + else if (blockedURLsSetting.get().length) + UI.inspectorView.setPanelIcon('network', 'smallicon-warning', Common.UIString('Requests may be blocked')); + else UI.inspectorView.setPanelIcon('network', '', ''); - } } } }; @@ -854,12 +845,10 @@ function javaScriptDisabledChanged() { var javaScriptDisabled = Common.moduleSetting('javaScriptDisabled').get(); - if (javaScriptDisabled) { - UI.inspectorView.setPanelIcon( - 'sources', 'smallicon-warning', Common.UIString('JavaScript is disabled')); - } else { + if (javaScriptDisabled) + UI.inspectorView.setPanelIcon('sources', 'smallicon-warning', Common.UIString('JavaScript is disabled')); + else UI.inspectorView.setPanelIcon('sources', '', ''); - } } } }; @@ -891,8 +880,7 @@ */ Main.Main.InspectedNodeRevealer = class { constructor() { - SDK.targetManager.addModelListener( - SDK.DOMModel, SDK.DOMModel.Events.NodeInspected, this._inspectNode, this); + SDK.targetManager.addModelListener(SDK.DOMModel, SDK.DOMModel.Events.NodeInspected, this._inspectNode, this); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/main/OverlayController.js b/third_party/WebKit/Source/devtools/front_end/main/OverlayController.js index 480f3b9..31acef8 100644 --- a/third_party/WebKit/Source/devtools/front_end/main/OverlayController.js +++ b/third_party/WebKit/Source/devtools/front_end/main/OverlayController.js
@@ -14,14 +14,14 @@ // TODO(dgozman): we should get DebuggerResumed on navigations instead of listening to GlobalObjectCleared. SDK.targetManager.addModelListener( SDK.DebuggerModel, SDK.DebuggerModel.Events.GlobalObjectCleared, this._updateOverlay, this); - SDK.targetManager.addEventListener( - SDK.TargetManager.Events.SuspendStateChanged, this._updateAllOverlays, this); + SDK.targetManager.addEventListener(SDK.TargetManager.Events.SuspendStateChanged, this._updateAllOverlays, this); } _updateAllOverlays() { - for (var target of SDK.targetManager.targets(SDK.Target.Capability.Browser)) + for (var target of SDK.targetManager.targets(SDK.Target.Capability.Browser)) { this._updateTargetOverlay( /** @type {!SDK.DebuggerModel} */ (SDK.DebuggerModel.fromTarget(target))); + } } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/network/BlockedURLsPane.js b/third_party/WebKit/Source/devtools/front_end/network/BlockedURLsPane.js index d63ac03..5e3690c 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/BlockedURLsPane.js +++ b/third_party/WebKit/Source/devtools/front_end/network/BlockedURLsPane.js
@@ -162,8 +162,7 @@ _contextMenu(index, event) { var contextMenu = new UI.ContextMenu(event); contextMenu.appendItem(Common.UIString.capitalize('Add ^pattern'), this._addButtonClicked.bind(this)); - contextMenu.appendItem( - Common.UIString.capitalize('Remove ^pattern'), this._removeBlockedURL.bind(this, index)); + contextMenu.appendItem(Common.UIString.capitalize('Remove ^pattern'), this._removeBlockedURL.bind(this, index)); contextMenu.appendItem(Common.UIString.capitalize('Remove ^all'), this._removeAll.bind(this)); contextMenu.show(); }
diff --git a/third_party/WebKit/Source/devtools/front_end/network/EventSourceMessagesView.js b/third_party/WebKit/Source/devtools/front_end/network/EventSourceMessagesView.js index eabfc4e0..e062f051 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/EventSourceMessagesView.js +++ b/third_party/WebKit/Source/devtools/front_end/network/EventSourceMessagesView.js
@@ -40,16 +40,14 @@ for (var i = 0; i < messages.length; ++i) this._dataGrid.insertChild(new Network.EventSourceMessageNode(messages[i])); - this._request.addEventListener( - SDK.NetworkRequest.Events.EventSourceMessageAdded, this._messageAdded, this); + this._request.addEventListener(SDK.NetworkRequest.Events.EventSourceMessageAdded, this._messageAdded, this); } /** * @override */ willHide() { - this._request.removeEventListener( - SDK.NetworkRequest.Events.EventSourceMessageAdded, this._messageAdded, this); + this._request.removeEventListener(SDK.NetworkRequest.Events.EventSourceMessageAdded, this._messageAdded, this); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/network/HARWriter.js b/third_party/WebKit/Source/devtools/front_end/network/HARWriter.js index 634b71832..baae4d4 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/HARWriter.js +++ b/third_party/WebKit/Source/devtools/front_end/network/HARWriter.js
@@ -47,8 +47,9 @@ if (typeof content === 'undefined' && requests[i].finished) { ++this._pendingRequests; requests[i].requestContent().then(this._onContentAvailable.bind(this, entries[i], requests[i])); - } else if (content !== null) + } else if (content !== null) { this._setEntryContent(entries[i], requests[i]); + } } var compositeProgress = new Common.CompositeProgress(progress); this._writeProgress = compositeProgress.createSubProgress(); @@ -56,8 +57,9 @@ this._requestsProgress = compositeProgress.createSubProgress(); this._requestsProgress.setTitle(Common.UIString('Collecting content…')); this._requestsProgress.setTotalWork(this._pendingRequests); - } else + } else { this._beginWrite(); + } } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/network/JSONView.js b/third_party/WebKit/Source/devtools/front_end/network/JSONView.js index a6ef0576..72cabe1b 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/JSONView.js +++ b/third_party/WebKit/Source/devtools/front_end/network/JSONView.js
@@ -76,8 +76,7 @@ returnObj = Network.JSONView._extractJSON(/** @type {string} */ (text)); if (!returnObj) return Promise.resolve(/** @type {?Network.ParsedJSON} */ (null)); - return Common.formatterWorkerPool.runTask('relaxedJSONParser', {content: returnObj.data}) - .then(handleReturnedJSON); + return Common.formatterWorkerPool.runTask('relaxedJSONParser', {content: returnObj.data}).then(handleReturnedJSON); /** * @param {?MessageEvent} event
diff --git a/third_party/WebKit/Source/devtools/front_end/network/NetworkConfigView.js b/third_party/WebKit/Source/devtools/front_end/network/NetworkConfigView.js index d9d3a41..caa4d5d 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/NetworkConfigView.js +++ b/third_party/WebKit/Source/devtools/front_end/network/NetworkConfigView.js
@@ -32,8 +32,7 @@ var groupElement = userAgentSelectElement.createChild('optgroup'); groupElement.label = userAgentDescriptor.title; for (var userAgentVersion of userAgentDescriptor.values) { - var userAgentValue = - SDK.MultitargetNetworkManager.patchUserAgentWithChromeVersion(userAgentVersion.value); + var userAgentValue = SDK.MultitargetNetworkManager.patchUserAgentWithChromeVersion(userAgentVersion.value); groupElement.appendChild(new Option(userAgentVersion.title, userAgentValue)); } }
diff --git a/third_party/WebKit/Source/devtools/front_end/network/NetworkDataGridNode.js b/third_party/WebKit/Source/devtools/front_end/network/NetworkDataGridNode.js index 890413a..6eafa64 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/NetworkDataGridNode.js +++ b/third_party/WebKit/Source/devtools/front_end/network/NetworkDataGridNode.js
@@ -471,8 +471,9 @@ cell.createTextChild(failText); this._appendSubtitle(cell, this._request.localizedFailDescription); cell.title = failText + ' ' + this._request.localizedFailDescription; - } else + } else { this._setTextAndTitle(cell, failText); + } } else if (this._request.statusCode) { cell.createTextChild('' + this._request.statusCode); this._appendSubtitle(cell, this._request.statusText);
diff --git a/third_party/WebKit/Source/devtools/front_end/network/NetworkItemView.js b/third_party/WebKit/Source/devtools/front_end/network/NetworkItemView.js index f92c857b2..099abf3 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/NetworkItemView.js +++ b/third_party/WebKit/Source/devtools/front_end/network/NetworkItemView.js
@@ -52,8 +52,7 @@ var frameView = new Network.ResourceWebSocketFrameView(request); this.appendTab('webSocketFrames', Common.UIString('Frames'), frameView); } else if (request.mimeType === 'text/event-stream') { - this.appendTab( - 'eventSource', Common.UIString('EventStream'), new Network.EventSourceMessagesView(request)); + this.appendTab('eventSource', Common.UIString('EventStream'), new Network.EventSourceMessagesView(request)); } else { var responseView = new Network.RequestResponseView(request); var previewView = new Network.RequestPreviewView(request, responseView);
diff --git a/third_party/WebKit/Source/devtools/front_end/network/NetworkLogView.js b/third_party/WebKit/Source/devtools/front_end/network/NetworkLogView.js index a354065..091ba51c8 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/NetworkLogView.js +++ b/third_party/WebKit/Source/devtools/front_end/network/NetworkLogView.js
@@ -214,15 +214,15 @@ * @return {boolean} */ static _requestMixedContentFilter(value, request) { - if (value === Network.NetworkLogView.MixedContentFilterValues.Displayed) { + if (value === Network.NetworkLogView.MixedContentFilterValues.Displayed) return request.mixedContentType === 'optionally-blockable'; - } else if (value === Network.NetworkLogView.MixedContentFilterValues.Blocked) { + else if (value === Network.NetworkLogView.MixedContentFilterValues.Blocked) return request.mixedContentType === 'blockable' && request.wasBlocked(); - } else if (value === Network.NetworkLogView.MixedContentFilterValues.BlockOverridden) { + else if (value === Network.NetworkLogView.MixedContentFilterValues.BlockOverridden) return request.mixedContentType === 'blockable' && !request.wasBlocked(); - } else if (value === Network.NetworkLogView.MixedContentFilterValues.All) { + else if (value === Network.NetworkLogView.MixedContentFilterValues.All) return request.mixedContentType !== 'none'; - } + return false; } @@ -410,10 +410,9 @@ this._filterBar.addFilter(this._textFilterUI); var dataURLSetting = this._networkHideDataURLSetting; - this._dataURLFilterUI = new UI.CheckboxFilterUI( - 'hide-data-url', Common.UIString('Hide data URLs'), true, dataURLSetting); - this._dataURLFilterUI.addEventListener( - UI.FilterUI.Events.FilterChanged, this._filterChanged.bind(this), this); + this._dataURLFilterUI = + new UI.CheckboxFilterUI('hide-data-url', Common.UIString('Hide data URLs'), true, dataURLSetting); + this._dataURLFilterUI.addEventListener(UI.FilterUI.Events.FilterChanged, this._filterChanged.bind(this), this); this._filterBar.addFilter(this._dataURLFilterUI); var filterItems = []; @@ -421,8 +420,7 @@ var category = Common.resourceCategories[categoryId]; filterItems.push({name: category.title, label: category.shortTitle, title: category.title}); } - this._resourceCategoryFilterUI = - new UI.NamedBitSetFilterUI(filterItems, this._networkResourceTypeFiltersSetting); + this._resourceCategoryFilterUI = new UI.NamedBitSetFilterUI(filterItems, this._networkResourceTypeFiltersSetting); this._resourceCategoryFilterUI.addEventListener( UI.FilterUI.Events.FilterChanged, this._filterChanged.bind(this), this); this._filterBar.addFilter(this._resourceCategoryFilterUI); @@ -430,8 +428,7 @@ _resetSuggestionBuilder() { this._suggestionBuilder = new Network.FilterSuggestionBuilder(Network.NetworkLogView._searchKeys); - this._suggestionBuilder.addItem( - Network.NetworkLogView.FilterType.Is, Network.NetworkLogView.IsFilterType.Running); + this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.Is, Network.NetworkLogView.IsFilterType.Running); this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.LargerThan, '100'); this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.LargerThan, '10k'); this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.LargerThan, '1M'); @@ -605,8 +602,7 @@ selectedRequestsNumber++; selectedTransferSize += requestTransferSize; } - if (request.url === request.target().inspectedURL() && - request.resourceType() === Common.resourceTypes.Document) + if (request.url === request.target().inspectedURL() && request.resourceType() === Common.resourceTypes.Document) baseTime = request.startTime; if (request.endTime > maxTime) maxTime = request.endTime; @@ -920,8 +916,8 @@ return; Network.NetworkLogView._subdomains(request.domain) - .forEach(this._suggestionBuilder.addItem.bind( - this._suggestionBuilder, Network.NetworkLogView.FilterType.Domain)); + .forEach( + this._suggestionBuilder.addItem.bind(this._suggestionBuilder, Network.NetworkLogView.FilterType.Domain)); this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.Method, request.requestMethod); this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.MimeType, request.mimeType); this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.Scheme, '' + request.scheme); @@ -929,14 +925,12 @@ if (request.mixedContentType !== 'none') { this._suggestionBuilder.addItem( - Network.NetworkLogView.FilterType.MixedContent, - Network.NetworkLogView.MixedContentFilterValues.All); + Network.NetworkLogView.FilterType.MixedContent, Network.NetworkLogView.MixedContentFilterValues.All); } if (request.mixedContentType === 'optionally-blockable') { this._suggestionBuilder.addItem( - Network.NetworkLogView.FilterType.MixedContent, - Network.NetworkLogView.MixedContentFilterValues.Displayed); + Network.NetworkLogView.FilterType.MixedContent, Network.NetworkLogView.MixedContentFilterValues.Displayed); } if (request.mixedContentType === 'blockable') { @@ -947,8 +941,7 @@ var responseHeaders = request.responseHeaders; for (var i = 0, l = responseHeaders.length; i < l; ++i) - this._suggestionBuilder.addItem( - Network.NetworkLogView.FilterType.HasResponseHeader, responseHeaders[i].name); + this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.HasResponseHeader, responseHeaders[i].name); var cookies = request.responseCookies; for (var i = 0, l = cookies ? cookies.length : 0; i < l; ++i) { var cookie = cookies[i]; @@ -1020,28 +1013,25 @@ var copyMenu = contextMenu.appendSubMenuItem(Common.UIString('Copy')); if (request) { copyMenu.appendItem( - UI.copyLinkAddressLabel(), - InspectorFrontendHost.copyText.bind(InspectorFrontendHost, request.contentURL())); + UI.copyLinkAddressLabel(), InspectorFrontendHost.copyText.bind(InspectorFrontendHost, request.contentURL())); copyMenu.appendSeparator(); - if (request.requestHeadersText()) + if (request.requestHeadersText()) { copyMenu.appendItem( Common.UIString.capitalize('Copy ^request ^headers'), this._copyRequestHeaders.bind(this, request)); - if (request.responseHeadersText) + } + if (request.responseHeadersText) { copyMenu.appendItem( Common.UIString.capitalize('Copy ^response ^headers'), this._copyResponseHeaders.bind(this, request)); + } if (request.finished) copyMenu.appendItem(Common.UIString.capitalize('Copy ^response'), this._copyResponse.bind(this, request)); if (Host.isWin()) { - copyMenu.appendItem( - Common.UIString('Copy as cURL (cmd)'), this._copyCurlCommand.bind(this, request, 'win')); - copyMenu.appendItem( - Common.UIString('Copy as cURL (bash)'), this._copyCurlCommand.bind(this, request, 'unix')); - copyMenu.appendItem( - Common.UIString('Copy All as cURL (cmd)'), this._copyAllCurlCommand.bind(this, 'win')); - copyMenu.appendItem( - Common.UIString('Copy All as cURL (bash)'), this._copyAllCurlCommand.bind(this, 'unix')); + copyMenu.appendItem(Common.UIString('Copy as cURL (cmd)'), this._copyCurlCommand.bind(this, request, 'win')); + copyMenu.appendItem(Common.UIString('Copy as cURL (bash)'), this._copyCurlCommand.bind(this, request, 'unix')); + copyMenu.appendItem(Common.UIString('Copy All as cURL (cmd)'), this._copyAllCurlCommand.bind(this, 'win')); + copyMenu.appendItem(Common.UIString('Copy All as cURL (bash)'), this._copyAllCurlCommand.bind(this, 'unix')); } else { copyMenu.appendItem(Common.UIString('Copy as cURL'), this._copyCurlCommand.bind(this, request, 'unix')); copyMenu.appendItem(Common.UIString('Copy All as cURL'), this._copyAllCurlCommand.bind(this, 'unix')); @@ -1055,24 +1045,22 @@ contextMenu.appendItem(Common.UIString.capitalize('Save as HAR with ^content'), this._exportAll.bind(this)); contextMenu.appendSeparator(); - contextMenu.appendItem( - Common.UIString.capitalize('Clear ^browser ^cache'), this._clearBrowserCache.bind(this)); - contextMenu.appendItem( - Common.UIString.capitalize('Clear ^browser ^cookies'), this._clearBrowserCookies.bind(this)); + contextMenu.appendItem(Common.UIString.capitalize('Clear ^browser ^cache'), this._clearBrowserCache.bind(this)); + contextMenu.appendItem(Common.UIString.capitalize('Clear ^browser ^cookies'), this._clearBrowserCookies.bind(this)); var blockedSetting = Common.moduleSetting('blockedURLs'); if (request && Runtime.experiments.isEnabled('requestBlocking')) { // Disabled until ready. contextMenu.appendSeparator(); var urlWithoutScheme = request.parsedURL.urlWithoutScheme(); - if (urlWithoutScheme && blockedSetting.get().indexOf(urlWithoutScheme) === -1) + if (urlWithoutScheme && blockedSetting.get().indexOf(urlWithoutScheme) === -1) { contextMenu.appendItem( Common.UIString.capitalize('Block ^request URL'), addBlockedURL.bind(null, urlWithoutScheme)); + } var domain = request.parsedURL.domain(); if (domain && blockedSetting.get().indexOf(domain) === -1) - contextMenu.appendItem( - Common.UIString.capitalize('Block ^request ^domain'), addBlockedURL.bind(null, domain)); + contextMenu.appendItem(Common.UIString.capitalize('Block ^request ^domain'), addBlockedURL.bind(null, domain)); function addBlockedURL(url) { var list = blockedSetting.get();
diff --git a/third_party/WebKit/Source/devtools/front_end/network/NetworkLogViewColumns.js b/third_party/WebKit/Source/devtools/front_end/network/NetworkLogViewColumns.js index cc072188..eab59841 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/NetworkLogViewColumns.js +++ b/third_party/WebKit/Source/devtools/front_end/network/NetworkLogViewColumns.js
@@ -92,8 +92,8 @@ this._popoverHelper.initializeCallbacks( this._getPopoverAnchor.bind(this), this._showPopover.bind(this), this._onHidePopover.bind(this)); - this._dataGrid = new UI.SortableDataGrid( - this._columns.map(Network.NetworkLogViewColumns._convertToDataGridDescriptor)); + this._dataGrid = + new UI.SortableDataGrid(this._columns.map(Network.NetworkLogViewColumns._convertToDataGridDescriptor)); this._dataGrid.element.addEventListener('mousedown', event => { if ((!this._dataGrid.selectedNode && event.button) || event.target.enclosingNodeOrSelfWithNodeName('a')) event.consume(); @@ -106,8 +106,7 @@ this._dataGrid.setHeaderContextMenuCallback(this._innerHeaderContextMenu.bind(this)); this._activeWaterfallSortId = Network.NetworkLogViewColumns.WaterfallSortIds.StartTime; - this._dataGrid.markColumnAsSortedBy( - Network.NetworkLogViewColumns._initialSortColumn, UI.DataGrid.Order.Ascending); + this._dataGrid.markColumnAsSortedBy(Network.NetworkLogViewColumns._initialSortColumn, UI.DataGrid.Order.Ascending); this._splitWidget = new UI.SplitWidget(true, true, 'networkPanelSplitViewWaterfall', 200); var widget = this._dataGrid.asWidget(); @@ -228,7 +227,7 @@ var innerElement = this._waterfallHeaderElement.createChild('div'); innerElement.textContent = Common.UIString('Waterfall'); this._waterfallColumnSortIcon = this._waterfallHeaderElement.createChild('div', 'sort-order-icon-container') - .createChild('div', 'sort-order-icon'); + .createChild('div', 'sort-order-icon'); /** * @this {Network.NetworkLogViewColumns} @@ -295,8 +294,7 @@ this._waterfallColumnSortIcon.classList.add('sort-descending'); this._waterfallRequestsAreStale = true; - var sortFunction = - Network.NetworkDataGridNode.RequestPropertyComparator.bind(null, this._activeWaterfallSortId); + var sortFunction = Network.NetworkDataGridNode.RequestPropertyComparator.bind(null, this._activeWaterfallSortId); this._dataGrid.sortNodes(sortFunction, !this._dataGrid.isSortOrderAscending()); return; } @@ -359,9 +357,9 @@ _saveColumns() { var saveableSettings = {}; - for (var columnConfig of this._columns) { + for (var columnConfig of this._columns) saveableSettings[columnConfig.id] = {visible: columnConfig.visible, title: columnConfig.title}; - } + this._persistantSettings.set(saveableSettings); }
diff --git a/third_party/WebKit/Source/devtools/front_end/network/NetworkManageCustomHeadersView.js b/third_party/WebKit/Source/devtools/front_end/network/NetworkManageCustomHeadersView.js index 26c9df5..a85253b 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/NetworkManageCustomHeadersView.js +++ b/third_party/WebKit/Source/devtools/front_end/network/NetworkManageCustomHeadersView.js
@@ -29,8 +29,8 @@ placeholder.textContent = Common.UIString('No custom headers'); this._list.setEmptyPlaceholder(placeholder); this._list.show(this.contentElement); - this.contentElement.appendChild(createTextButton( - Common.UIString('Add custom header\u2026'), this._addButtonClicked.bind(this), 'add-button')); + this.contentElement.appendChild( + createTextButton(Common.UIString('Add custom header\u2026'), this._addButtonClicked.bind(this), 'add-button')); /** @type {!Map.<string, !{title: string, editable: boolean}>} */ this._columnConfigs = new Map();
diff --git a/third_party/WebKit/Source/devtools/front_end/network/NetworkOverview.js b/third_party/WebKit/Source/devtools/front_end/network/NetworkOverview.js index 983ac96..017d02c 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/NetworkOverview.js +++ b/third_party/WebKit/Source/devtools/front_end/network/NetworkOverview.js
@@ -27,8 +27,7 @@ SDK.targetManager.addModelListener( SDK.ResourceTreeModel, SDK.ResourceTreeModel.Events.Load, this._loadEventFired, this); SDK.targetManager.addModelListener( - SDK.ResourceTreeModel, SDK.ResourceTreeModel.Events.DOMContentLoaded, - this._domContentLoadedEventFired, this); + SDK.ResourceTreeModel, SDK.ResourceTreeModel.Events.DOMContentLoaded, this._domContentLoadedEventFired, this); this.reset(); }
diff --git a/third_party/WebKit/Source/devtools/front_end/network/NetworkPanel.js b/third_party/WebKit/Source/devtools/front_end/network/NetworkPanel.js index 464b4b60..93f2900 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/NetworkPanel.js +++ b/third_party/WebKit/Source/devtools/front_end/network/NetworkPanel.js
@@ -54,8 +54,7 @@ // Create top overview component. this._overviewPane = new UI.TimelineOverviewPane('network'); - this._overviewPane.addEventListener( - UI.TimelineOverviewPane.Events.WindowChanged, this._onWindowChanged.bind(this)); + this._overviewPane.addEventListener(UI.TimelineOverviewPane.Events.WindowChanged, this._onWindowChanged.bind(this)); this._overviewPane.element.id = 'network-overview-panel'; this._networkOverview = new Network.NetworkOverview(); this._overviewPane.setOverviewControls([this._networkOverview]); @@ -97,18 +96,14 @@ this._updateUI(); SDK.targetManager.addModelListener( - SDK.ResourceTreeModel, SDK.ResourceTreeModel.Events.WillReloadPage, this._willReloadPage, - this); - SDK.targetManager.addModelListener( - SDK.ResourceTreeModel, SDK.ResourceTreeModel.Events.Load, this._load, this); - this._networkLogView.addEventListener( - Network.NetworkLogView.Events.RequestSelected, this._onRequestSelected, this); + SDK.ResourceTreeModel, SDK.ResourceTreeModel.Events.WillReloadPage, this._willReloadPage, this); + SDK.targetManager.addModelListener(SDK.ResourceTreeModel, SDK.ResourceTreeModel.Events.Load, this._load, this); + this._networkLogView.addEventListener(Network.NetworkLogView.Events.RequestSelected, this._onRequestSelected, this); this._networkLogView.addEventListener( Network.NetworkLogView.Events.SearchCountUpdated, this._onSearchCountUpdated, this); this._networkLogView.addEventListener( Network.NetworkLogView.Events.SearchIndexUpdated, this._onSearchIndexUpdated, this); - this._networkLogView.addEventListener( - Network.NetworkLogView.Events.UpdateRequest, this._onUpdateRequest, this); + this._networkLogView.addEventListener(Network.NetworkLogView.Events.UpdateRequest, this._onUpdateRequest, this); Components.DataSaverInfobar.maybeShowInPanel(this); } @@ -293,9 +288,10 @@ * @param {!Common.Event} event */ _load(event) { - if (this._filmStripRecorder && this._filmStripRecorder.isRecording()) + if (this._filmStripRecorder && this._filmStripRecorder.isRecording()) { this._pendingStopTimer = setTimeout(this._stopFilmStripRecording.bind(this), Network.NetworkPanel.displayScreenshotDelay); + } } _stopFilmStripRecording() {
diff --git a/third_party/WebKit/Source/devtools/front_end/network/NetworkTimeCalculator.js b/third_party/WebKit/Source/devtools/front_end/network/NetworkTimeCalculator.js index e666b495..6978a222 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/NetworkTimeCalculator.js +++ b/third_party/WebKit/Source/devtools/front_end/network/NetworkTimeCalculator.js
@@ -341,8 +341,7 @@ Network.NetworkTimeCalculator._downloadFormat = new Common.UIStringFormat('%s download'); /** @type {!Common.UIStringFormat} */ -Network.NetworkTimeCalculator._fromServiceWorkerFormat = - new Common.UIStringFormat('%s (from ServiceWorker)'); +Network.NetworkTimeCalculator._fromServiceWorkerFormat = new Common.UIStringFormat('%s (from ServiceWorker)'); /** @type {!Common.UIStringFormat} */ Network.NetworkTimeCalculator._fromCacheFormat = new Common.UIStringFormat('%s (from cache)');
diff --git a/third_party/WebKit/Source/devtools/front_end/network/NetworkWaterfallColumn.js b/third_party/WebKit/Source/devtools/front_end/network/NetworkWaterfallColumn.js index 1819cfb..1d801c5 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/NetworkWaterfallColumn.js +++ b/third_party/WebKit/Source/devtools/front_end/network/NetworkWaterfallColumn.js
@@ -53,8 +53,7 @@ this._rowStripeColor = UI.themeSupport.patchColor('#f5f5f5', colorUsage.Background); this._rowHoverColor = UI.themeSupport.patchColor( '#ebf2fc', /** @type {!UI.ThemeSupport.ColorUsage} */ (colorUsage.Background | colorUsage.Selection)); - this._parentInitiatorColor = - UI.themeSupport.patchColor('hsla(120, 68%, 54%, 0.2)', colorUsage.Background); + this._parentInitiatorColor = UI.themeSupport.patchColor('hsla(120, 68%, 54%, 0.2)', colorUsage.Background); this._initiatedColor = UI.themeSupport.patchColor('hsla(0, 68%, 54%, 0.2)', colorUsage.Background); /** @type {!Map<!Common.ResourceType, string>} */ @@ -85,11 +84,10 @@ _getPopoverAnchor(element, event) { if (!this._hoveredRequest) return; - var useTimingBars = - !Common.moduleSetting('networkColorCodeResourceTypes').get() && !this._calculator.startAtZero; + var useTimingBars = !Common.moduleSetting('networkColorCodeResourceTypes').get() && !this._calculator.startAtZero; if (useTimingBars) { var range = Network.RequestTimingView.calculateRequestTimeRanges(this._hoveredRequest, 0) - .find(data => data.name === Network.RequestTimeRangeNames.Total); + .find(data => data.name === Network.RequestTimeRangeNames.Total); var start = this._timeToPosition(range.start); var end = this._timeToPosition(range.end); } else { @@ -129,8 +127,7 @@ _showPopover(anchor, popover) { if (!this._hoveredRequest) return; - var content = - Network.RequestTimingView.createTimingTable(this._hoveredRequest, this._calculator.minimumBoundary()); + var content = Network.RequestTimingView.createTimingTable(this._hoveredRequest, this._calculator.minimumBoundary()); popover.showForAnchor(content, anchor); } @@ -280,8 +277,7 @@ } _draw() { - var useTimingBars = - !Common.moduleSetting('networkColorCodeResourceTypes').get() && !this._calculator.startAtZero; + var useTimingBars = !Common.moduleSetting('networkColorCodeResourceTypes').get() && !this._calculator.startAtZero; var requests = this._requestData; var context = this._canvas.getContext('2d'); context.save(); @@ -455,7 +451,7 @@ if (!this._calculator.startAtZero) { var queueingRange = Network.RequestTimingView.calculateRequestTimeRanges(request, 0) - .find(data => data.name === Network.RequestTimeRangeNames.Total); + .find(data => data.name === Network.RequestTimeRangeNames.Total); var leftLabelWidth = labels ? context.measureText(labels.left).width : 0; var leftTextPlacedInBar = leftLabelWidth < ranges.mid - ranges.start; const wiskerTextPadding = 13; @@ -464,8 +460,7 @@ if (ranges.start - textOffset > queueingStart) { context.beginPath(); context.globalAlpha = 1; - context.strokeStyle = UI.themeSupport.patchColor( - '#a5a5a5', UI.ThemeSupport.ColorUsage.Foreground); + context.strokeStyle = UI.themeSupport.patchColor('#a5a5a5', UI.ThemeSupport.ColorUsage.Foreground); context.moveTo(queueingStart, Math.floor(height / 2)); context.lineTo(ranges.start - textOffset, Math.floor(height / 2)); @@ -538,8 +533,8 @@ context.save(); var ranges = Network.RequestTimingView.calculateRequestTimeRanges(request, 0); for (var range of ranges) { - if (range.name === Network.RequestTimeRangeNames.Total || - range.name === Network.RequestTimeRangeNames.Sending || range.end - range.start === 0) + if (range.name === Network.RequestTimeRangeNames.Total || range.name === Network.RequestTimeRangeNames.Sending || + range.end - range.start === 0) continue; context.beginPath(); var lineWidth = 0;
diff --git a/third_party/WebKit/Source/devtools/front_end/network/RequestCookiesView.js b/third_party/WebKit/Source/devtools/front_end/network/RequestCookiesView.js index af770d0..fa8ea96 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/RequestCookiesView.js +++ b/third_party/WebKit/Source/devtools/front_end/network/RequestCookiesView.js
@@ -47,10 +47,8 @@ * @override */ wasShown() { - this._request.addEventListener( - SDK.NetworkRequest.Events.RequestHeadersChanged, this._refreshCookies, this); - this._request.addEventListener( - SDK.NetworkRequest.Events.ResponseHeadersChanged, this._refreshCookies, this); + this._request.addEventListener(SDK.NetworkRequest.Events.RequestHeadersChanged, this._refreshCookies, this); + this._request.addEventListener(SDK.NetworkRequest.Events.ResponseHeadersChanged, this._refreshCookies, this); if (!this._gotCookies) { if (!this._emptyWidget) { @@ -68,10 +66,8 @@ * @override */ willHide() { - this._request.removeEventListener( - SDK.NetworkRequest.Events.RequestHeadersChanged, this._refreshCookies, this); - this._request.removeEventListener( - SDK.NetworkRequest.Events.ResponseHeadersChanged, this._refreshCookies, this); + this._request.removeEventListener(SDK.NetworkRequest.Events.RequestHeadersChanged, this._refreshCookies, this); + this._request.removeEventListener(SDK.NetworkRequest.Events.ResponseHeadersChanged, this._refreshCookies, this); } get _gotCookies() {
diff --git a/third_party/WebKit/Source/devtools/front_end/network/RequestHeadersView.js b/third_party/WebKit/Source/devtools/front_end/network/RequestHeadersView.js index 054dc2a..d8e03ed9 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/RequestHeadersView.js +++ b/third_party/WebKit/Source/devtools/front_end/network/RequestHeadersView.js
@@ -53,8 +53,7 @@ root.expandTreeElementsWhenArrowing = true; this.element.appendChild(root.element); - var generalCategory = - new Network.RequestHeadersView.Category(root, 'general', Common.UIString('General')); + var generalCategory = new Network.RequestHeadersView.Category(root, 'general', Common.UIString('General')); generalCategory.hidden = false; this._urlItem = generalCategory.createLeaf(); this._requestMethodItem = generalCategory.createLeaf(); @@ -74,14 +73,11 @@ * @override */ wasShown() { - this._request.addEventListener( - SDK.NetworkRequest.Events.RemoteAddressChanged, this._refreshRemoteAddress, this); - this._request.addEventListener( - SDK.NetworkRequest.Events.RequestHeadersChanged, this._refreshRequestHeaders, this); + this._request.addEventListener(SDK.NetworkRequest.Events.RemoteAddressChanged, this._refreshRemoteAddress, this); + this._request.addEventListener(SDK.NetworkRequest.Events.RequestHeadersChanged, this._refreshRequestHeaders, this); this._request.addEventListener( SDK.NetworkRequest.Events.ResponseHeadersChanged, this._refreshResponseHeaders, this); - this._request.addEventListener( - SDK.NetworkRequest.Events.FinishedLoading, this._refreshHTTPInformation, this); + this._request.addEventListener(SDK.NetworkRequest.Events.FinishedLoading, this._refreshHTTPInformation, this); this._refreshURL(); this._refreshQueryString(); @@ -95,14 +91,12 @@ * @override */ willHide() { - this._request.removeEventListener( - SDK.NetworkRequest.Events.RemoteAddressChanged, this._refreshRemoteAddress, this); + this._request.removeEventListener(SDK.NetworkRequest.Events.RemoteAddressChanged, this._refreshRemoteAddress, this); this._request.removeEventListener( SDK.NetworkRequest.Events.RequestHeadersChanged, this._refreshRequestHeaders, this); this._request.removeEventListener( SDK.NetworkRequest.Events.ResponseHeadersChanged, this._refreshResponseHeaders, this); - this._request.removeEventListener( - SDK.NetworkRequest.Events.FinishedLoading, this._refreshHTTPInformation, this); + this._request.removeEventListener(SDK.NetworkRequest.Events.FinishedLoading, this._refreshHTTPInformation, this); } /** @@ -155,9 +149,10 @@ var queryString = this._request.queryString(); var queryParameters = this._request.queryParameters; this._queryStringCategory.hidden = !queryParameters; - if (queryParameters) + if (queryParameters) { this._refreshParams( Common.UIString('Query String Parameters'), queryParameters, queryString, this._queryStringCategory); + } } _refreshFormData() { @@ -231,8 +226,8 @@ return; } - var toggleTitle = this._decodeRequestParameters ? Common.UIString('view URL encoded') : - Common.UIString('view decoded'); + var toggleTitle = + this._decodeRequestParameters ? Common.UIString('view URL encoded') : Common.UIString('view decoded'); var toggleButton = this._createToggleButton(toggleTitle); toggleButton.addEventListener('click', this._toggleURLDecoding.bind(this), false); paramsTreeElement.listItemElement.appendChild(toggleButton); @@ -245,8 +240,8 @@ paramNameValue.appendChild(name); paramNameValue.appendChild(value); } else { - paramNameValue.appendChild(this._formatParameter( - Common.UIString('(empty)'), 'empty-request-header', this._decodeRequestParameters)); + paramNameValue.appendChild( + this._formatParameter(Common.UIString('(empty)'), 'empty-request-header', this._decodeRequestParameters)); } var paramTreeElement = new TreeElement(paramNameValue); @@ -295,8 +290,7 @@ * @return {!Element} */ _createViewSourceToggle(viewSource, handler) { - var viewSourceToggleTitle = - viewSource ? Common.UIString('view parsed') : Common.UIString('view source'); + var viewSourceToggleTitle = viewSource ? Common.UIString('view parsed') : Common.UIString('view source'); var viewSourceToggleButton = this._createToggleButton(viewSourceToggleTitle); viewSourceToggleButton.addEventListener('click', handler, false); return viewSourceToggleButton; @@ -371,8 +365,7 @@ else statusCodeImage.type = 'smallicon-red-ball'; - requestMethodElement.title = - this._formatHeader(Common.UIString('Request Method'), this._request.requestMethod); + requestMethodElement.title = this._formatHeader(Common.UIString('Request Method'), this._request.requestMethod); var statusTextElement = statusCodeFragment.createChild('div', 'header-value source-code'); var statusText = this._request.statusCode + ' ' + this._request.statusText;
diff --git a/third_party/WebKit/Source/devtools/front_end/network/RequestResponseView.js b/third_party/WebKit/Source/devtools/front_end/network/RequestResponseView.js index fbd73d86..b881e357 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/RequestResponseView.js +++ b/third_party/WebKit/Source/devtools/front_end/network/RequestResponseView.js
@@ -63,8 +63,7 @@ contentLoaded() { if ((!this.request.content || !this.sourceView) && !this.request.contentError()) { if (!this._emptyWidget) { - this._emptyWidget = - this._createMessageView(Common.UIString('This request has no response data available.')); + this._emptyWidget = this._createMessageView(Common.UIString('This request has no response data available.')); this._emptyWidget.show(this.element); } } else {
diff --git a/third_party/WebKit/Source/devtools/front_end/network/RequestTimingView.js b/third_party/WebKit/Source/devtools/front_end/network/RequestTimingView.js index 24d6aff..4226a3b 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/RequestTimingView.js +++ b/third_party/WebKit/Source/devtools/front_end/network/RequestTimingView.js
@@ -150,8 +150,7 @@ if (request.fetchedViaServiceWorker) { addOffsetRange(Network.RequestTimeRangeNames.Blocking, 0, timing.workerStart); - addOffsetRange( - Network.RequestTimeRangeNames.ServiceWorkerPreparation, timing.workerStart, timing.workerReady); + addOffsetRange(Network.RequestTimeRangeNames.ServiceWorkerPreparation, timing.workerStart, timing.workerReady); addOffsetRange(Network.RequestTimeRangeNames.ServiceWorker, timing.workerReady, timing.sendEnd); addOffsetRange(Network.RequestTimeRangeNames.Waiting, timing.sendEnd, timing.receiveHeadersEnd); } else if (!timing.pushStart) { @@ -165,11 +164,11 @@ addOffsetRange(Network.RequestTimeRangeNames.Waiting, timing.sendEnd, timing.receiveHeadersEnd); } - if (request.endTime !== -1) + if (request.endTime !== -1) { addRange( - timing.pushStart ? Network.RequestTimeRangeNames.ReceivingPush : - Network.RequestTimeRangeNames.Receiving, + timing.pushStart ? Network.RequestTimeRangeNames.ReceivingPush : Network.RequestTimeRangeNames.Receiving, request.responseReceivedTime, endTime); + } return result; } @@ -269,8 +268,7 @@ * @param {number} right */ function addTiming(serverTiming, right) { - var colorGenerator = - new UI.FlameChart.ColorGenerator({min: 0, max: 360, count: 36}, {min: 50, max: 80}, 80); + var colorGenerator = new UI.FlameChart.ColorGenerator({min: 0, max: 360, count: 36}, {min: 50, max: 80}, 80); var isTotal = serverTiming.metric.toLowerCase() === 'total'; var tr = tableElement.createChild('tr', isTotal ? 'network-timing-footer' : ''); var metric = tr.createChild('td', 'network-timing-metric'); @@ -318,16 +316,14 @@ willHide() { this._request.removeEventListener(SDK.NetworkRequest.Events.TimingChanged, this._refresh, this); this._request.removeEventListener(SDK.NetworkRequest.Events.FinishedLoading, this._refresh, this); - this._calculator.removeEventListener( - Network.NetworkTimeCalculator.Events.BoundariesChanged, this._refresh, this); + this._calculator.removeEventListener(Network.NetworkTimeCalculator.Events.BoundariesChanged, this._refresh, this); } _refresh() { if (this._tableElement) this._tableElement.remove(); - this._tableElement = - Network.RequestTimingView.createTimingTable(this._request, this._calculator.minimumBoundary()); + this._tableElement = Network.RequestTimingView.createTimingTable(this._request, this._calculator.minimumBoundary()); this.element.appendChild(this._tableElement); } }; @@ -352,8 +348,8 @@ Network.RequestTimingView.ConnectionSetupRangeNames = new Set([ Network.RequestTimeRangeNames.Queueing, Network.RequestTimeRangeNames.Blocking, - Network.RequestTimeRangeNames.Connecting, Network.RequestTimeRangeNames.DNS, - Network.RequestTimeRangeNames.Proxy, Network.RequestTimeRangeNames.SSL + Network.RequestTimeRangeNames.Connecting, Network.RequestTimeRangeNames.DNS, Network.RequestTimeRangeNames.Proxy, + Network.RequestTimeRangeNames.SSL ]); /** @typedef {{name: !Network.RequestTimeRangeNames, start: number, end: number}} */
diff --git a/third_party/WebKit/Source/devtools/front_end/network/ResourceWebSocketFrameView.js b/third_party/WebKit/Source/devtools/front_end/network/ResourceWebSocketFrameView.js index 4d740102..dc001513 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/ResourceWebSocketFrameView.js +++ b/third_party/WebKit/Source/devtools/front_end/network/ResourceWebSocketFrameView.js
@@ -33,13 +33,8 @@ this._splitWidget.show(this.element); var columns = /** @type {!Array<!UI.DataGrid.ColumnDescriptor>} */ ([ - {id: 'data', title: Common.UIString('Data'), sortable: false, weight: 88}, { - id: 'length', - title: Common.UIString('Length'), - sortable: false, - align: UI.DataGrid.Align.Right, - weight: 5 - }, + {id: 'data', title: Common.UIString('Data'), sortable: false, weight: 88}, + {id: 'length', title: Common.UIString('Length'), sortable: false, align: UI.DataGrid.Align.Right, weight: 5}, {id: 'time', title: Common.UIString('Time'), sortable: true, weight: 7} ]); @@ -47,8 +42,8 @@ this._dataGrid.setRowContextMenuCallback(onRowContextMenu); this._dataGrid.setStickToBottom(true); this._dataGrid.setCellClass('websocket-frame-view-td'); - this._timeComparator = /** @type {!UI.SortableDataGrid.NodeComparator} */ ( - Network.ResourceWebSocketFrameNodeTimeComparator); + this._timeComparator = + /** @type {!UI.SortableDataGrid.NodeComparator} */ (Network.ResourceWebSocketFrameNodeTimeComparator); this._dataGrid.sortNodes(this._timeComparator, false); this._dataGrid.markColumnAsSortedBy('time', UI.DataGrid.Order.Ascending); this._dataGrid.addEventListener(UI.DataGrid.Events.SortingChanged, this._sortItems, this); @@ -240,8 +235,7 @@ * @return {!Common.ContentProvider} */ contentProvider() { - return Common.StaticContentProvider.fromString( - this._url, Common.resourceTypes.WebSocket, this._dataText); + return Common.StaticContentProvider.fromString(this._url, Common.resourceTypes.WebSocket, this._dataText); } };
diff --git a/third_party/WebKit/Source/devtools/front_end/network/networkLogView.css b/third_party/WebKit/Source/devtools/front_end/network/networkLogView.css index ea2e0fd..fe3c989 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/networkLogView.css +++ b/third_party/WebKit/Source/devtools/front_end/network/networkLogView.css
@@ -72,6 +72,10 @@ vertical-align: middle; } +.network-log-grid.data-grid .corner { + display: none; +} + .network-log-grid.data-grid.small td { height: 21px; } @@ -349,7 +353,7 @@ } .network-waterfall-header:hover { - background-color:hsla(0, 0%, 80%, .5); + background-color: hsl(0, 0%, 90%); } .network-waterfall-header div { @@ -370,6 +374,8 @@ bottom: 1px; display: flex; align-items: center; + padding-left: 0px; + background-color: white; } .network-waterfall-header .sort-order-icon {
diff --git a/third_party/WebKit/Source/devtools/front_end/persistence/Automapping.js b/third_party/WebKit/Source/devtools/front_end/persistence/Automapping.js index 9cfb094..b04ca83 100644 --- a/third_party/WebKit/Source/devtools/front_end/persistence/Automapping.js +++ b/third_party/WebKit/Source/devtools/front_end/persistence/Automapping.js
@@ -200,7 +200,8 @@ _createBinding(networkSourceCode) { if (networkSourceCode.url().startsWith('file://')) { var fileSourceCode = this._fileSystemUISourceCodes.get(networkSourceCode.url()); - var binding = fileSourceCode ? new Persistence.PersistenceBinding(networkSourceCode, fileSourceCode, false) : null; + var binding = + fileSourceCode ? new Persistence.PersistenceBinding(networkSourceCode, fileSourceCode, false) : null; return Promise.resolve(binding); }
diff --git a/third_party/WebKit/Source/devtools/front_end/persistence/DefaultMapping.js b/third_party/WebKit/Source/devtools/front_end/persistence/DefaultMapping.js index c7acf11..c2e54ec 100644 --- a/third_party/WebKit/Source/devtools/front_end/persistence/DefaultMapping.js +++ b/third_party/WebKit/Source/devtools/front_end/persistence/DefaultMapping.js
@@ -23,10 +23,8 @@ workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded, this._onUISourceCodeAdded, this), workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeRemoved, this._onUISourceCodeRemoved, this), workspace.addEventListener(Workspace.Workspace.Events.ProjectRemoved, this._onProjectRemoved, this), - this._fileSystemMapping.addEventListener( - Workspace.FileSystemMapping.Events.FileMappingAdded, this._remap, this), - this._fileSystemMapping.addEventListener( - Workspace.FileSystemMapping.Events.FileMappingRemoved, this._remap, this) + this._fileSystemMapping.addEventListener(Workspace.FileSystemMapping.Events.FileMappingAdded, this._remap, this), + this._fileSystemMapping.addEventListener(Workspace.FileSystemMapping.Events.FileMappingRemoved, this._remap, this) ]; this._remap(); }
diff --git a/third_party/WebKit/Source/devtools/front_end/persistence/Persistence.js b/third_party/WebKit/Source/devtools/front_end/persistence/Persistence.js index f6f8cc9..9fc05e0b 100644 --- a/third_party/WebKit/Source/devtools/front_end/persistence/Persistence.js +++ b/third_party/WebKit/Source/devtools/front_end/persistence/Persistence.js
@@ -33,8 +33,8 @@ */ _onBindingCreated(binding) { if (binding.network.isDirty()) { - Common.console.log(Common.UIString( - '%s can not be persisted to file system due to unsaved changes.', binding.network.name())); + Common.console.log( + Common.UIString('%s can not be persisted to file system due to unsaved changes.', binding.network.name())); return; } if (binding.fileSystem.isDirty()) @@ -108,10 +108,10 @@ _syncNodeJSContent(binding, uiSourceCode, currentContent, newContent) { if (uiSourceCode === binding.fileSystem) { if (newContent.startsWith(Persistence.Persistence._NodePrefix) && - newContent.endsWith(Persistence.Persistence._NodeSuffix)) + newContent.endsWith(Persistence.Persistence._NodeSuffix)) { newContent = newContent.substring( - Persistence.Persistence._NodePrefix.length, - newContent.length - Persistence.Persistence._NodeSuffix.length); + Persistence.Persistence._NodePrefix.length, newContent.length - Persistence.Persistence._NodeSuffix.length); + } if (currentContent.startsWith(Persistence.Persistence._NodeShebang)) newContent = Persistence.Persistence._NodeShebang + newContent; } else { @@ -149,9 +149,10 @@ */ _copyBreakpoints(from, to) { var breakpoints = this._breakpointManager.breakpointsForUISourceCode(from); - for (var breakpoint of breakpoints) + for (var breakpoint of breakpoints) { this._breakpointManager.setBreakpoint( to, breakpoint.lineNumber(), breakpoint.columnNumber(), breakpoint.condition(), breakpoint.enabled()); + } } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/persistence/PersistenceUtils.js b/third_party/WebKit/Source/devtools/front_end/persistence/PersistenceUtils.js index c69504b..beadea7 100644 --- a/third_party/WebKit/Source/devtools/front_end/persistence/PersistenceUtils.js +++ b/third_party/WebKit/Source/devtools/front_end/persistence/PersistenceUtils.js
@@ -37,7 +37,7 @@ * @param {!Common.Event} event */ _bindingChanged(event) { - var binding = /** @type {!Persistence.PersistenceBinding} */(event.data); + var binding = /** @type {!Persistence.PersistenceBinding} */ (event.data); this.dispatchEventToListeners(Components.LinkDecorator.Events.LinkIconChanged, binding.network); }
diff --git a/third_party/WebKit/Source/devtools/front_end/platform/utilities.js b/third_party/WebKit/Source/devtools/front_end/platform/utilities.js index 609d974..6a4bc8e 100644 --- a/third_party/WebKit/Source/devtools/front_end/platform/utilities.js +++ b/third_party/WebKit/Source/devtools/front_end/platform/utilities.js
@@ -333,8 +333,9 @@ else return chunkb.length - chunka.length; } - } else if (chunka !== chunkb) + } else if (chunka !== chunkb) { return (chunka < chunkb) ? -1 : 1; + } a = a.substring(chunka.length); b = b.substring(chunkb.length); } @@ -632,10 +633,11 @@ value: function(k, comparator) { if (k < 0 || k >= this.length) return; - if (!comparator) + if (!comparator) { comparator = function(a, b) { return a - b; }; + } var low = 0; var high = this.length - 1;
diff --git a/third_party/WebKit/Source/devtools/front_end/profiler/CPUProfileFlameChart.js b/third_party/WebKit/Source/devtools/front_end/profiler/CPUProfileFlameChart.js index 4481a4d3..d489167 100644 --- a/third_party/WebKit/Source/devtools/front_end/profiler/CPUProfileFlameChart.js +++ b/third_party/WebKit/Source/devtools/front_end/profiler/CPUProfileFlameChart.js
@@ -528,8 +528,7 @@ if (!timelineData) return; this._resetCanvas( - this._overviewContainer.clientWidth, - this._overviewContainer.clientHeight - UI.FlameChart.DividersBarHeight); + this._overviewContainer.clientWidth, this._overviewContainer.clientHeight - UI.FlameChart.DividersBarHeight); this._overviewCalculator._updateBoundaries(this); this._overviewGrid.updateDividers(this._overviewCalculator); this._drawOverviewCanvas();
diff --git a/third_party/WebKit/Source/devtools/front_end/profiler/CPUProfileView.js b/third_party/WebKit/Source/devtools/front_end/profiler/CPUProfileView.js index 3627ff82..010d83c 100644 --- a/third_party/WebKit/Source/devtools/front_end/profiler/CPUProfileView.js +++ b/third_party/WebKit/Source/devtools/front_end/profiler/CPUProfileView.js
@@ -86,11 +86,9 @@ Profiler.CPUProfileType.instance = this; SDK.targetManager.addModelListener( - SDK.CPUProfilerModel, SDK.CPUProfilerModel.Events.ConsoleProfileStarted, - this._consoleProfileStarted, this); + SDK.CPUProfilerModel, SDK.CPUProfilerModel.Events.ConsoleProfileStarted, this._consoleProfileStarted, this); SDK.targetManager.addModelListener( - SDK.CPUProfilerModel, SDK.CPUProfilerModel.Events.ConsoleProfileFinished, - this._consoleProfileFinished, this); + SDK.CPUProfilerModel, SDK.CPUProfilerModel.Events.ConsoleProfileFinished, this._consoleProfileFinished, this); } /** @@ -132,8 +130,7 @@ } get description() { - return Common.UIString( - 'CPU profiles show where the execution time is spent in your page\'s JavaScript functions.'); + return Common.UIString('CPU profiles show where the execution time is spent in your page\'s JavaScript functions.'); } /** @@ -179,8 +176,8 @@ var script = scriptLocation.script(); var target = scriptLocation.target(); var message = new SDK.ConsoleMessage( - target, SDK.ConsoleMessage.MessageSource.ConsoleAPI, SDK.ConsoleMessage.MessageLevel.Debug, - messageText, type, undefined, undefined, undefined, undefined, [{ + target, SDK.ConsoleMessage.MessageSource.ConsoleAPI, SDK.ConsoleMessage.MessageLevel.Debug, messageText, type, + undefined, undefined, undefined, undefined, [{ functionName: '', scriptId: scriptLocation.scriptId, url: script ? script.contentURL() : '', @@ -365,8 +362,7 @@ */ function onCloseFrame(depth, node, startTime, totalTime, selfTime) { var index = stack.pop(); - entries[index] = - new Profiler.CPUFlameChartDataProvider.ChartEntry(depth, totalTime, startTime, selfTime, node); + entries[index] = new Profiler.CPUFlameChartDataProvider.ChartEntry(depth, totalTime, startTime, selfTime, node); maxDepth = Math.max(maxDepth, depth); } this._cpuProfile.forEachFrame(onOpenFrame, onCloseFrame);
diff --git a/third_party/WebKit/Source/devtools/front_end/profiler/HeapProfileView.js b/third_party/WebKit/Source/devtools/front_end/profiler/HeapProfileView.js index 10b5034d..e10fb662 100644 --- a/third_party/WebKit/Source/devtools/front_end/profiler/HeapProfileView.js +++ b/third_party/WebKit/Source/devtools/front_end/profiler/HeapProfileView.js
@@ -15,8 +15,7 @@ this.profile = new Profiler.SamplingHeapProfileModel(profileHeader._profile || profileHeader.protocolProfile()); this.adjustedTotal = this.profile.total; var views = [ - Profiler.ProfileView.ViewTypes.Flame, Profiler.ProfileView.ViewTypes.Heavy, - Profiler.ProfileView.ViewTypes.Tree + Profiler.ProfileView.ViewTypes.Flame, Profiler.ProfileView.ViewTypes.Heavy, Profiler.ProfileView.ViewTypes.Tree ]; this.initialize(new Profiler.HeapProfileView.NodeFormatter(this), views); } @@ -72,8 +71,7 @@ } get buttonTooltip() { - return this._recording ? Common.UIString('Stop heap profiling') : - Common.UIString('Start heap profiling'); + return this._recording ? Common.UIString('Stop heap profiling') : Common.UIString('Start heap profiling'); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/profiler/HeapSnapshotDataGrids.js b/third_party/WebKit/Source/devtools/front_end/profiler/HeapSnapshotDataGrids.js index 410c78f..80afb43 100644 --- a/third_party/WebKit/Source/devtools/front_end/profiler/HeapSnapshotDataGrids.js +++ b/third_party/WebKit/Source/devtools/front_end/profiler/HeapSnapshotDataGrids.js
@@ -57,8 +57,7 @@ */ this._nameFilter = null; this._nodeFilter = new Profiler.HeapSnapshotCommon.NodeFilter(); - this.addEventListener( - Profiler.HeapSnapshotSortableDataGrid.Events.SortingComplete, this._sortingComplete, this); + this.addEventListener(Profiler.HeapSnapshotSortableDataGrid.Events.SortingComplete, this._sortingComplete, this); this.addEventListener(UI.DataGrid.Events.SortingChanged, this.sortingChanged, this); } @@ -102,8 +101,7 @@ } _sortingComplete() { - this.removeEventListener( - Profiler.HeapSnapshotSortableDataGrid.Events.SortingComplete, this._sortingComplete, this); + this.removeEventListener(Profiler.HeapSnapshotSortableDataGrid.Events.SortingComplete, this._sortingComplete, this); this._populatedAndSorted = true; this.dispatchEventToListeners(Profiler.HeapSnapshotSortableDataGrid.Events.ContentShown, this); } @@ -113,8 +111,7 @@ */ willHide() { if (this._nameFilter) - this._nameFilter.removeEventListener( - UI.ToolbarInput.Event.TextChanged, this._onNameFilterChanged, this); + this._nameFilter.removeEventListener(UI.ToolbarInput.Event.TextChanged, this._onNameFilterChanged, this); this._clearCurrentHighlight(); } @@ -136,8 +133,7 @@ } if (node instanceof Profiler.HeapSnapshotRetainingObjectNode) - contextMenu.appendItem( - Common.UIString.capitalize('Reveal in Summary ^view'), revealInSummaryView.bind(this)); + contextMenu.appendItem(Common.UIString.capitalize('Reveal in Summary ^view'), revealInSummaryView.bind(this)); } resetSortingCache() { @@ -571,13 +567,8 @@ columns = columns || (/** @type {!Array<!UI.DataGrid.ColumnDescriptor>} */ ([ {id: 'object', title: Common.UIString('Object'), disclosure: true, sortable: true}, - {id: 'distance', title: Common.UIString('Distance'), width: '65px', sortable: true, fixedWidth: true}, { - id: 'shallowSize', - title: Common.UIString('Shallow Size'), - width: '105px', - sortable: true, - fixedWidth: true - }, + {id: 'distance', title: Common.UIString('Distance'), width: '65px', sortable: true, fixedWidth: true}, + {id: 'shallowSize', title: Common.UIString('Shallow Size'), width: '105px', sortable: true, fixedWidth: true}, { id: 'retainedSize', title: Common.UIString('Retained Size'), @@ -633,20 +624,8 @@ fixedWidth: true, sort: UI.DataGrid.Order.Ascending }, - { - id: 'shallowSize', - title: Common.UIString('Shallow Size'), - width: '105px', - sortable: true, - fixedWidth: true - }, - { - id: 'retainedSize', - title: Common.UIString('Retained Size'), - width: '105px', - sortable: true, - fixedWidth: true - } + {id: 'shallowSize', title: Common.UIString('Shallow Size'), width: '105px', sortable: true, fixedWidth: true}, + {id: 'retainedSize', title: Common.UIString('Retained Size'), width: '105px', sortable: true, fixedWidth: true} ]); super(dataDisplayDelegate, columns); } @@ -700,14 +679,8 @@ var columns = /** @type {!Array<!UI.DataGrid.ColumnDescriptor>} */ ([ {id: 'object', title: Common.UIString('Constructor'), disclosure: true, sortable: true}, {id: 'distance', title: Common.UIString('Distance'), width: '65px', sortable: true, fixedWidth: true}, - {id: 'count', title: Common.UIString('Objects Count'), width: '90px', sortable: true, fixedWidth: true}, { - id: 'shallowSize', - title: Common.UIString('Shallow Size'), - width: '105px', - sortable: true, - fixedWidth: true - }, - { + {id: 'count', title: Common.UIString('Objects Count'), width: '90px', sortable: true, fixedWidth: true}, + {id: 'shallowSize', title: Common.UIString('Shallow Size'), width: '105px', sortable: true, fixedWidth: true}, { id: 'retainedSize', title: Common.UIString('Retained Size'), width: '105px', @@ -824,10 +797,11 @@ } this.removeTopLevelNodes(); this.resetSortingCache(); - for (var constructor in aggregates) + for (var constructor in aggregates) { this.appendNode( this.rootNode(), new Profiler.HeapSnapshotConstructorNode(this, constructor, aggregates[constructor], nodeFilter)); + } this.sortingChanged(); this._lastFilter = nodeFilter; }
diff --git a/third_party/WebKit/Source/devtools/front_end/profiler/HeapSnapshotGridNodes.js b/third_party/WebKit/Source/devtools/front_end/profiler/HeapSnapshotGridNodes.js index 604d9d3b..bd3e1f7 100644 --- a/third_party/WebKit/Source/devtools/front_end/profiler/HeapSnapshotGridNodes.js +++ b/third_party/WebKit/Source/devtools/front_end/profiler/HeapSnapshotGridNodes.js
@@ -125,9 +125,10 @@ dispose() { if (this._providerObject) this._providerObject.dispose(); - for (var node = this.children[0]; node; node = node.traverseNextNode(true, this, true)) + for (var node = this.children[0]; node; node = node.traverseNextNode(true, this, true)) { if (node.dispose) node.dispose(); + } } /** @@ -159,8 +160,7 @@ */ _toUIDistance(distance) { var baseSystemDistance = Profiler.HeapSnapshotCommon.baseSystemDistance; - return distance >= 0 && distance < baseSystemDistance ? Common.UIString('%d', distance) : - Common.UIString('\u2212'); + return distance >= 0 && distance < baseSystemDistance ? Common.UIString('%d', distance) : Common.UIString('\u2212'); } /** @@ -490,13 +490,14 @@ this._retainedSize = node.retainedSize; this.snapshotNodeId = node.id; this.snapshotNodeIndex = node.nodeIndex; - if (this._type === 'string') + if (this._type === 'string') { this._reachableFromWindow = true; - else if (this._type === 'object' && this._name.startsWith('Window')) { + } else if (this._type === 'object' && this._name.startsWith('Window')) { this._name = this.shortenWindowURL(this._name, false); this._reachableFromWindow = true; - } else if (node.canBeQueried) + } else if (node.canBeQueried) { this._reachableFromWindow = true; + } if (node.detachedDOMTreeNode) this.detachedDOMTreeNode = true; @@ -616,8 +617,7 @@ if (!error && object.type) callback(target.runtimeModel.createRemoteObject(object)); else - callback(target.runtimeModel.createRemoteObjectFromPrimitiveValue( - Common.UIString('Preview is not available'))); + callback(target.runtimeModel.createRemoteObjectFromPrimitiveValue(Common.UIString('Preview is not available'))); } if (this._type === 'string') @@ -650,8 +650,9 @@ if (url.length > 40) url = url.trimMiddle(40); return fullName.substr(0, startPos + 2) + url + fullName.substr(endPos); - } else + } else { return fullName; + } } }; @@ -1200,9 +1201,10 @@ var items = itemsRange.items; for (var i = 0; i < items.length; i++) items[i].isAddedNotRemoved = true; - if (itemsRange.endPosition < endPosition) + if (itemsRange.endPosition < endPosition) { return this._deletedNodesProvider.serializeItemsRange( 0, endPosition - itemsRange.endPosition, didReceiveDeletedItems.bind(this, itemsRange)); + } itemsRange.totalLength = this._addedCount + this._removedCount; didReceiveAllItems.call(this, itemsRange);
diff --git a/third_party/WebKit/Source/devtools/front_end/profiler/HeapSnapshotProxy.js b/third_party/WebKit/Source/devtools/front_end/profiler/HeapSnapshotProxy.js index aff3058..a6ab8de1 100644 --- a/third_party/WebKit/Source/devtools/front_end/profiler/HeapSnapshotProxy.js +++ b/third_party/WebKit/Source/devtools/front_end/profiler/HeapSnapshotProxy.js
@@ -152,9 +152,10 @@ } _checkLongRunningCalls() { - for (var callId of this._previousCallbacks) + for (var callId of this._previousCallbacks) { if (!this._callbacks.has(callId)) this._previousCallbacks.delete(callId); + } var hasLongRunningCalls = !!this._previousCallbacks.size; this.dispatchEventToListeners('wait', hasLongRunningCalls); for (var callId of this._callbacks.keysArray()) @@ -172,9 +173,10 @@ return; } if (data.error) { - if (data.errorMethodName) - Common.console.error(Common.UIString( - 'An error occurred when a call to method \'%s\' was requested', data.errorMethodName)); + if (data.errorMethodName) { + Common.console.error( + Common.UIString('An error occurred when a call to method \'%s\' was requested', data.errorMethodName)); + } Common.console.error(data['errorCallStack']); this._callbacks.delete(data.callId); return; @@ -378,8 +380,7 @@ * @return {!Profiler.HeapSnapshotProviderProxy} */ createRetainingEdgesProvider(nodeIndex) { - return this.callFactoryMethod( - null, 'createRetainingEdgesProvider', Profiler.HeapSnapshotProviderProxy, nodeIndex); + return this.callFactoryMethod(null, 'createRetainingEdgesProvider', Profiler.HeapSnapshotProviderProxy, nodeIndex); } /** @@ -397,8 +398,7 @@ * @return {?Profiler.HeapSnapshotProviderProxy} */ createDeletedNodesProvider(nodeIndexes) { - return this.callFactoryMethod( - null, 'createDeletedNodesProvider', Profiler.HeapSnapshotProviderProxy, nodeIndexes); + return this.callFactoryMethod(null, 'createDeletedNodesProvider', Profiler.HeapSnapshotProviderProxy, nodeIndexes); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/profiler/HeapSnapshotView.js b/third_party/WebKit/Source/devtools/front_end/profiler/HeapSnapshotView.js index 3c391b09..11f37c8 100644 --- a/third_party/WebKit/Source/devtools/front_end/profiler/HeapSnapshotView.js +++ b/third_party/WebKit/Source/devtools/front_end/profiler/HeapSnapshotView.js
@@ -70,8 +70,7 @@ this._statisticsView = new Profiler.HeapSnapshotStatisticsView(); this._constructorsDataGrid = new Profiler.HeapSnapshotConstructorsDataGrid(this); - this._constructorsDataGrid.addEventListener( - UI.DataGrid.Events.SelectedNode, this._selectionChanged, this); + this._constructorsDataGrid.addEventListener(UI.DataGrid.Events.SelectedNode, this._selectionChanged, this); this._constructorsWidget = this._constructorsDataGrid.asWidget(); this._constructorsWidget.setMinimumSize(50, 25); @@ -82,8 +81,7 @@ if (isHeapTimeline && Common.moduleSetting('recordAllocationStacks').get()) { this._allocationDataGrid = new Profiler.AllocationDataGrid(profile.target(), this); - this._allocationDataGrid.addEventListener( - UI.DataGrid.Events.SelectedNode, this._onSelectAllocationNode, this); + this._allocationDataGrid.addEventListener(UI.DataGrid.Events.SelectedNode, this._onSelectAllocationNode, this); this._allocationWidget = this._allocationDataGrid.asWidget(); this._allocationWidget.setMinimumSize(50, 25); @@ -103,8 +101,7 @@ this._tabbedPane = new UI.TabbedPane(); this._tabbedPane.appendTab('retainers', Common.UIString('Retainers'), this._retainmentWidget); - this._tabbedPane.appendTab( - 'allocation-stack', Common.UIString('Allocation stack'), this._allocationStackView); + this._tabbedPane.appendTab('allocation-stack', Common.UIString('Allocation stack'), this._allocationStackView); splitWidgetResizer = this._tabbedPane.headerElement(); this._objectDetailsView = this._tabbedPane; @@ -122,8 +119,7 @@ this._splitWidget.hideDefaultResizer(); this._splitWidget.installResizer(splitWidgetResizer); - this._retainmentDataGrid.addEventListener( - UI.DataGrid.Events.SelectedNode, this._inspectedObjectChanged, this); + this._retainmentDataGrid.addEventListener(UI.DataGrid.Events.SelectedNode, this._inspectedObjectChanged, this); this._retainmentDataGrid.reset(); this._perspectives = []; @@ -866,8 +862,7 @@ Profiler.HeapSnapshotView.AllocationPerspective = class extends Profiler.HeapSnapshotView.Perspective { constructor() { super(Common.UIString('Allocation')); - this._allocationSplitWidget = - new UI.SplitWidget(false, true, 'heapSnapshotAllocationSplitViewState', 200, 200); + this._allocationSplitWidget = new UI.SplitWidget(false, true, 'heapSnapshotAllocationSplitViewState', 200, 200); this._allocationSplitWidget.setSidebarWidget(new UI.VBox()); } @@ -958,8 +953,7 @@ SDK.targetManager.addModelListener( SDK.HeapProfilerModel, SDK.HeapProfilerModel.Events.ResetProfiles, this._resetProfiles, this); SDK.targetManager.addModelListener( - SDK.HeapProfilerModel, SDK.HeapProfilerModel.Events.AddHeapSnapshotChunk, - this._addHeapSnapshotChunk, this); + SDK.HeapProfilerModel, SDK.HeapProfilerModel.Events.AddHeapSnapshotChunk, this._addHeapSnapshotChunk, this); SDK.targetManager.addModelListener( SDK.HeapProfilerModel, SDK.HeapProfilerModel.Events.ReportHeapSnapshotProgress, this._reportHeapSnapshotProgress, this); @@ -1617,8 +1611,7 @@ * @param {!Event} event */ onError(reader, event) { - Common.console.error( - 'Failed to read heap snapshot from temp file: ' + /** @type {!ErrorEvent} */ (event).message); + Common.console.error('Failed to read heap snapshot from temp file: ' + /** @type {!ErrorEvent} */ (event).message); this.onTransferFinished(); } };
diff --git a/third_party/WebKit/Source/devtools/front_end/profiler/ProfileLauncherView.js b/third_party/WebKit/Source/devtools/front_end/profiler/ProfileLauncherView.js index 4d6a882..b6421d13 100644 --- a/third_party/WebKit/Source/devtools/front_end/profiler/ProfileLauncherView.js +++ b/third_party/WebKit/Source/devtools/front_end/profiler/ProfileLauncherView.js
@@ -53,8 +53,7 @@ this._controlButton = createTextButton('', this._controlButtonClicked.bind(this), 'control-profiling'); this._contentElement.appendChild(this._controlButton); this._recordButtonEnabled = true; - this._loadButton = - createTextButton(Common.UIString('Load'), this._loadButtonClicked.bind(this), 'load-profile'); + this._loadButton = createTextButton(Common.UIString('Load'), this._loadButtonClicked.bind(this), 'load-profile'); this._contentElement.appendChild(this._loadButton); SDK.targetManager.observeTargets(this); } @@ -83,8 +82,7 @@ } _updateLoadButtonLayout() { - this._loadButton.classList.toggle( - 'multi-target', SDK.targetManager.targets(SDK.Target.Capability.JS).length > 1); + this._loadButton.classList.toggle('multi-target', SDK.targetManager.targets(SDK.Target.Capability.JS).length > 1); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/profiler/ProfileView.js b/third_party/WebKit/Source/devtools/front_end/profiler/ProfileView.js index c642e48..c30218d 100644 --- a/third_party/WebKit/Source/devtools/front_end/profiler/ProfileView.js +++ b/third_party/WebKit/Source/devtools/front_end/profiler/ProfileView.js
@@ -32,18 +32,15 @@ this.viewSelectComboBox = new UI.ToolbarComboBox(this._changeView.bind(this)); - this.focusButton = - new UI.ToolbarButton(Common.UIString('Focus selected function'), 'largeicon-visibility'); + this.focusButton = new UI.ToolbarButton(Common.UIString('Focus selected function'), 'largeicon-visibility'); this.focusButton.setEnabled(false); this.focusButton.addEventListener('click', this._focusClicked, this); - this.excludeButton = - new UI.ToolbarButton(Common.UIString('Exclude selected function'), 'largeicon-delete'); + this.excludeButton = new UI.ToolbarButton(Common.UIString('Exclude selected function'), 'largeicon-delete'); this.excludeButton.setEnabled(false); this.excludeButton.addEventListener('click', this._excludeClicked, this); - this.resetButton = - new UI.ToolbarButton(Common.UIString('Restore all functions'), 'largeicon-refresh'); + this.resetButton = new UI.ToolbarButton(Common.UIString('Restore all functions'), 'largeicon-refresh'); this.resetButton.setEnabled(false); this.resetButton.addEventListener('click', this._resetClicked, this); @@ -74,8 +71,7 @@ this._viewType = Common.settings.createSetting('profileView', Profiler.ProfileView.ViewTypes.Heavy); viewTypes = viewTypes || [ - Profiler.ProfileView.ViewTypes.Flame, Profiler.ProfileView.ViewTypes.Heavy, - Profiler.ProfileView.ViewTypes.Tree + Profiler.ProfileView.ViewTypes.Flame, Profiler.ProfileView.ViewTypes.Heavy, Profiler.ProfileView.ViewTypes.Tree ]; var optionNames = new Map([ @@ -142,9 +138,10 @@ * @return {!Profiler.ProfileDataGridTree} */ _getBottomUpProfileDataGridTree() { - if (!this._bottomUpProfileDataGridTree) + if (!this._bottomUpProfileDataGridTree) { this._bottomUpProfileDataGridTree = new Profiler.BottomUpProfileDataGridTree( this._nodeFormatter, this._searchableView, this.profile.root, this.adjustedTotal); + } return this._bottomUpProfileDataGridTree; } @@ -152,9 +149,10 @@ * @return {!Profiler.ProfileDataGridTree} */ _getTopDownProfileDataGridTree() { - if (!this._topDownProfileDataGridTree) + if (!this._topDownProfileDataGridTree) { this._topDownProfileDataGridTree = new Profiler.TopDownProfileDataGridTree( this._nodeFormatter, this._searchableView, this.profile.root, this.adjustedTotal); + } return this._topDownProfileDataGridTree; } @@ -401,8 +399,7 @@ */ onTransferStarted() { this._jsonifiedProfile = ''; - this.updateStatus( - Common.UIString('Loading\u2026 %s', Number.bytesToString(this._jsonifiedProfile.length)), true); + this.updateStatus(Common.UIString('Loading\u2026 %s', Number.bytesToString(this._jsonifiedProfile.length)), true); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/profiler/ProfilesPanel.js b/third_party/WebKit/Source/devtools/front_end/profiler/ProfilesPanel.js index 4e5931c..95dfcdb 100644 --- a/third_party/WebKit/Source/devtools/front_end/profiler/ProfilesPanel.js +++ b/third_party/WebKit/Source/devtools/front_end/profiler/ProfilesPanel.js
@@ -428,8 +428,7 @@ this._toggleRecordButton = UI.Toolbar.createActionButton(this._toggleRecordAction); toolbar.appendToolbarItem(this._toggleRecordButton); - this.clearResultsButton = - new UI.ToolbarButton(Common.UIString('Clear all profiles'), 'largeicon-clear'); + this.clearResultsButton = new UI.ToolbarButton(Common.UIString('Clear all profiles'), 'largeicon-clear'); this.clearResultsButton.addEventListener('click', this._reset, this); toolbar.appendToolbarItem(this.clearResultsButton); @@ -455,8 +454,7 @@ this.contentElement.addEventListener('keydown', this._onKeyDown.bind(this), false); - SDK.targetManager.addEventListener( - SDK.TargetManager.Events.SuspendStateChanged, this._onSuspendStateChanged, this); + SDK.targetManager.addEventListener(SDK.TargetManager.Events.SuspendStateChanged, this._onSuspendStateChanged, this); } /** @@ -678,12 +676,13 @@ */ _handleContextMenuEvent(event) { var contextMenu = new UI.ContextMenu(event); - if (this.visibleView instanceof Profiler.HeapSnapshotView) { + if (this.visibleView instanceof Profiler.HeapSnapshotView) this.visibleView.populateContextMenu(contextMenu, event); - } - if (this.panelSidebarElement().isSelfOrAncestor(event.srcElement)) + + if (this.panelSidebarElement().isSelfOrAncestor(event.srcElement)) { contextMenu.appendItem( Common.UIString('Load\u2026'), this._fileSelectorElement.click.bind(this._fileSelectorElement)); + } contextMenu.show(); } @@ -848,8 +847,7 @@ this.showObject(result, viewName); } - contextMenu.appendItem( - Common.UIString.capitalize('Reveal in Summary ^view'), revealInView.bind(this, 'Summary')); + contextMenu.appendItem(Common.UIString.capitalize('Reveal in Summary ^view'), revealInView.bind(this, 'Summary')); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/profiler/TargetsComboBoxController.js b/third_party/WebKit/Source/devtools/front_end/profiler/TargetsComboBoxController.js index c8a5cfab..ec209c5 100644 --- a/third_party/WebKit/Source/devtools/front_end/profiler/TargetsComboBoxController.js +++ b/third_party/WebKit/Source/devtools/front_end/profiler/TargetsComboBoxController.js
@@ -19,8 +19,7 @@ this._targetToOption = new Map(); UI.context.addFlavorChangeListener(SDK.Target, this._targetChangedExternally, this); - SDK.targetManager.addEventListener( - SDK.TargetManager.Events.NameChanged, this._targetNameChanged, this); + SDK.targetManager.addEventListener(SDK.TargetManager.Events.NameChanged, this._targetNameChanged, this); SDK.targetManager.observeTargets(this, SDK.Target.Capability.JS); }
diff --git a/third_party/WebKit/Source/devtools/front_end/profiler/TopDownProfileDataGrid.js b/third_party/WebKit/Source/devtools/front_end/profiler/TopDownProfileDataGrid.js index f276f32..22e472a 100644 --- a/third_party/WebKit/Source/devtools/front_end/profiler/TopDownProfileDataGrid.js +++ b/third_party/WebKit/Source/devtools/front_end/profiler/TopDownProfileDataGrid.js
@@ -46,9 +46,10 @@ var children = container._remainingChildren; var childrenLength = children.length; - for (var i = 0; i < childrenLength; ++i) + for (var i = 0; i < childrenLength; ++i) { container.appendChild(new Profiler.TopDownProfileDataGridNode( children[i], /** @type {!Profiler.TopDownProfileDataGridTree} */ (container.tree))); + } container._remainingChildren = null; }
diff --git a/third_party/WebKit/Source/devtools/front_end/resources/AppManifestView.js b/third_party/WebKit/Source/devtools/front_end/resources/AppManifestView.js index 5383828..0840f0c 100644 --- a/third_party/WebKit/Source/devtools/front_end/resources/AppManifestView.js +++ b/third_party/WebKit/Source/devtools/front_end/resources/AppManifestView.js
@@ -17,8 +17,8 @@ this._identitySection = this._reportView.appendSection(Common.UIString('Identity')); var toolbar = this._identitySection.createToolbar(); toolbar.renderAsLinks(); - var addToHomeScreen = new UI.ToolbarButton( - Common.UIString('Add to homescreen'), undefined, Common.UIString('Add to homescreen')); + var addToHomeScreen = + new UI.ToolbarButton(Common.UIString('Add to homescreen'), undefined, Common.UIString('Add to homescreen')); addToHomeScreen.addEventListener('click', this._addToHomescreen.bind(this)); toolbar.appendToolbarItem(addToHomeScreen); @@ -56,8 +56,7 @@ return; this._resourceTreeModel = resourceTreeModel; this._updateManifest(); - resourceTreeModel.addEventListener( - SDK.ResourceTreeModel.Events.MainFrameNavigated, this._updateManifest, this); + resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.MainFrameNavigated, this._updateManifest, this); } /** @@ -68,8 +67,7 @@ var resourceTreeModel = SDK.ResourceTreeModel.fromTarget(target); if (!this._resourceTreeModel || this._resourceTreeModel !== resourceTreeModel) return; - resourceTreeModel.removeEventListener( - SDK.ResourceTreeModel.Events.MainFrameNavigated, this._updateManifest, this); + resourceTreeModel.removeEventListener(SDK.ResourceTreeModel.Events.MainFrameNavigated, this._updateManifest, this); delete this._resourceTreeModel; } @@ -86,9 +84,10 @@ this._reportView.setURL(url); this._errorsSection.clearContent(); this._errorsSection.element.classList.toggle('hidden', !errors.length); - for (var error of errors) + for (var error of errors) { this._errorsSection.appendRow().appendChild( createLabel(error.message, error.critical ? 'smallicon-error' : 'smallicon-warning')); + } if (!data) data = '{}'; @@ -98,14 +97,14 @@ this._shortNameField.textContent = stringProperty('short_name'); this._startURLField.removeChildren(); var startURL = stringProperty('start_url'); - if (startURL) + if (startURL) { this._startURLField.appendChild(Components.linkifyResourceAsNode( /** @type {string} */ (Common.ParsedURL.completeURL(url, startURL)), undefined, undefined, undefined, undefined, startURL)); + } this._themeColorSwatch.classList.toggle('hidden', !stringProperty('theme_color')); - var themeColor = - Common.Color.parse(stringProperty('theme_color') || 'white') || Common.Color.parse('white'); + var themeColor = Common.Color.parse(stringProperty('theme_color') || 'white') || Common.Color.parse('white'); this._themeColorSwatch.setColor(/** @type {!Common.Color} */ (themeColor)); this._backgroundColorSwatch.classList.toggle('hidden', !stringProperty('background_color')); var backgroundColor =
diff --git a/third_party/WebKit/Source/devtools/front_end/resources/ApplicationCacheItemsView.js b/third_party/WebKit/Source/devtools/front_end/resources/ApplicationCacheItemsView.js index 0e2db5e..fbe91d08 100644 --- a/third_party/WebKit/Source/devtools/front_end/resources/ApplicationCacheItemsView.js +++ b/third_party/WebKit/Source/devtools/front_end/resources/ApplicationCacheItemsView.js
@@ -45,8 +45,7 @@ this._frameId = frameId; - this._emptyWidget = - new UI.EmptyWidget(Common.UIString('No Application Cache information available.')); + this._emptyWidget = new UI.EmptyWidget(Common.UIString('No Application Cache information available.')); this._emptyWidget.show(this.element); this._markDirty(); @@ -181,12 +180,7 @@ _createDataGrid() { var columns = /** @type {!Array<!UI.DataGrid.ColumnDescriptor>} */ ([ - { - id: 'resource', - title: Common.UIString('Resource'), - sort: UI.DataGrid.Order.Ascending, - sortable: true - }, + {id: 'resource', title: Common.UIString('Resource'), sort: UI.DataGrid.Order.Ascending, sortable: true}, {id: 'type', title: Common.UIString('Type'), sortable: true}, {id: 'size', title: Common.UIString('Size'), align: UI.DataGrid.Align.Right, sortable: true} ]);
diff --git a/third_party/WebKit/Source/devtools/front_end/resources/ClearStorageView.js b/third_party/WebKit/Source/devtools/front_end/resources/ClearStorageView.js index bc852dd..6e2f3bb 100644 --- a/third_party/WebKit/Source/devtools/front_end/resources/ClearStorageView.js +++ b/third_party/WebKit/Source/devtools/front_end/resources/ClearStorageView.js
@@ -23,9 +23,9 @@ of [Protocol.Storage.StorageType.Appcache, Protocol.Storage.StorageType.Cache_storage, Protocol.Storage.StorageType.Cookies, Protocol.Storage.StorageType.Indexeddb, Protocol.Storage.StorageType.Local_storage, Protocol.Storage.StorageType.Service_workers, - Protocol.Storage.StorageType.Websql]) { + Protocol.Storage.StorageType.Websql]) this._settings.set(type, Common.settings.createSetting('clear-storage-' + type, true)); - } + var application = this._reportView.appendSection(Common.UIString('Application')); this._appendItem(application, Common.UIString('Unregister service workers'), 'service_workers');
diff --git a/third_party/WebKit/Source/devtools/front_end/resources/CookieItemsView.js b/third_party/WebKit/Source/devtools/front_end/resources/CookieItemsView.js index c1d1fec..c334644 100644 --- a/third_party/WebKit/Source/devtools/front_end/resources/CookieItemsView.js +++ b/third_party/WebKit/Source/devtools/front_end/resources/CookieItemsView.js
@@ -102,15 +102,16 @@ return; } - if (!this._cookiesTable) + if (!this._cookiesTable) { this._cookiesTable = new Components.CookiesTable(false, this._update.bind(this), this._showDeleteButton.bind(this)); + } this._cookiesTable.setCookies(this._cookies); this._emptyWidget.detach(); this._cookiesTable.show(this.element); - this._treeElement.subtitle = String.sprintf( - Common.UIString('%d cookies (%s)'), this._cookies.length, Number.bytesToString(this._totalSize)); + this._treeElement.subtitle = + String.sprintf(Common.UIString('%d cookies (%s)'), this._cookies.length, Number.bytesToString(this._totalSize)); this._clearButton.setVisible(true); this._deleteButton.setVisible(!!this._cookiesTable.selectedCookie()); }
diff --git a/third_party/WebKit/Source/devtools/front_end/resources/DOMStorageItemsView.js b/third_party/WebKit/Source/devtools/front_end/resources/DOMStorageItemsView.js index 3e810dd0..303f117 100644 --- a/third_party/WebKit/Source/devtools/front_end/resources/DOMStorageItemsView.js +++ b/third_party/WebKit/Source/devtools/front_end/resources/DOMStorageItemsView.js
@@ -46,8 +46,7 @@ Resources.DOMStorage.Events.DOMStorageItemsCleared, this._domStorageItemsCleared, this); this.domStorage.addEventListener( Resources.DOMStorage.Events.DOMStorageItemRemoved, this._domStorageItemRemoved, this); - this.domStorage.addEventListener( - Resources.DOMStorage.Events.DOMStorageItemAdded, this._domStorageItemAdded, this); + this.domStorage.addEventListener(Resources.DOMStorage.Events.DOMStorageItemAdded, this._domStorageItemAdded, this); this.domStorage.addEventListener( Resources.DOMStorage.Events.DOMStorageItemUpdated, this._domStorageItemUpdated, this); } @@ -124,9 +123,10 @@ event.consume(true); this.deleteButton.setVisible(true); - for (var i = 0; i < children.length; ++i) + for (var i = 0; i < children.length; ++i) { if (children[i].data.key === storageData.key) return; + } var childNode = new UI.DataGridNode({key: storageData.key, value: storageData.value}, false); rootNode.insertChild(childNode, children.length - 1); @@ -198,8 +198,7 @@ keys.push(key); } - var dataGrid = - new UI.DataGrid(columns, this._editingCallback.bind(this), this._deleteCallback.bind(this)); + var dataGrid = new UI.DataGrid(columns, this._editingCallback.bind(this), this._deleteCallback.bind(this)); dataGrid.setName('DOMStorageItemsView'); length = nodes.length; for (var i = 0; i < length; ++i) @@ -228,8 +227,9 @@ domStorage.removeItem(oldText); domStorage.setItem(newText, editingNode.data.value || ''); this._removeDupes(editingNode); - } else + } else { domStorage.setItem(editingNode.data.key || '', newText); + } } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/resources/DOMStorageModel.js b/third_party/WebKit/Source/devtools/front_end/resources/DOMStorageModel.js index 25d9f81..58bb873 100644 --- a/third_party/WebKit/Source/devtools/front_end/resources/DOMStorageModel.js +++ b/third_party/WebKit/Source/devtools/front_end/resources/DOMStorageModel.js
@@ -122,9 +122,9 @@ */ static fromTarget(target) { var model = /** @type {?Resources.DOMStorageModel} */ (target.model(Resources.DOMStorageModel)); - if (!model) { + if (!model) model = new Resources.DOMStorageModel(target, SDK.SecurityOriginManager.fromTarget(target)); - } + return model; }
diff --git a/third_party/WebKit/Source/devtools/front_end/resources/DatabaseTableView.js b/third_party/WebKit/Source/devtools/front_end/resources/DatabaseTableView.js index 139483d..6b98450e 100644 --- a/third_party/WebKit/Source/devtools/front_end/resources/DatabaseTableView.js +++ b/third_party/WebKit/Source/devtools/front_end/resources/DatabaseTableView.js
@@ -40,8 +40,7 @@ this.refreshButton = new UI.ToolbarButton(Common.UIString('Refresh'), 'largeicon-refresh'); this.refreshButton.addEventListener('click', this._refreshButtonClicked, this); this._visibleColumnsInput = new UI.ToolbarInput(Common.UIString('Visible columns'), 1); - this._visibleColumnsInput.addEventListener( - UI.ToolbarInput.Event.TextChanged, this._onVisibleColumnsChanged, this); + this._visibleColumnsInput.addEventListener(UI.ToolbarInput.Event.TextChanged, this._onVisibleColumnsChanged, this); } /** @@ -80,8 +79,7 @@ this._dataGrid = UI.SortableDataGrid.create(columnNames, values); this._visibleColumnsInput.setVisible(!!this._dataGrid); if (!this._dataGrid) { - this._emptyWidget = - new UI.EmptyWidget(Common.UIString('The “%s”\ntable is empty.', this.tableName)); + this._emptyWidget = new UI.EmptyWidget(Common.UIString('The “%s”\ntable is empty.', this.tableName)); this._emptyWidget.show(this.element); return; } @@ -132,8 +130,7 @@ var errorMsgElement = createElement('div'); errorMsgElement.className = 'storage-table-error'; - errorMsgElement.textContent = - Common.UIString('An error occurred trying to\nread the “%s” table.', this.tableName); + errorMsgElement.textContent = Common.UIString('An error occurred trying to\nread the “%s” table.', this.tableName); this.element.appendChild(errorMsgElement); }
diff --git a/third_party/WebKit/Source/devtools/front_end/resources/IndexedDBModel.js b/third_party/WebKit/Source/devtools/front_end/resources/IndexedDBModel.js index a5de852f..cf70e6c 100644 --- a/third_party/WebKit/Source/devtools/front_end/resources/IndexedDBModel.js +++ b/third_party/WebKit/Source/devtools/front_end/resources/IndexedDBModel.js
@@ -260,9 +260,8 @@ var result = []; for (var securityOrigin in this._databaseNamesBySecurityOrigin) { var databaseNames = this._databaseNamesBySecurityOrigin[securityOrigin]; - for (var i = 0; i < databaseNames.length; ++i) { + for (var i = 0; i < databaseNames.length; ++i) result.push(new Resources.IndexedDBModel.DatabaseId(securityOrigin, databaseNames[i])); - } } return result; }
diff --git a/third_party/WebKit/Source/devtools/front_end/resources/IndexedDBViews.js b/third_party/WebKit/Source/devtools/front_end/resources/IndexedDBViews.js index e0d55ac9..0b4a589 100644 --- a/third_party/WebKit/Source/devtools/front_end/resources/IndexedDBViews.js +++ b/third_party/WebKit/Source/devtools/front_end/resources/IndexedDBViews.js
@@ -62,8 +62,7 @@ _refreshDatabase() { this._formatHeader( - this._securityOriginElement, Common.UIString('Security origin'), - this._database.databaseId.securityOrigin); + this._securityOriginElement, Common.UIString('Security origin'), this._database.databaseId.securityOrigin); this._formatHeader(this._nameElement, Common.UIString('Name'), this._database.databaseId.name); this._formatHeader(this._versionElement, Common.UIString('Version'), this._database.version); } @@ -102,8 +101,7 @@ this._refreshButton = new UI.ToolbarButton(Common.UIString('Refresh'), 'largeicon-refresh'); this._refreshButton.addEventListener('click', this._refreshButtonClicked, this); - this._clearButton = - new UI.ToolbarButton(Common.UIString('Clear object store'), 'largeicon-clear'); + this._clearButton = new UI.ToolbarButton(Common.UIString('Clear object store'), 'largeicon-clear'); this._clearButton.addEventListener('click', this._clearButtonClicked, this); this._pageSize = 50; @@ -121,18 +119,15 @@ var columns = /** @type {!Array<!UI.DataGrid.ColumnDescriptor>} */ ([]); columns.push({id: 'number', title: Common.UIString('#'), sortable: false, width: '50px'}); - columns.push({ - id: 'key', - titleDOMFragment: this._keyColumnHeaderFragment(Common.UIString('Key'), keyPath), - sortable: false - }); - if (this._isIndex) + columns.push( + {id: 'key', titleDOMFragment: this._keyColumnHeaderFragment(Common.UIString('Key'), keyPath), sortable: false}); + if (this._isIndex) { columns.push({ id: 'primaryKey', - titleDOMFragment: - this._keyColumnHeaderFragment(Common.UIString('Primary key'), this._objectStore.keyPath), + titleDOMFragment: this._keyColumnHeaderFragment(Common.UIString('Primary key'), this._objectStore.keyPath), sortable: false }); + } columns.push({id: 'value', title: Common.UIString('Value'), sortable: false}); var dataGrid = new UI.DataGrid(columns); @@ -183,13 +178,11 @@ _createEditorToolbar() { var editorToolbar = new UI.Toolbar('data-view-toolbar', this.element); - this._pageBackButton = - new UI.ToolbarButton(Common.UIString('Show previous page'), 'largeicon-play-back'); + this._pageBackButton = new UI.ToolbarButton(Common.UIString('Show previous page'), 'largeicon-play-back'); this._pageBackButton.addEventListener('click', this._pageBackButtonClicked, this); editorToolbar.appendToolbarItem(this._pageBackButton); - this._pageForwardButton = - new UI.ToolbarButton(Common.UIString('Show next page'), 'largeicon-play'); + this._pageForwardButton = new UI.ToolbarButton(Common.UIString('Show next page'), 'largeicon-play'); this._pageForwardButton.setEnabled(false); this._pageForwardButton.addEventListener('click', this._pageForwardButtonClicked, this); editorToolbar.appendToolbarItem(this._pageForwardButton); @@ -292,13 +285,14 @@ } var idbKeyRange = key ? window.IDBKeyRange.lowerBound(key) : null; - if (this._isIndex) + if (this._isIndex) { this._model.loadIndexData( this._databaseId, this._objectStore.name, this._index.name, idbKeyRange, skipCount, pageSize, callback.bind(this)); - else + } else { this._model.loadObjectStoreData( this._databaseId, this._objectStore.name, idbKeyRange, skipCount, pageSize, callback.bind(this)); + } } _refreshButtonClicked(event) {
diff --git a/third_party/WebKit/Source/devtools/front_end/resources/ResourcesPanel.js b/third_party/WebKit/Source/devtools/front_end/resources/ResourcesPanel.js index e8088173..a54b1626 100644 --- a/third_party/WebKit/Source/devtools/front_end/resources/ResourcesPanel.js +++ b/third_party/WebKit/Source/devtools/front_end/resources/ResourcesPanel.js
@@ -144,8 +144,7 @@ if (resourceTreeModel.cachedResourcesLoaded()) this._initialize(); - resourceTreeModel.addEventListener( - SDK.ResourceTreeModel.Events.CachedResourcesLoaded, this._initialize, this); + resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.CachedResourcesLoaded, this._initialize, this); resourceTreeModel.addEventListener( SDK.ResourceTreeModel.Events.WillLoadCachedResources, this._resetWithFrames, this); } @@ -161,14 +160,12 @@ var resourceTreeModel = SDK.ResourceTreeModel.fromTarget(target); if (resourceTreeModel) { - resourceTreeModel.removeEventListener( - SDK.ResourceTreeModel.Events.CachedResourcesLoaded, this._initialize, this); + resourceTreeModel.removeEventListener(SDK.ResourceTreeModel.Events.CachedResourcesLoaded, this._initialize, this); resourceTreeModel.removeEventListener( SDK.ResourceTreeModel.Events.WillLoadCachedResources, this._resetWithFrames, this); } this._databaseModel.removeEventListener(Resources.DatabaseModel.Events.DatabaseAdded, this._databaseAdded, this); - this._databaseModel.removeEventListener( - Resources.DatabaseModel.Events.DatabasesRemoved, this._resetWebSQL, this); + this._databaseModel.removeEventListener(Resources.DatabaseModel.Events.DatabasesRemoved, this._resetWebSQL, this); this._resetWithFrames(); } @@ -232,9 +229,10 @@ } var queryViews = this._databaseQueryViews.valuesArray(); - for (var i = 0; i < queryViews.length; ++i) + for (var i = 0; i < queryViews.length; ++i) { queryViews[i].removeEventListener( Resources.DatabaseQueryView.Events.SchemaUpdated, this._updateDatabaseTables, this); + } this._databaseTableViews.clear(); this._databaseQueryViews.clear(); this._databaseTreeElements.clear(); @@ -304,8 +302,7 @@ _populateResourceTree(resourceTreeModel) { this._treeElementForFrameId = {}; resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.FrameAdded, this._frameAdded, this); - resourceTreeModel.addEventListener( - SDK.ResourceTreeModel.Events.FrameNavigated, this._frameNavigated, this); + resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.FrameNavigated, this._frameNavigated, this); resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.FrameDetached, this._frameDetached, this); resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.ResourceAdded, this._resourceAdded, this); @@ -613,9 +610,10 @@ } showApplicationCache(frameId) { - if (!this._applicationCacheViews[frameId]) + if (!this._applicationCacheViews[frameId]) { this._applicationCacheViews[frameId] = new Resources.ApplicationCacheItemsView(this._applicationCacheModel, frameId); + } this._innerShowView(this._applicationCacheViews[frameId]); } @@ -698,8 +696,7 @@ domStorageModel.enable(); domStorageModel.storages().forEach(this._addDOMStorage.bind(this)); domStorageModel.addEventListener(Resources.DOMStorageModel.Events.DOMStorageAdded, this._domStorageAdded, this); - domStorageModel.addEventListener( - Resources.DOMStorageModel.Events.DOMStorageRemoved, this._domStorageRemoved, this); + domStorageModel.addEventListener(Resources.DOMStorageModel.Events.DOMStorageRemoved, this._domStorageRemoved, this); } /** @@ -715,14 +712,13 @@ this._applicationCacheModel.addEventListener( SDK.ApplicationCacheModel.Events.FrameManifestAdded, this._applicationCacheFrameManifestAdded, this); this._applicationCacheModel.addEventListener( - SDK.ApplicationCacheModel.Events.FrameManifestRemoved, this._applicationCacheFrameManifestRemoved, - this); + SDK.ApplicationCacheModel.Events.FrameManifestRemoved, this._applicationCacheFrameManifestRemoved, this); this._applicationCacheModel.addEventListener( SDK.ApplicationCacheModel.Events.FrameManifestsReset, this._resetAppCache, this); this._applicationCacheModel.addEventListener( - SDK.ApplicationCacheModel.Events.FrameManifestStatusUpdated, - this._applicationCacheFrameManifestStatusChanged, this); + SDK.ApplicationCacheModel.Events.FrameManifestStatusUpdated, this._applicationCacheFrameManifestStatusChanged, + this); this._applicationCacheModel.addEventListener( SDK.ApplicationCacheModel.Events.NetworkStateChanged, this._applicationCacheNetworkStateChanged, this); } @@ -995,8 +991,7 @@ appendResource(resource) { var resourceType = resource.resourceType(); var categoryName = resourceType.name(); - var categoryElement = - resourceType === Common.resourceTypes.Document ? this : this._categoryElements[categoryName]; + var categoryElement = resourceType === Common.resourceTypes.Document ? this : this._categoryElements[categoryName]; if (!categoryElement) { categoryElement = new Resources.StorageCategoryTreeElement( this._storagePanel, resource.resourceType().category().title, categoryName, null, true); @@ -1223,9 +1218,7 @@ * @param {!Resources.ResourcesPanel} storagePanel */ constructor(storagePanel) { - super( - storagePanel, Common.UIString('Cache Storage'), 'CacheStorage', - ['database-tree-item', 'resource-tree-item']); + super(storagePanel, Common.UIString('Cache Storage'), 'CacheStorage', ['database-tree-item', 'resource-tree-item']); } _initialize() { @@ -1238,11 +1231,9 @@ this._addCache(model, cache); } SDK.targetManager.addModelListener( - SDK.ServiceWorkerCacheModel, SDK.ServiceWorkerCacheModel.Events.CacheAdded, this._cacheAdded, - this); + SDK.ServiceWorkerCacheModel, SDK.ServiceWorkerCacheModel.Events.CacheAdded, this._cacheAdded, this); SDK.targetManager.addModelListener( - SDK.ServiceWorkerCacheModel, SDK.ServiceWorkerCacheModel.Events.CacheRemoved, - this._cacheRemoved, this); + SDK.ServiceWorkerCacheModel, SDK.ServiceWorkerCacheModel.Events.CacheRemoved, this._cacheRemoved, this); } /** @@ -1397,9 +1388,7 @@ * @param {!Resources.ResourcesPanel} storagePanel */ constructor(storagePanel) { - super( - storagePanel, Common.UIString('Service Workers'), ['service-worker-tree-item', 'resource-tree-item'], - false); + super(storagePanel, Common.UIString('Service Workers'), ['service-worker-tree-item', 'resource-tree-item'], false); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/resources/ServiceWorkerCacheViews.js b/third_party/WebKit/Source/devtools/front_end/resources/ServiceWorkerCacheViews.js index b5a88037f..d688bee 100644 --- a/third_party/WebKit/Source/devtools/front_end/resources/ServiceWorkerCacheViews.js +++ b/third_party/WebKit/Source/devtools/front_end/resources/ServiceWorkerCacheViews.js
@@ -35,24 +35,20 @@ */ _createDataGrid() { var columns = /** @type {!Array<!UI.DataGrid.ColumnDescriptor>} */ ([ - {id: 'number', title: Common.UIString('#'), width: '50px'}, - {id: 'request', title: Common.UIString('Request')}, + {id: 'number', title: Common.UIString('#'), width: '50px'}, {id: 'request', title: Common.UIString('Request')}, {id: 'response', title: Common.UIString('Response')} ]); - return new UI.DataGrid( - columns, undefined, this._deleteButtonClicked.bind(this), this._updateData.bind(this, true)); + return new UI.DataGrid(columns, undefined, this._deleteButtonClicked.bind(this), this._updateData.bind(this, true)); } _createEditorToolbar() { var editorToolbar = new UI.Toolbar('data-view-toolbar', this.element); - this._pageBackButton = - new UI.ToolbarButton(Common.UIString('Show previous page'), 'largeicon-play-back'); + this._pageBackButton = new UI.ToolbarButton(Common.UIString('Show previous page'), 'largeicon-play-back'); this._pageBackButton.addEventListener('click', this._pageBackButtonClicked, this); editorToolbar.appendToolbarItem(this._pageBackButton); - this._pageForwardButton = - new UI.ToolbarButton(Common.UIString('Show next page'), 'largeicon-play'); + this._pageForwardButton = new UI.ToolbarButton(Common.UIString('Show next page'), 'largeicon-play'); this._pageForwardButton.setEnabled(false); this._pageForwardButton.addEventListener('click', this._pageForwardButtonClicked, this); editorToolbar.appendToolbarItem(this._pageForwardButton);
diff --git a/third_party/WebKit/Source/devtools/front_end/resources/ServiceWorkersView.js b/third_party/WebKit/Source/devtools/front_end/resources/ServiceWorkersView.js index 28865149..74d0b5e 100644 --- a/third_party/WebKit/Source/devtools/front_end/resources/ServiceWorkersView.js +++ b/third_party/WebKit/Source/devtools/front_end/resources/ServiceWorkersView.js
@@ -153,20 +153,18 @@ this._toolbar = section.createToolbar(); this._toolbar.renderAsLinks(); - this._updateButton = - new UI.ToolbarButton(Common.UIString('Update'), undefined, Common.UIString('Update')); + this._updateButton = new UI.ToolbarButton(Common.UIString('Update'), undefined, Common.UIString('Update')); this._updateButton.addEventListener('click', this._updateButtonClicked.bind(this)); this._toolbar.appendToolbarItem(this._updateButton); - this._pushButton = new UI.ToolbarButton( - Common.UIString('Emulate push event'), undefined, Common.UIString('Push')); + this._pushButton = new UI.ToolbarButton(Common.UIString('Emulate push event'), undefined, Common.UIString('Push')); this._pushButton.addEventListener('click', this._pushButtonClicked.bind(this)); this._toolbar.appendToolbarItem(this._pushButton); - this._syncButton = new UI.ToolbarButton( - Common.UIString('Emulate background sync event'), undefined, Common.UIString('Sync')); + this._syncButton = + new UI.ToolbarButton(Common.UIString('Emulate background sync event'), undefined, Common.UIString('Sync')); this._syncButton.addEventListener('click', this._syncButtonClicked.bind(this)); this._toolbar.appendToolbarItem(this._syncButton); - this._deleteButton = new UI.ToolbarButton( - Common.UIString('Unregister service worker'), undefined, Common.UIString('Unregister')); + this._deleteButton = + new UI.ToolbarButton(Common.UIString('Unregister service worker'), undefined, Common.UIString('Unregister')); this._deleteButton.addEventListener('click', this._unregisterButtonClicked.bind(this)); this._toolbar.appendToolbarItem(this._deleteButton); @@ -257,8 +255,7 @@ for (var client of active.controlledClients) { var clientLabelText = clientsList.createChild('div', 'service-worker-client'); if (this._clientInfoCache.has(client)) - this._updateClientInfo( - clientLabelText, /** @type {!SDK.TargetInfo} */ (this._clientInfoCache.get(client))); + this._updateClientInfo(clientLabelText, /** @type {!SDK.TargetInfo} */ (this._clientInfoCache.get(client))); this._subTargetsManager.getTargetInfo(client, this._onClientInfo.bind(this, clientLabelText)); } } @@ -280,8 +277,7 @@ installingEntry.createChild('div', 'service-worker-subtitle').textContent = new Date(installing.scriptResponseTime * 1000).toLocaleString(); if (!this._targetForVersionId(installing.id) && (installing.isRunning() || installing.isStarting())) - createLink( - installingEntry, Common.UIString('inspect'), this._inspectButtonClicked.bind(this, installing.id)); + createLink(installingEntry, Common.UIString('inspect'), this._inspectButtonClicked.bind(this, installing.id)); } this._section.setFieldVisible(Common.UIString('Errors'), !!this._registration.errors.length); @@ -290,8 +286,8 @@ errorsLabel.classList.add('service-worker-errors-label'); errorsValue.appendChild(errorsLabel); this._moreButton = createLink( - errorsValue, this._errorsList.classList.contains('hidden') ? Common.UIString('details') : - Common.UIString('hide'), + errorsValue, + this._errorsList.classList.contains('hidden') ? Common.UIString('details') : Common.UIString('hide'), this._moreErrorsButtonClicked.bind(this)); createLink(errorsValue, Common.UIString('clear'), this._clearErrorsButtonClicked.bind(this));
diff --git a/third_party/WebKit/Source/devtools/front_end/sass/SASSSourceMapFactory.js b/third_party/WebKit/Source/devtools/front_end/sass/SASSSourceMapFactory.js index 5375c2b..78a0b9c 100644 --- a/third_party/WebKit/Source/devtools/front_end/sass/SASSSourceMapFactory.js +++ b/third_party/WebKit/Source/devtools/front_end/sass/SASSSourceMapFactory.js
@@ -78,8 +78,8 @@ var sassNode = sassAST.findNodeForPosition(entry.sourceLineNumber, entry.sourceColumnNumber); if (!sassNode) return; - if (cssNode.parent && (cssNode.parent instanceof Sass.SASSSupport.Property) && - cssNode === cssNode.parent.name && cssNode.text.trim() !== sassNode.text.trim()) { + if (cssNode.parent && (cssNode.parent instanceof Sass.SASSSupport.Property) && cssNode === cssNode.parent.name && + cssNode.text.trim() !== sassNode.text.trim()) { valid = false; reportError(cssNode, sassNode); return;
diff --git a/third_party/WebKit/Source/devtools/front_end/sass/SASSSupport.js b/third_party/WebKit/Source/devtools/front_end/sass/SASSSupport.js index 2cc6587..7a1cbb5 100644 --- a/third_party/WebKit/Source/devtools/front_end/sass/SASSSupport.js +++ b/third_party/WebKit/Source/devtools/front_end/sass/SASSSupport.js
@@ -370,10 +370,8 @@ var disabled = disabledStates[i]; this.document.edits.push(this._insertPropertyEdit(anchorProperty, nameText, valueText, disabled)); - var name = new Sass.SASSSupport.TextNode( - this.document, nameText, Common.TextRange.createFromLocation(0, 0)); - var value = new Sass.SASSSupport.TextNode( - this.document, valueText, Common.TextRange.createFromLocation(0, 0)); + var name = new Sass.SASSSupport.TextNode(this.document, nameText, Common.TextRange.createFromLocation(0, 0)); + var value = new Sass.SASSSupport.TextNode(this.document, valueText, Common.TextRange.createFromLocation(0, 0)); var newProperty = new Sass.SASSSupport.Property( this.document, name, value, Common.TextRange.createFromLocation(0, 0), disabled); @@ -613,8 +611,7 @@ * @param {number} newPropertyIndex */ function addChange(type, oldRule, newRule, oldPropertyIndex, newPropertyIndex) { - changes.push( - new Sass.SASSSupport.PropertyChange(type, oldRule, newRule, oldPropertyIndex, newPropertyIndex)); + changes.push(new Sass.SASSSupport.PropertyChange(type, oldRule, newRule, oldPropertyIndex, newPropertyIndex)); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/screencast/ScreencastApp.js b/third_party/WebKit/Source/devtools/front_end/screencast/ScreencastApp.js index c0ed3349..25f1ac0 100644 --- a/third_party/WebKit/Source/devtools/front_end/screencast/ScreencastApp.js +++ b/third_party/WebKit/Source/devtools/front_end/screencast/ScreencastApp.js
@@ -9,8 +9,7 @@ Screencast.ScreencastApp = class { constructor() { this._enabledSetting = Common.settings.createSetting('screencastEnabled', true); - this._toggleButton = - new UI.ToolbarToggle(Common.UIString('Toggle screencast'), 'largeicon-phone'); + this._toggleButton = new UI.ToolbarToggle(Common.UIString('Toggle screencast'), 'largeicon-phone'); this._toggleButton.setToggled(this._enabledSetting.get()); this._toggleButton.addEventListener('click', this._toggleButtonClicked, this); SDK.targetManager.observeTargets(this); @@ -32,8 +31,7 @@ presentUI(document) { var rootView = new UI.RootView(); - this._rootSplitWidget = - new UI.SplitWidget(false, true, 'InspectorView.screencastSplitViewState', 300, 300); + this._rootSplitWidget = new UI.SplitWidget(false, true, 'InspectorView.screencastSplitViewState', 300, 300); this._rootSplitWidget.setVertical(true); this._rootSplitWidget.setSecondIsSidebar(true); this._rootSplitWidget.show(rootView.element);
diff --git a/third_party/WebKit/Source/devtools/front_end/screencast/ScreencastView.js b/third_party/WebKit/Source/devtools/front_end/screencast/ScreencastView.js index 509a78ec..f270442 100644 --- a/third_party/WebKit/Source/devtools/front_end/screencast/ScreencastView.js +++ b/third_party/WebKit/Source/devtools/front_end/screencast/ScreencastView.js
@@ -90,13 +90,11 @@ this._shortcuts[UI.KeyboardShortcut.makeKey('l', UI.KeyboardShortcut.Modifiers.Ctrl)] = this._focusNavigationBar.bind(this); - this._resourceTreeModel.addEventListener( - SDK.ResourceTreeModel.Events.ScreencastFrame, this._screencastFrame, this); + this._resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.ScreencastFrame, this._screencastFrame, this); this._resourceTreeModel.addEventListener( SDK.ResourceTreeModel.Events.ScreencastVisibilityChanged, this._screencastVisibilityChanged, this); - SDK.targetManager.addEventListener( - SDK.TargetManager.Events.SuspendStateChanged, this._onSuspendStateChange, this); + SDK.targetManager.addEventListener(SDK.TargetManager.Events.SuspendStateChanged, this._onSuspendStateChange, this); this._updateGlasspane(); } @@ -532,8 +530,7 @@ _cssColor(color) { if (!color) return 'transparent'; - return Common.Color.fromRGBA([color.r, color.g, color.b, color.a]).asString(Common.Color.Format.RGBA) || - ''; + return Common.Color.fromRGBA([color.r, color.g, color.b, color.a]).asString(Common.Color.Format.RGBA) || ''; } /** @@ -625,8 +622,9 @@ } else if (anchorTop - titleHeight - arrowHeight > 0) { boxY = anchorTop - titleHeight - arrowHeight + 3; renderArrowDown = true; - } else + } else { boxY = arrowHeight; + } this._context.save(); this._context.translate(0.5, 0.5); @@ -804,10 +802,8 @@ this._element = element; SDK.targetManager.addModelListener( - SDK.ResourceTreeModel, SDK.ResourceTreeModel.Events.MainFrameNavigated, - this._onMainFrameNavigated, this); - SDK.targetManager.addModelListener( - SDK.ResourceTreeModel, SDK.ResourceTreeModel.Events.Load, this._onLoad, this); + SDK.ResourceTreeModel, SDK.ResourceTreeModel.Events.MainFrameNavigated, this._onMainFrameNavigated, this); + SDK.targetManager.addModelListener(SDK.ResourceTreeModel, SDK.ResourceTreeModel.Events.Load, this._onLoad, this); SDK.targetManager.addModelListener( SDK.NetworkManager, SDK.NetworkManager.Events.RequestStarted, this._onRequestStarted, this); SDK.targetManager.addModelListener(
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/ApplicationCacheModel.js b/third_party/WebKit/Source/devtools/front_end/sdk/ApplicationCacheModel.js index 0252af47..e592f77 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/ApplicationCacheModel.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/ApplicationCacheModel.js
@@ -41,8 +41,7 @@ this._agent = target.applicationCacheAgent(); this._agent.enable(); - resourceTreeModel.addEventListener( - SDK.ResourceTreeModel.Events.FrameNavigated, this._frameNavigated, this); + resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.FrameNavigated, this._frameNavigated, this); resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.FrameDetached, this._frameDetached, this); this._statuses = {}; @@ -113,9 +112,10 @@ return; } - for (var i = 0; i < framesWithManifests.length; ++i) + for (var i = 0; i < framesWithManifests.length; ++i) { this._frameManifestUpdated( framesWithManifests[i].frameId, framesWithManifests[i].manifestURL, framesWithManifests[i].status); + } } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/CSSMatchedStyles.js b/third_party/WebKit/Source/devtools/front_end/sdk/CSSMatchedStyles.js index 09801b82..c87e476d 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/CSSMatchedStyles.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/CSSMatchedStyles.js
@@ -39,16 +39,15 @@ function addAttributesStyle() { if (!attributesPayload) return; - var style = new SDK.CSSStyleDeclaration( - cssModel, null, attributesPayload, SDK.CSSStyleDeclaration.Type.Attributes); + var style = + new SDK.CSSStyleDeclaration(cssModel, null, attributesPayload, SDK.CSSStyleDeclaration.Type.Attributes); this._nodeForStyle.set(style, this._node); this._nodeStyles.push(style); } // Inline style has the greatest specificity. if (inlinePayload && this._node.nodeType() === Node.ELEMENT_NODE) { - var style = new SDK.CSSStyleDeclaration( - cssModel, null, inlinePayload, SDK.CSSStyleDeclaration.Type.Inline); + var style = new SDK.CSSStyleDeclaration(cssModel, null, inlinePayload, SDK.CSSStyleDeclaration.Type.Inline); this._nodeForStyle.set(style, this._node); this._nodeStyles.push(style); } @@ -75,8 +74,7 @@ for (var i = 0; parentNode && inheritedPayload && i < inheritedPayload.length; ++i) { var entryPayload = inheritedPayload[i]; var inheritedInlineStyle = entryPayload.inlineStyle ? - new SDK.CSSStyleDeclaration( - cssModel, null, entryPayload.inlineStyle, SDK.CSSStyleDeclaration.Type.Inline) : + new SDK.CSSStyleDeclaration(cssModel, null, entryPayload.inlineStyle, SDK.CSSStyleDeclaration.Type.Inline) : null; if (inheritedInlineStyle && this._containsInherited(inheritedInlineStyle)) { this._nodeForStyle.set(inheritedInlineStyle, parentNode); @@ -395,8 +393,8 @@ foundImportantProperties.add(canonicalName); if (isKnownProperty) { - var overloaded = /** @type {!SDK.CSSProperty} */ ( - propertyToEffectiveRule.get(canonicalName).get(canonicalName)); + var overloaded = + /** @type {!SDK.CSSProperty} */ (propertyToEffectiveRule.get(canonicalName).get(canonicalName)); result.set(overloaded, SDK.CSSMatchedStyles.PropertyState.Overloaded); propertyToEffectiveRule.get(canonicalName).delete(canonicalName); }
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/CSSMetadata.js b/third_party/WebKit/Source/devtools/front_end/sdk/CSSMetadata.js index a6d1c6a..38870667 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/CSSMetadata.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/CSSMetadata.js
@@ -178,8 +178,7 @@ var acceptedKeywords = ['inherit', 'initial']; propertyName = propertyName.toLowerCase(); var unprefixedName = propertyName.replace(/^-webkit-/, ''); - var entry = SDK.CSSMetadata._propertyDataMap[propertyName] || - SDK.CSSMetadata._propertyDataMap[unprefixedName]; + var entry = SDK.CSSMetadata._propertyDataMap[propertyName] || SDK.CSSMetadata._propertyDataMap[unprefixedName]; if (entry && entry.values) acceptedKeywords.pushAll(entry.values); if (this.isColorAwareProperty(propertyName)) { @@ -218,8 +217,7 @@ */ SDK.cssMetadata = function() { if (!SDK.CSSMetadata._instance) - SDK.CSSMetadata._instance = - new SDK.CSSMetadata(SDK.CSSMetadata._generatedProperties || []); + SDK.CSSMetadata._instance = new SDK.CSSMetadata(SDK.CSSMetadata._generatedProperties || []); return SDK.CSSMetadata._instance; };
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/CSSModel.js b/third_party/WebKit/Source/devtools/front_end/sdk/CSSModel.js index d7531e0..4ae6163 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/CSSModel.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/CSSModel.js
@@ -41,8 +41,7 @@ this._domModel = domModel; this._agent = target.cssAgent(); this._styleLoader = new SDK.CSSModel.ComputedStyleLoader(this); - SDK.targetManager.addEventListener( - SDK.TargetManager.Events.MainFrameNavigated, this._mainFrameNavigated, this); + SDK.targetManager.addEventListener(SDK.TargetManager.Events.MainFrameNavigated, this._mainFrameNavigated, this); target.registerCSSDispatcher(new SDK.CSSDispatcher(this)); this._agent.enable().then(this._wasEnabled.bind(this)); /** @type {!Map.<string, !SDK.CSSStyleSheetHeader>} */ @@ -304,8 +303,7 @@ this._sourceMapByURL.set(header.sourceMapURL, editResult.map); this.dispatchEventToListeners( - SDK.CSSModel.Events.SourceMapChanged, - {sourceMap: editResult.map, newSources: editResult.newSources}); + SDK.CSSModel.Events.SourceMapChanged, {sourceMap: editResult.map, newSources: editResult.newSources}); return Promise.resolve(true); } @@ -627,12 +625,10 @@ if (error || !inlinePayload) return null; var inlineStyle = inlinePayload ? - new SDK.CSSStyleDeclaration( - this, null, inlinePayload, SDK.CSSStyleDeclaration.Type.Inline) : + new SDK.CSSStyleDeclaration(this, null, inlinePayload, SDK.CSSStyleDeclaration.Type.Inline) : null; var attributesStyle = attributesStylePayload ? - new SDK.CSSStyleDeclaration( - this, null, attributesStylePayload, SDK.CSSStyleDeclaration.Type.Attributes) : + new SDK.CSSStyleDeclaration(this, null, attributesStylePayload, SDK.CSSStyleDeclaration.Type.Attributes) : null; return new SDK.CSSModel.InlineStyleResult(inlineStyle, attributesStyle); } @@ -788,8 +784,7 @@ * @param {!SDK.CSSModel.Edit=} edit */ _fireStyleSheetChanged(styleSheetId, edit) { - this.dispatchEventToListeners( - SDK.CSSModel.Events.StyleSheetChanged, {styleSheetId: styleSheetId, edit: edit}); + this.dispatchEventToListeners(SDK.CSSModel.Events.StyleSheetChanged, {styleSheetId: styleSheetId, edit: edit}); } /** @@ -1167,9 +1162,10 @@ * @return {!Promise<?Map<string, string>>} */ computedStylePromise(nodeId) { - if (!this._nodeIdToPromise.has(nodeId)) + if (!this._nodeIdToPromise.has(nodeId)) { this._nodeIdToPromise.set( nodeId, this._cssModel._agent.getComputedStyleForNode(nodeId, parsePayload).then(cleanUp.bind(this))); + } return /** @type {!Promise.<?Map.<string, string>>} */ (this._nodeIdToPromise.get(nodeId));
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/CSSRule.js b/third_party/WebKit/Source/devtools/front_end/sdk/CSSRule.js index 40edbb5..7c3463e 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/CSSRule.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/CSSRule.js
@@ -41,8 +41,7 @@ this.sourceURL = styleSheetHeader.sourceURL; } this.origin = payload.origin; - this.style = new SDK.CSSStyleDeclaration( - this._cssModel, this, payload.style, SDK.CSSStyleDeclaration.Type.Regular); + this.style = new SDK.CSSStyleDeclaration(this._cssModel, this, payload.style, SDK.CSSStyleDeclaration.Type.Regular); } /** @@ -120,8 +119,7 @@ selectorList: { selectors: [{text: selectorText}], }, - style: - {styleSheetId: '0', range: new Common.TextRange(0, 0, 0, 0), shorthandEntries: [], cssProperties: []} + style: {styleSheetId: '0', range: new Common.TextRange(0, 0, 0, 0), shorthandEntries: [], cssProperties: []} }; return new SDK.CSSStyleRule(cssModel, /** @type {!Protocol.CSS.CSSRule} */ (dummyPayload)); } @@ -165,8 +163,7 @@ if (!firstRange) return null; var lastRange = this.selectors.peekLast().range; - return new Common.TextRange( - firstRange.startLine, firstRange.startColumn, lastRange.endLine, lastRange.endColumn); + return new Common.TextRange(firstRange.startLine, firstRange.startColumn, lastRange.endLine, lastRange.endColumn); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/CSSStyleDeclaration.js b/third_party/WebKit/Source/devtools/front_end/sdk/CSSStyleDeclaration.js index 4762fbf..055b48d 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/CSSStyleDeclaration.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/CSSStyleDeclaration.js
@@ -252,8 +252,7 @@ */ newBlankProperty(index) { index = (typeof index === 'undefined') ? this.pastLastSourcePropertyIndex() : index; - var property = - new SDK.CSSProperty(this, index, '', '', false, false, true, false, '', this._insertionRange(index)); + var property = new SDK.CSSProperty(this, index, '', '', false, false, true, false, '', this._insertionRange(index)); return property; }
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/CSSStyleSheetHeader.js b/third_party/WebKit/Source/devtools/front_end/sdk/CSSStyleSheetHeader.js index d067b6d..0c4d358 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/CSSStyleSheetHeader.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/CSSStyleSheetHeader.js
@@ -43,9 +43,8 @@ * @param {string=} sourceMapURL */ setSourceMapURL(sourceMapURL) { - var completeSourceMapURL = this.sourceURL && sourceMapURL ? - Common.ParsedURL.completeURL(this.sourceURL, sourceMapURL) : - sourceMapURL; + var completeSourceMapURL = + this.sourceURL && sourceMapURL ? Common.ParsedURL.completeURL(this.sourceURL, sourceMapURL) : sourceMapURL; this.sourceMapURL = completeSourceMapURL; }
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/ConsoleModel.js b/third_party/WebKit/Source/devtools/front_end/sdk/ConsoleModel.js index a8e15f18..7bb07cc 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/ConsoleModel.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/ConsoleModel.js
@@ -52,9 +52,9 @@ this._logAgent.enable(); if (!InspectorFrontendHost.isUnderTest()) { this._logAgent.startViolationsReport([ - {name: 'longTask', threshold: 50 }, - {name: 'longLayout', threshold: 30}, - {name: 'blockedEvent', threshold: 100}]); + {name: 'longTask', threshold: 50}, {name: 'longLayout', threshold: 30}, + {name: 'blockedEvent', threshold: 100} + ]); } } } @@ -69,8 +69,7 @@ var requestedText = text; var commandMessage = new SDK.ConsoleMessage( - target, SDK.ConsoleMessage.MessageSource.JS, null, text, - SDK.ConsoleMessage.MessageType.Command); + target, SDK.ConsoleMessage.MessageSource.JS, null, text, SDK.ConsoleMessage.MessageType.Command); commandMessage.setExecutionContextId(executionContext.id); target.consoleModel.addMessage(commandMessage); @@ -131,8 +130,7 @@ msg.target().subTargetsManager.targetForId(msg.workerId)) return; - if (msg.source === SDK.ConsoleMessage.MessageSource.ConsoleAPI && - msg.type === SDK.ConsoleMessage.MessageType.Clear) + if (msg.source === SDK.ConsoleMessage.MessageSource.ConsoleAPI && msg.type === SDK.ConsoleMessage.MessageType.Clear) this.clear(); if (msg.level === SDK.ConsoleMessage.MessageLevel.RevokedError && msg._revokedExceptionId) { @@ -176,8 +174,7 @@ */ _isBlacklisted(msg) { if (msg.source !== SDK.ConsoleMessage.MessageSource.Network || - msg.level !== SDK.ConsoleMessage.MessageLevel.Error || !msg.url || - !msg.url.startsWith('chrome-extension')) + msg.level !== SDK.ConsoleMessage.MessageLevel.Error || !msg.url || !msg.url.startsWith('chrome-extension')) return false; // ignore Chromecast's cast_sender spam @@ -351,9 +348,8 @@ static fromException(target, exceptionDetails, messageType, timestamp, forceUrl) { return new SDK.ConsoleMessage( target, SDK.ConsoleMessage.MessageSource.JS, SDK.ConsoleMessage.MessageLevel.Error, - SDK.ConsoleMessage.simpleTextFromException(exceptionDetails), messageType, - forceUrl || exceptionDetails.url, exceptionDetails.lineNumber, exceptionDetails.columnNumber, undefined, - exceptionDetails.exception ? + SDK.ConsoleMessage.simpleTextFromException(exceptionDetails), messageType, forceUrl || exceptionDetails.url, + exceptionDetails.lineNumber, exceptionDetails.columnNumber, undefined, exceptionDetails.exception ? [SDK.RemoteObject.fromLocalObject(exceptionDetails.text), exceptionDetails.exception] : undefined, exceptionDetails.stackTrace, timestamp, exceptionDetails.executionContextId, exceptionDetails.scriptId); @@ -424,8 +420,7 @@ */ isErrorOrWarning() { return ( - this.level === SDK.ConsoleMessage.MessageLevel.Warning || - this.level === SDK.ConsoleMessage.MessageLevel.Error); + this.level === SDK.ConsoleMessage.MessageLevel.Warning || this.level === SDK.ConsoleMessage.MessageLevel.Error); } /** @@ -602,8 +597,7 @@ targetRemoved(target) { if (this._mainTarget === target) { delete this._mainTarget; - target.consoleModel.removeEventListener( - SDK.ConsoleModel.Events.ConsoleCleared, this._consoleCleared, this); + target.consoleModel.removeEventListener(SDK.ConsoleModel.Events.ConsoleCleared, this._consoleCleared, this); } }
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/DOMModel.js b/third_party/WebKit/Source/devtools/front_end/sdk/DOMModel.js index 1acb20d0..bf4881b 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/DOMModel.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/DOMModel.js
@@ -106,14 +106,12 @@ } if (payload.templateContent) { - this._templateContent = - SDK.DOMNode.create(this._domModel, this.ownerDocument, true, payload.templateContent); + this._templateContent = SDK.DOMNode.create(this._domModel, this.ownerDocument, true, payload.templateContent); this._templateContent.parentNode = this; } if (payload.importedDocument) { - this._importedDocument = - SDK.DOMNode.create(this._domModel, this.ownerDocument, true, payload.importedDocument); + this._importedDocument = SDK.DOMNode.create(this._domModel, this.ownerDocument, true, payload.importedDocument); this._importedDocument.parentNode = this; } @@ -313,8 +311,7 @@ var ancestorShadowRoot = this.ancestorShadowRoot(); if (!ancestorShadowRoot) return null; - return ancestorShadowRoot.shadowRootType() === SDK.DOMNode.ShadowRootTypes.UserAgent ? ancestorShadowRoot : - null; + return ancestorShadowRoot.shadowRootType() === SDK.DOMNode.ShadowRootTypes.UserAgent ? ancestorShadowRoot : null; } /** @@ -669,9 +666,10 @@ */ _setDistributedNodePayloads(payloads) { this._distributedNodes = []; - for (var payload of payloads) - this._distributedNodes.push(new SDK.DOMNodeShortcut( - this._domModel.target(), payload.backendNodeId, payload.nodeType, payload.nodeName)); + for (var payload of payloads) { + this._distributedNodes.push( + new SDK.DOMNodeShortcut(this._domModel.target(), payload.backendNodeId, payload.nodeType, payload.nodeName)); + } } _renumber() { @@ -1261,9 +1259,9 @@ * @this {SDK.DOMModel} */ function onDocumentAvailable() { - if (this._document) + if (this._document) { func(callbackWrapper); - else { + } else { if (callbackWrapper) callbackWrapper('No document'); } @@ -1708,8 +1706,7 @@ */ highlightDOMNodeForTwoSeconds(nodeId) { this.highlightDOMNode(nodeId); - this._hideDOMNodeHighlightTimeout = - setTimeout(SDK.DOMModel.hideDOMNodeHighlight.bind(SDK.DOMModel), 2000); + this._hideDOMNodeHighlightTimeout = setTimeout(SDK.DOMModel.hideDOMNodeHighlight.bind(SDK.DOMModel), 2000); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/DebuggerModel.js b/third_party/WebKit/Source/devtools/front_end/sdk/DebuggerModel.js index 19e6640..74a277e8 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/DebuggerModel.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/DebuggerModel.js
@@ -149,13 +149,13 @@ _pauseOnExceptionStateChanged() { var state; - if (!Common.moduleSetting('pauseOnExceptionEnabled').get()) { + if (!Common.moduleSetting('pauseOnExceptionEnabled').get()) state = SDK.DebuggerModel.PauseOnExceptionsState.DontPauseOnExceptions; - } else if (Common.moduleSetting('pauseOnCaughtException').get()) { + else if (Common.moduleSetting('pauseOnCaughtException').get()) state = SDK.DebuggerModel.PauseOnExceptionsState.PauseOnAllExceptions; - } else { + else state = SDK.DebuggerModel.PauseOnExceptionsState.PauseOnUncaughtExceptions; - } + this._agent.setPauseOnExceptions(state); } @@ -226,8 +226,7 @@ function didSetBreakpoint(error, breakpointId, locations) { if (callback) { var rawLocations = locations ? - locations.map( - SDK.DebuggerModel.Location.fromPayload.bind(SDK.DebuggerModel.Location, this)) : + locations.map(SDK.DebuggerModel.Location.fromPayload.bind(SDK.DebuggerModel.Location, this)) : []; callback(error ? null : breakpointId, rawLocations); } @@ -383,10 +382,11 @@ return; } - if (!error && callFrames && callFrames.length) + if (!error && callFrames && callFrames.length) { this._pausedScript( callFrames, this._debuggerPausedDetails.reason, this._debuggerPausedDetails.auxData, this._debuggerPausedDetails.breakpointIds, asyncStackTrace); + } callback(error, exceptionDetails); } @@ -413,10 +413,8 @@ this._debuggerPausedDetails = debuggerPausedDetails; if (this._debuggerPausedDetails) { if (Runtime.experiments.isEnabled('emptySourceMapAutoStepping')) { - if (this.dispatchEventToListeners( - SDK.DebuggerModel.Events.BeforeDebuggerPaused, this._debuggerPausedDetails)) { + if (this.dispatchEventToListeners(SDK.DebuggerModel.Events.BeforeDebuggerPaused, this._debuggerPausedDetails)) return false; - } } this.dispatchEventToListeners(SDK.DebuggerModel.Events.DebuggerPaused, this._debuggerPausedDetails); } @@ -551,9 +549,8 @@ closestScript = script; break; } - return closestScript ? - new SDK.DebuggerModel.Location(this, closestScript.scriptId, lineNumber, columnNumber) : - null; + return closestScript ? new SDK.DebuggerModel.Location(this, closestScript.scriptId, lineNumber, columnNumber) : + null; } /** @@ -687,9 +684,10 @@ } } var debuggerLocation = null; - if (location) + if (location) { debuggerLocation = this.createRawLocationByScriptId( location.value.scriptId, location.value.lineNumber, location.value.columnNumber); + } return {location: debuggerLocation, functionName: functionName ? functionName.value : ''}; } } @@ -761,8 +759,7 @@ * @override */ dispose() { - Common.moduleSetting('pauseOnExceptionEnabled') - .removeChangeListener(this._pauseOnExceptionStateChanged, this); + Common.moduleSetting('pauseOnExceptionEnabled').removeChangeListener(this._pauseOnExceptionStateChanged, this); Common.moduleSetting('pauseOnCaughtException').removeChangeListener(this._pauseOnExceptionStateChanged, this); Common.moduleSetting('enableAsyncStackTraces').removeChangeListener(this.asyncStackTracesStateChanged, this); } @@ -975,8 +972,7 @@ * @return {!SDK.DebuggerModel.Location} */ static fromPayload(debuggerModel, payload) { - return new SDK.DebuggerModel.Location( - debuggerModel, payload.scriptId, payload.lineNumber, payload.columnNumber); + return new SDK.DebuggerModel.Location(debuggerModel, payload.scriptId, payload.lineNumber, payload.columnNumber); } /** @@ -1250,12 +1246,14 @@ return this._object; var runtimeModel = this._callFrame.target().runtimeModel; - var declarativeScope = this._type !== Protocol.Debugger.ScopeType.With && this._type !== Protocol.Debugger.ScopeType.Global; - if (declarativeScope) + var declarativeScope = + this._type !== Protocol.Debugger.ScopeType.With && this._type !== Protocol.Debugger.ScopeType.Global; + if (declarativeScope) { this._object = runtimeModel.createScopeRemoteObject( this._payload.object, new SDK.ScopeRef(this._ordinal, this._callFrame.id)); - else + } else { this._object = runtimeModel.createRemoteObject(this._payload.object); + } return this._object; } @@ -1264,7 +1262,8 @@ * @return {string} */ description() { - var declarativeScope = this._type !== Protocol.Debugger.ScopeType.With && this._type !== Protocol.Debugger.ScopeType.Global; + var declarativeScope = + this._type !== Protocol.Debugger.ScopeType.With && this._type !== Protocol.Debugger.ScopeType.Global; return declarativeScope ? '' : (this._payload.object.description || ''); } };
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/HeapProfilerModel.js b/third_party/WebKit/Source/devtools/front_end/sdk/HeapProfilerModel.js index 5062e3a..7179be7 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/HeapProfilerModel.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/HeapProfilerModel.js
@@ -45,8 +45,7 @@ */ lastSeenObjectId(lastSeenObjectId, timestamp) { this.dispatchEventToListeners( - SDK.HeapProfilerModel.Events.LastSeenObjectId, - {lastSeenObjectId: lastSeenObjectId, timestamp: timestamp}); + SDK.HeapProfilerModel.Events.LastSeenObjectId, {lastSeenObjectId: lastSeenObjectId, timestamp: timestamp}); } /** @@ -63,8 +62,7 @@ */ reportHeapSnapshotProgress(done, total, finished) { this.dispatchEventToListeners( - SDK.HeapProfilerModel.Events.ReportHeapSnapshotProgress, - {done: done, total: total, finished: finished}); + SDK.HeapProfilerModel.Events.ReportHeapSnapshotProgress, {done: done, total: total, finished: finished}); } resetProfiles() {
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/InspectorBackend.js b/third_party/WebKit/Source/devtools/front_end/sdk/InspectorBackend.js index 87c97db..cace94a 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/InspectorBackend.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/InspectorBackend.js
@@ -345,10 +345,11 @@ --this._pendingResponsesCount; delete this._callbacks[messageObject.id]; - if (InspectorBackendClass.Options.dumpInspectorTimeStats) + if (InspectorBackendClass.Options.dumpInspectorTimeStats) { console.log( 'time-stats: ' + callback.methodName + ' = ' + (processingStartTime - callback.sendRequestTime) + ' + ' + (Date.now() - processingStartTime)); + } if (this._scripts && !this._pendingResponsesCount) this._deprecatedRunAfterPendingDispatches();
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/InspectorBackendHostedMode.js b/third_party/WebKit/Source/devtools/front_end/sdk/InspectorBackendHostedMode.js index 79de893..f3346d24 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/InspectorBackendHostedMode.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/InspectorBackendHostedMode.js
@@ -62,9 +62,9 @@ var types = domain['types'] || []; for (var j = 0; j < types.length; ++j) { var type = types[j]; - if ((type['type'] === 'string') && type['enum']) + if ((type['type'] === 'string') && type['enum']) { result.push(generateEnum(domain.domain + '.' + type.id, type['enum'])); - else if (type['type'] === 'object') { + } else if (type['type'] === 'object') { var properties = type['properties'] || []; for (var k = 0; k < properties.length; ++k) { var property = properties[k]; @@ -83,9 +83,9 @@ var parameter = parameters[k]; var type; - if (parameter.type) + if (parameter.type) { type = jsTypes[parameter.type] || parameter.type; - else { + } else { var ref = parameter['$ref']; if (ref.indexOf('.') !== -1) type = rawTypes[ref];
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/NetworkLog.js b/third_party/WebKit/Source/devtools/front_end/sdk/NetworkLog.js index 3fc4922bd..176ae779 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/NetworkLog.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/NetworkLog.js
@@ -46,8 +46,7 @@ resourceTreeModel.addEventListener( SDK.ResourceTreeModel.Events.MainFrameNavigated, this._onMainFrameNavigated, this); resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.Load, this._onLoad, this); - resourceTreeModel.addEventListener( - SDK.ResourceTreeModel.Events.DOMContentLoaded, this._onDOMContentLoaded, this); + resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.DOMContentLoaded, this._onDOMContentLoaded, this); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/NetworkManager.js b/third_party/WebKit/Source/devtools/front_end/sdk/NetworkManager.js index 0a8fce5..64907b7 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/NetworkManager.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/NetworkManager.js
@@ -237,8 +237,7 @@ if (!this._mimeTypeIsConsistentWithType(networkRequest)) { var consoleModel = this._manager._target.consoleModel; consoleModel.addMessage(new SDK.ConsoleMessage( - consoleModel.target(), SDK.ConsoleMessage.MessageSource.Network, - SDK.ConsoleMessage.MessageLevel.Log, + consoleModel.target(), SDK.ConsoleMessage.MessageSource.Network, SDK.ConsoleMessage.MessageLevel.Log, Common.UIString( 'Resource interpreted as %s but transferred with MIME type %s: "%s".', networkRequest.resourceType().title(), networkRequest.mimeType, networkRequest.url), @@ -264,10 +263,10 @@ return true; var resourceType = networkRequest.resourceType(); - if (resourceType !== Common.resourceTypes.Stylesheet && - resourceType !== Common.resourceTypes.Document && resourceType !== Common.resourceTypes.TextTrack) { + if (resourceType !== Common.resourceTypes.Stylesheet && resourceType !== Common.resourceTypes.Document && + resourceType !== Common.resourceTypes.TextTrack) return true; - } + if (!networkRequest.mimeType) return true; // Might be not known for cached resources with null responses. @@ -321,8 +320,9 @@ return; this.responseReceived(requestId, frameId, loaderId, time, Protocol.Page.ResourceType.Other, redirectResponse); networkRequest = this._appendRedirect(requestId, time, request.url); - } else + } else { networkRequest = this._createNetworkRequest(requestId, frameId, loaderId, request.url, documentURL, initiator); + } networkRequest.hasNetworkData = true; this._updateNetworkRequestWithRequest(networkRequest, request); networkRequest.setIssueTime(time, wallTime); @@ -432,8 +432,7 @@ if (blockedReason === Protocol.Network.BlockedReason.Inspector) { var consoleModel = this._manager._target.consoleModel; consoleModel.addMessage(new SDK.ConsoleMessage( - consoleModel.target(), SDK.ConsoleMessage.MessageSource.Network, - SDK.ConsoleMessage.MessageLevel.Warning, + consoleModel.target(), SDK.ConsoleMessage.MessageSource.Network, SDK.ConsoleMessage.MessageLevel.Warning, Common.UIString('Request was blocked by DevTools: "%s".', networkRequest.url), SDK.ConsoleMessage.MessageType.Log, '', 0, 0, networkRequest.requestId)); } @@ -646,8 +645,7 @@ * @param {?Protocol.Network.Initiator} initiator */ _createNetworkRequest(requestId, frameId, loaderId, url, documentURL, initiator) { - return new SDK.NetworkRequest( - this._manager._target, requestId, url, documentURL, frameId, loaderId, initiator); + return new SDK.NetworkRequest(this._manager._target, requestId, url, documentURL, frameId, loaderId, initiator); } };
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/NetworkRequest.js b/third_party/WebKit/Source/devtools/front_end/sdk/NetworkRequest.js index f42a9e7..4dbbcc9 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/NetworkRequest.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/NetworkRequest.js
@@ -517,10 +517,10 @@ var inspectedURL = this.target().inspectedURL().asParsedURL(); this._path = this._path.trimURL(inspectedURL ? inspectedURL.host : ''); - if (this._parsedURL.lastPathComponent || this._parsedURL.queryParams) + if (this._parsedURL.lastPathComponent || this._parsedURL.queryParams) { this._name = this._parsedURL.lastPathComponent + (this._parsedURL.queryParams ? '?' + this._parsedURL.queryParams : ''); - else if (this._parsedURL.folderPathComponents) { + } else if (this._parsedURL.folderPathComponents) { this._name = this._parsedURL.folderPathComponents.substring(this._parsedURL.folderPathComponents.lastIndexOf('/') + 1) + '/'; @@ -734,8 +734,7 @@ */ get responseCookies() { if (!this._responseCookies) - this._responseCookies = - SDK.CookieParser.parseSetCookie(this.target(), this.responseHeaderValue('Set-Cookie')); + this._responseCookies = SDK.CookieParser.parseSetCookie(this.target(), this.responseHeaderValue('Set-Cookie')); return this._responseCookies; } @@ -1137,8 +1136,7 @@ * @param {boolean} sent */ addFrame(response, time, sent) { - var type = sent ? SDK.NetworkRequest.WebSocketFrameType.Send : - SDK.NetworkRequest.WebSocketFrameType.Receive; + var type = sent ? SDK.NetworkRequest.WebSocketFrameType.Send : SDK.NetworkRequest.WebSocketFrameType.Receive; this._addFrame({ type: type, text: response.payloadData,
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/RemoteObject.js b/third_party/WebKit/Source/devtools/front_end/sdk/RemoteObject.js index 0fc047a7..586b9c4 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/RemoteObject.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/RemoteObject.js
@@ -426,11 +426,11 @@ if (unserializableValue === Protocol.Runtime.UnserializableValue.Infinity || unserializableValue === Protocol.Runtime.UnserializableValue.NegativeInfinity || unserializableValue === Protocol.Runtime.UnserializableValue.Negative0 || - unserializableValue === Protocol.Runtime.UnserializableValue.NaN) { + unserializableValue === Protocol.Runtime.UnserializableValue.NaN) this.value = Number(unserializableValue); - } else { + else this.value = unserializableValue; - } + } else { this.value = value; } @@ -639,8 +639,7 @@ if (!property.value) continue; var propertyValue = this._target.runtimeModel.createRemoteObject(property.value); - internalPropertiesResult.push( - new SDK.RemoteObjectProperty(property.name, propertyValue, true, false)); + internalPropertiesResult.push(new SDK.RemoteObjectProperty(property.name, propertyValue, true, false)); } } callback(result, internalPropertiesResult);
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/Resource.js b/third_party/WebKit/Source/devtools/front_end/sdk/Resource.js index 1f72458a..9c55e71 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/Resource.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/Resource.js
@@ -222,11 +222,12 @@ callback(searchMatches || []); } - if (this.frameId) + if (this.frameId) { this.target().pageAgent().searchInResource( this.frameId, this.url, query, caseSensitive, isRegex, callbackWrapper); - else + } else { callback([]); + } } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/ResourceTreeModel.js b/third_party/WebKit/Source/devtools/front_end/sdk/ResourceTreeModel.js index 48ea293..5a0ed86 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/ResourceTreeModel.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/ResourceTreeModel.js
@@ -40,8 +40,7 @@ constructor(target, networkManager, securityOriginManager) { super(SDK.ResourceTreeModel, target); if (networkManager) { - networkManager.addEventListener( - SDK.NetworkManager.Events.RequestFinished, this._onRequestFinished, this); + networkManager.addEventListener(SDK.NetworkManager.Events.RequestFinished, this._onRequestFinished, this); networkManager.addEventListener( SDK.NetworkManager.Events.RequestUpdateDropped, this._onRequestUpdateDropped, this); } @@ -426,9 +425,9 @@ if (!frameB && frameA) return 1; - if (frameA && frameB) { + if (frameA && frameB) return frameA.id.localeCompare(frameB.id); - } + return SDK.ExecutionContext.comparator(a, b); } };
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/RuntimeModel.js b/third_party/WebKit/Source/devtools/front_end/sdk/RuntimeModel.js index 127d627b..e0e519f5 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/RuntimeModel.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/RuntimeModel.js
@@ -98,9 +98,9 @@ _executionContextCreated(context) { // The private script context should be hidden behind an experiment. if (context.name === SDK.RuntimeModel._privateScript && !context.origin && - !Runtime.experiments.isEnabled('privateScriptInspection')) { + !Runtime.experiments.isEnabled('privateScriptInspection')) return; - } + var data = context.auxData || {isDefault: true}; var executionContext = new SDK.ExecutionContext( this.target(), context.id, context.name, context.origin, data['isDefault'], data['frameId']); @@ -392,9 +392,9 @@ */ exceptionRevoked(reason, exceptionId) { var consoleMessage = new SDK.ConsoleMessage( - this._runtimeModel.target(), SDK.ConsoleMessage.MessageSource.JS, - SDK.ConsoleMessage.MessageLevel.RevokedError, reason, undefined, undefined, undefined, undefined, - undefined, undefined, undefined, undefined, undefined, undefined); + this._runtimeModel.target(), SDK.ConsoleMessage.MessageSource.JS, SDK.ConsoleMessage.MessageLevel.RevokedError, + reason, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, + undefined); consoleMessage.setRevokedExceptionId(exceptionId); this._runtimeModel.target().consoleModel.addMessage(consoleMessage); } @@ -411,8 +411,7 @@ var level = SDK.ConsoleMessage.MessageLevel.Log; if (type === SDK.ConsoleMessage.MessageType.Debug) level = SDK.ConsoleMessage.MessageLevel.Debug; - if (type === SDK.ConsoleMessage.MessageType.Error || - type === SDK.ConsoleMessage.MessageType.Assert) + if (type === SDK.ConsoleMessage.MessageType.Error || type === SDK.ConsoleMessage.MessageType.Assert) level = SDK.ConsoleMessage.MessageLevel.Error; if (type === SDK.ConsoleMessage.MessageType.Warning) level = SDK.ConsoleMessage.MessageLevel.Warning;
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/Script.js b/third_party/WebKit/Source/devtools/front_end/sdk/Script.js index 11571ddd..177b47e 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/Script.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/Script.js
@@ -115,9 +115,8 @@ var text = Common.UIString( '\'//@ sourceURL\' and \'//@ sourceMappingURL\' are deprecated, please use \'//# sourceURL=\' and \'//# sourceMappingURL=\' instead.'); var msg = new SDK.ConsoleMessage( - script.target(), SDK.ConsoleMessage.MessageSource.JS, SDK.ConsoleMessage.MessageLevel.Warning, - text, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, - script.scriptId); + script.target(), SDK.ConsoleMessage.MessageSource.JS, SDK.ConsoleMessage.MessageLevel.Warning, text, undefined, + undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, script.scriptId); consoleModel.addMessage(msg); } @@ -258,11 +257,12 @@ // We append correct sourceURL to script for consistency only. It's not actually needed for things to work correctly. newSource = this._appendSourceURLCommentIfNeeded(newSource); - if (this.scriptId) + if (this.scriptId) { this.target().debuggerAgent().setScriptSource( this.scriptId, newSource, undefined, didEditScriptSource.bind(this)); - else + } else { callback('Script failed to parse'); + } } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/ServiceWorkerCacheModel.js b/third_party/WebKit/Source/devtools/front_end/sdk/ServiceWorkerCacheModel.js index 66a1570..0408bacd 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/ServiceWorkerCacheModel.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/ServiceWorkerCacheModel.js
@@ -34,8 +34,7 @@ var instance = /** @type {?SDK.ServiceWorkerCacheModel} */ (target.model(SDK.ServiceWorkerCacheModel)); if (!instance) - instance = - new SDK.ServiceWorkerCacheModel(target, SDK.SecurityOriginManager.fromTarget(target)); + instance = new SDK.ServiceWorkerCacheModel(target, SDK.SecurityOriginManager.fromTarget(target)); return instance; } @@ -203,8 +202,8 @@ var oldCaches = new Map(); for (var cacheJson of cachesJson) { - var cache = new SDK.ServiceWorkerCacheModel.Cache( - cacheJson.securityOrigin, cacheJson.cacheName, cacheJson.cacheId); + var cache = + new SDK.ServiceWorkerCacheModel.Cache(cacheJson.securityOrigin, cacheJson.cacheName, cacheJson.cacheId); updatingCachesIds.add(cache.cacheId); if (this._caches.has(cache.cacheId)) continue; @@ -264,9 +263,9 @@ return; } var entries = []; - for (var i = 0; i < dataEntries.length; ++i) { + for (var i = 0; i < dataEntries.length; ++i) entries.push(new SDK.ServiceWorkerCacheModel.Entry(dataEntries[i].request, dataEntries[i].response)); - } + callback(entries, hasMore); } this._agent.requestEntries(cache.cacheId, skipCount, pageSize, innerCallback);
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/ServiceWorkerManager.js b/third_party/WebKit/Source/devtools/front_end/sdk/ServiceWorkerManager.js index e910c1e5..712f1ea5 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/ServiceWorkerManager.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/ServiceWorkerManager.js
@@ -535,8 +535,7 @@ serviceWorkerManager.addEventListener( SDK.ServiceWorkerManager.Events.RegistrationDeleted, this._registrationsUpdated, this); SDK.targetManager.addModelListener( - SDK.RuntimeModel, SDK.RuntimeModel.Events.ExecutionContextCreated, - this._executionContextCreated, this); + SDK.RuntimeModel, SDK.RuntimeModel.Events.ExecutionContextCreated, this._executionContextCreated, this); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/SourceMap.js b/third_party/WebKit/Source/devtools/front_end/sdk/SourceMap.js index a6a2b28..7ebf895 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/SourceMap.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/SourceMap.js
@@ -374,9 +374,10 @@ return []; var mappings = this.mappings(); var info = this._sourceInfos.get(sourceURL); - if (info.reverseMappings === null) + if (info.reverseMappings === null) { info.reverseMappings = mappings.filter((mapping) => mapping.sourceURL === sourceURL).sort(sourceMappingComparator); + } return info.reverseMappings; /** @@ -445,9 +446,9 @@ var sourceURL = sources[sourceIndex]; while (true) { - if (stringCharIterator.peek() === ',') + if (stringCharIterator.peek() === ',') { stringCharIterator.next(); - else { + } else { while (stringCharIterator.peek() === ';') { lineNumber += 1; columnNumber = 0;
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/SubTargetsManager.js b/third_party/WebKit/Source/devtools/front_end/sdk/SubTargetsManager.js index 2c02e63..605acf35f 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/SubTargetsManager.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/SubTargetsManager.js
@@ -29,16 +29,14 @@ this._agent.setRemoteLocations(defaultLocations); this._agent.setDiscoverTargets(true); } - SDK.targetManager.addEventListener( - SDK.TargetManager.Events.MainFrameNavigated, this._mainFrameNavigated, this); + SDK.targetManager.addEventListener(SDK.TargetManager.Events.MainFrameNavigated, this._mainFrameNavigated, this); } /** * @param {!SDK.Target} target * @return {?SDK.SubTargetsManager} */ - static fromTarget(target) - { + static fromTarget(target) { return /** @type {?SDK.SubTargetsManager} */ (target.model(SDK.SubTargetsManager)); } @@ -128,12 +126,11 @@ if (type === 'worker') return SDK.Target.Capability.JS | SDK.Target.Capability.Log; if (type === 'service_worker') - return SDK.Target.Capability.Log | SDK.Target.Capability.Network | - SDK.Target.Capability.Target; - if (type === 'iframe') - return SDK.Target.Capability.Browser | SDK.Target.Capability.DOM | - SDK.Target.Capability.JS | SDK.Target.Capability.Log | - SDK.Target.Capability.Network | SDK.Target.Capability.Target; + return SDK.Target.Capability.Log | SDK.Target.Capability.Network | SDK.Target.Capability.Target; + if (type === 'iframe') { + return SDK.Target.Capability.Browser | SDK.Target.Capability.DOM | SDK.Target.Capability.JS | + SDK.Target.Capability.Log | SDK.Target.Capability.Network | SDK.Target.Capability.Target; + } if (type === 'node') return SDK.Target.Capability.JS; return 0; @@ -193,7 +190,8 @@ var connection = this._connections.get(targetId); connection._onDisconnect.call(null, 'target terminated'); this._connections.delete(targetId); - this.dispatchEventToListeners(SDK.SubTargetsManager.Events.PendingTargetDetached, this._pendingTargets.get(targetId)); + this.dispatchEventToListeners( + SDK.SubTargetsManager.Events.PendingTargetDetached, this._pendingTargets.get(targetId)); } /** @@ -447,8 +445,7 @@ /** * @param {!SDK.Target} target */ - notifyAttached(target) - { + notifyAttached(target) { if (this._attachedCallback) this._attachedCallback(target); this._connectPromise = null; @@ -458,8 +455,7 @@ /** * @return {boolean} */ - canConnect() - { + canConnect() { return this._isRemote; } };
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/TargetManager.js b/third_party/WebKit/Source/devtools/front_end/sdk/TargetManager.js index f7d7a98..dca142a 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/TargetManager.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/TargetManager.js
@@ -174,8 +174,8 @@ if (target.hasNetworkCapability()) networkManager = new SDK.NetworkManager(target); if (networkManager && target.hasDOMCapability()) { - resourceTreeModel = new SDK.ResourceTreeModel( - target, networkManager, SDK.SecurityOriginManager.fromTarget(target)); + resourceTreeModel = + new SDK.ResourceTreeModel(target, networkManager, SDK.SecurityOriginManager.fromTarget(target)); new SDK.NetworkLog(target, resourceTreeModel, networkManager); } @@ -225,15 +225,11 @@ if (this._targets.length === 1 && resourceTreeModel) { resourceTreeModel[SDK.TargetManager._listenersSymbol] = [ setupRedispatch.call( - this, SDK.ResourceTreeModel.Events.MainFrameNavigated, - SDK.TargetManager.Events.MainFrameNavigated), + this, SDK.ResourceTreeModel.Events.MainFrameNavigated, SDK.TargetManager.Events.MainFrameNavigated), setupRedispatch.call(this, SDK.ResourceTreeModel.Events.Load, SDK.TargetManager.Events.Load), setupRedispatch.call( - this, SDK.ResourceTreeModel.Events.PageReloadRequested, - SDK.TargetManager.Events.PageReloadRequested), - setupRedispatch.call( - this, SDK.ResourceTreeModel.Events.WillReloadPage, - SDK.TargetManager.Events.WillReloadPage) + this, SDK.ResourceTreeModel.Events.PageReloadRequested, SDK.TargetManager.Events.PageReloadRequested), + setupRedispatch.call(this, SDK.ResourceTreeModel.Events.WillReloadPage, SDK.TargetManager.Events.WillReloadPage) ]; } var copy = this._observersForTarget(target); @@ -344,18 +340,16 @@ } _connectAndCreateMainTarget() { - var capabilities = SDK.Target.Capability.Browser | SDK.Target.Capability.DOM | - SDK.Target.Capability.JS | SDK.Target.Capability.Log | - SDK.Target.Capability.Network | SDK.Target.Capability.Target; + var capabilities = SDK.Target.Capability.Browser | SDK.Target.Capability.DOM | SDK.Target.Capability.JS | + SDK.Target.Capability.Log | SDK.Target.Capability.Network | SDK.Target.Capability.Target; if (Runtime.queryParam('isSharedWorker')) { - capabilities = SDK.Target.Capability.Browser | SDK.Target.Capability.Log | - SDK.Target.Capability.Network | SDK.Target.Capability.Target; + capabilities = SDK.Target.Capability.Browser | SDK.Target.Capability.Log | SDK.Target.Capability.Network | + SDK.Target.Capability.Target; } else if (Runtime.queryParam('v8only')) { capabilities = SDK.Target.Capability.JS; } - var target = - this.createTarget(Common.UIString('Main'), capabilities, this._createMainConnection.bind(this), null); + var target = this.createTarget(Common.UIString('Main'), capabilities, this._createMainConnection.bind(this), null); target.runtimeAgent().runIfWaitingForDebugger(); }
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/TracingModel.js b/third_party/WebKit/Source/devtools/front_end/sdk/TracingModel.js index 6961d7f..1bc28ab 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/TracingModel.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/TracingModel.js
@@ -70,9 +70,10 @@ if (typeof payload.id2 === 'undefined') return scope && payload.id ? `${scope}@${payload.id}` : payload.id; var id2 = payload.id2; - if (typeof id2 === 'object' && ('global' in id2) !== ('local' in id2)) + if (typeof id2 === 'object' && ('global' in id2) !== ('local' in id2)) { return typeof id2['global'] !== 'undefined' ? `:${scope}:${id2['global']}` : `:${scope}:${payload.pid}:${id2['local']}`; + } console.error( `Unexpected id2 field at ${payload.ts / 1000}, one and only one of 'local' and 'global' should be present.`); } @@ -105,8 +106,7 @@ tracingModel.devToolsMetadataEvents().filter(e => e.name === 'TracingStartedInBrowser'); if (tracingStartedInBrowser.length === 1) return tracingStartedInBrowser[0].thread; - Common.console.error( - 'Failed to find browser main thread in trace, some timeline features may be unavailable'); + Common.console.error('Failed to find browser main thread in trace, some timeline features may be unavailable'); return null; } @@ -513,8 +513,7 @@ */ static fromPayload(payload, thread) { var event = new SDK.TracingModel.Event( - payload.cat, payload.name, /** @type {!SDK.TracingModel.Phase} */ (payload.ph), payload.ts / 1000, - thread); + payload.cat, payload.name, /** @type {!SDK.TracingModel.Phase} */ (payload.ph), payload.ts / 1000, thread); if (payload.args) event.addArgs(payload.args); else @@ -713,8 +712,7 @@ */ _addStep(event) { this.steps.push(event); - if (event.phase === SDK.TracingModel.Phase.AsyncEnd || - event.phase === SDK.TracingModel.Phase.NestableAsyncEnd) { + if (event.phase === SDK.TracingModel.Phase.AsyncEnd || event.phase === SDK.TracingModel.Phase.NestableAsyncEnd) { this.setEndTime(event.startTime); // FIXME: ideally, we shouldn't do this, but this makes the logic of converting // async console events to sync ones much simpler. @@ -887,12 +885,13 @@ if (!stack.length) continue; var top = stack.pop(); - if (top.name !== e.name || top.categoriesString !== e.categoriesString) + if (top.name !== e.name || top.categoriesString !== e.categoriesString) { console.error( 'B/E events mismatch at ' + top.startTime + ' (' + top.name + ') vs. ' + e.startTime + ' (' + e.name + ')'); - else + } else { top._complete(e); + } break; case phases.Begin: stack.push(e);
diff --git a/third_party/WebKit/Source/devtools/front_end/security/SecurityModel.js b/third_party/WebKit/Source/devtools/front_end/security/SecurityModel.js index a91ca22..8e65e9a 100644 --- a/third_party/WebKit/Source/devtools/front_end/security/SecurityModel.js +++ b/third_party/WebKit/Source/devtools/front_end/security/SecurityModel.js
@@ -39,8 +39,9 @@ } else { securityStateMap = new Map(); var ordering = [ - Protocol.Security.SecurityState.Info, Protocol.Security.SecurityState.Insecure, Protocol.Security.SecurityState.Neutral, - Protocol.Security.SecurityState.Warning, Protocol.Security.SecurityState.Secure, + Protocol.Security.SecurityState.Info, Protocol.Security.SecurityState.Insecure, + Protocol.Security.SecurityState.Neutral, Protocol.Security.SecurityState.Warning, + Protocol.Security.SecurityState.Secure, // Unknown is max so that failed/cancelled requests don't overwrite the origin security state for successful requests, // and so that failed/cancelled requests appear at the bottom of the origins list. Protocol.Security.SecurityState.Unknown
diff --git a/third_party/WebKit/Source/devtools/front_end/security/SecurityPanel.js b/third_party/WebKit/Source/devtools/front_end/security/SecurityPanel.js index 4a9c4221..0d797c63 100644 --- a/third_party/WebKit/Source/devtools/front_end/security/SecurityPanel.js +++ b/third_party/WebKit/Source/devtools/front_end/security/SecurityPanel.js
@@ -14,8 +14,7 @@ this._sidebarMainViewElement = new Security.SecurityPanelSidebarTreeElement( Common.UIString('Overview'), this._setVisibleView.bind(this, this._mainView), 'security-main-view-sidebar-tree-item', 'lock-icon'); - this._sidebarTree = - new Security.SecurityPanelSidebarTree(this._sidebarMainViewElement, this.showOrigin.bind(this)); + this._sidebarTree = new Security.SecurityPanelSidebarTree(this._sidebarMainViewElement, this.showOrigin.bind(this)); this.panelSidebarElement().appendChild(this._sidebarTree.element); /** @type {!Map<!Protocol.Network.LoaderId, !SDK.NetworkRequest>} */ @@ -183,7 +182,8 @@ var securityState = /** @type {!Protocol.Security.SecurityState} */ (request.securityState()); - if (request.mixedContentType === Protocol.Network.RequestMixedContentType.Blockable && this._ranInsecureContentStyle) + if (request.mixedContentType === Protocol.Network.RequestMixedContentType.Blockable && + this._ranInsecureContentStyle) securityState = this._ranInsecureContentStyle; else if ( request.mixedContentType === Protocol.Network.RequestMixedContentType.OptionallyBlockable && @@ -205,9 +205,9 @@ originState.securityState = securityState; var securityDetails = request.securityDetails(); - if (securityDetails) { + if (securityDetails) originState.securityDetails = securityDetails; - } + this._origins.set(origin, originState); @@ -296,10 +296,8 @@ var networkManager = SDK.NetworkManager.fromTarget(target); if (networkManager) { listeners = listeners.concat([ - networkManager.addEventListener( - SDK.NetworkManager.Events.ResponseReceived, this._onResponseReceived, this), - networkManager.addEventListener( - SDK.NetworkManager.Events.RequestFinished, this._onRequestFinished, this), + networkManager.addEventListener(SDK.NetworkManager.Events.ResponseReceived, this._onResponseReceived, this), + networkManager.addEventListener(SDK.NetworkManager.Events.RequestFinished, this._onRequestFinished, this), ]); } @@ -603,8 +601,7 @@ var lockSpectrum = this._summarySection.createChild('div', 'lock-spectrum'); lockSpectrum.createChild('div', 'lock-icon lock-icon-secure').title = Common.UIString('Secure'); lockSpectrum.createChild('div', 'lock-icon lock-icon-neutral').title = Common.UIString('Not Secure'); - lockSpectrum.createChild('div', 'lock-icon lock-icon-insecure').title = - Common.UIString('Not Secure (Broken)'); + lockSpectrum.createChild('div', 'lock-icon lock-icon-insecure').title = Common.UIString('Not Secure (Broken)'); this._summarySection.createChild('div', 'triangle-pointer-container') .createChild('div', 'triangle-pointer-wrapper') @@ -629,8 +626,8 @@ text.createChild('div').textContent = explanation.description; if (explanation.hasCertificate) { - text.appendChild(Security.SecurityPanel.createCertificateViewerButton( - Common.UIString('View certificate'), this._panel)); + text.appendChild( + Security.SecurityPanel.createCertificateViewerButton(Common.UIString('View certificate'), this._panel)); } return text; @@ -671,11 +668,10 @@ this._securityExplanationsMain.removeChildren(); this._securityExplanationsExtra.removeChildren(); for (var explanation of this._explanations) { - if (explanation.securityState === Protocol.Security.SecurityState.Info) { + if (explanation.securityState === Protocol.Security.SecurityState.Info) this._addExplanation(this._securityExplanationsExtra, explanation); - } else { + else this._addExplanation(this._securityExplanationsMain, explanation); - } } this._addMixedContentExplanations(); @@ -700,7 +696,7 @@ if (this._insecureContentStatus && (this._insecureContentStatus.ranMixedContent || this._insecureContentStatus.displayedMixedContent)) { - if (this._insecureContentStatus.ranMixedContent) + if (this._insecureContentStatus.ranMixedContent) { this._addMixedContentExplanation( this._securityExplanationsMain, this._insecureContentStatus.ranInsecureContentStyle, Common.UIString('Active Mixed Content'), @@ -708,19 +704,22 @@ 'You have recently allowed non-secure content (such as scripts or iframes) to run on this site.'), Network.NetworkLogView.MixedContentFilterValues.BlockOverridden, showBlockOverriddenMixedContentInNetworkPanel); - if (this._insecureContentStatus.displayedMixedContent) + } + if (this._insecureContentStatus.displayedMixedContent) { this._addMixedContentExplanation( this._securityExplanationsMain, this._insecureContentStatus.displayedInsecureContentStyle, Common.UIString('Mixed Content'), Common.UIString('The site includes HTTP resources.'), Network.NetworkLogView.MixedContentFilterValues.Displayed, showDisplayedMixedContentInNetworkPanel); + } } - if (this._panel.filterRequestCount(Network.NetworkLogView.MixedContentFilterValues.Blocked) > 0) + if (this._panel.filterRequestCount(Network.NetworkLogView.MixedContentFilterValues.Blocked) > 0) { this._addMixedContentExplanation( this._securityExplanationsExtra, Protocol.Security.SecurityState.Info, Common.UIString('Blocked mixed content'), Common.UIString('Your page requested non-secure resources that were blocked.'), Network.NetworkLogView.MixedContentFilterValues.Blocked, showBlockedMixedContentInNetworkPanel); + } /** * @param {!Event} e @@ -783,11 +782,11 @@ } var requestsAnchor = explanation.createChild('div', 'security-mixed-content link'); - if (filterRequestCount === 1) { + if (filterRequestCount === 1) requestsAnchor.textContent = Common.UIString('View %d request in Network Panel', filterRequestCount); - } else { + else requestsAnchor.textContent = Common.UIString('View %d requests in Network Panel', filterRequestCount); - } + requestsAnchor.href = ''; requestsAnchor.addEventListener('click', networkFilterFn); } @@ -810,12 +809,12 @@ } if (this._insecureContentStatus.displayedContentWithCertErrors) { - this._addExplanation(this._securityExplanationsMain, /** @type {!Protocol.Security.SecurityStateExplanation} */ ({ - 'securityState': this._insecureContentStatus.displayedInsecureContentStyle, - 'summary': Common.UIString('Content with certificate errors'), - 'description': Common.UIString( - 'This site includes resources that were loaded with certificate errors.') - })); + this._addExplanation( + this._securityExplanationsMain, /** @type {!Protocol.Security.SecurityStateExplanation} */ ({ + 'securityState': this._insecureContentStatus.displayedInsecureContentStyle, + 'summary': Common.UIString('Content with certificate errors'), + 'description': Common.UIString('This site includes resources that were loaded with certificate errors.') + })); } } }; @@ -857,8 +856,7 @@ if (originState.securityDetails) { var connectionSection = this.element.createChild('div', 'origin-view-section'); - connectionSection.createChild('div', 'origin-view-section-title').textContent = - Common.UIString('Connection'); + connectionSection.createChild('div', 'origin-view-section-title').textContent = Common.UIString('Connection'); var table = new Security.SecurityDetailsTable(); connectionSection.appendChild(table.element()); @@ -873,8 +871,7 @@ // Create the certificate section outside the callback, so that it appears in the right place. var certificateSection = this.element.createChild('div', 'origin-view-section'); - certificateSection.createChild('div', 'origin-view-section-title').textContent = - Common.UIString('Certificate'); + certificateSection.createChild('div', 'origin-view-section-title').textContent = Common.UIString('Certificate'); if (originState.securityDetails.signedCertificateTimestampList.length) { // Create the Certificate Transparency section outside the callback, so that it appears in the right place. @@ -949,8 +946,7 @@ Common.UIString('The security details above are from the first inspected response.'); } else if (originState.securityState !== Protocol.Security.SecurityState.Unknown) { var notSecureSection = this.element.createChild('div', 'origin-view-section'); - notSecureSection.createChild('div', 'origin-view-section-title').textContent = - Common.UIString('Not Secure'); + notSecureSection.createChild('div', 'origin-view-section-title').textContent = Common.UIString('Not Secure'); notSecureSection.createChild('div').textContent = Common.UIString('Your connection to this origin is not secure.'); } else { @@ -1038,10 +1034,9 @@ row.createChild('div').textContent = key; var valueDiv = row.createChild('div'); - if (typeof value === 'string') { + if (typeof value === 'string') valueDiv.textContent = value; - } else { + else valueDiv.appendChild(value); - } } };
diff --git a/third_party/WebKit/Source/devtools/front_end/services/ServiceManager.js b/third_party/WebKit/Source/devtools/front_end/services/ServiceManager.js index 4db082eb..f55a4bd 100644 --- a/third_party/WebKit/Source/devtools/front_end/services/ServiceManager.js +++ b/third_party/WebKit/Source/devtools/front_end/services/ServiceManager.js
@@ -35,8 +35,7 @@ url += '?remoteBase=' + remoteBase; var worker = isSharedWorker ? new SharedWorker(url, appName) : new Worker(url); - var connection = - new Services.ServiceManager.Connection(new Services.ServiceManager.WorkerServicePort(worker)); + var connection = new Services.ServiceManager.Connection(new Services.ServiceManager.WorkerServicePort(worker)); return connection._createService(serviceName); } };
diff --git a/third_party/WebKit/Source/devtools/front_end/settings/EditFileSystemView.js b/third_party/WebKit/Source/devtools/front_end/settings/EditFileSystemView.js index 7c5a0618..d6e143f 100644 --- a/third_party/WebKit/Source/devtools/front_end/settings/EditFileSystemView.js +++ b/third_party/WebKit/Source/devtools/front_end/settings/EditFileSystemView.js
@@ -153,8 +153,7 @@ element.classList.add('locked'); if (item instanceof Workspace.FileSystemMapping.Entry) { var entry = /** @type {!Workspace.FileSystemMapping.Entry} */ (item); - var urlPrefix = - entry.configurable ? entry.urlPrefix : Common.UIString('%s (via .devtools)', entry.urlPrefix); + var urlPrefix = entry.configurable ? entry.urlPrefix : Common.UIString('%s (via .devtools)', entry.urlPrefix); var urlPrefixElement = element.createChild('div', 'file-system-value'); urlPrefixElement.textContent = urlPrefix; urlPrefixElement.title = urlPrefix; @@ -203,9 +202,10 @@ this._fileSystemPath, this._normalizePrefix(editor.control('urlPrefix').value), this._normalizePrefix(editor.control('pathPrefix').value)); } else { - if (!isNew) + if (!isNew) { Workspace.isolatedFileSystemManager.fileSystem(this._fileSystemPath) .removeExcludedFolder(/** @type {string} */ (item)); + } Workspace.isolatedFileSystemManager.fileSystem(this._fileSystemPath) .addExcludedFolder(this._normalizePrefix(editor.control('pathPrefix').value)); }
diff --git a/third_party/WebKit/Source/devtools/front_end/settings/SettingsScreen.js b/third_party/WebKit/Source/devtools/front_end/settings/SettingsScreen.js index 9ae4eb94..85c68583 100644 --- a/third_party/WebKit/Source/devtools/front_end/settings/SettingsScreen.js +++ b/third_party/WebKit/Source/devtools/front_end/settings/SettingsScreen.js
@@ -45,8 +45,8 @@ .createChild('div', 'settings-window-title') .textContent = Common.UIString('Settings'); - this._tabbedLocation = UI.viewManager.createTabbedLocation( - () => Settings.SettingsScreen._showSettingsScreen(), 'settings-view'); + this._tabbedLocation = + UI.viewManager.createTabbedLocation(() => Settings.SettingsScreen._showSettingsScreen(), 'settings-view'); var tabbedPane = this._tabbedLocation.tabbedPane(); tabbedPane.leftToolbar().appendToolbarItem(new UI.ToolbarItem(settingsLabelElement)); tabbedPane.setShrinkableTabs(false); @@ -314,8 +314,8 @@ inputElement.type = 'text'; inputElement.style.width = '270px'; var folderExcludeSetting = Workspace.isolatedFileSystemManager.workspaceFolderExcludePatternSetting(); - var setValue = UI.bindInput( - inputElement, folderExcludeSetting.set.bind(folderExcludeSetting), regexValidator, false); + var setValue = + UI.bindInput(inputElement, folderExcludeSetting.set.bind(folderExcludeSetting), regexValidator, false); folderExcludeSetting.addChangeListener(() => setValue.call(null, folderExcludeSetting.get())); setValue(folderExcludeSetting.get()); return p;
diff --git a/third_party/WebKit/Source/devtools/front_end/snippets/ScriptSnippetModel.js b/third_party/WebKit/Source/devtools/front_end/snippets/ScriptSnippetModel.js index b3c58509..0f5b84c 100644 --- a/third_party/WebKit/Source/devtools/front_end/snippets/ScriptSnippetModel.js +++ b/third_party/WebKit/Source/devtools/front_end/snippets/ScriptSnippetModel.js
@@ -280,8 +280,8 @@ */ _printRunScriptResult(target, result, scriptId, sourceURL) { var consoleMessage = new SDK.ConsoleMessage( - target, SDK.ConsoleMessage.MessageSource.JS, SDK.ConsoleMessage.MessageLevel.Log, '', - undefined, sourceURL, undefined, undefined, undefined, [result], undefined, undefined, undefined, scriptId); + target, SDK.ConsoleMessage.MessageSource.JS, SDK.ConsoleMessage.MessageLevel.Log, '', undefined, sourceURL, + undefined, undefined, undefined, [result], undefined, undefined, undefined, scriptId); target.consoleModel.addMessage(consoleMessage); } @@ -291,8 +291,8 @@ * @param {?string=} sourceURL */ _printRunOrCompileScriptResultFailure(target, exceptionDetails, sourceURL) { - target.consoleModel.addMessage(SDK.ConsoleMessage.fromException( - target, exceptionDetails, undefined, undefined, sourceURL || undefined)); + target.consoleModel.addMessage( + SDK.ConsoleMessage.fromException(target, exceptionDetails, undefined, undefined, sourceURL || undefined)); } /** @@ -534,8 +534,7 @@ * @this {Snippets.SnippetContentProvider} */ function performSearch() { - callback( - Common.ContentProvider.performSearchInContent(this._snippet.content, query, caseSensitive, isRegex)); + callback(Common.ContentProvider.performSearchInContent(this._snippet.content, query, caseSensitive, isRegex)); } // searchInContent should call back later.
diff --git a/third_party/WebKit/Source/devtools/front_end/snippets/SnippetStorage.js b/third_party/WebKit/Source/devtools/front_end/snippets/SnippetStorage.js index 3c8d928..af727702 100644 --- a/third_party/WebKit/Source/devtools/front_end/snippets/SnippetStorage.js +++ b/third_party/WebKit/Source/devtools/front_end/snippets/SnippetStorage.js
@@ -37,8 +37,7 @@ /** @type {!Map<string,!Snippets.Snippet>} */ this._snippets = new Map(); - this._lastSnippetIdentifierSetting = - Common.settings.createSetting(settingPrefix + 'Snippets_lastIdentifier', 0); + this._lastSnippetIdentifierSetting = Common.settings.createSetting(settingPrefix + 'Snippets_lastIdentifier', 0); this._snippetsSetting = Common.settings.createSetting(settingPrefix + 'Snippets', []); this._namePrefix = namePrefix;
diff --git a/third_party/WebKit/Source/devtools/front_end/source_frame/ImageView.js b/third_party/WebKit/Source/devtools/front_end/source_frame/ImageView.js index 6750e988..11e5909 100644 --- a/third_party/WebKit/Source/devtools/front_end/source_frame/ImageView.js +++ b/third_party/WebKit/Source/devtools/front_end/source_frame/ImageView.js
@@ -53,8 +53,7 @@ */ syncToolbarItems() { return [ - this._sizeLabel, new UI.ToolbarSeparator(), this._dimensionsLabel, new UI.ToolbarSeparator(), - this._mimeTypeLabel + this._sizeLabel, new UI.ToolbarSeparator(), this._dimensionsLabel, new UI.ToolbarSeparator(), this._mimeTypeLabel ]; } @@ -110,9 +109,10 @@ var contextMenu = new UI.ContextMenu(event); if (!this._parsedURL.isDataURL()) contextMenu.appendItem(Common.UIString.capitalize('Copy ^image URL'), this._copyImageURL.bind(this)); - if (this._imagePreviewElement.src) + if (this._imagePreviewElement.src) { contextMenu.appendItem( Common.UIString.capitalize('Copy ^image as Data URI'), this._copyImageAsDataURL.bind(this)); + } contextMenu.appendItem(Common.UIString.capitalize('Open ^image in ^new ^tab'), this._openInNewTab.bind(this)); contextMenu.appendItem(Common.UIString.capitalize('Save\u2026'), this._saveImage.bind(this)); contextMenu.show();
diff --git a/third_party/WebKit/Source/devtools/front_end/source_frame/SourceFrame.js b/third_party/WebKit/Source/devtools/front_end/source_frame/SourceFrame.js index 1774b085..f6b9c01 100644 --- a/third_party/WebKit/Source/devtools/front_end/source_frame/SourceFrame.js +++ b/third_party/WebKit/Source/devtools/front_end/source_frame/SourceFrame.js
@@ -388,8 +388,7 @@ * @return {number} */ _searchResultIndexForCurrentSelection() { - return this._searchResults.lowerBound( - this._textEditor.selection().collapseToEnd(), Common.TextRange.comparator); + return this._searchResults.lowerBound(this._textEditor.selection().collapseToEnd(), Common.TextRange.comparator); } /** @@ -452,12 +451,13 @@ var oldText = this._textEditor.text(range); var regex = searchConfig.toSearchRegex(); var text; - if (regex.__fromRegExpQuery) + if (regex.__fromRegExpQuery) { text = oldText.replace(regex, replacement); - else + } else { text = oldText.replace(regex, function() { return replacement; }); + } var newRange = this._textEditor.editRange(range, text); this._textEditor.setSelection(newRange.collapseToEnd()); @@ -475,12 +475,13 @@ var range = this._textEditor.fullRange(); var regex = searchConfig.toSearchRegex(true); - if (regex.__fromRegExpQuery) + if (regex.__fromRegExpQuery) { text = text.replace(regex, replacement); - else + } else { text = text.replace(regex, function() { return replacement; }); + } var ranges = this._collectRegexMatches(regex); if (!ranges.length) @@ -494,9 +495,10 @@ var replacementLineCount = replacementLineEndings.length; var lastLineNumber = lastRange.startLine + replacementLineEndings.length - 1; var lastColumnNumber = lastRange.startColumn; - if (replacementLineEndings.length > 1) + if (replacementLineEndings.length > 1) { lastColumnNumber = replacementLineEndings[replacementLineCount - 1] - replacementLineEndings[replacementLineCount - 2] - 1; + } this._textEditor.editRange(range, text); this._textEditor.revealPosition(lastLineNumber, lastColumnNumber); @@ -562,11 +564,12 @@ textRange = textRange.normalize(); var selectedText = this._textEditor.text(textRange); - if (textRange.startLine === textRange.endLine) + if (textRange.startLine === textRange.endLine) { this._sourcePosition.setText(Common.UIString('%d characters selected', selectedText.length)); - else + } else { this._sourcePosition.setText(Common.UIString( '%d lines, %d characters selected', textRange.endLine - textRange.startLine + 1, selectedText.length)); + } } _handleKeyDown(e) {
diff --git a/third_party/WebKit/Source/devtools/front_end/source_frame/SourcesTextEditor.js b/third_party/WebKit/Source/devtools/front_end/source_frame/SourcesTextEditor.js index 7057ba6..00d3811 100644 --- a/third_party/WebKit/Source/devtools/front_end/source_frame/SourcesTextEditor.js +++ b/third_party/WebKit/Source/devtools/front_end/source_frame/SourcesTextEditor.js
@@ -392,10 +392,11 @@ if (!position) continue; var line = this.line(position.lineNumber); - if (line.length === position.columnNumber && Common.TextUtils.lineIndent(line).length === line.length) + if (line.length === position.columnNumber && Common.TextUtils.lineIndent(line).length === line.length) { this.codeMirror().replaceRange( '', new CodeMirror.Pos(position.lineNumber, 0), new CodeMirror.Pos(position.lineNumber, position.columnNumber)); + } } this._autoAppendedSpaces = []; @@ -485,8 +486,7 @@ dispose() { super.dispose(); Common.moduleSetting('textEditorIndent').removeChangeListener(this._onUpdateEditorIndentation, this); - Common.moduleSetting('textEditorAutoDetectIndent') - .removeChangeListener(this._onUpdateEditorIndentation, this); + Common.moduleSetting('textEditorAutoDetectIndent').removeChangeListener(this._onUpdateEditorIndentation, this); Common.moduleSetting('showWhitespacesInEditor').removeChangeListener(this._updateWhitespace, this); } @@ -586,9 +586,9 @@ var pos = stream.pos; if (stream.match(/^\s+$/, true)) return true ? 'trailing-whitespace' : null; - do { + do stream.next(); - } while (!stream.eol() && stream.peek() !== ' '); + while (!stream.eol() && stream.peek() !== ' '); return null; } var whitespaceMode = {token: nextToken}; @@ -902,9 +902,9 @@ if (stream.match(token) && (stream.eol() || !Common.TextUtils.isWordChar(stream.peek()))) return stream.column() === selectionStart.ch ? 'token-highlight column-with-selection' : 'token-highlight'; var eatenChar; - do { + do eatenChar = stream.next(); - } while (eatenChar && (Common.TextUtils.isWordChar(eatenChar) || stream.peek() !== tokenFirstChar)); + while (eatenChar && (Common.TextUtils.isWordChar(eatenChar) || stream.peek() !== tokenFirstChar)); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/AdvancedSearchView.js b/third_party/WebKit/Source/devtools/front_end/sources/AdvancedSearchView.js index 5f2aa13..f99d5b7 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/AdvancedSearchView.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/AdvancedSearchView.js
@@ -235,11 +235,12 @@ } _updateSearchResultsMessage() { - if (this._searchMatchesCount && this._searchResultsCount) - this._searchResultsMessageElement.textContent = Common.UIString( - 'Found %d matches in %d files.', this._searchMatchesCount, this._nonEmptySearchResultsCount); - else + if (this._searchMatchesCount && this._searchResultsCount) { + this._searchResultsMessageElement.textContent = + Common.UIString('Found %d matches in %d files.', this._searchMatchesCount, this._nonEmptySearchResultsCount); + } else { this._searchResultsMessageElement.textContent = ''; + } } _resetResults() {
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/CSSSourceFrame.js b/third_party/WebKit/Source/devtools/front_end/sources/CSSSourceFrame.js index 217a8ec..371a746d 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/CSSSourceFrame.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/CSSSourceFrame.js
@@ -111,8 +111,7 @@ var swatchPositions = []; var regexes = [ - SDK.CSSMetadata.VariableRegex, SDK.CSSMetadata.URLRegex, - Common.Geometry.CubicBezier.Regex, Common.Color.Regex + SDK.CSSMetadata.VariableRegex, SDK.CSSMetadata.URLRegex, Common.Geometry.CubicBezier.Regex, Common.Color.Regex ]; var handlers = new Map(); handlers.set(Common.Color.Regex, this._createColorSwatch.bind(this)); @@ -145,8 +144,7 @@ */ function putSwatchesInline() { var clearRange = new Common.TextRange(startLine, 0, endLine, this.textEditor.line(endLine).length); - this.textEditor.bookmarks(clearRange, Sources.CSSSourceFrame.SwatchBookmark) - .forEach(marker => marker.clear()); + this.textEditor.bookmarks(clearRange, Sources.CSSSourceFrame.SwatchBookmark).forEach(marker => marker.clear()); for (var i = 0; i < swatches.length; i++) { var swatch = swatches[i]; @@ -250,9 +248,10 @@ this._bezierEditor.addEventListener(UI.BezierEditor.Events.BezierChanged, this._bezierChanged, this); } var cubicBezier = Common.Geometry.CubicBezier.parse(swatch.bezierText()); - if (!cubicBezier) + if (!cubicBezier) { cubicBezier = /** @type {!Common.Geometry.CubicBezier} */ (Common.Geometry.CubicBezier.parse('linear')); + } this._bezierEditor.setBezier(cubicBezier); this._swatchPopoverHelper.show(this._bezierEditor, swatch.iconElement(), this._swatchPopoverHidden.bind(this)); }
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/CallStackSidebarPane.js b/third_party/WebKit/Source/devtools/front_end/sources/CallStackSidebarPane.js index fe46c36..7c87bfd 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/CallStackSidebarPane.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/CallStackSidebarPane.js
@@ -105,8 +105,7 @@ if (this._hiddenCallFrames === 1) element.textContent = Common.UIString('1 stack frame is hidden (black-boxed).'); else - element.textContent = - Common.UIString('%d stack frames are hidden (black-boxed).', this._hiddenCallFrames); + element.textContent = Common.UIString('%d stack frames are hidden (black-boxed).', this._hiddenCallFrames); element.createTextChild(' '); var showAllLink = element.createChild('span', 'link'); showAllLink.textContent = Common.UIString('Show'); @@ -210,9 +209,10 @@ _callFrameContextMenu(callFrame, event) { var contextMenu = new UI.ContextMenu(event); var debuggerCallFrame = callFrame._debuggerCallFrame; - if (debuggerCallFrame) + if (debuggerCallFrame) { contextMenu.appendItem( Common.UIString.capitalize('Restart ^frame'), debuggerCallFrame.restart.bind(debuggerCallFrame)); + } contextMenu.appendItem(Common.UIString.capitalize('Copy ^stack ^trace'), this._copyStackTrace.bind(this)); @@ -252,24 +252,25 @@ var manager = Bindings.blackboxManager; if (canBlackbox) { - if (isBlackboxed) + if (isBlackboxed) { contextMenu.appendItem( Common.UIString.capitalize('Stop ^blackboxing'), manager.unblackboxUISourceCode.bind(manager, uiSourceCode)); - else + } else { contextMenu.appendItem( - Common.UIString.capitalize('Blackbox ^script'), - manager.blackboxUISourceCode.bind(manager, uiSourceCode)); + Common.UIString.capitalize('Blackbox ^script'), manager.blackboxUISourceCode.bind(manager, uiSourceCode)); + } } if (isContentScript) { - if (isBlackboxed) + if (isBlackboxed) { contextMenu.appendItem( Common.UIString.capitalize('Stop blackboxing ^all ^content ^scripts'), manager.blackboxContentScripts.bind(manager)); - else + } else { contextMenu.appendItem( Common.UIString.capitalize('Blackbox ^all ^content ^scripts'), manager.unblackboxContentScripts.bind(manager)); + } } }
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/DebuggerPausedMessage.js b/third_party/WebKit/Source/devtools/front_end/sources/DebuggerPausedMessage.js index 424115f..b2c3ed1 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/DebuggerPausedMessage.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/DebuggerPausedMessage.js
@@ -46,19 +46,17 @@ } else if (details.reason === SDK.DebuggerModel.BreakReason.PromiseRejection) { var description = details.auxData['description'] || details.auxData['value'] || ''; var descriptionFirstLine = description.split('\n', 1)[0]; - messageWrapper = - buildWrapper(Common.UIString('Paused on promise rejection'), descriptionFirstLine, description); + messageWrapper = buildWrapper(Common.UIString('Paused on promise rejection'), descriptionFirstLine, description); } else if (details.reason === SDK.DebuggerModel.BreakReason.Assert) { messageWrapper = buildWrapper(Common.UIString('Paused on assertion')); } else if (details.reason === SDK.DebuggerModel.BreakReason.DebugCommand) { messageWrapper = buildWrapper(Common.UIString('Paused on debugged function')); } else if (details.callFrames.length) { var uiLocation = debuggerWorkspaceBinding.rawLocationToUILocation(details.callFrames[0].location()); - var breakpoint = - uiLocation ? breakpointManager.findBreakpoint( - uiLocation.uiSourceCode, uiLocation.lineNumber, uiLocation.columnNumber) : null; - var defaultText = - breakpoint ? Common.UIString('Paused on breakpoint') : Common.UIString('Debugger paused'); + var breakpoint = uiLocation ? + breakpointManager.findBreakpoint(uiLocation.uiSourceCode, uiLocation.lineNumber, uiLocation.columnNumber) : + null; + var defaultText = breakpoint ? Common.UIString('Paused on breakpoint') : Common.UIString('Debugger paused'); messageWrapper = buildWrapper(defaultText); } else { console.warn(
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/EditingLocationHistoryManager.js b/third_party/WebKit/Source/devtools/front_end/sources/EditingLocationHistoryManager.js index 6676279a..1d00c4e 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/EditingLocationHistoryManager.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/EditingLocationHistoryManager.js
@@ -38,8 +38,7 @@ */ constructor(sourcesView, currentSourceFrameCallback) { this._sourcesView = sourcesView; - this._historyManager = - new Sources.SimpleHistoryManager(Sources.EditingLocationHistoryManager.HistoryDepth); + this._historyManager = new Sources.SimpleHistoryManager(Sources.EditingLocationHistoryManager.HistoryDepth); this._currentSourceFrameCallback = currentSourceFrameCallback; }
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/EventListenerBreakpointsSidebarPane.js b/third_party/WebKit/Source/devtools/front_end/sources/EventListenerBreakpointsSidebarPane.js index d26f9993..65c9e0b 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/EventListenerBreakpointsSidebarPane.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/EventListenerBreakpointsSidebarPane.js
@@ -23,8 +23,7 @@ // Otherwise, inspector page reacts on drop event and tries to load the event data. // this._createCategory(Common.UIString("Drag"), ["drag", "drop", "dragstart", "dragend", "dragenter", "dragleave", "dragover"]); this._createCategory( - Common.UIString('Animation'), ['requestAnimationFrame', 'cancelAnimationFrame', 'animationFrameFired'], - true); + Common.UIString('Animation'), ['requestAnimationFrame', 'cancelAnimationFrame', 'animationFrameFired'], true); this._createCategory( Common.UIString('Clipboard'), ['copy', 'cut', 'paste', 'beforecopy', 'beforecut', 'beforepaste']); this._createCategory( @@ -69,10 +68,8 @@ ['XMLHttpRequest', 'XMLHttpRequestUpload']); SDK.targetManager.observeTargets(this, SDK.Target.Capability.DOM); - SDK.targetManager.addModelListener( - SDK.DebuggerModel, SDK.DebuggerModel.Events.DebuggerPaused, this._update, this); - SDK.targetManager.addModelListener( - SDK.DebuggerModel, SDK.DebuggerModel.Events.DebuggerResumed, this._update, this); + SDK.targetManager.addModelListener(SDK.DebuggerModel, SDK.DebuggerModel.Events.DebuggerPaused, this._update, this); + SDK.targetManager.addModelListener(SDK.DebuggerModel, SDK.DebuggerModel.Events.DebuggerResumed, this._update, this); UI.context.addFlavorChangeListener(SDK.Target, this._update, this); } @@ -105,8 +102,7 @@ return Common.UIString('WebGL Error Fired (%s)', errorName); } if (eventName === 'instrumentation:scriptBlockedByCSP' && auxData['directiveText']) - return Common.UIString( - 'Script blocked due to Content Security Policy directive: %s', auxData['directiveText']); + return Common.UIString('Script blocked due to Content Security Policy directive: %s', auxData['directiveText']); } return Sources.EventListenerBreakpointsSidebarPane._eventNamesForUI[eventName] || eventName.substring(eventName.indexOf(':') + 1); @@ -191,8 +187,7 @@ var targetName = details.auxData['targetName']; var breakpointItem = this._findBreakpointItem(eventName, targetName); if (!breakpointItem || !breakpointItem.checkbox.checked) - breakpointItem = - this._findBreakpointItem(eventName, Sources.EventListenerBreakpointsSidebarPane.eventTargetAny); + breakpointItem = this._findBreakpointItem(eventName, Sources.EventListenerBreakpointsSidebarPane.eventTargetAny); if (!breakpointItem) return; UI.viewManager.showView('sources.eventListenerBreakpoints');
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/FileBasedSearchResultsPane.js b/third_party/WebKit/Source/devtools/front_end/sources/FileBasedSearchResultsPane.js index aaba72d..c9c483b2 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/FileBasedSearchResultsPane.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/FileBasedSearchResultsPane.js
@@ -77,8 +77,8 @@ _updateMatchesUI() { this.removeChildren(); - var toIndex = Math.min( - this._searchResult.searchMatches.length, Sources.FileBasedSearchResultsPane.fileMatchesShownAtOnce); + var toIndex = + Math.min(this._searchResult.searchMatches.length, Sources.FileBasedSearchResultsPane.fileMatchesShownAtOnce); if (toIndex < this._searchResult.searchMatches.length) { this._appendSearchMatches(0, toIndex - 1); this._appendShowMoreMatchesElement(toIndex - 1);
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/FilteredUISourceCodeListDelegate.js b/third_party/WebKit/Source/devtools/front_end/sources/FilteredUISourceCodeListDelegate.js index 2e073f5..9d15ae67 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/FilteredUISourceCodeListDelegate.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/FilteredUISourceCodeListDelegate.js
@@ -17,8 +17,7 @@ this._defaultScores = defaultScores; this._scorer = new Sources.FilePathScoreFunction(''); - Workspace.workspace.addEventListener( - Workspace.Workspace.Events.UISourceCodeAdded, this._uiSourceCodeAdded, this); + Workspace.workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded, this._uiSourceCodeAdded, this); Workspace.workspace.addEventListener(Workspace.Workspace.Events.ProjectRemoved, this._projectRemoved, this); } @@ -210,7 +209,6 @@ dispose() { Workspace.workspace.removeEventListener( Workspace.Workspace.Events.UISourceCodeAdded, this._uiSourceCodeAdded, this); - Workspace.workspace.removeEventListener( - Workspace.Workspace.Events.ProjectRemoved, this._projectRemoved, this); + Workspace.workspace.removeEventListener(Workspace.Workspace.Events.ProjectRemoved, this._projectRemoved, this); } };
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/InplaceFormatterEditorAction.js b/third_party/WebKit/Source/devtools/front_end/sources/InplaceFormatterEditorAction.js index 6d2c45b..b703d27 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/InplaceFormatterEditorAction.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/InplaceFormatterEditorAction.js
@@ -81,8 +81,7 @@ */ function contentLoaded(content) { var highlighterType = Bindings.NetworkProject.uiSourceCodeMimeType(uiSourceCode); - Sources.Formatter.format( - uiSourceCode.contentType(), highlighterType, content || '', innerCallback.bind(this)); + Sources.Formatter.format(uiSourceCode.contentType(), highlighterType, content || '', innerCallback.bind(this)); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/JavaScriptBreakpointsSidebarPane.js b/third_party/WebKit/Source/devtools/front_end/sources/JavaScriptBreakpointsSidebarPane.js index 69e066cc..3ac3e1fa 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/JavaScriptBreakpointsSidebarPane.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/JavaScriptBreakpointsSidebarPane.js
@@ -5,130 +5,206 @@ * @implements {UI.ContextFlavorListener} * @unrestricted */ -Sources.JavaScriptBreakpointsSidebarPane = class extends UI.VBox { +Sources.JavaScriptBreakpointsSidebarPane = class extends UI.ThrottledWidget { constructor() { - super(); + super(true); this.registerRequiredCSS('components/breakpointsList.css'); this._breakpointManager = Bindings.breakpointManager; + this._breakpointManager.addEventListener(Bindings.BreakpointManager.Events.BreakpointAdded, this.update, this); + this._breakpointManager.addEventListener(Bindings.BreakpointManager.Events.BreakpointRemoved, this.update, this); + this._breakpointManager.addEventListener( + Bindings.BreakpointManager.Events.BreakpointsActiveStateChanged, this.update, this); - this._listElement = createElementWithClass('ol', 'breakpoint-list'); + /** @type {?Element} */ + this._listElement = null; + this.update(); + } - this.emptyElement = this.element.createChild('div', 'gray-info-message'); - this.emptyElement.textContent = Common.UIString('No Breakpoints'); - - this._items = new Map(); - + /** + * @override + * @return {!Promise<?>} + */ + doUpdate() { var breakpointLocations = this._breakpointManager.allBreakpointLocations(); - for (var i = 0; i < breakpointLocations.length; ++i) - this._addBreakpoint(breakpointLocations[i].breakpoint, breakpointLocations[i].uiLocation); + if (!breakpointLocations.length) { + this._listElement = null; + this.contentElement.removeChildren(); + var emptyElement = this.contentElement.createChild('div', 'gray-info-message'); + emptyElement.textContent = Common.UIString('No Breakpoints'); + this.contentElement.appendChild(emptyElement); + this._didUpdateForTest(); + return Promise.resolve(); + } - this._breakpointManager.addEventListener( - Bindings.BreakpointManager.Events.BreakpointAdded, this._breakpointAdded, this); - this._breakpointManager.addEventListener( - Bindings.BreakpointManager.Events.BreakpointRemoved, this._breakpointRemoved, this); + if (!this._listElement) { + this.contentElement.removeChildren(); + this._listElement = this.contentElement.createChild('div'); + this.contentElement.appendChild(this._listElement); + } - this.emptyElement.addEventListener('contextmenu', this._emptyElementContextMenu.bind(this), true); - this._breakpointManager.addEventListener( - Bindings.BreakpointManager.Events.BreakpointsActiveStateChanged, this._breakpointsActiveStateChanged, this); - this._breakpointsActiveStateChanged(); - this._update(); - } + breakpointLocations.sort((item1, item2) => item1.uiLocation.compareTo(item2.uiLocation)); - _emptyElementContextMenu(event) { - var contextMenu = new UI.ContextMenu(event); - this._appendBreakpointActiveItem(contextMenu); - contextMenu.show(); + /** @type {!Multimap<string, !{breakpoint: !Bindings.BreakpointManager.Breakpoint, uiLocation: !Workspace.UILocation}>} */ + var locationForEntry = new Multimap(); + for (var breakpointLocation of breakpointLocations) { + var uiLocation = breakpointLocation.uiLocation; + var entryDescriptor = uiLocation.uiSourceCode.url() + ':' + uiLocation.lineNumber; + locationForEntry.set(entryDescriptor, breakpointLocation); + } + + var details = UI.context.flavor(SDK.DebuggerPausedDetails); + var selectedUILocation = details && details.callFrames.length ? + Bindings.debuggerWorkspaceBinding.rawLocationToUILocation(details.callFrames[0].location()) : + null; + + var shouldShowView = false; + var entry = this._listElement.firstChild; + var promises = []; + for (var descriptor of locationForEntry.keysArray()) { + if (!entry) { + entry = this._listElement.createChild('div', 'breakpoint-entry'); + entry.addEventListener('contextmenu', this._breakpointContextMenu.bind(this), true); + entry.addEventListener('click', this._revealLocation.bind(this), false); + var checkboxLabel = createCheckboxLabel(''); + checkboxLabel.addEventListener('click', this._breakpointCheckboxClicked.bind(this), false); + entry.appendChild(checkboxLabel); + entry[Sources.JavaScriptBreakpointsSidebarPane._checkboxLabelSymbol] = checkboxLabel; + var snippetElement = entry.createChild('div', 'source-text monospace'); + entry[Sources.JavaScriptBreakpointsSidebarPane._snippetElementSymbol] = snippetElement; + } + + var locations = Array.from(locationForEntry.get(descriptor)); + var uiLocation = locations[0].uiLocation; + var isSelected = + !!selectedUILocation && locations.some(location => location.uiLocation.id() === selectedUILocation.id()); + var hasEnabled = locations.some(location => location.breakpoint.enabled()); + var hasDisabled = locations.some(location => !location.breakpoint.enabled()); + promises.push(this._resetEntry(/** @type {!Element}*/ (entry), uiLocation, isSelected, hasEnabled, hasDisabled)); + + if (isSelected) + shouldShowView = true; + entry = entry.nextSibling; + } + while (entry) { + var next = entry.nextSibling; + entry.remove(); + entry = next; + } + if (shouldShowView) + UI.viewManager.showView('sources.jsBreakpoints'); + this._listElement.classList.toggle('breakpoints-list-deactivated', !this._breakpointManager.breakpointsActive()); + Promise.all(promises).then(() => this._didUpdateForTest()); + return Promise.resolve(); } /** - * @param {!UI.ContextMenu} contextMenu - */ - _appendBreakpointActiveItem(contextMenu) { - var breakpointActive = this._breakpointManager.breakpointsActive(); - var breakpointActiveTitle = breakpointActive ? Common.UIString.capitalize('Deactivate ^breakpoints') : - Common.UIString.capitalize('Activate ^breakpoints'); - contextMenu.appendItem( - breakpointActiveTitle, - this._breakpointManager.setBreakpointsActive.bind(this._breakpointManager, !breakpointActive)); - } - - /** - * @param {!Common.Event} event - */ - _breakpointAdded(event) { - this._breakpointRemoved(event); - - var breakpoint = /** @type {!Bindings.BreakpointManager.Breakpoint} */ (event.data.breakpoint); - var uiLocation = /** @type {!Workspace.UILocation} */ (event.data.uiLocation); - this._addBreakpoint(breakpoint, uiLocation); - } - - /** - * @param {!Bindings.BreakpointManager.Breakpoint} breakpoint + * @param {!Element} element * @param {!Workspace.UILocation} uiLocation + * @param {boolean} isSelected + * @param {boolean} hasEnabled + * @param {boolean} hasDisabled + * @return {!Promise<undefined>} */ - _addBreakpoint(breakpoint, uiLocation) { - var element = createElementWithClass('li', 'cursor-pointer'); - element.addEventListener('contextmenu', this._breakpointContextMenu.bind(this, breakpoint), true); - element.addEventListener('click', this._breakpointClicked.bind(this, uiLocation), false); + _resetEntry(element, uiLocation, isSelected, hasEnabled, hasDisabled) { + element[Sources.JavaScriptBreakpointsSidebarPane._locationSymbol] = uiLocation; + element.classList.toggle('breakpoint-hit', isSelected); - var checkboxLabel = createCheckboxLabel(uiLocation.linkText(), breakpoint.enabled()); - element.appendChild(checkboxLabel); - checkboxLabel.addEventListener('click', this._breakpointCheckboxClicked.bind(this, breakpoint), false); + var checkboxLabel = element[Sources.JavaScriptBreakpointsSidebarPane._checkboxLabelSymbol]; + checkboxLabel.textElement.textContent = uiLocation.linkText(); + checkboxLabel.checkboxElement.checked = hasEnabled; + checkboxLabel.checkboxElement.indeterminate = hasEnabled && hasDisabled; - var snippetElement = element.createChild('div', 'source-text monospace'); + var snippetElement = element[Sources.JavaScriptBreakpointsSidebarPane._snippetElementSymbol]; + return uiLocation.uiSourceCode.requestContent().then(fillSnippetElement.bind(null, snippetElement)); /** + * @param {!Element} snippetElement * @param {?string} content - * @this {Sources.JavaScriptBreakpointsSidebarPane} */ - function didRequestContent(content) { + function fillSnippetElement(snippetElement, content) { var lineNumber = uiLocation.lineNumber; - var columnNumber = uiLocation.columnNumber; var text = new Common.Text(content || ''); if (lineNumber < text.lineCount()) { var lineText = text.lineAt(lineNumber); var maxSnippetLength = 200; - var snippetStartIndex = columnNumber > 100 ? columnNumber : 0; - snippetElement.textContent = lineText.substr(snippetStartIndex).trimEnd(maxSnippetLength); + snippetElement.textContent = lineText.trimEnd(maxSnippetLength); } - this.didReceiveBreakpointLineForTest(uiLocation.uiSourceCode, lineNumber, columnNumber); } - - uiLocation.uiSourceCode.requestContent().then(didRequestContent.bind(this)); - - element._data = uiLocation; - var currentElement = this._listElement.firstChild; - while (currentElement) { - if (currentElement._data && this._compareBreakpoints(currentElement._data, element._data) > 0) - break; - currentElement = currentElement.nextSibling; - } - this._addListElement(element, currentElement); - - var breakpointItem = {element: element, checkbox: checkboxLabel.checkboxElement}; - this._items.set(breakpoint, breakpointItem); } /** - * @param {!Workspace.UISourceCode} uiSourceCode - * @param {number} lineNumber - * @param {number} columnNumber + * @param {!Event} event + * @return {?Workspace.UILocation} */ - didReceiveBreakpointLineForTest(uiSourceCode, lineNumber, columnNumber) { + _uiLocationFromEvent(event) { + var node = event.target.enclosingNodeOrSelfWithClass('breakpoint-entry'); + if (!node) + return null; + return node[Sources.JavaScriptBreakpointsSidebarPane._locationSymbol] || null; } /** - * @param {!Common.Event} event + * @param {!Event} event */ - _breakpointRemoved(event) { - var breakpoint = /** @type {!Bindings.BreakpointManager.Breakpoint} */ (event.data.breakpoint); - var breakpointItem = this._items.get(breakpoint); - if (!breakpointItem) + _breakpointCheckboxClicked(event) { + var uiLocation = this._uiLocationFromEvent(event); + if (!uiLocation) return; - this._items.remove(breakpoint); - this._removeListElement(breakpointItem.element); + + var breakpoints = this._breakpointManager.findBreakpoints(uiLocation.uiSourceCode, uiLocation.lineNumber); + var newState = event.target.checkboxElement.checked; + for (var breakpoint of breakpoints) + breakpoint.setEnabled(newState); + event.consume(); + } + + /** + * @param {!Event} event + */ + _revealLocation(event) { + var uiLocation = this._uiLocationFromEvent(event); + if (uiLocation) + Common.Revealer.reveal(uiLocation); + } + + /** + * @param {!Event} event + */ + _breakpointContextMenu(event) { + var uiLocation = this._uiLocationFromEvent(event); + if (!uiLocation) + return; + + var breakpoints = this._breakpointManager.findBreakpoints(uiLocation.uiSourceCode, uiLocation.lineNumber); + + var contextMenu = new UI.ContextMenu(event); + var removeEntryTitle = breakpoints.length > 1 ? Common.UIString('Remove all breakpoints in line') : + Common.UIString('Remove breakpoint'); + contextMenu.appendItem(removeEntryTitle, () => breakpoints.map(breakpoint => breakpoint.remove())); + + contextMenu.appendSeparator(); + var breakpointActive = this._breakpointManager.breakpointsActive(); + var breakpointActiveTitle = + breakpointActive ? Common.UIString('Deactivate breakpoints') : Common.UIString('Activate breakpoints'); + contextMenu.appendItem( + breakpointActiveTitle, + this._breakpointManager.setBreakpointsActive.bind(this._breakpointManager, !breakpointActive)); + + contextMenu.appendSeparator(); + if (breakpoints.some(breakpoint => !breakpoint.enabled())) { + var enableTitle = Common.UIString('Enable all breakpoints'); + contextMenu.appendItem( + enableTitle, this._breakpointManager.toggleAllBreakpoints.bind(this._breakpointManager, true)); + } + if (breakpoints.some(breakpoint => breakpoint.enabled())) { + var disableTitle = Common.UIString('Disable all breakpoints'); + contextMenu.appendItem( + disableTitle, this._breakpointManager.toggleAllBreakpoints.bind(this._breakpointManager, false)); + } + var removeAllTitle = Common.UIString('Remove all breakpoints'); + contextMenu.appendItem(removeAllTitle, this._breakpointManager.removeAllBreakpoints.bind(this._breakpointManager)); + contextMenu.show(); } /** @@ -136,132 +212,13 @@ * @param {?Object} object */ flavorChanged(object) { - this._update(); + this.update(); } - _update() { - var details = UI.context.flavor(SDK.DebuggerPausedDetails); - var uiLocation = details && details.callFrames.length ? - Bindings.debuggerWorkspaceBinding.rawLocationToUILocation(details.callFrames[0].location()) : - null; - var breakpoint = uiLocation ? - this._breakpointManager.findBreakpoint( - uiLocation.uiSourceCode, uiLocation.lineNumber, uiLocation.columnNumber) : - null; - var breakpointItem = this._items.get(breakpoint); - if (!breakpointItem) { - if (this._highlightedBreakpointItem) { - this._highlightedBreakpointItem.element.classList.remove('breakpoint-hit'); - delete this._highlightedBreakpointItem; - } - return; - } - - breakpointItem.element.classList.add('breakpoint-hit'); - this._highlightedBreakpointItem = breakpointItem; - UI.viewManager.showView('sources.jsBreakpoints'); - } - - _breakpointsActiveStateChanged() { - this._listElement.classList.toggle('breakpoints-list-deactivated', !this._breakpointManager.breakpointsActive()); - } - - /** - * @param {!Workspace.UILocation} uiLocation - */ - _breakpointClicked(uiLocation) { - Common.Revealer.reveal(uiLocation); - } - - /** - * @param {!Bindings.BreakpointManager.Breakpoint} breakpoint - * @param {!Event} event - */ - _breakpointCheckboxClicked(breakpoint, event) { - // Breakpoint element has it's own click handler. - event.consume(); - breakpoint.setEnabled(event.target.checkboxElement.checked); - } - - /** - * @param {!Bindings.BreakpointManager.Breakpoint} breakpoint - * @param {!Event} event - */ - _breakpointContextMenu(breakpoint, event) { - var breakpoints = this._items.valuesArray(); - var contextMenu = new UI.ContextMenu(event); - contextMenu.appendItem(Common.UIString.capitalize('Remove ^breakpoint'), breakpoint.remove.bind(breakpoint)); - if (breakpoints.length > 1) { - var removeAllTitle = Common.UIString.capitalize('Remove ^all ^breakpoints'); - contextMenu.appendItem( - removeAllTitle, this._breakpointManager.removeAllBreakpoints.bind(this._breakpointManager)); - } - - contextMenu.appendSeparator(); - this._appendBreakpointActiveItem(contextMenu); - - function enabledBreakpointCount(breakpoints) { - var count = 0; - for (var i = 0; i < breakpoints.length; ++i) { - if (breakpoints[i].checkbox.checked) - count++; - } - return count; - } - if (breakpoints.length > 1) { - var enableBreakpointCount = enabledBreakpointCount(breakpoints); - var enableTitle = Common.UIString.capitalize('Enable ^all ^breakpoints'); - var disableTitle = Common.UIString.capitalize('Disable ^all ^breakpoints'); - - contextMenu.appendSeparator(); - - contextMenu.appendItem( - enableTitle, this._breakpointManager.toggleAllBreakpoints.bind(this._breakpointManager, true), - !(enableBreakpointCount !== breakpoints.length)); - contextMenu.appendItem( - disableTitle, this._breakpointManager.toggleAllBreakpoints.bind(this._breakpointManager, false), - !(enableBreakpointCount > 1)); - } - - contextMenu.show(); - } - - _addListElement(element, beforeElement) { - if (beforeElement) - this._listElement.insertBefore(element, beforeElement); - else { - if (!this._listElement.firstChild) { - this.element.removeChild(this.emptyElement); - this.element.appendChild(this._listElement); - } - this._listElement.appendChild(element); - } - } - - _removeListElement(element) { - this._listElement.removeChild(element); - if (!this._listElement.firstChild) { - this.element.removeChild(this._listElement); - this.element.appendChild(this.emptyElement); - } - } - - _compare(x, y) { - if (x !== y) - return x < y ? -1 : 1; - return 0; - } - - _compareBreakpoints(b1, b2) { - return this._compare(b1.uiSourceCode.url(), b2.uiSourceCode.url()) || this._compare(b1.lineNumber, b2.lineNumber); - } - - reset() { - this._listElement.removeChildren(); - if (this._listElement.parentElement) { - this.element.removeChild(this._listElement); - this.element.appendChild(this.emptyElement); - } - this._items.clear(); + _didUpdateForTest() { } }; + +Sources.JavaScriptBreakpointsSidebarPane._locationSymbol = Symbol('location'); +Sources.JavaScriptBreakpointsSidebarPane._checkboxLabelSymbol = Symbol('checkbox-label'); +Sources.JavaScriptBreakpointsSidebarPane._snippetElementSymbol = Symbol('snippet-element');
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/JavaScriptCompiler.js b/third_party/WebKit/Source/devtools/front_end/sources/JavaScriptCompiler.js index ba9f6fd3..a04ab1f 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/JavaScriptCompiler.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/JavaScriptCompiler.js
@@ -67,8 +67,7 @@ return; var text = SDK.ConsoleMessage.simpleTextFromException(exceptionDetails); this._sourceFrame.uiSourceCode().addLineMessage( - Workspace.UISourceCode.Message.Level.Error, text, exceptionDetails.lineNumber, - exceptionDetails.columnNumber); + Workspace.UISourceCode.Message.Level.Error, text, exceptionDetails.lineNumber, exceptionDetails.columnNumber); this._compilationFinishedForTest(); } }
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/JavaScriptSourceFrame.js b/third_party/WebKit/Source/devtools/front_end/sources/JavaScriptSourceFrame.js index 2d978c8..13de635 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/JavaScriptSourceFrame.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/JavaScriptSourceFrame.js
@@ -97,16 +97,13 @@ if (originURL) { var parsedURL = originURL.asParsedURL(); if (parsedURL) - result.push( - new UI.ToolbarText(Common.UIString('(source mapped from %s)', parsedURL.displayName))); + result.push(new UI.ToolbarText(Common.UIString('(source mapped from %s)', parsedURL.displayName))); } if (this.uiSourceCode().project().type() === Workspace.projectTypes.Snippets) { result.push(new UI.ToolbarSeparator(true)); var runSnippet = UI.Toolbar.createActionButtonForId('debugger.run-snippet'); - runSnippet.setText(Host.isMac() ? - Common.UIString('\u2318+Enter') : - Common.UIString('Ctrl+Enter')); + runSnippet.setText(Host.isMac() ? Common.UIString('\u2318+Enter') : Common.UIString('Ctrl+Enter')); result.push(runSnippet); } @@ -124,8 +121,7 @@ if (this._divergedInfobar) this._divergedInfobar.dispose(); - var infobar = new UI.Infobar( - UI.Infobar.Type.Warning, Common.UIString('Workspace mapping mismatch')); + var infobar = new UI.Infobar(UI.Infobar.Type.Warning, Common.UIString('Workspace mapping mismatch')); this._divergedInfobar = infobar; var fileURL = this.uiSourceCode().url(); @@ -139,11 +135,12 @@ infobar.createDetailsRowMessage(); infobar.createDetailsRowMessage(Common.UIString('Possible solutions are:')); - if (Common.moduleSetting('cacheDisabled').get()) + if (Common.moduleSetting('cacheDisabled').get()) { infobar.createDetailsRowMessage(' - ').createTextChild(Common.UIString('Reload inspected page')); - else + } else { infobar.createDetailsRowMessage(' - ').createTextChild(Common.UIString( 'Check "Disable cache" in settings and reload inspected page (recommended setup for authoring and debugging)')); + } infobar.createDetailsRowMessage(' - ').createTextChild(Common.UIString( 'Check that your file and script are both loaded from the correct source and their contents match')); @@ -172,8 +169,7 @@ if (this._blackboxInfobar) this._blackboxInfobar.dispose(); - var infobar = new UI.Infobar( - UI.Infobar.Type.Warning, Common.UIString('This script is blackboxed in debugger')); + var infobar = new UI.Infobar(UI.Infobar.Type.Warning, Common.UIString('This script is blackboxed in debugger')); this._blackboxInfobar = infobar; infobar.createDetailsRowMessage( @@ -263,22 +259,18 @@ contextMenu.appendItem( Common.UIString('Add conditional breakpoint…'), this._editBreakpointCondition.bind(this, lineNumber)); contextMenu.appendItem( - Common.UIString('Never pause here'), - this._createNewBreakpoint.bind(this, lineNumber, 'false', true)); + Common.UIString('Never pause here'), this._createNewBreakpoint.bind(this, lineNumber, 'false', true)); } else { var breakpoint = breakpoints[0]; // This row has a breakpoint, we want to show edit and remove breakpoint, and either disable or enable. contextMenu.appendItem(Common.UIString('Remove breakpoint'), breakpoint.remove.bind(breakpoint)); contextMenu.appendItem( - Common.UIString('Edit breakpoint…'), - this._editBreakpointCondition.bind(this, lineNumber, breakpoint)); + Common.UIString('Edit breakpoint…'), this._editBreakpointCondition.bind(this, lineNumber, breakpoint)); if (breakpoint.enabled()) - contextMenu.appendItem( - Common.UIString('Disable breakpoint'), breakpoint.setEnabled.bind(breakpoint, false)); + contextMenu.appendItem(Common.UIString('Disable breakpoint'), breakpoint.setEnabled.bind(breakpoint, false)); else - contextMenu.appendItem( - Common.UIString('Enable breakpoint'), breakpoint.setEnabled.bind(breakpoint, true)); + contextMenu.appendItem(Common.UIString('Enable breakpoint'), breakpoint.setEnabled.bind(breakpoint, true)); } resolve(); } @@ -401,9 +393,10 @@ _restoreBreakpointsIfConsistentScripts() { var scriptFiles = this._scriptFileForTarget.valuesArray(); - for (var i = 0; i < scriptFiles.length; ++i) + for (var i = 0; i < scriptFiles.length; ++i) { if (scriptFiles[i].hasDivergedFromVM() || scriptFiles[i].isMergingToVM()) return; + } this._restoreBreakpointsAfterEditing(); } @@ -667,9 +660,10 @@ var localScope = callFrame.localScope(); var functionLocation = callFrame.functionLocation(); - if (localScope && functionLocation) + if (localScope && functionLocation) { Sources.SourceMapNamesResolver.resolveScopeInObject(localScope) .getAllProperties(false, this._prepareScopeVariables.bind(this, callFrame)); + } if (this._clearValueWidgetsTimer) { clearTimeout(this._clearValueWidgetsTimer); @@ -856,9 +850,10 @@ return; var breakpoint = /** @type {!Bindings.BreakpointManager.Breakpoint} */ (event.data.breakpoint); - if (this.loaded) + if (this.loaded) { this._addBreakpointDecoration( uiLocation.lineNumber, uiLocation.columnNumber, breakpoint.condition(), breakpoint.enabled(), false); + } } _breakpointRemoved(event) { @@ -914,8 +909,7 @@ if (newScriptFile) { newScriptFile.addEventListener(Bindings.ResourceScriptFile.Events.DidMergeToVM, this._didMergeToVM, this); - newScriptFile.addEventListener( - Bindings.ResourceScriptFile.Events.DidDivergeFromVM, this._didDivergeFromVM, this); + newScriptFile.addEventListener(Bindings.ResourceScriptFile.Events.DidDivergeFromVM, this._didDivergeFromVM, this); if (this.loaded) newScriptFile.checkMapping(); if (newScriptFile.hasSourceMapURL()) { @@ -1021,8 +1015,9 @@ breakpoints[0].setEnabled(!breakpoints[0].enabled()); else breakpoints[0].remove(); - } else + } else { this._createNewBreakpoint(lineNumber, '', true); + } } /** @@ -1032,8 +1027,8 @@ */ _createNewBreakpoint(lineNumber, condition, enabled) { findPossibleBreakpoints.call(this, lineNumber) - .then(checkNextLineIfNeeded.bind(this, lineNumber, 4)) - .then(setBreakpoint.bind(this)); + .then(checkNextLineIfNeeded.bind(this, lineNumber, 4)) + .then(setBreakpoint.bind(this)); /** * @this {!Sources.JavaScriptSourceFrame} @@ -1043,10 +1038,11 @@ function findPossibleBreakpoints(lineNumber) { const maxLengthToCheck = 1024; if (lineNumber >= this._textEditor.linesCount) - return Promise.resolve(/** @type {?Array<!Workspace.UILocation>} */([])); + return Promise.resolve(/** @type {?Array<!Workspace.UILocation>} */ ([])); if (this._textEditor.line(lineNumber).length >= maxLengthToCheck) - return Promise.resolve(/** @type {?Array<!Workspace.UILocation>} */([])); - return this._breakpointManager.possibleBreakpoints(this.uiSourceCode(), new Common.TextRange(lineNumber, 0, lineNumber + 1, 0)) + return Promise.resolve(/** @type {?Array<!Workspace.UILocation>} */ ([])); + return this._breakpointManager + .possibleBreakpoints(this.uiSourceCode(), new Common.TextRange(lineNumber, 0, lineNumber + 1, 0)) .then(locations => locations.length ? locations : null); }
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/NavigatorView.js b/third_party/WebKit/Source/devtools/front_end/sources/NavigatorView.js index c030bb57..ca78980 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/NavigatorView.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/NavigatorView.js
@@ -58,8 +58,7 @@ this._initGrouping(); SDK.targetManager.addModelListener( - SDK.ResourceTreeModel, SDK.ResourceTreeModel.Events.FrameNavigated, this._frameNavigated, - this); + SDK.ResourceTreeModel, SDK.ResourceTreeModel.Events.FrameNavigated, this._frameNavigated, this); SDK.targetManager.addModelListener( SDK.ResourceTreeModel, SDK.ResourceTreeModel.Events.FrameDetached, this._frameDetached, this); @@ -74,8 +73,7 @@ Persistence.persistence.addEventListener( Persistence.Persistence.Events.BindingRemoved, this._onBindingRemoved, this); } - SDK.targetManager.addEventListener( - SDK.TargetManager.Events.NameChanged, this._targetNameChanged, this); + SDK.targetManager.addEventListener(SDK.TargetManager.Events.NameChanged, this._targetNameChanged, this); SDK.targetManager.observeTargets(this); this._resetWorkspace(Workspace.workspace); @@ -229,10 +227,8 @@ _resetWorkspace(workspace) { this._workspace = workspace; this._workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded, this._uiSourceCodeAdded, this); - this._workspace.addEventListener( - Workspace.Workspace.Events.UISourceCodeRemoved, this._uiSourceCodeRemoved, this); - this._workspace.addEventListener( - Workspace.Workspace.Events.ProjectRemoved, this._projectRemoved.bind(this), this); + this._workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeRemoved, this._uiSourceCodeRemoved, this); + this._workspace.addEventListener(Workspace.Workspace.Events.ProjectRemoved, this._projectRemoved.bind(this), this); } /** @@ -376,8 +372,7 @@ var parentNode = this._folderNode(uiSourceCode, project, target, frame, projectOrigin, path.slice(0, -1), fromSourceMap); - var type = fromSourceMap ? Sources.NavigatorView.Types.SourceMapFolder : - Sources.NavigatorView.Types.NetworkFolder; + var type = fromSourceMap ? Sources.NavigatorView.Types.SourceMapFolder : Sources.NavigatorView.Types.NetworkFolder; if (project.type() === Workspace.projectTypes.FileSystem) type = Sources.NavigatorView.Types.FileSystemFolder; var name = path[path.length - 1]; @@ -541,8 +536,7 @@ parentNode = node.parent; if (!parentNode || !node.isEmpty()) break; - if (!(node instanceof Sources.NavigatorGroupTreeNode || - node instanceof Sources.NavigatorFolderTreeNode)) + if (!(node instanceof Sources.NavigatorGroupTreeNode || node instanceof Sources.NavigatorFolderTreeNode)) break; if (node._type === Sources.NavigatorView.Types.Frame) break; @@ -622,8 +616,7 @@ var project = uiSourceCode.project(); if (project.type() === Workspace.projectTypes.FileSystem) { var parentURL = uiSourceCode.parentURL(); - contextMenu.appendItem( - Common.UIString('Rename\u2026'), this._handleContextMenuRename.bind(this, uiSourceCode)); + contextMenu.appendItem(Common.UIString('Rename\u2026'), this._handleContextMenuRename.bind(this, uiSourceCode)); contextMenu.appendItem( Common.UIString('Make a copy\u2026'), this._handleContextMenuCreate.bind(this, project, parentURL, uiSourceCode)); @@ -651,8 +644,7 @@ return; contextMenu.appendItem(Common.UIString('New file'), this._handleContextMenuCreate.bind(this, project, path)); - contextMenu.appendItem( - Common.UIString('Exclude folder'), this._handleContextMenuExclude.bind(this, project, path)); + contextMenu.appendItem(Common.UIString('Exclude folder'), this._handleContextMenuExclude.bind(this, project, path)); function removeFolder() { var shouldRemove = window.confirm(Common.UIString('Are you sure you want to remove this folder?')); @@ -1449,8 +1441,7 @@ } _shouldMerge(node) { - return this._type !== Sources.NavigatorView.Types.Domain && - node instanceof Sources.NavigatorFolderTreeNode; + return this._type !== Sources.NavigatorView.Types.Domain && node instanceof Sources.NavigatorFolderTreeNode; } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/OpenResourceDialog.js b/third_party/WebKit/Source/devtools/front_end/sources/OpenResourceDialog.js index c58aa39..fdc7f3b 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/OpenResourceDialog.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/OpenResourceDialog.js
@@ -26,10 +26,8 @@ * @param {!Array<string>} history */ static show(sourcesView, query, defaultScores, history) { - Sources.OpenResourceDialog._instanceForTest = - new Sources.OpenResourceDialog(sourcesView, defaultScores, history); - var filteredItemSelectionDialog = - new UI.FilteredListWidget(Sources.OpenResourceDialog._instanceForTest); + Sources.OpenResourceDialog._instanceForTest = new Sources.OpenResourceDialog(sourcesView, defaultScores, history); + var filteredItemSelectionDialog = new UI.FilteredListWidget(Sources.OpenResourceDialog._instanceForTest); filteredItemSelectionDialog.showAsDialog(); filteredItemSelectionDialog.setQuery(query); }
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/RevisionHistoryView.js b/third_party/WebKit/Source/devtools/front_end/sources/RevisionHistoryView.js index a8bdbea4..f3fb497 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/RevisionHistoryView.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/RevisionHistoryView.js
@@ -63,8 +63,8 @@ */ static showHistory(uiSourceCode) { UI.viewManager.showView('sources.history'); - var historyView = /** @type {!Sources.RevisionHistoryView} */ ( - self.runtime.sharedInstance(Sources.RevisionHistoryView)); + var historyView = + /** @type {!Sources.RevisionHistoryView} */ (self.runtime.sharedInstance(Sources.RevisionHistoryView)); historyView._revealUISourceCode(uiSourceCode); }
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/ScopeChainSidebarPane.js b/third_party/WebKit/Source/devtools/front_end/sources/ScopeChainSidebarPane.js index d6f96cab..2d71f6790 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/ScopeChainSidebarPane.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/ScopeChainSidebarPane.js
@@ -47,8 +47,7 @@ var callFrame = UI.context.flavor(SDK.DebuggerModel.CallFrame); var details = UI.context.flavor(SDK.DebuggerPausedDetails); this._linkifier.reset(); - Sources.SourceMapNamesResolver.resolveThisObject(callFrame).then( - this._innerUpdate.bind(this, details, callFrame)); + Sources.SourceMapNamesResolver.resolveThisObject(callFrame).then(this._innerUpdate.bind(this, details, callFrame)); } /** @@ -84,15 +83,17 @@ extraProperties.push(new SDK.RemoteObjectProperty('this', thisObject)); if (i === 0) { var exception = details.exception(); - if (exception) + if (exception) { extraProperties.push(new SDK.RemoteObjectProperty( Common.UIString.capitalize('Exception'), exception, undefined, undefined, undefined, undefined, undefined, true)); + } var returnValue = callFrame.returnValue(); - if (returnValue) + if (returnValue) { extraProperties.push(new SDK.RemoteObjectProperty( - Common.UIString.capitalize('Return ^value'), returnValue, undefined, undefined, undefined, - undefined, undefined, true)); + Common.UIString.capitalize('Return ^value'), returnValue, undefined, undefined, undefined, undefined, + undefined, true)); + } } break; case Protocol.Debugger.ScopeType.Closure: @@ -129,8 +130,8 @@ titleElement.createChild('div', 'scope-chain-sidebar-pane-section-title').textContent = title; var section = new Components.ObjectPropertiesSection( - Sources.SourceMapNamesResolver.resolveScopeInObject(scope), titleElement, this._linkifier, - emptyPlaceholder, true, extraProperties); + Sources.SourceMapNamesResolver.resolveScopeInObject(scope), titleElement, this._linkifier, emptyPlaceholder, + true, extraProperties); this._expandController.watchSection(title + (subtitle ? ':' + subtitle : ''), section); if (scope.type() === Protocol.Debugger.ScopeType.Global)
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/ScriptFormatterEditorAction.js b/third_party/WebKit/Source/devtools/front_end/sources/ScriptFormatterEditorAction.js index d297db3..3e9b88f 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/ScriptFormatterEditorAction.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/ScriptFormatterEditorAction.js
@@ -208,9 +208,8 @@ return false; if (Persistence.persistence.binding(uiSourceCode)) return false; - var supportedProjectTypes = [ - Workspace.projectTypes.Network, Workspace.projectTypes.Debugger, Workspace.projectTypes.ContentScripts - ]; + var supportedProjectTypes = + [Workspace.projectTypes.Network, Workspace.projectTypes.Debugger, Workspace.projectTypes.ContentScripts]; if (supportedProjectTypes.indexOf(uiSourceCode.project().type()) === -1) return false; return uiSourceCode.contentType().hasScripts(); @@ -276,9 +275,9 @@ scripts.push(formatData.scripts[j]); } - if (scripts.length) + if (scripts.length) { formatData.scripts = scripts; - else { + } else { this._formattedPaths.remove(formatData.projectId + ':' + formatData.path); this._formatData.remove(uiSourceCodes[i]); this._project.removeFile(uiSourceCodes[i].url()); @@ -332,9 +331,10 @@ var uiSourceCodePath = formattedPath; var formattedUISourceCode = this._workspace.uiSourceCode(this._projectId, uiSourceCodePath); var formatData = formattedUISourceCode ? this._formatData.get(formattedUISourceCode) : null; - if (formatData) + if (formatData) { this._showIfNeeded( uiSourceCode, /** @type {!Workspace.UISourceCode} */ (formattedUISourceCode), formatData.mapping); + } return; } @@ -346,8 +346,7 @@ */ function contentLoaded(content) { var highlighterType = Bindings.NetworkProject.uiSourceCodeMimeType(uiSourceCode); - Sources.Formatter.format( - uiSourceCode.contentType(), highlighterType, content || '', innerCallback.bind(this)); + Sources.Formatter.format(uiSourceCode.contentType(), highlighterType, content || '', innerCallback.bind(this)); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/SimpleHistoryManager.js b/third_party/WebKit/Source/devtools/front_end/sources/SimpleHistoryManager.js index 5801ebd..e2b0d76 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/SimpleHistoryManager.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/SimpleHistoryManager.js
@@ -79,9 +79,9 @@ var filteredEntries = []; var removedBeforeActiveEntry = 0; for (var i = 0; i < this._entries.length; ++i) { - if (!filterOutCallback(this._entries[i])) { + if (!filterOutCallback(this._entries[i])) filteredEntries.push(this._entries[i]); - } else if (i <= this._activeEntryIndex) + else if (i <= this._activeEntryIndex) ++removedBeforeActiveEntry; } this._entries = filteredEntries;
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/SourceMapNamesResolver.js b/third_party/WebKit/Source/devtools/front_end/sources/SourceMapNamesResolver.js index d659300e..aac8697 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/SourceMapNamesResolver.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/SourceMapNamesResolver.js
@@ -73,8 +73,7 @@ continue; var start = scopeStart + id.offset - prefix.length; cursor.resetTo(start); - result.push( - new Sources.SourceMapNamesResolver.Identifier(id.name, cursor.lineNumber(), cursor.columnNumber())); + result.push(new Sources.SourceMapNamesResolver.Identifier(id.name, cursor.lineNumber(), cursor.columnNumber())); } return result; } @@ -254,8 +253,8 @@ Sources.SourceMapNamesResolver._resolveExpression = function( callFrame, uiSourceCode, lineNumber, startColumnNumber, endColumnNumber) { var target = callFrame.target(); - var rawLocation = Bindings.debuggerWorkspaceBinding.uiLocationToRawLocation( - target, uiSourceCode, lineNumber, startColumnNumber); + var rawLocation = + Bindings.debuggerWorkspaceBinding.uiLocationToRawLocation(target, uiSourceCode, lineNumber, startColumnNumber); if (!rawLocation) return Promise.resolve(''); @@ -282,8 +281,7 @@ var originalText = text.extract(textRange); if (!originalText) return Promise.resolve(''); - return Common.formatterWorkerPool.runTask('evaluatableJavaScriptSubstring', {content: originalText}) - .then(onResult); + return Common.formatterWorkerPool.runTask('evaluatableJavaScriptSubstring', {content: originalText}).then(onResult); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/SourcesNavigator.js b/third_party/WebKit/Source/devtools/front_end/sources/SourcesNavigator.js index 8b1cf10..0e52b82a 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/SourcesNavigator.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/SourcesNavigator.js
@@ -32,8 +32,7 @@ Sources.SourcesNavigatorView = class extends Sources.NavigatorView { constructor() { super(); - SDK.targetManager.addEventListener( - SDK.TargetManager.Events.InspectedURLChanged, this._inspectedURLChanged, this); + SDK.targetManager.addEventListener(SDK.TargetManager.Events.InspectedURLChanged, this._inspectedURLChanged, this); } /** @@ -95,8 +94,7 @@ Sources.NetworkNavigatorView = class extends Sources.NavigatorView { constructor() { super(); - SDK.targetManager.addEventListener( - SDK.TargetManager.Events.InspectedURLChanged, this._inspectedURLChanged, this); + SDK.targetManager.addEventListener(SDK.TargetManager.Events.InspectedURLChanged, this._inspectedURLChanged, this); } /** @@ -148,8 +146,7 @@ var toolbar = new UI.Toolbar('navigator-toolbar'); var title = Common.UIString('Add folder to workspace'); var addButton = new UI.ToolbarButton(title, 'largeicon-add', title); - addButton.addEventListener('click', () => - Workspace.isolatedFileSystemManager.addFileSystem()); + addButton.addEventListener('click', () => Workspace.isolatedFileSystemManager.addFileSystem()); toolbar.appendToolbarItem(addButton); this.element.insertBefore(toolbar.element, this.element.firstChild); }
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/SourcesPanel.js b/third_party/WebKit/Source/devtools/front_end/sources/SourcesPanel.js index 003dffd..2b37168 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/SourcesPanel.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/SourcesPanel.js
@@ -56,15 +56,13 @@ this._debuggerPausedMessage = new Sources.DebuggerPausedMessage(); const initialDebugSidebarWidth = 225; - this._splitWidget = - new UI.SplitWidget(true, true, 'sourcesPanelSplitViewState', initialDebugSidebarWidth); + this._splitWidget = new UI.SplitWidget(true, true, 'sourcesPanelSplitViewState', initialDebugSidebarWidth); this._splitWidget.enableShowModeSaving(); this._splitWidget.show(this.element); // Create scripts navigator const initialNavigatorWidth = 225; - this.editorView = - new UI.SplitWidget(true, false, 'sourcesPanelNavigatorSplitViewState', initialNavigatorWidth); + this.editorView = new UI.SplitWidget(true, false, 'sourcesPanelNavigatorSplitViewState', initialNavigatorWidth); this.editorView.enableShowModeSaving(); this.editorView.element.tabIndex = 0; this._splitWidget.setMainWidget(this.editorView); @@ -110,8 +108,7 @@ UI.context.addFlavorChangeListener(SDK.Target, this._onCurrentTargetChanged, this); UI.context.addFlavorChangeListener(SDK.DebuggerModel.CallFrame, this._callFrameChanged, this); SDK.targetManager.addModelListener( - SDK.DebuggerModel, SDK.DebuggerModel.Events.DebuggerWasEnabled, this._debuggerWasEnabled, - this); + SDK.DebuggerModel, SDK.DebuggerModel.Events.DebuggerWasEnabled, this._debuggerWasEnabled, this); SDK.targetManager.addModelListener( SDK.DebuggerModel, SDK.DebuggerModel.Events.DebuggerPaused, this._debuggerPaused, this); SDK.targetManager.addModelListener( @@ -143,8 +140,7 @@ panel._sourcesView.leftToolbar().removeToolbarItems(); panel._sourcesView.rightToolbar().removeToolbarItems(); panel._sourcesView.bottomToolbar().removeToolbarItems(); - var isInWrapper = - Sources.SourcesPanel.WrapperView.isShowing() && !UI.inspectorView.isDrawerMinimized(); + var isInWrapper = Sources.SourcesPanel.WrapperView.isShowing() && !UI.inspectorView.isDrawerMinimized(); if (panel._splitWidget.isVertical() || isInWrapper) panel._splitWidget.uninstallResizer(panel._sourcesView.toolbarContainerElement()); else @@ -180,8 +176,10 @@ _showThreadsIfNeeded() { if (Sources.ThreadsSidebarPane.shouldBeShown() && !this._threadsSidebarPane) { this._threadsSidebarPane = /** @type {!UI.View} */ (UI.viewManager.view('sources.threads')); - if (this._sidebarPaneStack) - this._sidebarPaneStack.showView(this._threadsSidebarPane, this._splitWidget.isVertical() ? this._watchSidebarPane : this._callstackPane); + if (this._sidebarPaneStack) { + this._sidebarPaneStack.showView( + this._threadsSidebarPane, this._splitWidget.isVertical() ? this._watchSidebarPane : this._callstackPane); + } } } @@ -360,8 +358,8 @@ */ showUISourceCode(uiSourceCode, lineNumber, columnNumber, omitFocus) { if (omitFocus) { - var wrapperShowing = Sources.SourcesPanel.WrapperView._instance && - Sources.SourcesPanel.WrapperView._instance.isShowing(); + var wrapperShowing = + Sources.SourcesPanel.WrapperView._instance && Sources.SourcesPanel.WrapperView._instance.isShowing(); if (!this.isShowing() && !wrapperShowing) return; } else { @@ -685,11 +683,10 @@ _createDebugToolbar() { var debugToolbar = new UI.Toolbar('scripts-debug-toolbar'); - var longResumeButton = new UI.ToolbarButton( - Common.UIString('Resume with all pauses blocked for 500 ms'), 'largeicon-play'); + var longResumeButton = + new UI.ToolbarButton(Common.UIString('Resume with all pauses blocked for 500 ms'), 'largeicon-play'); longResumeButton.addEventListener('click', this._longResume.bind(this), this); - debugToolbar.appendToolbarItem( - UI.Toolbar.createActionButton(this._togglePauseAction, [longResumeButton], [])); + debugToolbar.appendToolbarItem(UI.Toolbar.createActionButton(this._togglePauseAction, [longResumeButton], [])); debugToolbar.appendToolbarItem(UI.Toolbar.createActionButton(this._stepOverAction)); debugToolbar.appendToolbarItem(UI.Toolbar.createActionButton(this._stepIntoAction)); @@ -795,14 +792,15 @@ return; if (uiSourceCode.project().type() === Workspace.projectTypes.FileSystem) { var binding = Persistence.persistence.binding(uiSourceCode); - if (!binding) + if (!binding) { contextMenu.appendItem( Common.UIString.capitalize('Map to ^network ^resource\u2026'), this.mapFileSystemToNetwork.bind(this, uiSourceCode)); - else + } else { contextMenu.appendItem( Common.UIString.capitalize('Remove ^network ^mapping'), this._removeNetworkMapping.bind(this, binding.network)); + } } /** @@ -816,10 +814,11 @@ uiSourceCode.project().type() === Workspace.projectTypes.ContentScripts) { if (!this._workspace.projects().filter(filterProject).length) return; - if (this._networkMapping.uiSourceCodeForURLForAnyTarget(uiSourceCode.url()) === uiSourceCode) + if (this._networkMapping.uiSourceCodeForURLForAnyTarget(uiSourceCode.url()) === uiSourceCode) { contextMenu.appendItem( Common.UIString.capitalize('Map to ^file ^system ^resource\u2026'), this.mapNetworkToFileSystem.bind(this, uiSourceCode)); + } } } @@ -838,15 +837,14 @@ if (projectType !== Workspace.projectTypes.Debugger && !event.target.isSelfOrDescendant(this._navigatorTabbedLocation.widget().element)) { contextMenu.appendItem( - Common.UIString.capitalize('Reveal in ^navigator'), - this._handleContextMenuReveal.bind(this, uiSourceCode)); + Common.UIString.capitalize('Reveal in ^navigator'), this._handleContextMenuReveal.bind(this, uiSourceCode)); contextMenu.appendSeparator(); } this._appendUISourceCodeMappingItems(contextMenu, uiSourceCode); - if (projectType !== Workspace.projectTypes.FileSystem) + if (projectType !== Workspace.projectTypes.FileSystem) { contextMenu.appendItem( - Common.UIString.capitalize('Local ^modifications\u2026'), - this._showLocalHistory.bind(this, uiSourceCode)); + Common.UIString.capitalize('Local ^modifications\u2026'), this._showLocalHistory.bind(this, uiSourceCode)); + } } /** @@ -875,9 +873,10 @@ if (contentType.hasScripts()) { var target = UI.context.flavor(SDK.Target); var debuggerModel = SDK.DebuggerModel.fromTarget(target); - if (debuggerModel && debuggerModel.isPaused()) + if (debuggerModel && debuggerModel.isPaused()) { contextMenu.appendItem( Common.UIString.capitalize('Continue to ^here'), this._continueToLocation.bind(this, uiLocation)); + } } if (contentType.hasScripts() && projectType !== Workspace.projectTypes.Snippets) @@ -901,12 +900,12 @@ return; var remoteObject = /** @type {!SDK.RemoteObject} */ (target); contextMenu.appendItem( - Common.UIString.capitalize('Store as ^global ^variable'), - this._saveToTempVariable.bind(this, remoteObject)); - if (remoteObject.type === 'function') + Common.UIString.capitalize('Store as ^global ^variable'), this._saveToTempVariable.bind(this, remoteObject)); + if (remoteObject.type === 'function') { contextMenu.appendItem( Common.UIString.capitalize('Show ^function ^definition'), this._showFunctionDefinition.bind(this, remoteObject)); + } } /** @@ -952,11 +951,12 @@ return name; } - if (!!exceptionDetails || !global) + if (!!exceptionDetails || !global) { failedToSave(global); - else + } else { global.callFunction( remoteFunction, [SDK.RemoteObject.toCallArgument(remoteObject)], didSave.bind(null, global)); + } } /** @@ -966,11 +966,12 @@ */ function didSave(global, result, wasThrown) { global.release(); - if (wasThrown || !result || result.type !== 'string') + if (wasThrown || !result || result.type !== 'string') { failedToSave(result); - else + } else { SDK.ConsoleModel.evaluateCommandInConsole( /** @type {!SDK.ExecutionContext} */ (currentExecutionContext), result.value); + } } /** @@ -1303,8 +1304,7 @@ * @return {boolean} */ static isShowing() { - return !!Sources.SourcesPanel.WrapperView._instance && - Sources.SourcesPanel.WrapperView._instance.isShowing(); + return !!Sources.SourcesPanel.WrapperView._instance && Sources.SourcesPanel.WrapperView._instance.isShowing(); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/SourcesView.js b/third_party/WebKit/Source/devtools/front_end/sources/SourcesView.js index 64c6fdf9..f5455ca 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/SourcesView.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/SourcesView.js
@@ -26,15 +26,14 @@ /** @type {!Map.<!Workspace.UISourceCode, !UI.Widget>} */ this._sourceViewByUISourceCode = new Map(); - var tabbedEditorPlaceholderText = Host.isMac() ? Common.UIString('Hit \u2318+P to open a file') : - Common.UIString('Hit Ctrl+P to open a file'); + var tabbedEditorPlaceholderText = + Host.isMac() ? Common.UIString('Hit \u2318+P to open a file') : Common.UIString('Hit Ctrl+P to open a file'); this._editorContainer = new Sources.TabbedEditorContainer( this, Common.settings.createLocalSetting('previouslyViewedFiles', []), tabbedEditorPlaceholderText); this._editorContainer.show(this._searchableView.element); this._editorContainer.addEventListener( Sources.TabbedEditorContainer.Events.EditorSelected, this._editorSelected, this); - this._editorContainer.addEventListener( - Sources.TabbedEditorContainer.Events.EditorClosed, this._editorClosed, this); + this._editorContainer.addEventListener(Sources.TabbedEditorContainer.Events.EditorClosed, this._editorClosed, this); this._historyManager = new Sources.EditingLocationHistoryManager(this, this.currentSourceFrame.bind(this)); @@ -331,11 +330,9 @@ else if (contentType.isStyleSheet()) sourceFrame = new Sources.CSSSourceFrame(uiSourceCode); else if (contentType === Common.resourceTypes.Image) - sourceView = - new SourceFrame.ImageView(Bindings.NetworkProject.uiSourceCodeMimeType(uiSourceCode), uiSourceCode); + sourceView = new SourceFrame.ImageView(Bindings.NetworkProject.uiSourceCodeMimeType(uiSourceCode), uiSourceCode); else if (contentType === Common.resourceTypes.Font) - sourceView = - new SourceFrame.FontView(Bindings.NetworkProject.uiSourceCodeMimeType(uiSourceCode), uiSourceCode); + sourceView = new SourceFrame.FontView(Bindings.NetworkProject.uiSourceCodeMimeType(uiSourceCode), uiSourceCode); else sourceFrame = new Sources.UISourceCodeFrame(uiSourceCode); @@ -401,8 +398,7 @@ _removeSourceFrame(uiSourceCode) { var sourceView = this._sourceViewByUISourceCode.get(uiSourceCode); this._sourceViewByUISourceCode.remove(uiSourceCode); - uiSourceCode.removeEventListener( - Workspace.UISourceCode.Events.TitleChanged, this._uiSourceCodeTitleChanged, this); + uiSourceCode.removeEventListener(Workspace.UISourceCode.Events.TitleChanged, this._uiSourceCodeTitleChanged, this); if (sourceView && sourceView instanceof Sources.UISourceCodeFrame) /** @type {!Sources.UISourceCodeFrame} */ (sourceView).dispose(); }
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/TabbedEditorContainer.js b/third_party/WebKit/Source/devtools/front_end/sources/TabbedEditorContainer.js index ef3fc2b..fab5f62 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/TabbedEditorContainer.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/TabbedEditorContainer.js
@@ -421,8 +421,7 @@ } _updateHistory() { - var tabIds = - this._tabbedPane.lastOpenedTabIds(Sources.TabbedEditorContainer.maximalPreviouslyViewedFilesCount); + var tabIds = this._tabbedPane.lastOpenedTabIds(Sources.TabbedEditorContainer.maximalPreviouslyViewedFilesCount); /** * @param {string} tabId @@ -537,8 +536,7 @@ * @param {!Workspace.UISourceCode} uiSourceCode */ _removeUISourceCodeListeners(uiSourceCode) { - uiSourceCode.removeEventListener( - Workspace.UISourceCode.Events.TitleChanged, this._uiSourceCodeTitleChanged, this); + uiSourceCode.removeEventListener(Workspace.UISourceCode.Events.TitleChanged, this._uiSourceCodeTitleChanged, this); uiSourceCode.removeEventListener( Workspace.UISourceCode.Events.WorkingCopyChanged, this._uiSourceCodeWorkingCopyChanged, this); uiSourceCode.removeEventListener( @@ -558,7 +556,9 @@ tabId, 'smallicon-warning', Common.UIString('Changes to this file were not saved to file system.')); } else if (Runtime.experiments.isEnabled('persistence2') && Persistence.persistence.binding(uiSourceCode)) { var binding = Persistence.persistence.binding(uiSourceCode); - this._tabbedPane.setTabIcon(tabId, 'smallicon-green-checkmark', Persistence.PersistenceUtils.tooltipForUISourceCode(binding.fileSystem)); + this._tabbedPane.setTabIcon( + tabId, 'smallicon-green-checkmark', + Persistence.PersistenceUtils.tooltipForUISourceCode(binding.fileSystem)); } else { this._tabbedPane.setTabIcon(tabId, ''); } @@ -744,8 +744,9 @@ if (index !== -1) { item = this._items[index]; this._items.splice(index, 1); - } else + } else { item = new Sources.TabbedEditorContainer.HistoryItem(urls[i]); + } this._items.unshift(item); this._rebuildItemIndex(); }
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/ThreadsSidebarPane.js b/third_party/WebKit/Source/devtools/front_end/sources/ThreadsSidebarPane.js index 25da14ff..835d064 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/ThreadsSidebarPane.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/ThreadsSidebarPane.js
@@ -20,29 +20,28 @@ this.threadList = new Sources.UIList(); this.threadList.show(this.element); SDK.targetManager.addModelListener( - SDK.DebuggerModel, SDK.DebuggerModel.Events.DebuggerPaused, this._onDebuggerStateChanged, - this); + SDK.DebuggerModel, SDK.DebuggerModel.Events.DebuggerPaused, this._onDebuggerStateChanged, this); SDK.targetManager.addModelListener( - SDK.DebuggerModel, SDK.DebuggerModel.Events.DebuggerResumed, this._onDebuggerStateChanged, - this); + SDK.DebuggerModel, SDK.DebuggerModel.Events.DebuggerResumed, this._onDebuggerStateChanged, this); SDK.targetManager.addModelListener( - SDK.RuntimeModel, SDK.RuntimeModel.Events.ExecutionContextChanged, - this._onExecutionContextChanged, this); + SDK.RuntimeModel, SDK.RuntimeModel.Events.ExecutionContextChanged, this._onExecutionContextChanged, this); UI.context.addFlavorChangeListener(SDK.Target, this._targetChanged, this); - SDK.targetManager.addEventListener( - SDK.TargetManager.Events.NameChanged, this._targetNameChanged, this); - SDK.targetManager.addModelListener(SDK.SubTargetsManager, SDK.SubTargetsManager.Events.PendingTargetAdded, this._addTargetItem, this); - SDK.targetManager.addModelListener(SDK.SubTargetsManager, SDK.SubTargetsManager.Events.PendingTargetRemoved, this._pendingTargetRemoved, this); - SDK.targetManager.addModelListener(SDK.SubTargetsManager, SDK.SubTargetsManager.Events.PendingTargetAttached, this._addTargetItem, this); - SDK.targetManager.addModelListener(SDK.SubTargetsManager, SDK.SubTargetsManager.Events.PendingTargetDetached, this._targetDetached, this); + SDK.targetManager.addEventListener(SDK.TargetManager.Events.NameChanged, this._targetNameChanged, this); + SDK.targetManager.addModelListener( + SDK.SubTargetsManager, SDK.SubTargetsManager.Events.PendingTargetAdded, this._addTargetItem, this); + SDK.targetManager.addModelListener( + SDK.SubTargetsManager, SDK.SubTargetsManager.Events.PendingTargetRemoved, this._pendingTargetRemoved, this); + SDK.targetManager.addModelListener( + SDK.SubTargetsManager, SDK.SubTargetsManager.Events.PendingTargetAttached, this._addTargetItem, this); + SDK.targetManager.addModelListener( + SDK.SubTargetsManager, SDK.SubTargetsManager.Events.PendingTargetDetached, this._targetDetached, this); SDK.targetManager.observeTargets(this); var pendingTargets = []; for (var target of SDK.targetManager.targets(SDK.Target.Capability.Target)) pendingTargets = pendingTargets.concat(SDK.SubTargetsManager.fromTarget(target).pendingTargets()); - pendingTargets - .sort(Sources.ThreadsSidebarPane._pendingTargetsComparator) + pendingTargets.sort(Sources.ThreadsSidebarPane._pendingTargetsComparator) .forEach(pendingTarget => this._addListItem(pendingTarget)); } @@ -67,13 +66,12 @@ * @param {!SDK.PendingTarget} c2 * @return {number} */ - static _pendingTargetsComparator(c1, c2) - { + static _pendingTargetsComparator(c1, c2) { var t1 = c1.target(); var t2 = c2.target(); var name1 = t1 ? t1.name() : c1.name(); var name2 = t2 ? t2.name() : c2.name(); - if (!!t1 === !!t2) { // Either both are connected or disconnected + if (!!t1 === !!t2) { // Either both are connected or disconnected return name1.toLowerCase().localeCompare(name2.toLowerCase()); } else if (t1) { return -1; @@ -298,7 +296,7 @@ */ _targetRemoved(pendingTarget) { var item = this._pendingToListItem.get(pendingTarget); - if (!item) // Not all targets are represented in the UI. + if (!item) // Not all targets are represented in the UI. return; var target = item[Sources.ThreadsSidebarPane._targetSymbol]; item[Sources.ThreadsSidebarPane._targetSymbol] = null;
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/UISourceCodeFrame.js b/third_party/WebKit/Source/devtools/front_end/sources/UISourceCodeFrame.js index efdb524c..8cc30d6b 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/UISourceCodeFrame.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/UISourceCodeFrame.js
@@ -311,9 +311,10 @@ if (lineNumber < 0) lineNumber = 0; - if (!this._rowMessageBuckets[lineNumber]) + if (!this._rowMessageBuckets[lineNumber]) { this._rowMessageBuckets[lineNumber] = new Sources.UISourceCodeFrame.RowMessageBucket(this, this._textEditor, lineNumber); + } var messageBucket = this._rowMessageBuckets[lineNumber]; messageBucket.addMessage(message); } @@ -555,9 +556,9 @@ */ messagesDescription() { this._messagesDescriptionElement.removeChildren(); - for (var i = 0; i < this._messages.length; ++i) { + for (var i = 0; i < this._messages.length; ++i) this._messagesDescriptionElement.appendChild(this._messages[i].element); - } + return this._messagesDescriptionElement; } @@ -567,8 +568,7 @@ return; var lineNumber = position.lineNumber; if (this._level) - this._textEditor.toggleLineClass( - lineNumber, Sources.UISourceCodeFrame._lineClassPerLevel[this._level], false); + this._textEditor.toggleLineClass(lineNumber, Sources.UISourceCodeFrame._lineClassPerLevel[this._level], false); if (this._hasDecoration) this._textEditor.removeDecoration(this._decoration, lineNumber); this._hasDecoration = false; @@ -635,8 +635,7 @@ this._updateWavePosition(lineNumber, columnNumber); if (this._level) { - this._textEditor.toggleLineClass( - lineNumber, Sources.UISourceCodeFrame._lineClassPerLevel[this._level], false); + this._textEditor.toggleLineClass(lineNumber, Sources.UISourceCodeFrame._lineClassPerLevel[this._level], false); this._icon.type = ''; } this._level = maxMessage.level();
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/WatchExpressionsSidebarPane.js b/third_party/WebKit/Source/devtools/front_end/sources/WatchExpressionsSidebarPane.js index ff645a0..6385a2a 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/WatchExpressionsSidebarPane.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/WatchExpressionsSidebarPane.js
@@ -74,9 +74,10 @@ _saveExpressions() { var toSave = []; - for (var i = 0; i < this._watchExpressions.length; i++) + for (var i = 0; i < this._watchExpressions.length; i++) { if (this._watchExpressions[i].expression()) toSave.push(this._watchExpressions[i].expression()); + } this._watchExpressionsSetting.set(toSave); } @@ -167,19 +168,20 @@ isEditing |= watchExpression.isEditing(); if (!isEditing) - contextMenu.appendItem( - Common.UIString.capitalize('Add ^watch ^expression'), this._addButtonClicked.bind(this)); + contextMenu.appendItem(Common.UIString.capitalize('Add ^watch ^expression'), this._addButtonClicked.bind(this)); - if (this._watchExpressions.length > 1) + if (this._watchExpressions.length > 1) { contextMenu.appendItem( Common.UIString.capitalize('Delete ^all ^watch ^expressions'), this._deleteAllButtonClicked.bind(this)); + } var target = event.deepElementFromPoint(); if (!target) return; - for (var watchExpression of this._watchExpressions) + for (var watchExpression of this._watchExpressions) { if (watchExpression.element().isSelfOrAncestor(target)) watchExpression._populateContextMenu(contextMenu, event); + } } _deleteAllButtonClicked() { @@ -254,10 +256,11 @@ update() { var currentExecutionContext = UI.context.flavor(SDK.ExecutionContext); - if (currentExecutionContext && this._expression) + if (currentExecutionContext && this._expression) { currentExecutionContext.evaluate( this._expression, Sources.WatchExpression._watchObjectGroupId, false, true, false, false, false, this._createWatchExpression.bind(this)); + } } startEditing() { @@ -410,9 +413,10 @@ * @param {!Event} event */ _populateContextMenu(contextMenu, event) { - if (!this.isEditing()) + if (!this.isEditing()) { contextMenu.appendItem( Common.UIString.capitalize('Delete ^watch ^expression'), this._updateExpression.bind(this, null)); + } if (!this.isEditing() && this._result && (this._result.type === 'number' || this._result.type === 'string')) contextMenu.appendItem(Common.UIString.capitalize('Copy ^value'), this._copyValueButtonClicked.bind(this));
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/WorkspaceMappingTip.js b/third_party/WebKit/Source/devtools/front_end/sources/WorkspaceMappingTip.js index d048d5df..7a2e249 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/WorkspaceMappingTip.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/WorkspaceMappingTip.js
@@ -21,8 +21,7 @@ if (this._workspaceInfobarDisabledSetting.get() && this._workspaceMappingInfobarDisabledSetting.get()) return; this._sourcesView.addEventListener(Sources.SourcesView.Events.EditorSelected, this._editorSelected.bind(this)); - Persistence.persistence.addEventListener( - Persistence.Persistence.Events.BindingCreated, this._bindingCreated, this); + Persistence.persistence.addEventListener(Persistence.Persistence.Events.BindingCreated, this._bindingCreated, this); } /** @@ -64,8 +63,7 @@ return; var networkProjects = this._workspace.projectsForType(Workspace.projectTypes.Network); - networkProjects = - networkProjects.concat(this._workspace.projectsForType(Workspace.projectTypes.ContentScripts)); + networkProjects = networkProjects.concat(this._workspace.projectsForType(Workspace.projectTypes.ContentScripts)); for (var i = 0; i < networkProjects.length; ++i) { var name = uiSourceCode.name(); var networkUiSourceCodes = networkProjects[i].uiSourceCodes(); @@ -115,13 +113,12 @@ */ _showWorkspaceInfobar(uiSourceCode) { var infobar = UI.Infobar.create( - UI.Infobar.Type.Info, - Common.UIString('Serving from the file system? Add your files into the workspace.'), + UI.Infobar.Type.Info, Common.UIString('Serving from the file system? Add your files into the workspace.'), this._workspaceInfobarDisabledSetting); if (!infobar) return; - infobar.createDetailsRowMessage(Common.UIString( - 'If you add files into your DevTools workspace, your changes will be persisted to disk.')); + infobar.createDetailsRowMessage( + Common.UIString('If you add files into your DevTools workspace, your changes will be persisted to disk.')); infobar.createDetailsRowMessage( Common.UIString('To add a folder into the workspace, drag and drop it into the Sources panel.')); this._appendInfobar(uiSourceCode, infobar); @@ -138,8 +135,7 @@ else title = Common.UIString('Map workspace resource \'%s\' to network?', uiSourceCode.url()); - var infobar = UI.Infobar.create( - UI.Infobar.Type.Info, title, this._workspaceMappingInfobarDisabledSetting); + var infobar = UI.Infobar.create(UI.Infobar.Type.Info, title, this._workspaceMappingInfobarDisabledSetting); if (!infobar) return; infobar.createDetailsRowMessage(Common.UIString( @@ -173,8 +169,8 @@ var rowElement = infobar.createDetailsRowMessage(Common.UIString('For more information on workspaces, refer to the ')); - rowElement.appendChild(UI.linkifyDocumentationURLAsNode( - '../setup/setup-workflow', Common.UIString('workspaces documentation'))); + rowElement.appendChild( + UI.linkifyDocumentationURLAsNode('../setup/setup-workflow', Common.UIString('workspaces documentation'))); rowElement.createTextChild('.'); uiSourceCode[Sources.WorkspaceMappingTip._infobarSymbol] = infobar; uiSourceCodeFrame.attachInfobars([infobar]);
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/XHRBreakpointsSidebarPane.js b/third_party/WebKit/Source/devtools/front_end/sources/XHRBreakpointsSidebarPane.js index ceed7cb..69b130b 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/XHRBreakpointsSidebarPane.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/XHRBreakpointsSidebarPane.js
@@ -201,13 +201,13 @@ this._removeBreakpoint(url); this._setBreakpoint(text, element._checkboxElement.checked); this._saveBreakpoints(); - } else + } else { element.classList.remove('hidden'); + } } UI.InplaceEditor.startEditing( - inputElement, - new UI.InplaceEditor.Config(finishEditing.bind(this, true), finishEditing.bind(this, false))); + inputElement, new UI.InplaceEditor.Config(finishEditing.bind(this, true), finishEditing.bind(this, false))); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/terminal/TerminalWidget.js b/third_party/WebKit/Source/devtools/front_end/terminal/TerminalWidget.js index ca55518a..1fb6fd1 100644 --- a/third_party/WebKit/Source/devtools/front_end/terminal/TerminalWidget.js +++ b/third_party/WebKit/Source/devtools/front_end/terminal/TerminalWidget.js
@@ -27,8 +27,7 @@ if (!backend) { if (!this._unavailableLabel) { this._unavailableLabel = this.element.createChild('div', 'terminal-error-message fill'); - this._unavailableLabel.createChild('div').textContent = - Common.UIString('Terminal service is not available'); + this._unavailableLabel.createChild('div').textContent = Common.UIString('Terminal service is not available'); } if (this.isShowing()) setTimeout(this._init.bind(this), 2000);
diff --git a/third_party/WebKit/Source/devtools/front_end/text_editor/CodeMirrorTextEditor.js b/third_party/WebKit/Source/devtools/front_end/text_editor/CodeMirrorTextEditor.js index 5e1c09da..dd05680 100644 --- a/third_party/WebKit/Source/devtools/front_end/text_editor/CodeMirrorTextEditor.js +++ b/third_party/WebKit/Source/devtools/front_end/text_editor/CodeMirrorTextEditor.js
@@ -429,9 +429,9 @@ if (!valid(charNumber, length)) return constrainPosition(lineNumber, length, charNumber); - if (isWordStart(text, charNumber) || isWordEnd(text, charNumber)) { + if (isWordStart(text, charNumber) || isWordEnd(text, charNumber)) return {lineNumber: lineNumber, columnNumber: charNumber}; - } + return {lineNumber: lineNumber, columnNumber: direction === -1 ? charNumber + 1 : charNumber}; } @@ -849,11 +849,12 @@ var newPaddingBottom; var linesElement = this._codeMirrorElement.querySelector('.CodeMirror-lines'); var lineCount = this._codeMirror.lineCount(); - if (lineCount <= 1) + if (lineCount <= 1) { newPaddingBottom = 0; - else + } else { newPaddingBottom = Math.max(scrollInfo.clientHeight - this._codeMirror.getLineHandle(this._codeMirror.lastLine()).height, 0); + } newPaddingBottom += 'px'; linesElement.style.paddingBottom = newPaddingBottom; this._codeMirror.setSize(width, height); @@ -1425,9 +1426,9 @@ var last = selections[selections.length - 1]; var next = last; - do { + do next = this._findNextOccurrence(next, !!this._fullWordSelection); - } while (next && this._findRange(selections, next) && !next.equal(last)); + while (next && this._findRange(selections, next) && !next.equal(last)); if (!next) return;
diff --git a/third_party/WebKit/Source/devtools/front_end/text_editor/TextEditorAutocompleteController.js b/third_party/WebKit/Source/devtools/front_end/text_editor/TextEditorAutocompleteController.js index 808ee2cd..12cc3c1 100644 --- a/third_party/WebKit/Source/devtools/front_end/text_editor/TextEditorAutocompleteController.js +++ b/third_party/WebKit/Source/devtools/front_end/text_editor/TextEditorAutocompleteController.js
@@ -114,8 +114,9 @@ * @return {!Promise.<!UI.SuggestBox.Suggestions>} */ _wordsWithQuery(queryRange, substituteRange, force, tokenType) { - var external = - this._config.suggestionsCallback ? this._config.suggestionsCallback(queryRange, substituteRange, force, tokenType) : null; + var external = this._config.suggestionsCallback ? + this._config.suggestionsCallback(queryRange, substituteRange, force, tokenType) : + null; if (external) return external; @@ -283,11 +284,12 @@ } } - if (!this._hintMarker) + if (!this._hintMarker) { this._hintMarker = this._textEditor.addBookmark( cursor.line, cursor.ch, this._hintElement, TextEditor.TextEditorAutocompleteController.HintBookmark, true); - else if (this._lastHintText !== hint) + } else if (this._lastHintText !== hint) { this._hintMarker.refresh(); + } this._lastHintText = hint; } @@ -391,9 +393,9 @@ var scrollInfo = this._codeMirror.getScrollInfo(); var topmostLineNumber = this._codeMirror.lineAtHeight(scrollInfo.top, 'local'); var bottomLine = this._codeMirror.lineAtHeight(scrollInfo.top + scrollInfo.clientHeight, 'local'); - if (cursor.line < topmostLineNumber || cursor.line > bottomLine) + if (cursor.line < topmostLineNumber || cursor.line > bottomLine) { this.clearAutocomplete(); - else { + } else { this._updateAnchorBox(); this._suggestBox.setPosition(this._anchorBox); }
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline/MemoryCountersGraph.js b/third_party/WebKit/Source/devtools/front_end/timeline/MemoryCountersGraph.js index 20af2111..c1a1ce6 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline/MemoryCountersGraph.js +++ b/third_party/WebKit/Source/devtools/front_end/timeline/MemoryCountersGraph.js
@@ -41,14 +41,13 @@ super(delegate, model, filters); this._countersByName = {}; this._countersByName['jsHeapSizeUsed'] = this.createCounter( - Common.UIString('JS Heap'), Common.UIString('JS Heap: %s'), 'hsl(220, 90%, 43%)', - Number.bytesToString); - this._countersByName['documents'] = this.createCounter( - Common.UIString('Documents'), Common.UIString('Documents: %s'), 'hsl(0, 90%, 43%)'); + Common.UIString('JS Heap'), Common.UIString('JS Heap: %s'), 'hsl(220, 90%, 43%)', Number.bytesToString); + this._countersByName['documents'] = + this.createCounter(Common.UIString('Documents'), Common.UIString('Documents: %s'), 'hsl(0, 90%, 43%)'); this._countersByName['nodes'] = this.createCounter(Common.UIString('Nodes'), Common.UIString('Nodes: %s'), 'hsl(120, 90%, 43%)'); - this._countersByName['jsEventListeners'] = this.createCounter( - Common.UIString('Listeners'), Common.UIString('Listeners: %s'), 'hsl(38, 90%, 43%)'); + this._countersByName['jsEventListeners'] = + this.createCounter(Common.UIString('Listeners'), Common.UIString('Listeners: %s'), 'hsl(38, 90%, 43%)'); this._gpuMemoryCounter = this.createCounter( Common.UIString('GPU Memory'), Common.UIString('GPU Memory [KB]: %s'), 'hsl(300, 90%, 43%)', Number.bytesToString);
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline/TimelineController.js b/third_party/WebKit/Source/devtools/front_end/timeline/TimelineController.js index a02f1b6..ac9c4b8 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline/TimelineController.js +++ b/third_party/WebKit/Source/devtools/front_end/timeline/TimelineController.js
@@ -47,9 +47,9 @@ ]; categoriesArray.push(TimelineModel.TimelineModel.Category.LatencyInfo); - if (Runtime.experiments.isEnabled('timelineFlowEvents')) { + if (Runtime.experiments.isEnabled('timelineFlowEvents')) categoriesArray.push(disabledByDefault('toplevel.flow'), disabledByDefault('ipc.flow')); - } + if (Runtime.experiments.isEnabled('timelineV8RuntimeCallStats') && enableJSSampling) categoriesArray.push(disabledByDefault('v8.runtime_stats_sampling')); if (Runtime.experiments.isEnabled('timelineTracingJSProfile') && enableJSSampling) { @@ -125,7 +125,6 @@ * @param {!Array<!SDK.CSSModel.RuleUsage>} ruleUsageList */ function ruleListReceived(ruleUsageList) { - for (var rule of ruleUsageList) { if (rule.wasUsed) continue; @@ -197,7 +196,6 @@ * @param {function(?string)=} callback */ _startRecordingWithCategories(categories, enableJSSampling, callback) { - if (!Runtime.experiments.isEnabled('timelineRuleUsageRecording') || !this._markUnusedCSS.get()) SDK.targetManager.suspendAllTargets();
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline/TimelineEventOverview.js b/third_party/WebKit/Source/devtools/front_end/timeline/TimelineEventOverview.js index 797109f..7424476 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline/TimelineEventOverview.js +++ b/third_party/WebKit/Source/devtools/front_end/timeline/TimelineEventOverview.js
@@ -734,8 +734,8 @@ ctx.strokeStyle = 'hsl(220, 90%, 70%)'; ctx.stroke(); - this._heapSizeLabel.textContent = Common.UIString( - '%s \u2013 %s', Number.bytesToString(minUsedHeapSize), Number.bytesToString(maxUsedHeapSize)); + this._heapSizeLabel.textContent = + Common.UIString('%s \u2013 %s', Number.bytesToString(minUsedHeapSize), Number.bytesToString(maxUsedHeapSize)); } };
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline/TimelineFlameChart.js b/third_party/WebKit/Source/devtools/front_end/timeline/TimelineFlameChart.js index ceb4193..7170628 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline/TimelineFlameChart.js +++ b/third_party/WebKit/Source/devtools/front_end/timeline/TimelineFlameChart.js
@@ -303,15 +303,13 @@ var entryType = this._entryType(entryIndex); if (entryType === Timeline.TimelineFlameChartEntryType.Event) { var event = /** @type {!SDK.TracingModel.Event} */ (this._entryData[entryIndex]); - if (event.phase === SDK.TracingModel.Phase.AsyncStepInto || - event.phase === SDK.TracingModel.Phase.AsyncStepPast) + if (event.phase === SDK.TracingModel.Phase.AsyncStepInto || event.phase === SDK.TracingModel.Phase.AsyncStepPast) return event.name + ':' + event.args['step']; if (event._blackboxRoot) return Common.UIString('Blackboxed'); var name = Timeline.TimelineUIUtils.eventStyle(event).title; // TODO(yurys): support event dividers - var detailsText = - Timeline.TimelineUIUtils.buildDetailsTextForTraceEvent(event, this._model.targetByEvent(event)); + var detailsText = Timeline.TimelineUIUtils.buildDetailsTextForTraceEvent(event, this._model.targetByEvent(event)); if (event.name === TimelineModel.TimelineModel.RecordType.JSFrame && detailsText) return detailsText; return detailsText ? Common.UIString('%s (%s)', name, detailsText) : name; @@ -392,7 +390,8 @@ Common.UIString('Main'), this._model.mainThreadEvents(), this._model.mainThreadAsyncEvents(), true); } else { this._appendThreadTimelineData( - Common.UIString('Page'), this._model.eventsForFrame(TimelineModel.TimelineModel.PageFrame.mainFrameId), this._model.mainThreadAsyncEvents(), true); + Common.UIString('Page'), this._model.eventsForFrame(TimelineModel.TimelineModel.PageFrame.mainFrameId), + this._model.mainThreadAsyncEvents(), true); for (var frame of this._model.rootFrames()) { // Ignore top frame itself, since it should be part of page events. frame.children.forEach(this._appendFrameEvents.bind(this, 0)); @@ -402,9 +401,10 @@ var otherThreads = threads.filter(thread => !thread.name.startsWith('CompositorTileWorker')); if (compositorThreads.length) { this._appendHeader(Common.UIString('Raster'), this._headerLevel1); - for (var i = 0; i < compositorThreads.length; ++i) + for (var i = 0; i < compositorThreads.length; ++i) { this._appendSyncEvents( compositorThreads[i].events, Common.UIString('Rasterizer Thread %d', i), this._headerLevel2); + } } this._appendGPUEvents(); @@ -434,8 +434,9 @@ var events = this._model.eventsForFrame(frame.id); var clonedHeader = Object.assign({}, this._headerLevel1); clonedHeader.nestingLevel = level; - this._appendSyncEvents(events, Timeline.TimelineUIUtils.displayNameForFrame(frame), - /** @type {!UI.FlameChart.GroupStyle} */ (clonedHeader)); + this._appendSyncEvents( + events, Timeline.TimelineUIUtils.displayNameForFrame(frame), + /** @type {!UI.FlameChart.GroupStyle} */ (clonedHeader)); frame.children.forEach(this._appendFrameEvents.bind(this, level + 1)); } @@ -463,10 +464,11 @@ var maxStackDepth = 0; for (var i = 0; i < events.length; ++i) { var e = events[i]; - if (TimelineModel.TimelineModel.isMarkerEvent(e)) + if (TimelineModel.TimelineModel.isMarkerEvent(e)) { this._markers.push(new Timeline.TimelineFlameChartMarker( e.startTime, e.startTime - this._model.minimumRecordTime(), Timeline.TimelineUIUtils.markerStyleForEvent(e))); + } if (!SDK.TracingModel.isFlowPhase(e.phase)) { if (!e.endTime && e.phase !== SDK.TracingModel.Phase.Instant) continue; @@ -779,7 +781,8 @@ var type = this._entryType(entryIndex); return type === Timeline.TimelineFlameChartEntryType.Frame || type === Timeline.TimelineFlameChartEntryType.Event && - !!TimelineModel.TimelineData.forEvent(/** @type {!SDK.TracingModel.Event} */ (this._entryData[entryIndex])).warning; + !!TimelineModel.TimelineData.forEvent(/** @type {!SDK.TracingModel.Event} */ (this._entryData[entryIndex])) + .warning; } /** @@ -904,12 +907,13 @@ createSelection(entryIndex) { var type = this._entryType(entryIndex); var timelineSelection = null; - if (type === Timeline.TimelineFlameChartEntryType.Event) + if (type === Timeline.TimelineFlameChartEntryType.Event) { timelineSelection = Timeline.TimelineSelection.fromTraceEvent( /** @type {!SDK.TracingModel.Event} */ (this._entryData[entryIndex])); - else if (type === Timeline.TimelineFlameChartEntryType.Frame) + } else if (type === Timeline.TimelineFlameChartEntryType.Frame) { timelineSelection = Timeline.TimelineSelection.fromFrame( /** @type {!TimelineModel.TimelineFrame} */ (this._entryData[entryIndex])); + } if (timelineSelection) this._lastSelection = new Timeline.TimelineFlameChartView.Selection(timelineSelection, entryIndex); return timelineSelection; @@ -992,8 +996,8 @@ if (index === -1) return null; var request = this._requests[index]; - this._lastSelection = new Timeline.TimelineFlameChartView.Selection( - Timeline.TimelineSelection.fromNetworkRequest(request), index); + this._lastSelection = + new Timeline.TimelineFlameChartView.Selection(Timeline.TimelineSelection.fromNetworkRequest(request), index); return this._lastSelection.timelineSelection; } @@ -1012,9 +1016,10 @@ return -1; var request = /** @type{!TimelineModel.TimelineModel.NetworkRequest} */ (selection.object()); var index = this._requests.indexOf(request); - if (index !== -1) - this._lastSelection = new Timeline.TimelineFlameChartView.Selection( - Timeline.TimelineSelection.fromNetworkRequest(request), index); + if (index !== -1) { + this._lastSelection = + new Timeline.TimelineFlameChartView.Selection(Timeline.TimelineSelection.fromNetworkRequest(request), index); + } return index; } @@ -1331,8 +1336,7 @@ this._splitWidget = new UI.SplitWidget(false, false, 'timelineFlamechartMainView', 150); this._dataProvider = new Timeline.TimelineFlameChartDataProvider(this._model, frameModel, irModel, filters); - var mainViewGroupExpansionSetting = - Common.settings.createSetting('timelineFlamechartMainViewGroupExpansion', {}); + var mainViewGroupExpansionSetting = Common.settings.createSetting('timelineFlamechartMainViewGroupExpansion', {}); this._mainView = new UI.FlameChart(this._dataProvider, this, mainViewGroupExpansionSetting); this._networkDataProvider = new Timeline.TimelineFlameChartNetworkDataProvider(this._model); @@ -1345,8 +1349,7 @@ this._onMainEntrySelected = this._onEntrySelected.bind(this, this._dataProvider); this._onNetworkEntrySelected = this._onEntrySelected.bind(this, this._networkDataProvider); this._mainView.addEventListener(UI.FlameChart.Events.EntrySelected, this._onMainEntrySelected, this); - this._networkView.addEventListener( - UI.FlameChart.Events.EntrySelected, this._onNetworkEntrySelected, this); + this._networkView.addEventListener(UI.FlameChart.Events.EntrySelected, this._onNetworkEntrySelected, this); Bindings.blackboxManager.addChangeListener(this.refreshRecords, this); } @@ -1355,8 +1358,7 @@ */ dispose() { this._mainView.removeEventListener(UI.FlameChart.Events.EntrySelected, this._onMainEntrySelected, this); - this._networkView.removeEventListener( - UI.FlameChart.Events.EntrySelected, this._onNetworkEntrySelected, this); + this._networkView.removeEventListener(UI.FlameChart.Events.EntrySelected, this._onNetworkEntrySelected, this); Bindings.blackboxManager.removeChangeListener(this.refreshRecords, this); }
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline/TimelineLoader.js b/third_party/WebKit/Source/devtools/front_end/timeline/TimelineLoader.js index ba21e38..e6180daa 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline/TimelineLoader.js +++ b/third_party/WebKit/Source/devtools/front_end/timeline/TimelineLoader.js
@@ -84,11 +84,11 @@ this._delegate.loadingProgress(this._totalSize ? this._loadedBytes / this._totalSize : undefined); if (this._state === Timeline.TimelineLoader.State.Initial) { - if (chunk[0] === '{') + if (chunk[0] === '{') { this._state = Timeline.TimelineLoader.State.LookingForEvents; - else if (chunk[0] === '[') + } else if (chunk[0] === '[') { this._state = Timeline.TimelineLoader.State.ReadingEvents; - else { + } else { this._reportErrorAndCancelLoading(Common.UIString('Malformed timeline data: Unknown JSON format')); return; }
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline/TimelinePaintProfilerView.js b/third_party/WebKit/Source/devtools/front_end/timeline/TimelinePaintProfilerView.js index 189d2d99..2cb8329 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline/TimelinePaintProfilerView.js +++ b/third_party/WebKit/Source/devtools/front_end/timeline/TimelinePaintProfilerView.js
@@ -81,9 +81,9 @@ this._paintProfilerView.setSnapshotAndLog(null, [], null); var snapshotPromise; - if (this._pendingSnapshot) + if (this._pendingSnapshot) { snapshotPromise = Promise.resolve({rect: null, snapshot: this._pendingSnapshot}); - else if (this._event.name === TimelineModel.TimelineModel.RecordType.Paint) { + } else if (this._event.name === TimelineModel.TimelineModel.RecordType.Paint) { var picture = TimelineModel.TimelineData.forEvent(this._event).picture; snapshotPromise = picture.objectPromise() .then(data => SDK.PaintProfilerSnapshot.load(this._target, data['skp64']))
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline/TimelinePanel.js b/third_party/WebKit/Source/devtools/front_end/timeline/TimelinePanel.js index e74f5cd..f843de30 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline/TimelinePanel.js +++ b/third_party/WebKit/Source/devtools/front_end/timeline/TimelinePanel.js
@@ -77,8 +77,7 @@ this._captureNetworkSetting = Common.settings.createSetting('timelineCaptureNetwork', false); this._captureJSProfileSetting = Common.settings.createSetting('timelineEnableJSSampling', true); this._captureMemorySetting = Common.settings.createSetting('timelineCaptureMemory', false); - this._captureLayersAndPicturesSetting = - Common.settings.createSetting('timelineCaptureLayersAndPictures', false); + this._captureLayersAndPicturesSetting = Common.settings.createSetting('timelineCaptureLayersAndPictures', false); this._captureFilmStripSetting = Common.settings.createSetting('timelineCaptureFilmStrip', false); this._markUnusedCSS = Common.settings.createSetting('timelineMarkUnusedCSS', false); @@ -93,15 +92,13 @@ // Create top overview component. this._overviewPane = new UI.TimelineOverviewPane('timeline'); - this._overviewPane.addEventListener( - UI.TimelineOverviewPane.Events.WindowChanged, this._onWindowChanged.bind(this)); + this._overviewPane.addEventListener(UI.TimelineOverviewPane.Events.WindowChanged, this._onWindowChanged.bind(this)); this._overviewPane.show(topPaneElement); this._statusPaneContainer = timelinePane.element.createChild('div', 'status-pane-container fill'); this._createFileSelector(); - SDK.targetManager.addEventListener( - SDK.TargetManager.Events.PageReloadRequested, this._pageReloadRequested, this); + SDK.targetManager.addEventListener(SDK.TargetManager.Events.PageReloadRequested, this._pageReloadRequested, this); SDK.targetManager.addEventListener(SDK.TargetManager.Events.Load, this._loadEventFired, this); // Create top level properties splitter. @@ -124,8 +121,7 @@ this._detailsSplitWidget.show(timelinePane.element); this._detailsSplitWidget.hideSidebar(); - SDK.targetManager.addEventListener( - SDK.TargetManager.Events.SuspendStateChanged, this._onSuspendStateChanged, this); + SDK.targetManager.addEventListener(SDK.TargetManager.Events.SuspendStateChanged, this._onSuspendStateChanged, this); this._showRecordingHelpMessage(); /** @type {!SDK.TracingModel.Event}|undefined */ @@ -218,8 +214,7 @@ _layersView() { if (this._lazyLayersView) return this._lazyLayersView; - this._lazyLayersView = - new Timeline.TimelineLayersView(this._model, this._showSnapshotInPaintProfiler.bind(this)); + this._lazyLayersView = new Timeline.TimelineLayersView(this._model, this._showSnapshotInPaintProfiler.bind(this)); return this._lazyLayersView; } @@ -301,8 +296,7 @@ var perspectiveCombobox = new UI.ToolbarComboBox(onPerspectiveChanged.bind(this)); addPerspectiveOption(Timeline.TimelinePanel.Perspectives.Load, Common.UIString('Page Load')); - addPerspectiveOption( - Timeline.TimelinePanel.Perspectives.Responsiveness, Common.UIString('Responsiveness')); + addPerspectiveOption(Timeline.TimelinePanel.Perspectives.Responsiveness, Common.UIString('Responsiveness')); addPerspectiveOption(Timeline.TimelinePanel.Perspectives.Custom, Common.UIString('Custom')); this._panelToolbar.appendToolbarItem(perspectiveCombobox); @@ -325,8 +319,7 @@ } if (Runtime.experiments.isEnabled('timelineRecordingPerspectives') && perspectiveSetting.get() === Timeline.TimelinePanel.Perspectives.Load) { - this._reloadButton = - new UI.ToolbarButton(Common.UIString('Record & Reload'), 'largeicon-refresh'); + this._reloadButton = new UI.ToolbarButton(Common.UIString('Record & Reload'), 'largeicon-refresh'); this._reloadButton.addEventListener('click', () => SDK.targetManager.reloadPage()); this._panelToolbar.appendToolbarItem(this._reloadButton); } else { @@ -368,8 +361,7 @@ if (Runtime.experiments.isEnabled('timelineRuleUsageRecording')) { this._panelToolbar.appendToolbarItem(this._createSettingCheckbox( - Common.UIString('CSS coverage'), this._markUnusedCSS, - Common.UIString('Mark unused CSS in souces.'))); + Common.UIString('CSS coverage'), this._markUnusedCSS, Common.UIString('Mark unused CSS in souces.'))); } this._captureNetworkSetting.addChangeListener(this._onNetworkChanged, this); @@ -377,8 +369,7 @@ this._captureFilmStripSetting.addChangeListener(this._onModeChanged, this); this._panelToolbar.appendSeparator(); - var garbageCollectButton = - new UI.ToolbarButton(Common.UIString('Collect garbage'), 'largeicon-trash-bin'); + var garbageCollectButton = new UI.ToolbarButton(Common.UIString('Collect garbage'), 'largeicon-trash-bin'); garbageCollectButton.addEventListener('click', this._garbageCollectButtonClicked, this); this._panelToolbar.appendToolbarItem(garbageCollectButton); @@ -411,10 +402,11 @@ ]); for (var rate of predefinedRates) addGroupingOption(rate[1], rate[0]); - if (this._customCPUThrottlingRate && !predefinedRates.has(this._customCPUThrottlingRate)) + if (this._customCPUThrottlingRate && !predefinedRates.has(this._customCPUThrottlingRate)) { addGroupingOption( Common.UIString('Custom rate (%d\xD7 slowdown)', this._customCPUThrottlingRate), this._customCPUThrottlingRate); + } addGroupingOption(Common.UIString('Set custom rate\u2026'), 0); } @@ -525,9 +517,10 @@ this._flameChart.enableNetworkPane(this._captureNetworkSetting.get()); this._addModeView(this._flameChart); - if (this._captureMemorySetting.get()) - this._addModeView(new Timeline.MemoryCountersGraph( - this, this._model, [Timeline.TimelineUIUtils.visibleEventsFilter()])); + if (this._captureMemorySetting.get()) { + this._addModeView( + new Timeline.MemoryCountersGraph(this, this._model, [Timeline.TimelineUIUtils.visibleEventsFilter()])); + } this.doResize(); this.select(null); @@ -694,14 +687,13 @@ return e; } - var recordNode = encloseWithTag( - 'b', UI.shortcutRegistry.shortcutDescriptorsForAction('timeline.toggle-recording')[0].name); - var reloadNode = - encloseWithTag('b', UI.shortcutRegistry.shortcutDescriptorsForAction('main.reload')[0].name); + var recordNode = + encloseWithTag('b', UI.shortcutRegistry.shortcutDescriptorsForAction('timeline.toggle-recording')[0].name); + var reloadNode = encloseWithTag('b', UI.shortcutRegistry.shortcutDescriptorsForAction('main.reload')[0].name); var navigateNode = encloseWithTag('b', Common.UIString('WASD (ZQSD)')); var hintText = createElementWithClass('div'); - hintText.appendChild(UI.formatLocalized( - 'To capture a new timeline, click the record toolbar button or hit %s.', [recordNode])); + hintText.appendChild( + UI.formatLocalized('To capture a new timeline, click the record toolbar button or hit %s.', [recordNode])); hintText.createChild('br'); hintText.appendChild( UI.formatLocalized('To evaluate page load performance, hit %s to record the reload.', [reloadNode])); @@ -709,8 +701,8 @@ hintText.appendChild( UI.formatLocalized('After recording, select an area of interest in the overview by dragging.', [])); hintText.createChild('br'); - hintText.appendChild(UI.formatLocalized( - 'Then, zoom and pan the timeline with the mousewheel and %s keys.', [navigateNode])); + hintText.appendChild( + UI.formatLocalized('Then, zoom and pan the timeline with the mousewheel and %s keys.', [navigateNode])); this._hideRecordingHelpMessage(); this._helpMessageElement = this._searchableView.element.createChild('div', 'full-widget-dimmed-banner timeline-status-pane'); @@ -999,9 +991,10 @@ if (frame.layerTree) { var layersView = this._layersView(); layersView.showLayerTree(frame.layerTree); - if (!this._detailsView.hasTab(Timeline.TimelinePanel.DetailsTab.LayerViewer)) + if (!this._detailsView.hasTab(Timeline.TimelinePanel.DetailsTab.LayerViewer)) { this._detailsView.appendTab( Timeline.TimelinePanel.DetailsTab.LayerViewer, Common.UIString('Layers'), layersView); + } } break; case Timeline.TimelineSelection.Type.NetworkRequest: @@ -1058,10 +1051,11 @@ _showSnapshotInPaintProfiler(snapshot) { var paintProfilerView = this._paintProfilerView(); var hasProfileData = paintProfilerView.setSnapshot(snapshot); - if (!this._detailsView.hasTab(Timeline.TimelinePanel.DetailsTab.PaintProfiler)) + if (!this._detailsView.hasTab(Timeline.TimelinePanel.DetailsTab.PaintProfiler)) { this._detailsView.appendTab( - Timeline.TimelinePanel.DetailsTab.PaintProfiler, Common.UIString('Paint Profiler'), - paintProfilerView, undefined, undefined, true); + Timeline.TimelinePanel.DetailsTab.PaintProfiler, Common.UIString('Paint Profiler'), paintProfilerView, + undefined, undefined, true); + } this._detailsView.selectTab(Timeline.TimelinePanel.DetailsTab.PaintProfiler, true); } @@ -1087,10 +1081,11 @@ var hasProfileData = paintProfilerView.setEvent(target, event); if (!hasProfileData) return; - if (!this._detailsView.hasTab(Timeline.TimelinePanel.DetailsTab.PaintProfiler)) + if (!this._detailsView.hasTab(Timeline.TimelinePanel.DetailsTab.PaintProfiler)) { this._detailsView.appendTab( - Timeline.TimelinePanel.DetailsTab.PaintProfiler, Common.UIString('Paint Profiler'), - paintProfilerView, undefined, undefined, false); + Timeline.TimelinePanel.DetailsTab.PaintProfiler, Common.UIString('Paint Profiler'), paintProfilerView, + undefined, undefined, false); + } } /** @@ -1416,8 +1411,7 @@ * @return {!Timeline.TimelineSelection} */ static fromFrame(frame) { - return new Timeline.TimelineSelection( - Timeline.TimelineSelection.Type.Frame, frame.startTime, frame.endTime, frame); + return new Timeline.TimelineSelection(Timeline.TimelineSelection.Type.Frame, frame.startTime, frame.endTime, frame); } /** @@ -1860,8 +1854,7 @@ var filter = new UI.CheckboxFilterUI(category.name, category.title); filter.setColor(category.color, 'rgba(0, 0, 0, 0.2)'); categoryFiltersUI[category.name] = filter; - filter.addEventListener( - UI.FilterUI.Events.FilterChanged, categoriesFilterChanged.bind(this, categoryName)); + filter.addEventListener(UI.FilterUI.Events.FilterChanged, categoriesFilterChanged.bind(this, categoryName)); this._filterBar.addFilter(filter); } return this._filterBar; @@ -1927,8 +1920,7 @@ this._throttlingRate = value; this._targets.forEach(target => target.emulationAgent().setCPUThrottlingRate(value)); if (value !== 1) - UI.inspectorView.setPanelIcon( - 'timeline', 'smallicon-warning', Common.UIString('CPU throttling is enabled')); + UI.inspectorView.setPanelIcon('timeline', 'smallicon-warning', Common.UIString('CPU throttling is enabled')); else UI.inspectorView.setPanelIcon('timeline', '', ''); }
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline/TimelineTreeView.js b/third_party/WebKit/Source/devtools/front_end/timeline/TimelineTreeView.js index 2a77148..04f24028 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline/TimelineTreeView.js +++ b/third_party/WebKit/Source/devtools/front_end/timeline/TimelineTreeView.js
@@ -140,8 +140,7 @@ } for (var child of tree.children.values()) { // Exclude the idle time off the total calculation. - var gridNode = - new Timeline.TimelineTreeView.TreeGridNode(child, tree.totalTime, maxSelfTime, maxTotalTime, this); + var gridNode = new Timeline.TimelineTreeView.TreeGridNode(child, tree.totalTime, maxSelfTime, maxTotalTime, this); this._dataGrid.insertChild(gridNode); } this._sortingChanged(); @@ -168,10 +167,8 @@ * @param {!Array<!UI.DataGrid.ColumnDescriptor>} columns */ _populateColumns(columns) { - columns.push( - {id: 'self', title: Common.UIString('Self Time'), width: '110px', fixedWidth: true, sortable: true}); - columns.push( - {id: 'total', title: Common.UIString('Total Time'), width: '110px', fixedWidth: true, sortable: true}); + columns.push({id: 'self', title: Common.UIString('Self Time'), width: '110px', fixedWidth: true, sortable: true}); + columns.push({id: 'total', title: Common.UIString('Total Time'), width: '110px', fixedWidth: true, sortable: true}); columns.push({id: 'activity', title: Common.UIString('Activity'), disclosure: true, sortable: true}); } @@ -335,10 +332,9 @@ } else if (event) { const data = event.args['data']; const deoptReason = data && data['deoptReason']; - if (deoptReason) { - container.createChild('div', 'activity-warning').title = - Common.UIString('Not optimized: %s', deoptReason); - } + if (deoptReason) + container.createChild('div', 'activity-warning').title = Common.UIString('Not optimized: %s', deoptReason); + name.textContent = Timeline.TimelineUIUtils.eventTitle(event); const link = this._treeView._linkifyLocation(event); if (link) @@ -381,9 +377,10 @@ var textDiv = cell.createChild('div'); textDiv.createChild('span').textContent = Common.UIString('%.1f\u2009ms', value); - if (showPercents && this._treeView._exposePercentages()) + if (showPercents && this._treeView._exposePercentages()) { textDiv.createChild('span', 'percent-column').textContent = Common.UIString('%.1f\u2009%%', value / this._grandTotalTime * 100); + } if (maxTime) { textDiv.classList.add('background-percent-bar'); cell.createChild('div', 'background-bar-container').createChild('div', 'background-bar').style.width = @@ -510,10 +507,7 @@ case Timeline.AggregatedTimelineTreeView.GroupBy.Frame: var frame = this._model.pageFrameById(node.id); var frameName = frame ? Timeline.TimelineUIUtils.displayNameForFrame(frame, 80) : Common.UIString('Page'); - return { - name: frameName, - color: color - }; + return {name: frameName, color: color}; break; default: @@ -742,8 +736,7 @@ constructor(model, filters, delegate) { super(); this._filtersControl = new Timeline.TimelineFilters(); - this._filtersControl.addEventListener( - Timeline.TimelineFilters.Events.FilterChanged, this._onFilterChanged, this); + this._filtersControl.addEventListener(Timeline.TimelineFilters.Events.FilterChanged, this._onFilterChanged, this); this._init(model, filters); this._delegate = delegate; this._filters.push.apply(this._filters, this._filtersControl.filters()); @@ -818,13 +811,8 @@ * @param {!Array<!UI.DataGrid.ColumnDescriptor>} columns */ _populateColumns(columns) { - columns.push({ - id: 'startTime', - title: Common.UIString('Start Time'), - width: '110px', - fixedWidth: true, - sortable: true - }); + columns.push( + {id: 'startTime', title: Common.UIString('Start Time'), width: '110px', fixedWidth: true, sortable: true}); super._populateColumns(columns); }
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline/TimelineUIUtils.js b/third_party/WebKit/Source/devtools/front_end/timeline/TimelineUIUtils.js index 5adeac4..34e8cc4 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline/TimelineUIUtils.js +++ b/third_party/WebKit/Source/devtools/front_end/timeline/TimelineUIUtils.js
@@ -44,20 +44,18 @@ var categories = Timeline.TimelineUIUtils.categories(); var eventStyles = {}; - eventStyles[recordTypes.Task] = - new Timeline.TimelineRecordStyle(Common.UIString('Task'), categories['other']); - eventStyles[recordTypes.Program] = - new Timeline.TimelineRecordStyle(Common.UIString('Other'), categories['other']); + eventStyles[recordTypes.Task] = new Timeline.TimelineRecordStyle(Common.UIString('Task'), categories['other']); + eventStyles[recordTypes.Program] = new Timeline.TimelineRecordStyle(Common.UIString('Other'), categories['other']); eventStyles[recordTypes.Animation] = new Timeline.TimelineRecordStyle(Common.UIString('Animation'), categories['rendering']); eventStyles[recordTypes.EventDispatch] = new Timeline.TimelineRecordStyle(Common.UIString('Event'), categories['scripting']); - eventStyles[recordTypes.RequestMainThreadFrame] = new Timeline.TimelineRecordStyle( - Common.UIString('Request Main Thread Frame'), categories['rendering'], true); + eventStyles[recordTypes.RequestMainThreadFrame] = + new Timeline.TimelineRecordStyle(Common.UIString('Request Main Thread Frame'), categories['rendering'], true); eventStyles[recordTypes.BeginFrame] = new Timeline.TimelineRecordStyle(Common.UIString('Frame Start'), categories['rendering'], true); - eventStyles[recordTypes.BeginMainThreadFrame] = new Timeline.TimelineRecordStyle( - Common.UIString('Frame Start (main thread)'), categories['rendering'], true); + eventStyles[recordTypes.BeginMainThreadFrame] = + new Timeline.TimelineRecordStyle(Common.UIString('Frame Start (main thread)'), categories['rendering'], true); eventStyles[recordTypes.DrawFrame] = new Timeline.TimelineRecordStyle(Common.UIString('Draw Frame'), categories['rendering'], true); eventStyles[recordTypes.HitTest] = @@ -80,8 +78,7 @@ new Timeline.TimelineRecordStyle(Common.UIString('Update Layer'), categories['painting'], true); eventStyles[recordTypes.UpdateLayerTree] = new Timeline.TimelineRecordStyle(Common.UIString('Update Layer Tree'), categories['rendering']); - eventStyles[recordTypes.Paint] = - new Timeline.TimelineRecordStyle(Common.UIString('Paint'), categories['painting']); + eventStyles[recordTypes.Paint] = new Timeline.TimelineRecordStyle(Common.UIString('Paint'), categories['painting']); eventStyles[recordTypes.RasterTask] = new Timeline.TimelineRecordStyle(Common.UIString('Rasterize Paint'), categories['painting']); eventStyles[recordTypes.ScrollLayer] = @@ -110,8 +107,8 @@ new Timeline.TimelineRecordStyle(Common.UIString('Parse Script'), categories['scripting']); eventStyles[recordTypes.MarkLoad] = new Timeline.TimelineRecordStyle(Common.UIString('Load event'), categories['scripting'], true); - eventStyles[recordTypes.MarkDOMContent] = new Timeline.TimelineRecordStyle( - Common.UIString('DOMContentLoaded event'), categories['scripting'], true); + eventStyles[recordTypes.MarkDOMContent] = + new Timeline.TimelineRecordStyle(Common.UIString('DOMContentLoaded event'), categories['scripting'], true); eventStyles[recordTypes.MarkFirstPaint] = new Timeline.TimelineRecordStyle(Common.UIString('First paint'), categories['painting'], true); eventStyles[recordTypes.TimeStamp] = @@ -154,10 +151,10 @@ new Timeline.TimelineRecordStyle(Common.UIString('Fire Idle Callback'), categories['scripting']); eventStyles[recordTypes.WebSocketCreate] = new Timeline.TimelineRecordStyle(Common.UIString('Create WebSocket'), categories['scripting']); - eventStyles[recordTypes.WebSocketSendHandshakeRequest] = new Timeline.TimelineRecordStyle( - Common.UIString('Send WebSocket Handshake'), categories['scripting']); - eventStyles[recordTypes.WebSocketReceiveHandshakeResponse] = new Timeline.TimelineRecordStyle( - Common.UIString('Receive WebSocket Handshake'), categories['scripting']); + eventStyles[recordTypes.WebSocketSendHandshakeRequest] = + new Timeline.TimelineRecordStyle(Common.UIString('Send WebSocket Handshake'), categories['scripting']); + eventStyles[recordTypes.WebSocketReceiveHandshakeResponse] = + new Timeline.TimelineRecordStyle(Common.UIString('Receive WebSocket Handshake'), categories['scripting']); eventStyles[recordTypes.WebSocketDestroy] = new Timeline.TimelineRecordStyle(Common.UIString('Destroy WebSocket'), categories['scripting']); eventStyles[recordTypes.EmbedderCallback] = @@ -166,8 +163,7 @@ new Timeline.TimelineRecordStyle(Common.UIString('Image Decode'), categories['painting']); eventStyles[recordTypes.ResizeImage] = new Timeline.TimelineRecordStyle(Common.UIString('Image Resize'), categories['painting']); - eventStyles[recordTypes.GPUTask] = - new Timeline.TimelineRecordStyle(Common.UIString('GPU'), categories['gpu']); + eventStyles[recordTypes.GPUTask] = new Timeline.TimelineRecordStyle(Common.UIString('GPU'), categories['gpu']); eventStyles[recordTypes.LatencyInfo] = new Timeline.TimelineRecordStyle(Common.UIString('Input Latency'), categories['scripting']); @@ -233,8 +229,10 @@ const nativeGroup = TimelineModel.TimelineJSProfileProcessor.nativeGroup(frame.functionName); const groups = TimelineModel.TimelineJSProfileProcessor.NativeGroups; switch (nativeGroup) { - case groups.Compile: return Common.UIString('Compile'); - case groups.Parse: return Common.UIString('Parse'); + case groups.Compile: + return Common.UIString('Compile'); + case groups.Parse: + return Common.UIString('Parse'); } return frame.functionName; } @@ -286,8 +284,7 @@ } var result = eventStyles[event.name]; if (!result) { - result = - new Timeline.TimelineRecordStyle(event.name, Timeline.TimelineUIUtils.categories()['other'], true); + result = new Timeline.TimelineRecordStyle(event.name, Timeline.TimelineUIUtils.categories()['other'], true); eventStyles[event.name] = result; } return result; @@ -337,14 +334,8 @@ TimelineModel.TimelineIRModel.Phases.Response, {color: 'hsl(43, 83%, 64%)', label: Common.UIString('Response')} ], - [ - TimelineModel.TimelineIRModel.Phases.Scroll, - {color: 'hsl(256, 67%, 70%)', label: Common.UIString('Scroll')} - ], - [ - TimelineModel.TimelineIRModel.Phases.Fling, - {color: 'hsl(256, 67%, 70%)', label: Common.UIString('Fling')} - ], + [TimelineModel.TimelineIRModel.Phases.Scroll, {color: 'hsl(256, 67%, 70%)', label: Common.UIString('Scroll')}], + [TimelineModel.TimelineIRModel.Phases.Fling, {color: 'hsl(256, 67%, 70%)', label: Common.UIString('Fling')}], [TimelineModel.TimelineIRModel.Phases.Drag, {color: 'hsl(256, 67%, 70%)', label: Common.UIString('Drag')}], [ TimelineModel.TimelineIRModel.Phases.Animation, @@ -756,8 +747,7 @@ if (detailed) { contentHelper.appendTextRow(Common.UIString('Self Time'), Number.millisToString(event.selfTime, true)); - contentHelper.appendTextRow( - Common.UIString('Total Time'), Number.millisToString(event.duration || 0, true)); + contentHelper.appendTextRow(Common.UIString('Total Time'), Number.millisToString(event.duration || 0, true)); } switch (event.name) { @@ -803,26 +793,25 @@ var priority = Components.uiLabelForPriority(eventData['priority']); contentHelper.appendTextRow(Common.UIString('Priority'), priority); } - if (eventData['encodedDataLength']) + if (eventData['encodedDataLength']) { contentHelper.appendTextRow( - Common.UIString('Encoded Data Length'), - Common.UIString('%d Bytes', eventData['encodedDataLength'])); + Common.UIString('Encoded Data Length'), Common.UIString('%d Bytes', eventData['encodedDataLength'])); + } break; case recordTypes.CompileScript: case recordTypes.EvaluateScript: var url = eventData && eventData['url']; - if (url) + if (url) { contentHelper.appendLocationRow( Common.UIString('Script'), url, eventData['lineNumber'], eventData['columnNumber']); + } break; case recordTypes.Paint: var clip = eventData['clip']; - contentHelper.appendTextRow( - Common.UIString('Location'), Common.UIString('(%d, %d)', clip[0], clip[1])); + contentHelper.appendTextRow(Common.UIString('Location'), Common.UIString('(%d, %d)', clip[0], clip[1])); var clipWidth = Timeline.TimelineUIUtils.quadWidth(clip); var clipHeight = Timeline.TimelineUIUtils.quadHeight(clip); - contentHelper.appendTextRow( - Common.UIString('Dimensions'), Common.UIString('%d × %d', clipWidth, clipHeight)); + contentHelper.appendTextRow(Common.UIString('Dimensions'), Common.UIString('%d × %d', clipWidth, clipHeight)); // Fall-through intended. case recordTypes.PaintSetup: @@ -836,15 +825,15 @@ case recordTypes.ResizeImage: case recordTypes.DrawLazyPixelRef: relatedNodeLabel = Common.UIString('Owner Element'); - if (timelineData.url) + if (timelineData.url) { contentHelper.appendElementRow( Common.UIString('Image URL'), Components.linkifyResourceAsNode(timelineData.url)); + } break; case recordTypes.ParseAuthorStyleSheet: var url = eventData['styleSheetUrl']; if (url) - contentHelper.appendElementRow( - Common.UIString('Stylesheet URL'), Components.linkifyResourceAsNode(url)); + contentHelper.appendElementRow(Common.UIString('Stylesheet URL'), Components.linkifyResourceAsNode(url)); break; case recordTypes.UpdateLayoutTree: // We don't want to see default details. case recordTypes.RecalculateStyles: @@ -910,16 +899,18 @@ break; } - if (timelineData.timeWaitingForMainThread) + if (timelineData.timeWaitingForMainThread) { contentHelper.appendTextRow( Common.UIString('Time Waiting for Main Thread'), Number.millisToString(timelineData.timeWaitingForMainThread, true)); + } var relatedNode = relatedNodesMap && relatedNodesMap.get(timelineData.backendNodeId); - if (relatedNode) + if (relatedNode) { contentHelper.appendElementRow( relatedNodeLabel || Common.UIString('Related Node'), Components.DOMPresentationUtils.linkifyNodeReference(relatedNode)); + } if (event[Timeline.TimelineUIUtils._previewElementSymbol]) { contentHelper.addSection(Common.UIString('Preview')); @@ -988,8 +979,8 @@ var endOffset = endTime - model.minimumRecordTime(); var contentHelper = new Timeline.TimelineDetailsContentHelper(null, null); - contentHelper.addSection(Common.UIString( - 'Range: %s \u2013 %s', Number.millisToString(startOffset), Number.millisToString(endOffset))); + contentHelper.addSection( + Common.UIString('Range: %s \u2013 %s', Number.millisToString(startOffset), Number.millisToString(endOffset))); var pieChart = Timeline.TimelineUIUtils.generatePieChart(aggregatedStats); contentHelper.appendElementRow('', pieChart); return contentHelper.fragment; @@ -1040,7 +1031,8 @@ if (request.requestMethod) contentHelper.appendTextRow(Common.UIString('Request Method'), request.requestMethod); if (typeof request.priority === 'string') { - var priority = Components.uiLabelForPriority(/** @type {!Protocol.Network.ResourcePriority} */ (request.priority)); + var priority = + Components.uiLabelForPriority(/** @type {!Protocol.Network.ResourcePriority} */ (request.priority)); contentHelper.appendTextRow(Common.UIString('Priority'), priority); } if (request.mimeType) @@ -1055,7 +1047,7 @@ contentHelper.appendElementRow(title, link); } else { var initiator = TimelineModel.TimelineData.forEvent(sendRequest).initiator(); - if (initiator) { + if (initiator) { var initiatorURL = TimelineModel.TimelineData.forEvent(initiator).url; if (initiatorURL) { var link = linkifier.maybeLinkifyScriptLocation(target, null, initiatorURL, 0); @@ -1147,7 +1139,8 @@ var initiator = TimelineModel.TimelineData.forEvent(event).initiator(); // Indirect causes. - if (TimelineModel.InvalidationTracker.invalidationEventsFor(event) && target) { // Full invalidation tracking (experimental). + if (TimelineModel.InvalidationTracker.invalidationEventsFor(event) && + target) { // Full invalidation tracking (experimental). contentHelper.addSection(Common.UIString('Invalidations')); Timeline.TimelineUIUtils._generateInvalidations(event, target, relatedNodesMap, contentHelper); } else if (initiator) { // Partial invalidation tracking. @@ -1384,8 +1377,7 @@ */ static createDividerForRecord(record, zeroTime, position) { var startTime = Number.millisToString(record.startTime() - zeroTime); - var title = - Common.UIString('%s at %s', Timeline.TimelineUIUtils.eventTitle(record.traceEvent()), startTime); + var title = Common.UIString('%s at %s', Timeline.TimelineUIUtils.eventTitle(record.traceEvent()), startTime); return Timeline.TimelineUIUtils.createEventDivider(record.type(), title, position); } @@ -1426,8 +1418,8 @@ 'painting', Common.UIString('Painting'), true, 'hsl(109, 33%, 64%)', 'hsl(109, 33%, 55%)'), gpu: new Timeline.TimelineCategory( 'gpu', Common.UIString('GPU'), false, 'hsl(109, 33%, 64%)', 'hsl(109, 33%, 55%)'), - other: new Timeline.TimelineCategory( - 'other', Common.UIString('Other'), false, 'hsl(0, 0%, 87%)', 'hsl(0, 0%, 79%)'), + other: + new Timeline.TimelineCategory('other', Common.UIString('Other'), false, 'hsl(0, 0%, 87%)', 'hsl(0, 0%, 79%)'), idle: new Timeline.TimelineCategory( 'idle', Common.UIString('Idle'), false, 'hsl(0, 100%, 100%)', 'hsl(0, 100%, 100%)') }; @@ -1489,16 +1481,17 @@ // In case of self time, first add self, then children of the same category. if (selfCategory) { - if (selfTime) + if (selfTime) { appendLegendRow( selfCategory.name, Common.UIString('%s (self)', selfCategory.title), selfTime, selfCategory.color); + } // Children of the same category. var categoryTime = aggregatedStats[selfCategory.name]; var value = categoryTime - selfTime; - if (value > 0) + if (value > 0) { appendLegendRow( - selfCategory.name, Common.UIString('%s (children)', selfCategory.title), value, - selfCategory.childColor); + selfCategory.name, Common.UIString('%s (children)', selfCategory.title), value, selfCategory.childColor); + } } // Add other categories. @@ -1573,8 +1566,8 @@ return element; element.createTextChild(Common.UIString('. Long frame times are an indication of ')); element.appendChild(UI.linkifyURLAsNode( - 'https://developers.google.com/web/fundamentals/performance/rendering/', Common.UIString('jank'), - undefined, true)); + 'https://developers.google.com/web/fundamentals/performance/rendering/', Common.UIString('jank'), undefined, + true)); element.createTextChild('.'); return element; } @@ -1748,8 +1741,8 @@ break; case warnings.V8Deopt: span.appendChild(UI.linkifyURLAsNode( - 'https://github.com/GoogleChrome/devtools-docs/issues/53', Common.UIString('Not optimized'), - undefined, true)); + 'https://github.com/GoogleChrome/devtools-docs/issues/53', Common.UIString('Not optimized'), undefined, + true)); span.createTextChild(Common.UIString(': %s', eventData['deoptReason'])); break; default: @@ -1870,8 +1863,7 @@ stack, Timeline.TimelineUIUtils._stackTraceFromCallFrames(first.cause.stackTrace)); } - content.createTextChild( - this._invalidations.length > 1 ? Common.UIString('Nodes:') : Common.UIString('Node:')); + content.createTextChild(this._invalidations.length > 1 ? Common.UIString('Nodes:') : Common.UIString('Node:')); var nodeList = content.createChild('div', 'node-list'); var firstNode = true; for (var i = 0; i < this._invalidations.length; i++) { @@ -1885,19 +1877,19 @@ nodeList.appendChild(invalidationNode); var extraData = invalidation.extraData ? ', ' + invalidation.extraData : ''; - if (invalidation.changedId) + if (invalidation.changedId) { nodeList.createTextChild(Common.UIString('(changed id to "%s"%s)', invalidation.changedId, extraData)); - else if (invalidation.changedClass) - nodeList.createTextChild( - Common.UIString('(changed class to "%s"%s)', invalidation.changedClass, extraData)); - else if (invalidation.changedAttribute) + } else if (invalidation.changedClass) { + nodeList.createTextChild(Common.UIString('(changed class to "%s"%s)', invalidation.changedClass, extraData)); + } else if (invalidation.changedAttribute) { nodeList.createTextChild( Common.UIString('(changed attribute to "%s"%s)', invalidation.changedAttribute, extraData)); - else if (invalidation.changedPseudo) + } else if (invalidation.changedPseudo) { nodeList.createTextChild( Common.UIString('(changed pesudo to "%s"%s)', invalidation.changedPseudo, extraData)); - else if (invalidation.selectorPart) + } else if (invalidation.selectorPart) { nodeList.createTextChild(Common.UIString('(changed "%s"%s)', invalidation.selectorPart, extraData)); + } } }
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline_model/TimelineFrameModel.js b/third_party/WebKit/Source/devtools/front_end/timeline_model/TimelineFrameModel.js index 6984610..74e2a8a1 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline_model/TimelineFrameModel.js +++ b/third_party/WebKit/Source/devtools/front_end/timeline_model/TimelineFrameModel.js
@@ -219,9 +219,11 @@ frame._setEndTime(endTime); if (this._lastLayerTree) this._lastLayerTree._setPaints(frame._paints); - if (this._frames.length && (frame.startTime !== this._frames.peekLast().endTime || frame.startTime > frame.endTime)) + if (this._frames.length && + (frame.startTime !== this._frames.peekLast().endTime || frame.startTime > frame.endTime)) { console.assert( false, `Inconsistent frame time for frame ${this._frames.length} (${frame.startTime} - ${frame.endTime})`); + } this._frames.push(frame); if (typeof frame._mainFrameId === 'number') this._frameById[frame._mainFrameId] = frame; @@ -281,8 +283,8 @@ } else if (event.name === eventNames.TracingStartedInPage) { this._mainThread = event.thread; } else if ( - event.phase === SDK.TracingModel.Phase.SnapshotObject && - event.name === eventNames.LayerTreeHostImplSnapshot && parseInt(event.id, 0) === this._layerTreeId) { + event.phase === SDK.TracingModel.Phase.SnapshotObject && event.name === eventNames.LayerTreeHostImplSnapshot && + parseInt(event.id, 0) === this._layerTreeId) { var snapshot = /** @type {!SDK.TracingModel.ObjectSnapshot} */ (event); this.handleLayerTreeSnapshot(new TimelineModel.TracingFrameLayerTree(this._target, snapshot)); } else { @@ -328,9 +330,10 @@ this._currentTaskTimeByCategory = {}; this._lastTaskBeginTime = event.startTime; } - if (!this._framePendingCommit && TimelineModel.TimelineFrameModel._mainFrameMarkers.indexOf(event.name) >= 0) + if (!this._framePendingCommit && TimelineModel.TimelineFrameModel._mainFrameMarkers.indexOf(event.name) >= 0) { this._framePendingCommit = new TimelineModel.PendingFrame(this._lastTaskBeginTime || event.startTime, this._currentTaskTimeByCategory); + } if (!this._framePendingCommit) { this._addTimeForCategory(this._currentTaskTimeByCategory, event); return; @@ -339,7 +342,8 @@ if (event.name === eventNames.BeginMainThreadFrame && event.args['data'] && event.args['data']['frameId']) this._framePendingCommit.mainFrameId = event.args['data']['frameId']; - if (event.name === eventNames.Paint && event.args['data']['layerId'] && TimelineModel.TimelineData.forEvent(event).picture && this._target) + if (event.name === eventNames.Paint && event.args['data']['layerId'] && + TimelineModel.TimelineData.forEvent(event).picture && this._target) this._framePendingCommit.paints.push(new TimelineModel.LayerPaintEvent(event, this._target)); if (event.name === eventNames.CompositeLayers && event.args['layerTreeId'] === this._layerTreeId) this.handleCompositeLayers();
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline_model/TimelineJSProfile.js b/third_party/WebKit/Source/devtools/front_end/timeline_model/TimelineJSProfile.js index 0d0b916..2285fc1 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline_model/TimelineJSProfile.js +++ b/third_party/WebKit/Source/devtools/front_end/timeline_model/TimelineJSProfile.js
@@ -163,9 +163,8 @@ function extractStackTrace(e) { const recordTypes = TimelineModel.TimelineModel.RecordType; /** @type {!Array<!Protocol.Runtime.CallFrame>} */ - const callFrames = e.name === recordTypes.JSSample - ? e.args['data']['stackTrace'].slice().reverse() - : jsFramesStack.map(frameEvent => frameEvent.args['data']); + const callFrames = e.name === recordTypes.JSSample ? e.args['data']['stackTrace'].slice().reverse() : + jsFramesStack.map(frameEvent => frameEvent.args['data']); filterStackFrames(callFrames); const endTime = e.endTime || e.startTime; const minFrames = Math.min(callFrames.length, jsFramesStack.length); @@ -181,8 +180,8 @@ for (; i < callFrames.length; ++i) { const frame = callFrames[i]; const jsFrameEvent = new SDK.TracingModel.Event( - SDK.TracingModel.DevToolsTimelineEventCategory, recordTypes.JSFrame, - SDK.TracingModel.Phase.Complete, e.startTime, e.thread); + SDK.TracingModel.DevToolsTimelineEventCategory, recordTypes.JSFrame, SDK.TracingModel.Phase.Complete, + e.startTime, e.thread); jsFrameEvent.ordinal = e.ordinal; jsFrameEvent.addArgs({data: frame}); jsFrameEvent.setEndTime(endTime); @@ -192,9 +191,10 @@ } const firstTopLevelEvent = events.find(SDK.TracingModel.isTopLevelEvent); - if (firstTopLevelEvent) + if (firstTopLevelEvent) { TimelineModel.TimelineModel.forEachEvent( events, onStartEvent, onEndEvent, onInstantEvent, firstTopLevelEvent.startTime); + } return jsFrameEvents; } @@ -215,20 +215,13 @@ if (!map) { const nativeGroups = TimelineModel.TimelineJSProfileProcessor.NativeGroups; map = new Map([ - ['Compile', nativeGroups.Compile], - ['CompileCode', nativeGroups.Compile], - ['CompileCodeLazy', nativeGroups.Compile], - ['CompileDeserialize', nativeGroups.Compile], - ['CompileEval', nativeGroups.Compile], - ['CompileFullCode', nativeGroups.Compile], - ['CompileIgnition', nativeGroups.Compile], - ['CompilerDispatcher', nativeGroups.Compile], - ['CompileSerialize', nativeGroups.Compile], - ['ParseProgram', nativeGroups.Parse], - ['ParseFunction', nativeGroups.Parse], - ['RecompileConcurrent', nativeGroups.Compile], - ['RecompileSynchronous', nativeGroups.Compile], - ['ParseLazy', nativeGroups.Parse] + ['Compile', nativeGroups.Compile], ['CompileCode', nativeGroups.Compile], + ['CompileCodeLazy', nativeGroups.Compile], ['CompileDeserialize', nativeGroups.Compile], + ['CompileEval', nativeGroups.Compile], ['CompileFullCode', nativeGroups.Compile], + ['CompileIgnition', nativeGroups.Compile], ['CompilerDispatcher', nativeGroups.Compile], + ['CompileSerialize', nativeGroups.Compile], ['ParseProgram', nativeGroups.Parse], + ['ParseFunction', nativeGroups.Parse], ['RecompileConcurrent', nativeGroups.Compile], + ['RecompileSynchronous', nativeGroups.Compile], ['ParseLazy', nativeGroups.Parse] ]); /** @type {!Map<string, !TimelineModel.TimelineJSProfileProcessor.NativeGroups>} */ TimelineModel.TimelineJSProfileProcessor.nativeGroup._map = map;
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline_model/TimelineModel.js b/third_party/WebKit/Source/devtools/front_end/timeline_model/TimelineModel.js index 7bd738a..c193346 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline_model/TimelineModel.js +++ b/third_party/WebKit/Source/devtools/front_end/timeline_model/TimelineModel.js
@@ -125,7 +125,7 @@ var data = event.args['data'] || event.args['beginData']; var frame = data && data['frame']; if (!frame) - return ''; + return ''; var processId = event.thread.process().id(); return `${processId}.${frame}`; } @@ -317,13 +317,13 @@ } var result = { page: pageDevToolsMetadataEvents.filter(checkSessionId).sort(SDK.TracingModel.Event.compareStartTime), - workers: - workersDevToolsMetadataEvents.filter(checkSessionId).sort(SDK.TracingModel.Event.compareStartTime) + workers: workersDevToolsMetadataEvents.filter(checkSessionId).sort(SDK.TracingModel.Event.compareStartTime) }; - if (mismatchingIds.size) + if (mismatchingIds.size) { Common.console.error( 'Timeline recording was started in more than one page simultaneously. Session id mismatch: ' + this._sessionId + ' and ' + mismatchingIds.valuesArray() + '.'); + } return result; } @@ -354,8 +354,7 @@ // First Paint is actually a DrawFrame that happened after first CompositeLayers following last CommitLoadEvent. var recordTypes = TimelineModel.TimelineModel.RecordType; - var i = this._inspectedTargetEvents.lowerBound( - this._firstCompositeLayers, SDK.TracingModel.Event.compareStartTime); + var i = this._inspectedTargetEvents.lowerBound(this._firstCompositeLayers, SDK.TracingModel.Event.compareStartTime); for (; i < this._inspectedTargetEvents.length && this._inspectedTargetEvents[i].name !== recordTypes.DrawFrame; ++i) { } @@ -434,8 +433,7 @@ var event = threadEvents[i]; for (var top = recordStack.peekLast(); top && top._event.endTime <= event.startTime; top = recordStack.peekLast()) recordStack.pop(); - if (event.phase === SDK.TracingModel.Phase.AsyncEnd || - event.phase === SDK.TracingModel.Phase.NestableAsyncEnd) + if (event.phase === SDK.TracingModel.Phase.AsyncEnd || event.phase === SDK.TracingModel.Phase.NestableAsyncEnd) continue; var parentRecord = recordStack.peekLast(); // Maintain the back-end logic of old timeline, skip console.time() / console.timeEnd() that are not properly nested. @@ -761,8 +759,10 @@ if (!layerUpdateEvent || layerUpdateEvent.args['layerTreeId'] !== this._inspectedTargetLayerTreeId) break; var paintEvent = this._lastPaintForLayer[layerUpdateEvent.args['layerId']]; - if (paintEvent) - TimelineModel.TimelineData.forEvent(paintEvent).picture = /** @type {!SDK.TracingModel.ObjectSnapshot} */ (event); + if (paintEvent) { + TimelineModel.TimelineData.forEvent(paintEvent).picture = + /** @type {!SDK.TracingModel.ObjectSnapshot} */ (event); + } break; case recordTypes.ScrollLayer: @@ -828,9 +828,9 @@ break; case recordTypes.FireIdleCallback: - if (event.duration > eventData['allottedMilliseconds']) { + if (event.duration > eventData['allottedMilliseconds']) timelineData.warning = TimelineModel.TimelineModel.WarningType.IdleDeadlineExceeded; - } + break; } if (SDK.TracingModel.isAsyncPhase(event.phase)) @@ -843,10 +843,11 @@ parent.selfTime -= duration; if (parent.selfTime < 0) { var epsilon = 1e-3; - if (parent.selfTime < -epsilon) + if (parent.selfTime < -epsilon) { console.error( 'Children are longer than parent at ' + event.startTime + ' (' + (event.startTime - this.minimumRecordTime()).toFixed(3) + ') by ' + parent.selfTime.toFixed(3)); + } parent.selfTime = 0; } } @@ -894,7 +895,8 @@ var rendererMain = data['INPUT_EVENT_LATENCY_RENDERER_MAIN_COMPONENT']; if (rendererMain) { var time = rendererMain['time'] / 1000; - TimelineModel.TimelineData.forEvent(asyncEvent.steps[0]).timeWaitingForMainThread = time - asyncEvent.steps[0].startTime; + TimelineModel.TimelineData.forEvent(asyncEvent.steps[0]).timeWaitingForMainThread = + time - asyncEvent.steps[0].startTime; } } return groups.input; @@ -1323,9 +1325,8 @@ target() { var threadName = this._event.thread.name(); // FIXME: correctly specify target - return threadName === TimelineModel.TimelineModel.RendererMainThreadName ? - SDK.targetManager.targets()[0] || null : - null; + return threadName === TimelineModel.TimelineModel.RendererMainThreadName ? SDK.targetManager.targets()[0] || null : + null; } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline_model/TimelineProfileTree.js b/third_party/WebKit/Source/devtools/front_end/timeline_model/TimelineProfileTree.js index 073f7aa1..6595c34 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline_model/TimelineProfileTree.js +++ b/third_party/WebKit/Source/devtools/front_end/timeline_model/TimelineProfileTree.js
@@ -97,7 +97,8 @@ parent = parent.parent; } - var instantEventCallback = eventGroupIdCallback ? undefined : onStartEvent; // Ignore instant events when aggregating. + var instantEventCallback = + eventGroupIdCallback ? undefined : onStartEvent; // Ignore instant events when aggregating. TimelineModel.TimelineModel.forEachEvent(events, onStartEvent, onEndEvent, instantEventCallback, startTime, endTime); root.totalTime -= root.selfTime; root.selfTime = 0; @@ -124,7 +125,8 @@ * @param {!TimelineModel.TimelineProfileTree.Node} tdNode */ function processNode(tdNode) { - var buParent = typeof tdNode._groupId === 'string' ? aggregator.groupNodeForId(tdNode._groupId, tdNode.event) : buRoot; + var buParent = + typeof tdNode._groupId === 'string' ? aggregator.groupNodeForId(tdNode._groupId, tdNode.event) : buRoot; if (buParent !== buRoot && !buParent.parent) { buRoot.children.set(buParent.id, buParent); buParent.parent = buRoot; @@ -219,9 +221,9 @@ const frame = event.args['data']; const location = frame['scriptId'] || frame['url'] || ''; const functionName = frame['functionName']; - const name = TimelineModel.TimelineJSProfileProcessor.isNativeRuntimeFrame(frame) - ? TimelineModel.TimelineJSProfileProcessor.nativeGroup(functionName) || functionName - : functionName; + const name = TimelineModel.TimelineJSProfileProcessor.isNativeRuntimeFrame(frame) ? + TimelineModel.TimelineJSProfileProcessor.nativeGroup(functionName) || functionName : + functionName; return `f:${name}@${location}`; };
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline_model/TracingLayerTree.js b/third_party/WebKit/Source/devtools/front_end/timeline_model/TracingLayerTree.js index 9fdc0add..fac023b 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline_model/TracingLayerTree.js +++ b/third_party/WebKit/Source/devtools/front_end/timeline_model/TracingLayerTree.js
@@ -434,18 +434,22 @@ */ _createScrollRects(payload) { this._scrollRects = []; - if (payload.non_fast_scrollable_region) + if (payload.non_fast_scrollable_region) { this._scrollRects.push(this._scrollRectsFromParams( payload.non_fast_scrollable_region, SDK.Layer.ScrollRectType.NonFastScrollable.name)); - if (payload.touch_event_handler_region) + } + if (payload.touch_event_handler_region) { this._scrollRects.push(this._scrollRectsFromParams( payload.touch_event_handler_region, SDK.Layer.ScrollRectType.TouchEventHandler.name)); - if (payload.wheel_event_handler_region) + } + if (payload.wheel_event_handler_region) { this._scrollRects.push(this._scrollRectsFromParams( payload.wheel_event_handler_region, SDK.Layer.ScrollRectType.WheelEventHandler.name)); - if (payload.scroll_event_handler_region) + } + if (payload.scroll_event_handler_region) { this._scrollRects.push(this._scrollRectsFromParams( payload.scroll_event_handler_region, SDK.Layer.ScrollRectType.RepaintsOnScroll.name)); + } } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/BezierEditor.js b/third_party/WebKit/Source/devtools/front_end/ui/BezierEditor.js index 18e6359..c7e4111 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/BezierEditor.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/BezierEditor.js
@@ -206,8 +206,8 @@ var length = this._selectedCategory.presets.length; this._selectedCategory.presetIndex = (this._selectedCategory.presetIndex + (intensify ? 1 : -1) + length) % length; - this.setBezier(Common.Geometry.CubicBezier.parse( - this._selectedCategory.presets[this._selectedCategory.presetIndex].value)); + this.setBezier( + Common.Geometry.CubicBezier.parse(this._selectedCategory.presets[this._selectedCategory.presetIndex].value)); this._onchange(); this._startPreviewAnimation(); }
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/CSSShadowEditor.js b/third_party/WebKit/Source/devtools/front_end/ui/CSSShadowEditor.js index f9c61315..745dcf602 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/CSSShadowEditor.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/CSSShadowEditor.js
@@ -29,8 +29,7 @@ this._xySlider.tabIndex = -1; this._halfCanvasSize = UI.CSSShadowEditor.canvasSize / 2; this._innerCanvasSize = this._halfCanvasSize - UI.CSSShadowEditor.sliderThumbRadius; - UI.installDragHandle( - this._xySlider, this._dragStart.bind(this), this._dragMove.bind(this), null, 'default'); + UI.installDragHandle(this._xySlider, this._dragStart.bind(this), this._dragMove.bind(this), null, 'default'); this._xySlider.addEventListener('keydown', this._onCanvasArrowKey.bind(this), false); this._xySlider.addEventListener('blur', this._onCanvasBlur.bind(this), false); @@ -299,17 +298,17 @@ var newY = Math.round((constrainedPoint.y / this._innerCanvasSize) * UI.CSSShadowEditor.maxRange); if (event.shiftKey) { - this._model.setOffsetX( - new Common.CSSLength(newX, this._model.offsetX().unit || UI.CSSShadowEditor.defaultUnit)); - this._model.setOffsetY( - new Common.CSSLength(newY, this._model.offsetY().unit || UI.CSSShadowEditor.defaultUnit)); + this._model.setOffsetX(new Common.CSSLength(newX, this._model.offsetX().unit || UI.CSSShadowEditor.defaultUnit)); + this._model.setOffsetY(new Common.CSSLength(newY, this._model.offsetY().unit || UI.CSSShadowEditor.defaultUnit)); } else { - if (!event.altKey) + if (!event.altKey) { this._model.setOffsetX( new Common.CSSLength(newX, this._model.offsetX().unit || UI.CSSShadowEditor.defaultUnit)); - if (!UI.KeyboardShortcut.eventHasCtrlOrMeta(event)) + } + if (!UI.KeyboardShortcut.eventHasCtrlOrMeta(event)) { this._model.setOffsetY( new Common.CSSLength(newY, this._model.offsetY().unit || UI.CSSShadowEditor.defaultUnit)); + } } this._xInput.value = this._model.offsetX().asCSSText(); this._yInput.value = this._model.offsetY().asCSSText(); @@ -344,23 +343,21 @@ if (shiftX) { var offsetX = this._model.offsetX(); - var newAmount = Number.constrain( - offsetX.amount + shiftX, -UI.CSSShadowEditor.maxRange, UI.CSSShadowEditor.maxRange); + var newAmount = + Number.constrain(offsetX.amount + shiftX, -UI.CSSShadowEditor.maxRange, UI.CSSShadowEditor.maxRange); if (newAmount === offsetX.amount) return; - this._model.setOffsetX( - new Common.CSSLength(newAmount, offsetX.unit || UI.CSSShadowEditor.defaultUnit)); + this._model.setOffsetX(new Common.CSSLength(newAmount, offsetX.unit || UI.CSSShadowEditor.defaultUnit)); this._xInput.value = this._model.offsetX().asCSSText(); this._xInput.classList.remove('invalid'); } if (shiftY) { var offsetY = this._model.offsetY(); - var newAmount = Number.constrain( - offsetY.amount + shiftY, -UI.CSSShadowEditor.maxRange, UI.CSSShadowEditor.maxRange); + var newAmount = + Number.constrain(offsetY.amount + shiftY, -UI.CSSShadowEditor.maxRange, UI.CSSShadowEditor.maxRange); if (newAmount === offsetY.amount) return; - this._model.setOffsetY( - new Common.CSSLength(newAmount, offsetY.unit || UI.CSSShadowEditor.defaultUnit)); + this._model.setOffsetY(new Common.CSSLength(newAmount, offsetY.unit || UI.CSSShadowEditor.defaultUnit)); this._yInput.value = this._model.offsetY().asCSSText(); this._yInput.classList.remove('invalid'); }
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/ColorSwatch.js b/third_party/WebKit/Source/devtools/front_end/ui/ColorSwatch.js index 45ef36e..fc1afbe 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/ColorSwatch.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/ColorSwatch.js
@@ -14,8 +14,7 @@ */ static create() { if (!UI.ColorSwatch._constructor) - UI.ColorSwatch._constructor = - registerCustomElement('span', 'color-swatch', UI.ColorSwatch.prototype); + UI.ColorSwatch._constructor = registerCustomElement('span', 'color-swatch', UI.ColorSwatch.prototype); return /** @type {!UI.ColorSwatch} */ (new UI.ColorSwatch._constructor()); } @@ -165,8 +164,7 @@ */ static create() { if (!UI.BezierSwatch._constructor) - UI.BezierSwatch._constructor = - registerCustomElement('span', 'bezier-swatch', UI.BezierSwatch.prototype); + UI.BezierSwatch._constructor = registerCustomElement('span', 'bezier-swatch', UI.BezierSwatch.prototype); return /** @type {!UI.BezierSwatch} */ (new UI.BezierSwatch._constructor()); } @@ -224,9 +222,10 @@ * @return {!UI.CSSShadowSwatch} */ static create() { - if (!UI.CSSShadowSwatch._constructor) + if (!UI.CSSShadowSwatch._constructor) { UI.CSSShadowSwatch._constructor = registerCustomElement('span', 'css-shadow-swatch', UI.CSSShadowSwatch.prototype); + } return /** @type {!UI.CSSShadowSwatch} */ (new UI.CSSShadowSwatch._constructor()); }
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/Context.js b/third_party/WebKit/Source/devtools/front_end/ui/Context.js index 7be8c1d..2cd6e0b 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/Context.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/Context.js
@@ -34,9 +34,10 @@ */ _dispatchFlavorChange(flavorType, flavorValue) { for (var extension of self.runtime.extensions(UI.ContextFlavorListener)) { - if (extension.hasContextType(flavorType)) + if (extension.hasContextType(flavorType)) { extension.instance().then( instance => /** @type {!UI.ContextFlavorListener} */ (instance).flavorChanged(flavorValue)); + } } var dispatcher = this._eventDispatchers.get(flavorType); if (!dispatcher)
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/FilterBar.js b/third_party/WebKit/Source/devtools/front_end/ui/FilterBar.js index 162b64e..63a71a6 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/FilterBar.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/FilterBar.js
@@ -510,8 +510,7 @@ } _update() { - if ((Object.keys(this._allowedTypes).length === 0) || - this._allowedTypes[UI.NamedBitSetFilterUI.ALL_TYPES]) { + if ((Object.keys(this._allowedTypes).length === 0) || this._allowedTypes[UI.NamedBitSetFilterUI.ALL_TYPES]) { this._allowedTypes = {}; this._allowedTypes[UI.NamedBitSetFilterUI.ALL_TYPES] = true; }
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/ForwardedInputEventHandler.js b/third_party/WebKit/Source/devtools/front_end/ui/ForwardedInputEventHandler.js index ff6e89f..7c4901ea 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/ForwardedInputEventHandler.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/ForwardedInputEventHandler.js
@@ -23,8 +23,7 @@ if (type !== 'keydown') return; - UI.context.setFlavor( - UI.ShortcutRegistry.ForwardedShortcut, UI.ShortcutRegistry.ForwardedShortcut.instance); + UI.context.setFlavor(UI.ShortcutRegistry.ForwardedShortcut, UI.ShortcutRegistry.ForwardedShortcut.instance); UI.shortcutRegistry.handleKey(UI.KeyboardShortcut.makeKey(keyCode, modifiers), key); UI.context.setFlavor(UI.ShortcutRegistry.ForwardedShortcut, null); }
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/HistoryInput.js b/third_party/WebKit/Source/devtools/front_end/ui/HistoryInput.js index bdf69f61..88a4495 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/HistoryInput.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/HistoryInput.js
@@ -14,8 +14,7 @@ */ static create() { if (!UI.HistoryInput._constructor) - UI.HistoryInput._constructor = - registerCustomElement('input', 'history-input', UI.HistoryInput.prototype); + UI.HistoryInput._constructor = registerCustomElement('input', 'history-input', UI.HistoryInput.prototype); return /** @type {!UI.HistoryInput} */ (new UI.HistoryInput._constructor()); }
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/Icon.js b/third_party/WebKit/Source/devtools/front_end/ui/Icon.js index f284af0..3cd1868 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/Icon.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/Icon.js
@@ -113,58 +113,96 @@ 'smallicon-dropdown-arrow': {x: -18, y: -96, width: 12, height: 12, spritesheet: 'largeicons', isMask: true}, 'smallicon-checkmark': {x: -100, y: -20, width: 10, height: 10, spritesheet: 'smallicons', isMask: true}, 'smallicon-green-checkmark': {x: -120, y: -20, width: 10, height: 10, spritesheet: 'smallicons'}, + 'smallicon-triangle-right': {x: -4, y: -98, width: 10, height: 8, spritesheet: 'largeicons', isMask: true}, + 'smallicon-triangle-bottom': {x: -20, y: -98, width: 10, height: 8, spritesheet: 'largeicons', isMask: true}, + 'smallicon-arrow-in-circle': {x: -10, y: -127, width: 11, height: 11, spritesheet: 'largeicons', isMask: true}, 'largeicon-longclick-triangle': {x: -290, y: -46, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, 'largeicon-menu': {x: -192, y: -24, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, 'largeicon-delete': {x: -128, y: -0, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, 'largeicon-node-search': {x: -320, y: -120, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, 'largeicon-add': {x: -224, y: -120, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-clear': {x: -64, y: 0, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-rotate-screen': {x: -192, y: -144, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-phone': {x: -320, y: -96, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-block': {x: -32, y: -144, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-layout-editor': {x: 0, y: -144, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-foreground-color': {x: -128, y: -144, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-background-color': {x: -96, y: -144, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-text-shadow': {x: -192, y: -48, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-box-shadow': {x: -160, y: -48, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-pause-animation': {x: -320, y: 0, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-replay-animation': {x: -320, y: -24, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-play-animation': {x: -320, y: -48, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-eyedropper': {x: -288, y: -120, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-rotate': {x: -160, y: -120, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-center': {x: -128, y: -120, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-pan': {x: -98, y: -120, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-waterfall': {x: -128, y: -48, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-filter': {x: -32, y: -48, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-trash-bin': {x: -128, y: -24, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-pretty-print': {x: -256, y: -24, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-deactivate-breakpoints': {x: 0, y: -24, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-activate-breakpoints': {x: -32, y: 0, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-resume': {x: 0, y: -72, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-pause': {x: -32, y: -72, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-pause-on-exceptions': {x: -256, y: 0, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-play-back': {x: -64, y: -48, width: 28, height: 24, spritesheet: 'largeicons', isMask: true, transform: 'scaleX(-1)'}, - 'largeicon-play': {x: -64, y: -48, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-step-over': {x: -128, y: -72, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-step-out': {x: -96, y: -72, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-step-in': {x: -64, y: -72, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-camera': {x: -96, y: -24, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-stop-recording': {x: -288, y: -24, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-start-recording': {x: -288, y: 0, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-large-list': {x: -224, y: 0, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-visibility': {x: -96, y: 0, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-refresh': {x: 0, y: 0, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-dock-to-right': {x: -256, y: -48, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-dock-to-bottom': {x: -32, y: -24, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-undock': {x: 0, y: -48, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-clear': {x: -64, y: 0, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-rotate-screen': {x: -192, y: -144, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-phone': {x: -320, y: -96, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-block': {x: -32, y: -144, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-layout-editor': {x: 0, y: -144, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-foreground-color': {x: -128, y: -144, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-background-color': {x: -96, y: -144, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-text-shadow': {x: -192, y: -48, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-box-shadow': {x: -160, y: -48, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-pause-animation': {x: -320, y: 0, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-replay-animation': {x: -320, y: -24, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-play-animation': {x: -320, y: -48, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-eyedropper': {x: -288, y: -120, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-rotate': {x: -160, y: -120, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-center': {x: -128, y: -120, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-pan': {x: -98, y: -120, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-waterfall': {x: -128, y: -48, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-filter': {x: -32, y: -48, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-trash-bin': {x: -128, y: -24, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-pretty-print': {x: -256, y: -24, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-deactivate-breakpoints': {x: 0, y: -24, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-activate-breakpoints': {x: -32, y: 0, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-resume': {x: 0, y: -72, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-pause': {x: -32, y: -72, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-pause-on-exceptions': {x: -256, y: 0, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-play-back': + {x: -64, y: -48, width: 28, height: 24, spritesheet: 'largeicons', isMask: true, transform: 'scaleX(-1)'}, + 'largeicon-play': {x: -64, y: -48, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-step-over': {x: -128, y: -72, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-step-out': {x: -96, y: -72, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-step-in': {x: -64, y: -72, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-camera': {x: -96, y: -24, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-stop-recording': {x: -288, y: -24, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-start-recording': {x: -288, y: 0, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-large-list': {x: -224, y: 0, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-visibility': {x: -96, y: 0, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-refresh': {x: 0, y: 0, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-dock-to-right': {x: -256, y: -48, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-dock-to-bottom': {x: -32, y: -24, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-undock': {x: 0, y: -48, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-show-left-sidebar': {x: -160, y: -72, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-hide-left-sidebar': {x: -192, y: -72, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, - 'largeicon-show-right-sidebar': {x: -160, y: -72, width: 28, height: 24, spritesheet: 'largeicons', isMask: true, transform: 'rotate(180deg)'}, - 'largeicon-hide-right-sidebar': {x: -192, y: -72, width: 28, height: 24, spritesheet: 'largeicons', isMask: true, transform: 'rotate(180deg)'}, - 'largeicon-show-top-sidebar': {x: -160, y: -72, width: 28, height: 24, spritesheet: 'largeicons', isMask: true, transform: 'translate(4px, 0) rotate(90deg)'}, - 'largeicon-hide-top-sidebar': {x: -192, y: -72, width: 28, height: 24, spritesheet: 'largeicons', isMask: true, transform: 'translate(4px, 1px) rotate(90deg)'}, - 'largeicon-show-bottom-sidebar': {x: -160, y: -72, width: 28, height: 24, spritesheet: 'largeicons', isMask: true, transform: 'translate(4px, 0) rotate(-90deg)'}, - 'largeicon-hide-bottom-sidebar': {x: -192, y: -72, width: 28, height: 24, spritesheet: 'largeicons', isMask: true, transform: 'translate(4px, 1px) rotate(-90deg)'}, + 'largeicon-show-left-sidebar': {x: -160, y: -72, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-hide-left-sidebar': {x: -192, y: -72, width: 28, height: 24, spritesheet: 'largeicons', isMask: true}, + 'largeicon-show-right-sidebar': + {x: -160, y: -72, width: 28, height: 24, spritesheet: 'largeicons', isMask: true, transform: 'rotate(180deg)'}, + 'largeicon-hide-right-sidebar': + {x: -192, y: -72, width: 28, height: 24, spritesheet: 'largeicons', isMask: true, transform: 'rotate(180deg)'}, + 'largeicon-show-top-sidebar': { + x: -160, + y: -72, + width: 28, + height: 24, + spritesheet: 'largeicons', + isMask: true, + transform: 'translate(4px, 0) rotate(90deg)' + }, + 'largeicon-hide-top-sidebar': { + x: -192, + y: -72, + width: 28, + height: 24, + spritesheet: 'largeicons', + isMask: true, + transform: 'translate(4px, 1px) rotate(90deg)' + }, + 'largeicon-show-bottom-sidebar': { + x: -160, + y: -72, + width: 28, + height: 24, + spritesheet: 'largeicons', + isMask: true, + transform: 'translate(4px, 0) rotate(-90deg)' + }, + 'largeicon-hide-bottom-sidebar': { + x: -192, + y: -72, + width: 28, + height: 24, + spritesheet: 'largeicons', + isMask: true, + transform: 'translate(4px, 1px) rotate(-90deg)' + }, };
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/InplaceEditor.js b/third_party/WebKit/Source/devtools/front_end/ui/InplaceEditor.js index 56deeaa..843d0f1 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/InplaceEditor.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/InplaceEditor.js
@@ -154,7 +154,7 @@ */ function defaultFinishHandler(event) { var isMetaOrCtrl = Host.isMac() ? event.metaKey && !event.shiftKey && !event.ctrlKey && !event.altKey : - event.ctrlKey && !event.shiftKey && !event.metaKey && !event.altKey; + event.ctrlKey && !event.shiftKey && !event.metaKey && !event.altKey; if (isEnterKey(event) && (event.isMetaOrCtrlForTest || !isMultiline || isMetaOrCtrl)) return 'commit'; else if (event.keyCode === UI.KeyboardShortcut.Keys.Esc.code || event.key === 'Escape')
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/InspectorView.js b/third_party/WebKit/Source/devtools/front_end/ui/InspectorView.js index 63c7c84..ea2c1194 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/InspectorView.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/InspectorView.js
@@ -50,8 +50,7 @@ this._drawerTabbedLocation.enableMoreTabsButton(); this._drawerTabbedPane = this._drawerTabbedLocation.tabbedPane(); this._drawerTabbedPane.setMinimumSize(0, 27); - var closeDrawerButton = - new UI.ToolbarButton(Common.UIString('Close drawer'), 'largeicon-delete'); + var closeDrawerButton = new UI.ToolbarButton(Common.UIString('Close drawer'), 'largeicon-delete'); closeDrawerButton.addEventListener('click', this._closeDrawer.bind(this)); this._drawerTabbedPane.rightToolbar().appendToolbarItem(closeDrawerButton); this._drawerSplitWidget.installResizer(this._drawerTabbedPane.headerElement()); @@ -179,8 +178,7 @@ * @return {!UI.Panel} */ currentPanelDeprecated() { - return /** @type {!UI.Panel} */ ( - UI.viewManager.materializedWidget(this._tabbedPane.selectedTabId || '')); + return /** @type {!UI.Panel} */ (UI.viewManager.materializedWidget(this._tabbedPane.selectedTabId || '')); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/KeyboardShortcut.js b/third_party/WebKit/Source/devtools/front_end/ui/KeyboardShortcut.js index 7bdd7fa98..51c8139e 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/KeyboardShortcut.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/KeyboardShortcut.js
@@ -72,8 +72,7 @@ */ static makeKeyFromEventIgnoringModifiers(keyboardEvent) { var keyCode = keyboardEvent.keyCode || keyboardEvent['__keyCode']; - return UI.KeyboardShortcut._makeKeyFromCodeAndModifiers( - keyCode, UI.KeyboardShortcut.Modifiers.None); + return UI.KeyboardShortcut._makeKeyFromCodeAndModifiers(keyCode, UI.KeyboardShortcut.Modifiers.None); } /** @@ -290,5 +289,4 @@ UI.KeyboardShortcut.Descriptor; -UI.KeyboardShortcut.SelectAll = - UI.KeyboardShortcut.makeKey('a', UI.KeyboardShortcut.Modifiers.CtrlOrMeta); +UI.KeyboardShortcut.SelectAll = UI.KeyboardShortcut.makeKey('a', UI.KeyboardShortcut.Modifiers.CtrlOrMeta);
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/ListWidget.js b/third_party/WebKit/Source/devtools/front_end/ui/ListWidget.js index 47e1e3a..0148828 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/ListWidget.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/ListWidget.js
@@ -189,8 +189,8 @@ this._updatePlaceholder(); this._list.insertBefore(this._editor.element, insertionPoint); this._editor.beginEdit( - item, index, element ? Common.UIString('Save') : Common.UIString('Add'), - this._commitEditing.bind(this), this._stopEditing.bind(this)); + item, index, element ? Common.UIString('Save') : Common.UIString('Add'), this._commitEditing.bind(this), + this._stopEditing.bind(this)); } _commitEditing() {
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/Popover.js b/third_party/WebKit/Source/devtools/front_end/ui/Popover.js index 7d27e2a..7953b7a 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/Popover.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/Popover.js
@@ -181,9 +181,9 @@ if ((roomAbove > roomBelow) || (arrowDirection === UI.Popover.Orientation.Bottom)) { // Positioning above the anchor. if ((anchorBox.y > newElementPosition.height + arrowHeight + borderRadius) || - (arrowDirection === UI.Popover.Orientation.Bottom)) + (arrowDirection === UI.Popover.Orientation.Bottom)) { newElementPosition.y = anchorBox.y - newElementPosition.height - arrowHeight; - else { + } else { this._popupArrowElement.hidden = true; newElementPosition.y = borderRadius; newElementPosition.height = anchorBox.y - borderRadius * 2 - arrowHeight; @@ -298,9 +298,9 @@ } _mouseDown(event) { - if (this._disableOnClick || !this._eventInHoverElement(event)) + if (this._disableOnClick || !this._eventInHoverElement(event)) { this.hidePopover(); - else { + } else { this._killHidePopoverTimer(); this._handleMouseAction(event, true); }
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/ResizerWidget.js b/third_party/WebKit/Source/devtools/front_end/ui/ResizerWidget.js index 3e2ce38..f720a57 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/ResizerWidget.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/ResizerWidget.js
@@ -221,13 +221,12 @@ * @param {boolean} shiftKey */ sendDragMove(startX, currentX, startY, currentY, shiftKey) { - if (this._isVertical) + if (this._isVertical) { this.dispatchEventToListeners( - UI.ResizerWidget.Events.ResizeUpdate, - {startPosition: startY, currentPosition: currentY, shiftKey: shiftKey}); - else + UI.ResizerWidget.Events.ResizeUpdate, {startPosition: startY, currentPosition: currentY, shiftKey: shiftKey}); + } else { this.dispatchEventToListeners( - UI.ResizerWidget.Events.ResizeUpdate, - {startPosition: startX, currentPosition: currentX, shiftKey: shiftKey}); + UI.ResizerWidget.Events.ResizeUpdate, {startPosition: startX, currentPosition: currentX, shiftKey: shiftKey}); + } } };
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/SearchableView.js b/third_party/WebKit/Source/devtools/front_end/ui/SearchableView.js index 94ce46b0..32564d45 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/SearchableView.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/SearchableView.js
@@ -499,8 +499,7 @@ _replaceAll() { var searchConfig = this._currentSearchConfig(); - /** @type {!UI.Replaceable} */ (this._searchProvider) - .replaceAllWith(searchConfig, this._replaceInputElement.value); + /** @type {!UI.Replaceable} */ (this._searchProvider).replaceAllWith(searchConfig, this._replaceInputElement.value); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/SoftContextMenu.js b/third_party/WebKit/Source/devtools/front_end/ui/SoftContextMenu.js index 0704bba2..f647177 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/SoftContextMenu.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/SoftContextMenu.js
@@ -94,8 +94,7 @@ // Move submenus upwards if it does not fit. if (this._parentMenu && document.body.offsetHeight < this.element.offsetTop + this.element.offsetHeight) { y = Math.max( - UI.Dialog.modalHostView().element.totalOffsetTop(), - document.body.offsetHeight - this.element.offsetHeight); + UI.Dialog.modalHostView().element.totalOffsetTop(), document.body.offsetHeight - this.element.offsetHeight); this.element.style.top = y + 'px'; } @@ -270,9 +269,10 @@ this._highlightedMenuItemElement.classList.add('soft-context-menu-item-mouse-over'); this._contextMenuElement.focus(); if (scheduleSubMenu && this._highlightedMenuItemElement._subItems && - !this._highlightedMenuItemElement._subMenuTimer) + !this._highlightedMenuItemElement._subMenuTimer) { this._highlightedMenuItemElement._subMenuTimer = setTimeout(this._showSubMenu.bind(this, this._highlightedMenuItemElement), 150); + } } }
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/SplitWidget.js b/third_party/WebKit/Source/devtools/front_end/ui/SplitWidget.js index a8c0668..ea73d19 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/SplitWidget.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/SplitWidget.js
@@ -141,8 +141,7 @@ widget.element.classList.add('insertion-point-main'); widget.element.classList.remove('insertion-point-sidebar'); widget.attach(this); - if (this._showMode === UI.SplitWidget.ShowMode.OnlyMain || - this._showMode === UI.SplitWidget.ShowMode.Both) + if (this._showMode === UI.SplitWidget.ShowMode.OnlyMain || this._showMode === UI.SplitWidget.ShowMode.Both) widget.showWidget(this.element); this.setDefaultFocusedChild(widget); } @@ -163,8 +162,7 @@ widget.element.classList.add('insertion-point-sidebar'); widget.element.classList.remove('insertion-point-main'); widget.attach(this); - if (this._showMode === UI.SplitWidget.ShowMode.OnlySidebar || - this._showMode === UI.SplitWidget.ShowMode.Both) + if (this._showMode === UI.SplitWidget.ShowMode.OnlySidebar || this._showMode === UI.SplitWidget.ShowMode.Both) widget.showWidget(this.element); } this.resumeInvalidations(); @@ -427,9 +425,10 @@ if (this._sidebarSizeDIP === sizeDIP) return; - if (!this._resizerElementSize) + if (!this._resizerElementSize) { this._resizerElementSize = this._isVertical ? this._resizerElement.offsetWidth : this._resizerElement.offsetHeight; + } // Invalidate layout below. @@ -636,8 +635,7 @@ * @override */ willHide() { - UI.zoomManager.removeEventListener( - UI.ZoomManager.Events.ZoomChanged, this._onZoomChanged, this); + UI.zoomManager.removeEventListener(UI.ZoomManager.Events.ZoomChanged, this._onZoomChanged, this); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/StackView.js b/third_party/WebKit/Source/devtools/front_end/ui/StackView.js index 55ba9da..3230919 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/StackView.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/StackView.js
@@ -47,8 +47,8 @@ * @return {?UI.SplitWidget} */ appendView(view, sidebarSizeSettingName, defaultSidebarWidth, defaultSidebarHeight) { - var splitWidget = new UI.SplitWidget( - this._isVertical, true, sidebarSizeSettingName, defaultSidebarWidth, defaultSidebarHeight); + var splitWidget = + new UI.SplitWidget(this._isVertical, true, sidebarSizeSettingName, defaultSidebarWidth, defaultSidebarHeight); splitWidget.setMainWidget(view); splitWidget.hideSidebar();
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/SuggestBox.js b/third_party/WebKit/Source/devtools/front_end/ui/SuggestBox.js index 39c256e..5bce53f 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/SuggestBox.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/SuggestBox.js
@@ -504,9 +504,10 @@ * @return {?Element} */ itemElement(index) { - if (!this._elementList[index]) + if (!this._elementList[index]) { this._elementList[index] = this._createItemElement(this._userEnteredText, this._items[index].title, this._items[index].className); + } return this._elementList[index]; } };
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/TabbedPane.js b/third_party/WebKit/Source/devtools/front_end/ui/TabbedPane.js index 6d74108..eb382f9 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/TabbedPane.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/TabbedPane.js
@@ -531,8 +531,7 @@ var dropDownContainer = createElementWithClass('div', 'tabbed-pane-header-tabs-drop-down-container'); dropDownContainer.createChild('div', 'glyph'); this._dropDownMenu = new UI.DropDownMenu(dropDownContainer); - this._dropDownMenu.addEventListener( - UI.DropDownMenu.Events.ItemSelected, this._dropDownMenuItemSelected, this); + this._dropDownMenu.addEventListener(UI.DropDownMenu.Events.ItemSelected, this._dropDownMenuItemSelected, this); return dropDownContainer; } @@ -690,9 +689,10 @@ var extraWidth = measuredWidths[i] - measuredWidths[i - 1]; totalExtraWidth += (measuredWidths.length - i) * extraWidth; - if (totalWidth + totalExtraWidth >= totalMeasuredWidth) + if (totalWidth + totalExtraWidth >= totalMeasuredWidth) { return measuredWidths[i - 1] + (totalWidth + totalExtraWidth - totalMeasuredWidth) / (measuredWidths.length - i); + } } return totalWidth / measuredWidths.length; @@ -1039,10 +1039,11 @@ tabElement.addEventListener('mouseup', this._tabMouseUp.bind(this), false); tabElement.addEventListener('contextmenu', this._tabContextMenu.bind(this), false); - if (this._tabbedPane._allowTabReorder) + if (this._tabbedPane._allowTabReorder) { UI.installDragHandle( tabElement, this._startTabDragging.bind(this), this._tabDragging.bind(this), this._endTabDragging.bind(this), '-webkit-grabbing', 'pointer', 200); + } } return tabElement;
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/TextPrompt.js b/third_party/WebKit/Source/devtools/front_end/ui/TextPrompt.js index 85efa3d8..b0b3908f 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/TextPrompt.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/TextPrompt.js
@@ -333,7 +333,8 @@ } _refreshGhostText() { - if (this._queryRange && this._isCaretAtEndOfPrompt() && this._currentSuggestion.startsWith(this.text().substring(this._queryRange.startColumn))) { + if (this._queryRange && this._isCaretAtEndOfPrompt() && + this._currentSuggestion.startsWith(this.text().substring(this._queryRange.startColumn))) { this._ghostTextElement.textContent = this._currentSuggestion.substring(this._queryRange.endColumn - this._queryRange.startColumn); this._element.appendChild(this._ghostTextElement); @@ -355,9 +356,10 @@ */ autoCompleteSoon(force) { var immediately = this._isSuggestBoxVisible() || force; - if (!this._completeTimeout) + if (!this._completeTimeout) { this._completeTimeout = setTimeout(this.complete.bind(this, force), immediately ? 0 : this._autocompletionTimeout); + } } /** @@ -373,11 +375,11 @@ var shouldExit; - if (!force && !this._isCaretAtEndOfPrompt() && !this._isSuggestBoxVisible()) + if (!force && !this._isCaretAtEndOfPrompt() && !this._isSuggestBoxVisible()) { shouldExit = true; - else if (!selection.isCollapsed) + } else if (!selection.isCollapsed) { shouldExit = true; - else if (!force) { + } else if (!force) { // BUG72018: Do not show suggest box if caret is followed by a non-stop character. var wordSuffixRange = selectionRange.startContainer.rangeOfWord( selectionRange.endOffset, this._completionStopCharacters, this._element, 'forward'); @@ -483,10 +485,11 @@ selectedIndex = (this._disableDefaultSuggestionForEmptyInput && !this.text()) ? -1 : (selectedIndex || 0); - if (this._suggestBox) + if (this._suggestBox) { this._suggestBox.updateSuggestions( this._boxForAnchorAtStart(selection, fullWordRange), annotatedCompletions, selectedIndex, !this._isCaretAtEndOfPrompt(), this.text()); + } var beforeRange = this._createRange(); beforeRange.setStart(this._element, 0);
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/Tooltip.js b/third_party/WebKit/Source/devtools/front_end/ui/Tooltip.js index cb8123aa..4e41b82 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/Tooltip.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/Tooltip.js
@@ -108,8 +108,7 @@ // Show tooltip instantly if a tooltip was shown recently. var now = Date.now(); - var instant = - (this._tooltipLastClosed && now - this._tooltipLastClosed < UI.Tooltip.Timing.InstantThreshold); + var instant = (this._tooltipLastClosed && now - this._tooltipLastClosed < UI.Tooltip.Timing.InstantThreshold); this._tooltipElement.classList.toggle('instant', instant); this._tooltipLastOpened = instant ? now : now + UI.Tooltip.Timing.OpeningDelay;
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/UIUtils.js b/third_party/WebKit/Source/devtools/front_end/ui/UIUtils.js index de8d035b..0456783 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/UIUtils.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/UIUtils.js
@@ -132,8 +132,7 @@ this._elementDraggingEventListener = elementDrag; this._elementEndDraggingEventListener = elementDragEnd; console.assert( - (UI.DragHandler._documentForMouseOut || targetDocument) === targetDocument, - 'Dragging on multiple documents.'); + (UI.DragHandler._documentForMouseOut || targetDocument) === targetDocument, 'Dragging on multiple documents.'); UI.DragHandler._documentForMouseOut = targetDocument; this._dragEventsTargetDocument = targetDocument; this._dragEventsTargetDocumentTop = targetDocument.defaultView.top.document; @@ -310,9 +309,8 @@ constructor(document, dimmed) { this.element = createElement('div'); var background = dimmed ? 'rgba(255, 255, 255, 0.5)' : 'transparent'; - this._zIndex = UI._glassPane ? - UI._glassPane._zIndex + 1000 : - 3000; // Deliberately starts with 3000 to hide other z-indexed elements below. + this._zIndex = UI._glassPane ? UI._glassPane._zIndex + 1000 : + 3000; // Deliberately starts with 3000 to hide other z-indexed elements below. this.element.style.cssText = 'position:absolute;top:0;bottom:0;left:0;right:0;background-color:' + background + ';z-index:' + this._zIndex + ';overflow:hidden;'; document.body.appendChild(this.element); @@ -524,9 +522,10 @@ prefix = matches[1]; suffix = matches[3]; number = UI._modifiedFloatNumber(parseFloat(matches[2]), event); - if (number !== null) + if (number !== null) { replacementString = customNumberHandler ? customNumberHandler(prefix, number, suffix) : prefix + number + suffix; + } } } return replacementString; @@ -540,8 +539,7 @@ * @param {function(string, number, string):string=} customNumberHandler * @return {boolean} */ -UI.handleElementValueModifications = function( - event, element, finishHandler, suggestionHandler, customNumberHandler) { +UI.handleElementValueModifications = function(event, element, finishHandler, suggestionHandler, customNumberHandler) { /** * @return {?Range} * @suppressGlobalPropertiesCheck @@ -852,8 +850,7 @@ * @return {!Array.<!Element>} */ UI.highlightSearchResults = function(element, resultRanges, changes) { - return UI.highlightRangesWithStyleClass( - element, resultRanges, UI.highlightedSearchResultClassName, changes); + return UI.highlightRangesWithStyleClass(element, resultRanges, UI.highlightedSearchResultClassName, changes); }; /** @@ -1336,9 +1333,8 @@ styleElement.textContent = themeStyleSheet + '\n' + Runtime.resolveSourceURL(cssFile + '.theme'); node.appendChild(styleElement); } -} +}; -; (function() { registerCustomElement('button', 'text-button', { /** @@ -1614,7 +1610,7 @@ return setValue; }; - /** +/** * @param {!CanvasRenderingContext2D} context * @param {string} text * @param {number} maxWidth
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/View.js b/third_party/WebKit/Source/devtools/front_end/ui/View.js index ed6b267..90a28a55 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/View.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/View.js
@@ -189,8 +189,7 @@ } if (this._extension.descriptor()['hasToolbar']) - return this.widget().then( - widget => /** @type {!UI.ToolbarItem.ItemsProvider} */ (widget).toolbarItems()); + return this.widget().then(widget => /** @type {!UI.ToolbarItem.ItemsProvider} */ (widget).toolbarItems()); return Promise.resolve([]); } @@ -433,8 +432,7 @@ if (this._materializePromise) return this._materializePromise; var promises = []; - promises.push(this._view.toolbarItems().then( - UI.ViewManager._populateToolbar.bind(UI.ViewManager, this.element))); + promises.push(this._view.toolbarItems().then(UI.ViewManager._populateToolbar.bind(UI.ViewManager, this.element))); promises.push(this._view.widget().then(widget => { // Move focus from |this| to loaded |widget| if any. var shouldFocus = this.element.hasFocus(); @@ -480,8 +478,8 @@ if (this._materializePromise) return this._materializePromise; var promises = []; - promises.push(this._view.toolbarItems().then( - UI.ViewManager._populateToolbar.bind(UI.ViewManager, this._titleElement))); + promises.push( + this._view.toolbarItems().then(UI.ViewManager._populateToolbar.bind(UI.ViewManager, this._titleElement))); promises.push(this._view.widget().then(widget => { this._widget = widget; this._view[UI.View._widgetSymbol] = widget; @@ -612,8 +610,7 @@ * @override */ enableMoreTabsButton() { - this._tabbedPane.leftToolbar().appendToolbarItem( - new UI.ToolbarMenuButton(this._appendTabsToMenu.bind(this))); + this._tabbedPane.leftToolbar().appendToolbarItem(new UI.ToolbarMenuButton(this._appendTabsToMenu.bind(this))); this._tabbedPane.disableOverflowMenu(); } @@ -628,9 +625,7 @@ var persistedOrders = this._tabOrderSetting.get(); var orders = new Map(); for (var view of views) - orders.set( - view.viewId(), - persistedOrders[view.viewId()] || (++i) * UI.ViewManager._TabbedLocation.orderStep); + orders.set(view.viewId(), persistedOrders[view.viewId()] || (++i) * UI.ViewManager._TabbedLocation.orderStep); views.sort((a, b) => orders.get(a.viewId()) - orders.get(b.viewId())); }
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/ViewportControl.js b/third_party/WebKit/Source/devtools/front_end/ui/ViewportControl.js index df26c849..dfaea699 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/ViewportControl.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/ViewportControl.js
@@ -243,10 +243,11 @@ } else if (!hasVisibleSelection) { firstSelected = startSelection; lastSelected = endSelection; - } else if (topOverlap) + } else if (topOverlap) { firstSelected = isBackward ? this._headSelection : this._anchorSelection; - else if (bottomOverlap) + } else if (bottomOverlap) { lastSelected = isBackward ? this._anchorSelection : this._headSelection; + } if (isBackward) { this._anchorSelection = lastSelected; @@ -503,11 +504,12 @@ */ lastVisibleIndex() { var lastVisibleIndex; - if (this._stickToBottom) + if (this._stickToBottom) { lastVisibleIndex = this._itemCount - 1; - else + } else { lastVisibleIndex = this.firstVisibleIndex() + Math.ceil(this._visibleHeight() / this._provider.minimumRowHeight()) - 1; + } return Math.min(lastVisibleIndex, this._lastActiveIndex); }
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/Widget.js b/third_party/WebKit/Source/devtools/front_end/ui/Widget.js index f06d78c..9ffce99 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/Widget.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/Widget.js
@@ -288,12 +288,13 @@ while (currentParent && !currentParent.__widget) currentParent = currentParent.parentElementOrShadowHost(); - if (this._isRoot) + if (this._isRoot) { UI.Widget.__assert(!currentParent, 'Attempt to show root widget under another widget'); - else + } else { UI.Widget.__assert( currentParent && currentParent.__widget === this._parentWidget, 'Attempt to show under node belonging to alien widget'); + } var wasVisible = this._visible; if (wasVisible && this.element.parentElement === parentElement) @@ -750,7 +751,6 @@ }; Element.prototype.removeChildren = function() { - UI.Widget.__assert( - !this.__widgetCounter, 'Attempt to remove element containing widget via regular DOM operation'); + UI.Widget.__assert(!this.__widgetCounter, 'Attempt to remove element containing widget via regular DOM operation'); UI.Widget._originalRemoveChildren.call(this); };
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/ZoomManager.js b/third_party/WebKit/Source/devtools/front_end/ui/ZoomManager.js index 99dd413..31ea9fd 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/ZoomManager.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/ZoomManager.js
@@ -43,8 +43,7 @@ var oldZoomFactor = this._zoomFactor; this._zoomFactor = this._frontendHost.zoomFactor(); if (oldZoomFactor !== this._zoomFactor) - this.dispatchEventToListeners( - UI.ZoomManager.Events.ZoomChanged, {from: oldZoomFactor, to: this._zoomFactor}); + this.dispatchEventToListeners(UI.ZoomManager.Events.ZoomChanged, {from: oldZoomFactor, to: this._zoomFactor}); } };
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/inspectorCommon.css b/third_party/WebKit/Source/devtools/front_end/ui/inspectorCommon.css index d3039f97..782ba34 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/inspectorCommon.css +++ b/third_party/WebKit/Source/devtools/front_end/ui/inspectorCommon.css
@@ -322,7 +322,7 @@ z-index: 500; } -span[is=ui-icon] { +[is=ui-icon] { display: inline-block; flex-shrink: 0; }
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/toolbar.css b/third_party/WebKit/Source/devtools/front_end/ui/toolbar.css index 2532ad8..23306cd 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/toolbar.css +++ b/third_party/WebKit/Source/devtools/front_end/ui/toolbar.css
@@ -106,21 +106,11 @@ } .toolbar-glyph { - -webkit-mask-image: url(Images/toolbarButtonGlyphs.png); - -webkit-mask-size: 352px 168px; background-color: #5a5a5a; - width: 28px; - height: 24px; flex: none; transform: translateX(-2px); } -@media (-webkit-min-device-pixel-ratio: 1.1) { -.toolbar-glyph { - -webkit-mask-image: url(Images/toolbarButtonGlyphs_2x.png); -} -} /* media */ - /* Button */ .toolbar-button:disabled {
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/treeoutline.js b/third_party/WebKit/Source/devtools/front_end/ui/treeoutline.js index 118f3a43..78a1b74 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/treeoutline.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/treeoutline.js
@@ -220,12 +220,13 @@ } else { handled = this.selectedTreeElement.descendOrExpand(event.altKey); } - } else if (event.keyCode === 8 /* Backspace */ || event.keyCode === 46 /* Delete */) + } else if (event.keyCode === 8 /* Backspace */ || event.keyCode === 46 /* Delete */) { handled = this.selectedTreeElement.ondelete(); - else if (isEnterKey(event)) + } else if (isEnterKey(event)) { handled = this.selectedTreeElement.onenter(); - else if (event.keyCode === UI.KeyboardShortcut.Keys.Space.code) + } else if (event.keyCode === UI.KeyboardShortcut.Keys.Space.code) { handled = this.selectedTreeElement.onspace(); + } if (handled) event.consume(true);
diff --git a/third_party/WebKit/Source/devtools/front_end/ui_lazy/ChartViewport.js b/third_party/WebKit/Source/devtools/front_end/ui_lazy/ChartViewport.js index 84ffa29..f8ac02d 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui_lazy/ChartViewport.js +++ b/third_party/WebKit/Source/devtools/front_end/ui_lazy/ChartViewport.js
@@ -8,10 +8,10 @@ constructor() { super(true); - this.contentElement.addEventListener('mousewheel', this._onMouseWheel.bind(this), false); - this.contentElement.addEventListener('keydown', this._handleZoomPanKeys.bind(this), false); - this.viewportElement = this.contentElement.createChild('div', 'fill'); + this.viewportElement.addEventListener('mousewheel', this._onMouseWheel.bind(this), false); + this.viewportElement.addEventListener('keydown', this._handleZoomPanKeys.bind(this), false); + UI.installInertialDragHandle( this.viewportElement, this._startDragging.bind(this), this._dragging.bind(this), this._endDragging.bind(this), '-webkit-grabbing', null);
diff --git a/third_party/WebKit/Source/devtools/front_end/ui_lazy/CommandMenu.js b/third_party/WebKit/Source/devtools/front_end/ui_lazy/CommandMenu.js index 105bd48..877ad4ba 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui_lazy/CommandMenu.js +++ b/third_party/WebKit/Source/devtools/front_end/ui_lazy/CommandMenu.js
@@ -36,8 +36,7 @@ var category = extension.descriptor()['category'] || ''; var tags = extension.descriptor()['tags'] || ''; var setting = Common.settings.moduleSetting(extension.descriptor()['settingName']); - return UI.CommandMenu.createCommand( - category, tags, title, '', setting.set.bind(setting, value), availableHandler); + return UI.CommandMenu.createCommand(category, tags, title, '', setting.set.bind(setting, value), availableHandler); /** * @return {boolean}
diff --git a/third_party/WebKit/Source/devtools/front_end/ui_lazy/DataGrid.js b/third_party/WebKit/Source/devtools/front_end/ui_lazy/DataGrid.js index d80891e3..4ea0f93 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui_lazy/DataGrid.js +++ b/third_party/WebKit/Source/devtools/front_end/ui_lazy/DataGrid.js
@@ -797,8 +797,9 @@ if (this.selectedNode.parent.selectable) { nextSelectedNode = this.selectedNode.parent; handled = nextSelectedNode ? true : false; - } else if (this.selectedNode.parent) + } else if (this.selectedNode.parent) { this.selectedNode.parent.collapse(); + } } } else if (event.key === 'ArrowRight') { if (!this.selectedNode.revealed) { @@ -901,8 +902,7 @@ sortOrder = UI.DataGrid.Order.Descending; if (this._sortColumnCell) - this._sortColumnCell.classList.remove( - UI.DataGrid.Order.Ascending, UI.DataGrid.Order.Descending); + this._sortColumnCell.classList.remove(UI.DataGrid.Order.Ascending, UI.DataGrid.Order.Descending); this._sortColumnCell = cell; cell.classList.add(sortOrder); @@ -916,8 +916,7 @@ */ markColumnAsSortedBy(columnId, sortOrder) { if (this._sortColumnCell) - this._sortColumnCell.classList.remove( - UI.DataGrid.Order.Ascending, UI.DataGrid.Order.Descending); + this._sortColumnCell.classList.remove(UI.DataGrid.Order.Ascending, UI.DataGrid.Order.Descending); this._sortColumnCell = this._headerTableHeaders[columnId]; this._sortColumnCell.classList.add(sortOrder); } @@ -948,8 +947,9 @@ gridNode.deselect(); else gridNode.select(); - } else + } else { gridNode.select(); + } } /** @@ -985,14 +985,14 @@ if (gridNode && gridNode.selectable && !gridNode.isEventWithinDisclosureTriangle(event)) { if (this._editCallback) { - if (gridNode === this.creationNode) + if (gridNode === this.creationNode) { contextMenu.appendItem(Common.UIString.capitalize('Add ^new'), this._startEditing.bind(this, target)); - else { + } else { var columnId = this.columnIdFromNode(target); - if (columnId && this._columns[columnId].editable) + if (columnId && this._columns[columnId].editable) { contextMenu.appendItem( - Common.UIString('Edit "%s"', this._columns[columnId].title), - this._startEditing.bind(this, target)); + Common.UIString('Edit "%s"', this._columns[columnId].title), this._startEditing.bind(this, target)); + } } } if (this._deleteCallback && gridNode !== this.creationNode) @@ -1649,9 +1649,10 @@ if (this._isRoot) return; - if (this.revealed && !this._shouldRefreshChildren) + if (this.revealed && !this._shouldRefreshChildren) { for (var i = 0; i < this.children.length; ++i) this.children[i].revealed = true; + } if (this._shouldRefreshChildren) { for (var i = 0; i < this.children.length; ++i)
diff --git a/third_party/WebKit/Source/devtools/front_end/ui_lazy/FilteredListWidget.js b/third_party/WebKit/Source/devtools/front_end/ui_lazy/FilteredListWidget.js index a688c4c..f9a214b 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui_lazy/FilteredListWidget.js +++ b/third_party/WebKit/Source/devtools/front_end/ui_lazy/FilteredListWidget.js
@@ -218,8 +218,9 @@ bestItems.length = bestItemsToCollect; } minBestScore = bestScores.peekLast(); - } else + } else { filteredItems.push(i); + } } // Process everything in chunks.
diff --git a/third_party/WebKit/Source/devtools/front_end/ui_lazy/FlameChart.js b/third_party/WebKit/Source/devtools/front_end/ui_lazy/FlameChart.js index de78c1b..3ceb8f8 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui_lazy/FlameChart.js +++ b/third_party/WebKit/Source/devtools/front_end/ui_lazy/FlameChart.js
@@ -750,10 +750,11 @@ context.fillStyle = UI.themeSupport.patchColor('#6e6e6e', colorUsage.Foreground); context.beginPath(); forEachGroup.call(this, (offset, index, group) => { - if (this._isGroupCollapsible(index)) + if (this._isGroupCollapsible(index)) { drawExpansionArrow.call( this, this._expansionArrowIndent * (group.style.nestingLevel + 1), offset + textBaseHeight - this._arrowSide / 2, !!group.expanded); + } }); context.fill();
diff --git a/third_party/WebKit/Source/devtools/front_end/ui_lazy/OverviewGrid.js b/third_party/WebKit/Source/devtools/front_end/ui_lazy/OverviewGrid.js index 94da67db..d31f3448 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui_lazy/OverviewGrid.js +++ b/third_party/WebKit/Source/devtools/front_end/ui_lazy/OverviewGrid.js
@@ -146,10 +146,11 @@ UI.installDragHandle( this._parentElement, this._startWindowSelectorDragging.bind(this), this._windowSelectorDragging.bind(this), this._endWindowSelectorDragging.bind(this), 'text', null); - if (dividersLabelBarElement) + if (dividersLabelBarElement) { UI.installDragHandle( dividersLabelBarElement, this._startWindowDragging.bind(this), this._windowDragging.bind(this), null, '-webkit-grabbing', '-webkit-grab'); + } this._parentElement.addEventListener('mousewheel', this._onMouseWheel.bind(this), true); this._parentElement.addEventListener('dblclick', this._resizeWindowMaximum.bind(this), true);
diff --git a/third_party/WebKit/Source/devtools/front_end/ui_lazy/SortableDataGrid.js b/third_party/WebKit/Source/devtools/front_end/ui_lazy/SortableDataGrid.js index c29de90..94db8da0 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui_lazy/SortableDataGrid.js +++ b/third_party/WebKit/Source/devtools/front_end/ui_lazy/SortableDataGrid.js
@@ -114,8 +114,7 @@ } } - var comparator = columnIsNumeric ? UI.SortableDataGrid.NumericComparator : - UI.SortableDataGrid.StringComparator; + var comparator = columnIsNumeric ? UI.SortableDataGrid.NumericComparator : UI.SortableDataGrid.StringComparator; dataGrid.sortNodes(comparator.bind(null, sortColumnId), !dataGrid.isSortOrderAscending()); } return dataGrid;
diff --git a/third_party/WebKit/Source/devtools/front_end/workspace/UISourceCode.js b/third_party/WebKit/Source/devtools/front_end/workspace/UISourceCode.js index fff83b1..60e4f4f 100644 --- a/third_party/WebKit/Source/devtools/front_end/workspace/UISourceCode.js +++ b/third_party/WebKit/Source/devtools/front_end/workspace/UISourceCode.js
@@ -161,10 +161,11 @@ * @this {Workspace.UISourceCode} */ function innerCallback(success, newName, newURL, newContentType) { - if (success) + if (success) { this._updateName( /** @type {string} */ (newName), /** @type {string} */ (newURL), /** @type {!Common.ResourceType} */ (newContentType)); + } callback(success); } } @@ -356,9 +357,10 @@ this.dispatchEventToListeners(Workspace.UISourceCode.Events.WorkingCopyCommitted, {content: content}); this._project.workspace().dispatchEventToListeners( Workspace.Workspace.Events.WorkingCopyCommitted, {uiSourceCode: this, content: content}); - if (committedByUser) + if (committedByUser) { this._project.workspace().dispatchEventToListeners( Workspace.Workspace.Events.WorkingCopyCommittedByUser, {uiSourceCode: this, content: content}); + } } saveAs() {
diff --git a/third_party/WebKit/Source/devtools/front_end/workspace/Workspace.js b/third_party/WebKit/Source/devtools/front_end/workspace/Workspace.js index b6e2f2cb..07043498 100644 --- a/third_party/WebKit/Source/devtools/front_end/workspace/Workspace.js +++ b/third_party/WebKit/Source/devtools/front_end/workspace/Workspace.js
@@ -70,8 +70,8 @@ * @return {boolean} */ Workspace.Project.isServiceProject = function(project) { - return project.type() === Workspace.projectTypes.Debugger || - project.type() === Workspace.projectTypes.Formatter || project.type() === Workspace.projectTypes.Service; + return project.type() === Workspace.projectTypes.Debugger || project.type() === Workspace.projectTypes.Formatter || + project.type() === Workspace.projectTypes.Service; }; Workspace.Project.prototype = {
diff --git a/third_party/WebKit/Source/devtools/package.json b/third_party/WebKit/Source/devtools/package.json index 568e4c5..12d622c 100644 --- a/third_party/WebKit/Source/devtools/package.json +++ b/third_party/WebKit/Source/devtools/package.json
@@ -30,7 +30,7 @@ }, "homepage": "https://devtools.chrome.com", "devDependencies": { - "eslint": "3.9.1", + "eslint": "3.10.0", "clang-format": "1.0.45", "async": "1.5.2", "glob": "7.1.1",
diff --git a/third_party/WebKit/Source/devtools/scripts/hosted_mode/server.js b/third_party/WebKit/Source/devtools/scripts/hosted_mode/server.js index f821ba9..c72e47e 100644 --- a/third_party/WebKit/Source/devtools/scripts/hosted_mode/server.js +++ b/third_party/WebKit/Source/devtools/scripts/hosted_mode/server.js
@@ -116,7 +116,27 @@ if (proxyFileCache.has(proxyFileURL)) return Promise.resolve(proxyFileCache.get(proxyFileURL)); return utils.fetch(proxyFileURL) - .then(cacheProxyFile.bind(null, proxyFileURL)); + .then(cacheProxyFile.bind(null, proxyFileURL)) + .catch(onMissingFile); + } + + function onMissingFile() { + var isFullCheckout = utils.shellOutput("git config --get remote.origin.url") === "https://chromium.googlesource.com/chromium/src.git"; + var earlierCommitHash; + var gitLogCommand = `git log --max-count=1 --grep="Commit-Position" --before="12 hours ago"`; + if (isFullCheckout) { + earlierCommitHash = utils.shellOutput(`${gitLogCommand} --pretty=format:"%H"`); + } else { + var commitMessage = utils.shellOutput(`${gitLogCommand}`); + earlierCommitHash = commitMessage.match(/Cr-Mirrored-Commit: (.*)/)[1]; + } + var fallbackURL = proxyFilePathToURL[filePath](earlierCommitHash); + console.log("WARNING: Unable to fetch generated file based on browser's revision"); + console.log("Fetching earlier revision of same file as fallback"); + console.log("There may be a mismatch between the front-end and back-end"); + console.log(fallbackURL, "\n"); + return utils.fetch(fallbackURL) + .then(cacheProxyFile.bind(null, fallbackURL)); } function cacheProxyFile(proxyFileURL, data)
diff --git a/third_party/WebKit/Source/devtools/scripts/npm_test.js b/third_party/WebKit/Source/devtools/scripts/npm_test.js index c7fa96f1..cbf7ad1 100644 --- a/third_party/WebKit/Source/devtools/scripts/npm_test.js +++ b/third_party/WebKit/Source/devtools/scripts/npm_test.js
@@ -226,16 +226,10 @@ function build(contentShellResourcesPath) { var devtoolsResourcesPath = path.resolve(contentShellResourcesPath, "inspector"); - var copiedFrontendPath = path.resolve(devtoolsResourcesPath, "front_end"); - var debugPath = path.resolve(devtoolsResourcesPath, "debug"); - utils.removeRecursive(copiedFrontendPath); - utils.removeRecursive(debugPath); - utils.copyRecursive(SOURCE_PATH, devtoolsResourcesPath); - fs.renameSync(copiedFrontendPath, debugPath); var inspectorBackendCommandsPath = path.resolve(devtoolsResourcesPath, "InspectorBackendCommands.js"); var supportedCSSPropertiesPath = path.resolve(devtoolsResourcesPath, "SupportedCSSProperties.js"); - utils.copy(inspectorBackendCommandsPath, debugPath); - utils.copy(supportedCSSPropertiesPath, debugPath); + utils.copy(inspectorBackendCommandsPath, SOURCE_PATH); + utils.copy(supportedCSSPropertiesPath, SOURCE_PATH); } function runTests(buildDirectoryPath, options) @@ -245,8 +239,10 @@ "--build-directory", buildDirectoryPath, ]); - if (!options.useRelease) + if (!options.useRelease) { testArgs.push("--additional-driver-flag=--debug-devtools"); + testArgs.push(`--additional-driver-flag=--custom-devtools-frontend=${SOURCE_PATH}`); + } if (IS_DEBUG_ENABLED) { testArgs.push("--additional-driver-flag=--remote-debugging-port=9222"); testArgs.push("--time-out-ms=6000000");
diff --git a/third_party/WebKit/Source/devtools/scripts/utils.js b/third_party/WebKit/Source/devtools/scripts/utils.js index a0df35a..51bb66a 100644 --- a/third_party/WebKit/Source/devtools/scripts/utils.js +++ b/third_party/WebKit/Source/devtools/scripts/utils.js
@@ -7,6 +7,7 @@ var https = require("https"); var path = require("path"); var parseURL = require("url").parse; +var shell = require("child_process").execSync; var Stream = require("stream").Transform; function fetch(url) @@ -121,6 +122,11 @@ return sequence.indexOf(target) > -1; } +function shellOutput(command) +{ + return shell(command).toString().trim(); +} + module.exports = { fetch, atob, @@ -130,4 +136,5 @@ copyRecursive, removeRecursive, includes, + shellOutput, }; \ No newline at end of file
diff --git a/third_party/WebKit/Source/modules/EventModulesFactory.h b/third_party/WebKit/Source/modules/EventModulesFactory.h index d0b71cc..b044f32 100644 --- a/third_party/WebKit/Source/modules/EventModulesFactory.h +++ b/third_party/WebKit/Source/modules/EventModulesFactory.h
@@ -19,7 +19,7 @@ class EventModulesFactory final : public EventFactoryBase { public: static std::unique_ptr<EventModulesFactory> create() { - return wrapUnique(new EventModulesFactory()); + return makeUnique<EventModulesFactory>(); } Event* create(ExecutionContext*, const String& eventType) override;
diff --git a/third_party/WebKit/Source/modules/ModulesInitializer.cpp b/third_party/WebKit/Source/modules/ModulesInitializer.cpp index c3a9e6b..59f9c21 100644 --- a/third_party/WebKit/Source/modules/ModulesInitializer.cpp +++ b/third_party/WebKit/Source/modules/ModulesInitializer.cpp
@@ -59,19 +59,19 @@ // Canvas context types must be registered with the HTMLCanvasElement. HTMLCanvasElement::registerRenderingContextFactory( - wrapUnique(new CanvasRenderingContext2D::Factory())); + makeUnique<CanvasRenderingContext2D::Factory>()); HTMLCanvasElement::registerRenderingContextFactory( - wrapUnique(new WebGLRenderingContext::Factory())); + makeUnique<WebGLRenderingContext::Factory>()); HTMLCanvasElement::registerRenderingContextFactory( - wrapUnique(new WebGL2RenderingContext::Factory())); + makeUnique<WebGL2RenderingContext::Factory>()); HTMLCanvasElement::registerRenderingContextFactory( - wrapUnique(new ImageBitmapRenderingContext::Factory())); + makeUnique<ImageBitmapRenderingContext::Factory>()); // OffscreenCanvas context types must be registered with the OffscreenCanvas. OffscreenCanvas::registerRenderingContextFactory( - wrapUnique(new OffscreenCanvasRenderingContext2D::Factory())); + makeUnique<OffscreenCanvasRenderingContext2D::Factory>()); OffscreenCanvas::registerRenderingContextFactory( - wrapUnique(new WebGLRenderingContext::Factory())); + makeUnique<WebGLRenderingContext::Factory>()); ASSERT(isInitialized()); }
diff --git a/third_party/WebKit/Source/modules/canvas/HTMLCanvasElementModule.cpp b/third_party/WebKit/Source/modules/canvas/HTMLCanvasElementModule.cpp index 5d444a0..3345b84 100644 --- a/third_party/WebKit/Source/modules/canvas/HTMLCanvasElementModule.cpp +++ b/third_party/WebKit/Source/modules/canvas/HTMLCanvasElementModule.cpp
@@ -65,7 +65,10 @@ } OffscreenCanvas* offscreenCanvas = OffscreenCanvas::create(canvas.width(), canvas.height()); - offscreenCanvas->setAssociatedCanvasId(DOMNodeIds::idForNode(&canvas)); + + int canvasId = DOMNodeIds::idForNode(&canvas); + offscreenCanvas->setPlaceholderCanvasId(canvasId); + canvas.registerPlaceholder(canvasId); CanvasSurfaceLayerBridge* bridge = canvas.surfaceLayerBridge(); if (bridge) {
diff --git a/third_party/WebKit/Source/modules/canvas/HTMLCanvasElementModuleTest.cpp b/third_party/WebKit/Source/modules/canvas/HTMLCanvasElementModuleTest.cpp index 545ff92..1f235357 100644 --- a/third_party/WebKit/Source/modules/canvas/HTMLCanvasElementModuleTest.cpp +++ b/third_party/WebKit/Source/modules/canvas/HTMLCanvasElementModuleTest.cpp
@@ -49,7 +49,7 @@ TEST_F(HTMLCanvasElementModuleTest, TransferControlToOffscreen) { NonThrowableExceptionState exceptionState; OffscreenCanvas* offscreenCanvas = transferControlToOffscreen(exceptionState); - int canvasId = offscreenCanvas->getAssociatedCanvasId(); + int canvasId = offscreenCanvas->placeholderCanvasId(); EXPECT_EQ(canvasId, DOMNodeIds::idForNode(&(canvasElement()))); }
diff --git a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DState.cpp b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DState.cpp index 94fbc5c..17b4b39 100644 --- a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DState.cpp +++ b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DState.cpp
@@ -339,22 +339,19 @@ } SkDrawLooper* CanvasRenderingContext2DState::emptyDrawLooper() const { - if (!m_emptyDrawLooper) { - std::unique_ptr<DrawLooperBuilder> drawLooperBuilder = - DrawLooperBuilder::create(); - m_emptyDrawLooper = drawLooperBuilder->detachDrawLooper(); - } + if (!m_emptyDrawLooper) + m_emptyDrawLooper = DrawLooperBuilder().detachDrawLooper(); + return m_emptyDrawLooper.get(); } SkDrawLooper* CanvasRenderingContext2DState::shadowOnlyDrawLooper() const { if (!m_shadowOnlyDrawLooper) { - std::unique_ptr<DrawLooperBuilder> drawLooperBuilder = - DrawLooperBuilder::create(); - drawLooperBuilder->addShadow(m_shadowOffset, m_shadowBlur, m_shadowColor, - DrawLooperBuilder::ShadowIgnoresTransforms, - DrawLooperBuilder::ShadowRespectsAlpha); - m_shadowOnlyDrawLooper = drawLooperBuilder->detachDrawLooper(); + DrawLooperBuilder drawLooperBuilder; + drawLooperBuilder.addShadow(m_shadowOffset, m_shadowBlur, m_shadowColor, + DrawLooperBuilder::ShadowIgnoresTransforms, + DrawLooperBuilder::ShadowRespectsAlpha); + m_shadowOnlyDrawLooper = drawLooperBuilder.detachDrawLooper(); } return m_shadowOnlyDrawLooper.get(); } @@ -362,13 +359,12 @@ SkDrawLooper* CanvasRenderingContext2DState::shadowAndForegroundDrawLooper() const { if (!m_shadowAndForegroundDrawLooper) { - std::unique_ptr<DrawLooperBuilder> drawLooperBuilder = - DrawLooperBuilder::create(); - drawLooperBuilder->addShadow(m_shadowOffset, m_shadowBlur, m_shadowColor, - DrawLooperBuilder::ShadowIgnoresTransforms, - DrawLooperBuilder::ShadowRespectsAlpha); - drawLooperBuilder->addUnmodifiedContent(); - m_shadowAndForegroundDrawLooper = drawLooperBuilder->detachDrawLooper(); + DrawLooperBuilder drawLooperBuilder; + drawLooperBuilder.addShadow(m_shadowOffset, m_shadowBlur, m_shadowColor, + DrawLooperBuilder::ShadowIgnoresTransforms, + DrawLooperBuilder::ShadowRespectsAlpha); + drawLooperBuilder.addUnmodifiedContent(); + m_shadowAndForegroundDrawLooper = drawLooperBuilder.detachDrawLooper(); } return m_shadowAndForegroundDrawLooper.get(); }
diff --git a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DTest.cpp b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DTest.cpp index d838add..cbf193ae3 100644 --- a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DTest.cpp +++ b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DTest.cpp
@@ -588,7 +588,7 @@ IntSize sourceSize( 10, 10 * ExpensiveCanvasHeuristicParameters::ExpensiveImageSizeRatio); std::unique_ptr<UnacceleratedImageBufferSurface> sourceSurface = - wrapUnique(new UnacceleratedImageBufferSurface(sourceSize, NonOpaque)); + makeUnique<UnacceleratedImageBufferSurface>(sourceSize, NonOpaque); sourceCanvas->createImageBufferUsingSurfaceForTesting( std::move(sourceSurface)); @@ -624,7 +624,7 @@ IntSize sourceSize( 10, 10 * ExpensiveCanvasHeuristicParameters::ExpensiveImageSizeRatio + 1); std::unique_ptr<UnacceleratedImageBufferSurface> sourceSurface = - wrapUnique(new UnacceleratedImageBufferSurface(sourceSize, NonOpaque)); + makeUnique<UnacceleratedImageBufferSurface>(sourceSize, NonOpaque); sourceCanvas->createImageBufferUsingSurfaceForTesting( std::move(sourceSurface));
diff --git a/third_party/WebKit/Source/modules/compositorworker/AnimationWorkletThreadTest.cpp b/third_party/WebKit/Source/modules/compositorworker/AnimationWorkletThreadTest.cpp index 53cebf0c..f42cfe4 100644 --- a/third_party/WebKit/Source/modules/compositorworker/AnimationWorkletThreadTest.cpp +++ b/third_party/WebKit/Source/modules/compositorworker/AnimationWorkletThreadTest.cpp
@@ -99,7 +99,7 @@ // Attempts to run some simple script for |thread|. void checkWorkletCanExecuteScript(WorkerThread* thread) { - std::unique_ptr<WaitableEvent> waitEvent = wrapUnique(new WaitableEvent()); + std::unique_ptr<WaitableEvent> waitEvent = makeUnique<WaitableEvent>(); thread->workerBackingThread().backingThread().postTask( BLINK_FROM_HERE, crossThreadBind(&AnimationWorkletThreadTest::executeScriptInWorklet,
diff --git a/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerThreadTest.cpp b/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerThreadTest.cpp index 0218ab95..a059c5ad 100644 --- a/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerThreadTest.cpp +++ b/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerThreadTest.cpp
@@ -131,7 +131,7 @@ // Attempts to run some simple script for |worker|. void checkWorkerCanExecuteScript(WorkerThread* worker) { - std::unique_ptr<WaitableEvent> waitEvent = wrapUnique(new WaitableEvent()); + std::unique_ptr<WaitableEvent> waitEvent = makeUnique<WaitableEvent>(); worker->workerBackingThread().backingThread().postTask( BLINK_FROM_HERE, crossThreadBind(&CompositorWorkerThreadTest::executeScriptInWorker,
diff --git a/third_party/WebKit/Source/modules/crypto/NormalizeAlgorithm.cpp b/third_party/WebKit/Source/modules/crypto/NormalizeAlgorithm.cpp index ce63ecd..20ab62a 100644 --- a/third_party/WebKit/Source/modules/crypto/NormalizeAlgorithm.cpp +++ b/third_party/WebKit/Source/modules/crypto/NormalizeAlgorithm.cpp
@@ -531,7 +531,7 @@ if (!getUint16(raw, "length", length, context, error)) return false; - params = wrapUnique(new WebCryptoAesKeyGenParams(length)); + params = makeUnique<WebCryptoAesKeyGenParams>(length); return true; } @@ -573,7 +573,7 @@ if (!getOptionalUint32(raw, "length", hasLength, length, context, error)) return false; - params = wrapUnique(new WebCryptoHmacImportParams(hash, hasLength, length)); + params = makeUnique<WebCryptoHmacImportParams>(hash, hasLength, length); return true; } @@ -596,7 +596,7 @@ if (!getOptionalUint32(raw, "length", hasLength, length, context, error)) return false; - params = wrapUnique(new WebCryptoHmacKeyGenParams(hash, hasLength, length)); + params = makeUnique<WebCryptoHmacKeyGenParams>(hash, hasLength, length); return true; } @@ -614,7 +614,7 @@ if (!parseHash(raw, hash, context, error)) return false; - params = wrapUnique(new WebCryptoRsaHashedImportParams(hash)); + params = makeUnique<WebCryptoRsaHashedImportParams>(hash); return true; } @@ -736,7 +736,7 @@ if (!getUint32(raw, "saltLength", saltLengthBytes, context, error)) return false; - params = wrapUnique(new WebCryptoRsaPssParams(saltLengthBytes)); + params = makeUnique<WebCryptoRsaPssParams>(saltLengthBytes); return true; } @@ -753,7 +753,7 @@ if (!parseHash(raw, hash, context, error)) return false; - params = wrapUnique(new WebCryptoEcdsaParams(hash)); + params = makeUnique<WebCryptoEcdsaParams>(hash); return true; } @@ -807,7 +807,7 @@ if (!parseNamedCurve(raw, namedCurve, context, error)) return false; - params = wrapUnique(new WebCryptoEcKeyGenParams(namedCurve)); + params = makeUnique<WebCryptoEcKeyGenParams>(namedCurve); return true; } @@ -824,7 +824,7 @@ if (!parseNamedCurve(raw, namedCurve, context, error)) return false; - params = wrapUnique(new WebCryptoEcKeyImportParams(namedCurve)); + params = makeUnique<WebCryptoEcKeyImportParams>(namedCurve); return true; } @@ -895,7 +895,7 @@ if (!getUint16(raw, "length", length, context, error)) return false; - params = wrapUnique(new WebCryptoAesDerivedKeyParams(length)); + params = makeUnique<WebCryptoAesDerivedKeyParams>(length); return true; }
diff --git a/third_party/WebKit/Source/modules/fetch/BytesConsumerForDataConsumerHandleTest.cpp b/third_party/WebKit/Source/modules/fetch/BytesConsumerForDataConsumerHandleTest.cpp index 2d89fbf..20a03801 100644 --- a/third_party/WebKit/Source/modules/fetch/BytesConsumerForDataConsumerHandleTest.cpp +++ b/third_party/WebKit/Source/modules/fetch/BytesConsumerForDataConsumerHandleTest.cpp
@@ -86,7 +86,7 @@ std::unique_ptr<WebDataConsumerHandle::Reader> obtainReader( Client*) override { - return wrapUnique(new Reader(m_proxy)); + return makeUnique<Reader>(m_proxy); } Persistent<MockReaderProxy> m_proxy; };
diff --git a/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.cpp b/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.cpp index 9940a196..147887d 100644 --- a/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.cpp +++ b/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.cpp
@@ -42,7 +42,7 @@ : m_thread( WebThreadSupportingGC::create(name, BlinkGC::MainThreadHeapMode)), m_initializationPolicy(initializationPolicy), - m_waitableEvent(wrapUnique(new WaitableEvent())) { + m_waitableEvent(makeUnique<WaitableEvent>()) { m_thread->postTask( BLINK_FROM_HERE, crossThreadBind(&Thread::initialize, crossThreadUnretained(this))); @@ -58,7 +58,7 @@ void DataConsumerHandleTestUtil::Thread::initialize() { if (m_initializationPolicy >= ScriptExecution) { - m_isolateHolder = wrapUnique(new gin::IsolateHolder()); + m_isolateHolder = makeUnique<gin::IsolateHolder>(); isolate()->Enter(); } m_thread->initialize(); @@ -195,7 +195,7 @@ m_client(nullptr), m_result(ShouldWait), m_isHandleAttached(true), - m_detached(wrapUnique(new WaitableEvent())) {} + m_detached(makeUnique<WaitableEvent>()) {} const DataConsumerHandleTestUtil::Command& DataConsumerHandleTestUtil::ReplayingHandle::Context::top() { @@ -246,7 +246,7 @@ std::unique_ptr<WebDataConsumerHandle::Reader> DataConsumerHandleTestUtil::ReplayingHandle::obtainReader(Client* client) { - return WTF::wrapUnique(new ReaderImpl(m_context, client)); + return makeUnique<ReaderImpl>(m_context, client); } void DataConsumerHandleTestUtil::ReplayingHandle::add(const Command& command) { @@ -273,7 +273,7 @@ m_data.append(buffer, size); } std::unique_ptr<HandleReadResult> result = - wrapUnique(new HandleReadResult(r, m_data)); + makeUnique<HandleReadResult>(r, m_data); m_data.clear(); Platform::current()->currentThread()->getWebTaskRunner()->postTask( BLINK_FROM_HERE, @@ -313,7 +313,7 @@ m_reader->endRead(readSize); } std::unique_ptr<HandleReadResult> result = - wrapUnique(new HandleReadResult(r, m_data)); + makeUnique<HandleReadResult>(r, m_data); m_data.clear(); Platform::current()->currentThread()->getWebTaskRunner()->postTask( BLINK_FROM_HERE,
diff --git a/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.h b/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.h index fa37bec..2ce5c19 100644 --- a/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.h +++ b/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.h
@@ -219,7 +219,7 @@ : m_name(name.isolatedCopy()), m_context(context) {} std::unique_ptr<Reader> obtainReader(Client*) { - return WTF::wrapUnique(new ReaderImpl(m_name, m_context)); + return makeUnique<ReaderImpl>(m_name, m_context); } const char* debugName() const override { return "ThreadingTestBase::DataConsumerHandle"; @@ -270,7 +270,7 @@ void run(std::unique_ptr<WebDataConsumerHandle> handle) { ThreadHolder holder(this); - m_waitableEvent = wrapUnique(new WaitableEvent()); + m_waitableEvent = makeUnique<WaitableEvent>(); m_handle = std::move(handle); postTaskToReadingThreadAndWait( @@ -302,7 +302,7 @@ void run(std::unique_ptr<WebDataConsumerHandle> handle) { ThreadHolder holder(this); - m_waitableEvent = wrapUnique(new WaitableEvent()); + m_waitableEvent = makeUnique<WaitableEvent>(); m_handle = std::move(handle); postTaskToReadingThreadAndWait( @@ -476,7 +476,7 @@ public: explicit HandleReaderRunner(std::unique_ptr<WebDataConsumerHandle> handle) : m_thread(wrapUnique(new Thread("reading thread"))), - m_event(wrapUnique(new WaitableEvent())), + m_event(makeUnique<WaitableEvent>()), m_isDone(false) { m_thread->thread()->postTask(BLINK_FROM_HERE, crossThreadBind(&HandleReaderRunner::start,
diff --git a/third_party/WebKit/Source/modules/fetch/FetchDataLoader.cpp b/third_party/WebKit/Source/modules/fetch/FetchDataLoader.cpp index 56c28f00..cb76438 100644 --- a/third_party/WebKit/Source/modules/fetch/FetchDataLoader.cpp +++ b/third_party/WebKit/Source/modules/fetch/FetchDataLoader.cpp
@@ -108,7 +108,7 @@ DCHECK(!m_rawData); DCHECK(!m_consumer); m_client = client; - m_rawData = wrapUnique(new ArrayBufferBuilder()); + m_rawData = makeUnique<ArrayBufferBuilder>(); m_consumer = consumer; m_consumer->setClient(this); onStateChange();
diff --git a/third_party/WebKit/Source/modules/fetch/FetchHeaderList.cpp b/third_party/WebKit/Source/modules/fetch/FetchHeaderList.cpp index 79c3397..b757b11 100644 --- a/third_party/WebKit/Source/modules/fetch/FetchHeaderList.cpp +++ b/third_party/WebKit/Source/modules/fetch/FetchHeaderList.cpp
@@ -53,7 +53,7 @@ return; } } - m_headerList.append(wrapUnique(new Header(lowercasedName, value))); + m_headerList.append(makeUnique<Header>(lowercasedName, value)); } String FetchHeaderList::extractMIMEType() const {
diff --git a/third_party/WebKit/Source/modules/fetch/ResponseTest.cpp b/third_party/WebKit/Source/modules/fetch/ResponseTest.cpp index 061e744..ab7d613 100644 --- a/third_party/WebKit/Source/modules/fetch/ResponseTest.cpp +++ b/third_party/WebKit/Source/modules/fetch/ResponseTest.cpp
@@ -38,7 +38,7 @@ {0, 0}}; std::unique_ptr<WebServiceWorkerResponse> webResponse = - wrapUnique(new WebServiceWorkerResponse()); + makeUnique<WebServiceWorkerResponse>(); webResponse->setURL(url); webResponse->setStatus(status); webResponse->setStatusText(statusText);
diff --git a/third_party/WebKit/Source/modules/indexeddb/IDBValue.cpp b/third_party/WebKit/Source/modules/indexeddb/IDBValue.cpp index 4081f05..476fa418 100644 --- a/third_party/WebKit/Source/modules/indexeddb/IDBValue.cpp +++ b/third_party/WebKit/Source/modules/indexeddb/IDBValue.cpp
@@ -22,7 +22,7 @@ IDBKey* primaryKey, const IDBKeyPath& keyPath) : m_data(data), - m_blobData(wrapUnique(new Vector<RefPtr<BlobDataHandle>>())), + m_blobData(makeUnique<Vector<RefPtr<BlobDataHandle>>>()), m_blobInfo(wrapUnique(new Vector<WebBlobInfo>(webBlobInfo.size()))), m_primaryKey(primaryKey && primaryKey->isValid() ? primaryKey : nullptr), m_keyPath(keyPath) { @@ -37,7 +37,7 @@ IDBKey* primaryKey, const IDBKeyPath& keyPath) : m_data(value->m_data), - m_blobData(wrapUnique(new Vector<RefPtr<BlobDataHandle>>())), + m_blobData(makeUnique<Vector<RefPtr<BlobDataHandle>>>()), m_blobInfo( wrapUnique(new Vector<WebBlobInfo>(value->m_blobInfo->size()))), m_primaryKey(primaryKey),
diff --git a/third_party/WebKit/Source/modules/nfc/NFC.cpp b/third_party/WebKit/Source/modules/nfc/NFC.cpp index 37382c9..87fa30c 100644 --- a/third_party/WebKit/Source/modules/nfc/NFC.cpp +++ b/third_party/WebKit/Source/modules/nfc/NFC.cpp
@@ -131,7 +131,7 @@ record->record_type = NFCRecordType::TEXT; record->media_type = kPlainTextMimeType; record->media_type.append(kCharSetUTF8); - record->data = mojo::WTFArray<uint8_t>::From(string); + record->data = mojo::WTFArray<uint8_t>::From(string).PassStorage(); return record; } }; @@ -142,7 +142,7 @@ NFCRecordPtr record = NFCRecord::New(); record->record_type = NFCRecordType::OPAQUE_RECORD; record->media_type = kOpaqueMimeType; - record->data = mojo::WTFArray<uint8_t>::From(buffer); + record->data = mojo::WTFArray<uint8_t>::From(buffer).PassStorage(); return record; } }; @@ -151,8 +151,7 @@ struct TypeConverter<NFCMessagePtr, WTF::String> { static NFCMessagePtr Convert(const WTF::String& string) { NFCMessagePtr message = NFCMessage::New(); - message->data = mojo::WTFArray<NFCRecordPtr>::New(1); - message->data[0] = NFCRecord::From(string); + message->data.append(NFCRecord::From(string)); return message; } }; @@ -223,14 +222,14 @@ break; } - recordPtr->data = mojo::WTFArray<uint8_t>::From(record.data()); - + auto recordData = mojo::WTFArray<uint8_t>::From(record.data()); // If JS object cannot be converted to uint8_t array, return null, // interrupt NFCMessage conversion algorithm and reject promise with // SyntaxError exception. - if (recordPtr->data.is_null()) + if (recordData.is_null()) return nullptr; + recordPtr->data = recordData.PassStorage(); return recordPtr; } }; @@ -248,7 +247,6 @@ messagePtr->data[i] = std::move(record); } - messagePtr->data = mojo::WTFArray<NFCRecordPtr>::From(message.data()); return messagePtr; } }; @@ -257,8 +255,7 @@ struct TypeConverter<NFCMessagePtr, blink::DOMArrayBuffer*> { static NFCMessagePtr Convert(blink::DOMArrayBuffer* buffer) { NFCMessagePtr message = NFCMessage::New(); - message->data = mojo::WTFArray<NFCRecordPtr>::New(1); - message->data[0] = NFCRecord::From(buffer); + message->data.append(NFCRecord::From(buffer)); return message; } }; @@ -581,7 +578,7 @@ m_requests.clear(); } -void NFC::OnWatch(mojo::WTFArray<uint32_t> ids, mojom::NFCMessagePtr) { +void NFC::OnWatch(const WTF::Vector<uint32_t>& ids, mojom::NFCMessagePtr) { // TODO(shalamov): Not implemented. }
diff --git a/third_party/WebKit/Source/modules/nfc/NFC.h b/third_party/WebKit/Source/modules/nfc/NFC.h index 0999bf08..9dabcebd 100644 --- a/third_party/WebKit/Source/modules/nfc/NFC.h +++ b/third_party/WebKit/Source/modules/nfc/NFC.h
@@ -69,7 +69,7 @@ void OnConnectionError(); // device::nfc::mojom::blink::NFCClient implementation. - void OnWatch(mojo::WTFArray<uint32_t> ids, + void OnWatch(const WTF::Vector<uint32_t>& ids, device::nfc::mojom::blink::NFCMessagePtr) override; private:
diff --git a/third_party/WebKit/Source/modules/offscreencanvas2d/OffscreenCanvasRenderingContext2D.cpp b/third_party/WebKit/Source/modules/offscreencanvas2d/OffscreenCanvasRenderingContext2D.cpp index 7200092..4599d147 100644 --- a/third_party/WebKit/Source/modules/offscreencanvas2d/OffscreenCanvasRenderingContext2D.cpp +++ b/third_party/WebKit/Source/modules/offscreencanvas2d/OffscreenCanvasRenderingContext2D.cpp
@@ -49,7 +49,7 @@ ExceptionState& exceptionState) { UseCounter::Feature feature = UseCounter::OffscreenCanvasCommit2D; UseCounter::count(scriptState->getExecutionContext(), feature); - if (getOffscreenCanvas()->getAssociatedCanvasId() < 0) { + if (!getOffscreenCanvas()->hasPlaceholderCanvas()) { // If an OffscreenCanvas has no associated canvas Id, it indicates that // it is not an OffscreenCanvas created by transfering control from html // canvas.
diff --git a/third_party/WebKit/Source/modules/serviceworkers/NavigationPreloadManager.cpp b/third_party/WebKit/Source/modules/serviceworkers/NavigationPreloadManager.cpp index 1dd01989..3499f96e 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/NavigationPreloadManager.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/NavigationPreloadManager.cpp
@@ -42,7 +42,7 @@ ScriptPromise promise = resolver->promise(); m_registration->webRegistration()->setNavigationPreloadHeader( value, client->provider(), - wrapUnique(new SetNavigationPreloadHeaderCallbacks(resolver))); + makeUnique<SetNavigationPreloadHeaderCallbacks>(resolver)); return promise; } @@ -57,7 +57,7 @@ ScriptPromise promise = resolver->promise(); m_registration->webRegistration()->getNavigationPreloadState( client->provider(), - wrapUnique(new GetNavigationPreloadStateCallbacks(resolver))); + makeUnique<GetNavigationPreloadStateCallbacks>(resolver)); return promise; } @@ -77,7 +77,7 @@ ScriptPromise promise = resolver->promise(); m_registration->webRegistration()->enableNavigationPreload( enable, client->provider(), - wrapUnique(new EnableNavigationPreloadCallbacks(resolver))); + makeUnique<EnableNavigationPreloadCallbacks>(resolver)); return promise; }
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerContainer.cpp b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerContainer.cpp index 5bfdcc4..61ffad0 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerContainer.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerContainer.cpp
@@ -356,7 +356,7 @@ ->completeURL(options.scope()); registerServiceWorkerImpl(executionContext, scriptURL, patternURL, - wrapUnique(new RegistrationCallback(resolver))); + makeUnique<RegistrationCallback>(resolver)); return promise; }
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerContainerTest.cpp b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerContainerTest.cpp index 213c392..add153a6 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerContainerTest.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerContainerTest.cpp
@@ -173,7 +173,7 @@ const ScriptValueTest& valueTest) { // When the registration is rejected, a register call must not reach // the provider. - provide(wrapUnique(new NotReachedWebServiceWorkerProvider())); + provide(makeUnique<NotReachedWebServiceWorkerProvider>()); ServiceWorkerContainer* container = ServiceWorkerContainer::create(getExecutionContext()); @@ -187,7 +187,7 @@ void testGetRegistrationRejected(const String& documentURL, const ScriptValueTest& valueTest) { - provide(wrapUnique(new NotReachedWebServiceWorkerProvider())); + provide(makeUnique<NotReachedWebServiceWorkerProvider>()); ServiceWorkerContainer* container = ServiceWorkerContainer::create(getExecutionContext());
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerLinkResource.cpp b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerLinkResource.cpp index ff708d87..c1a6801 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerLinkResource.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerLinkResource.cpp
@@ -90,15 +90,14 @@ document.addConsoleMessage(ConsoleMessage::create( JSMessageSource, ErrorMessageLevel, "Cannot register service worker with <link> element. " + message)); - wrapUnique(new RegistrationCallback(m_owner)) - ->onError(WebServiceWorkerError( - WebServiceWorkerError::ErrorTypeSecurity, message)); + makeUnique<RegistrationCallback>(m_owner)->onError(WebServiceWorkerError( + WebServiceWorkerError::ErrorTypeSecurity, message)); return; } container->registerServiceWorkerImpl( &document, scriptURL, scopeURL, - wrapUnique(new RegistrationCallback(m_owner))); + makeUnique<RegistrationCallback>(m_owner)); } bool ServiceWorkerLinkResource::hasLoaded() const {
diff --git a/third_party/WebKit/Source/modules/vr/NavigatorVR.cpp b/third_party/WebKit/Source/modules/vr/NavigatorVR.cpp index f5fb788..838a27e 100644 --- a/third_party/WebKit/Source/modules/vr/NavigatorVR.cpp +++ b/third_party/WebKit/Source/modules/vr/NavigatorVR.cpp
@@ -107,6 +107,16 @@ } } +void NavigatorVR::fireVrDisplayOnBlur(VRDisplay* display) { + fireVREvent(VRDisplayEvent::create(EventTypeNames::vrdisplayblur, true, false, + display, "")); +} + +void NavigatorVR::fireVrDisplayOnFocus(VRDisplay* display) { + fireVREvent(VRDisplayEvent::create(EventTypeNames::vrdisplayfocus, true, + false, display, "")); +} + void NavigatorVR::fireVREvent(VRDisplayEvent* event) { if (frame() && frame()->localDOMWindow()) { frame()->localDOMWindow()->enqueueWindowEvent(event);
diff --git a/third_party/WebKit/Source/modules/vr/NavigatorVR.h b/third_party/WebKit/Source/modules/vr/NavigatorVR.h index 2deba6b..c38ca66 100644 --- a/third_party/WebKit/Source/modules/vr/NavigatorVR.h +++ b/third_party/WebKit/Source/modules/vr/NavigatorVR.h
@@ -39,6 +39,8 @@ VRController* controller(); Document* document(); + void fireVrDisplayOnBlur(VRDisplay*); + void fireVrDisplayOnFocus(VRDisplay*); void fireVREvent(VRDisplayEvent*); DECLARE_VIRTUAL_TRACE();
diff --git a/third_party/WebKit/Source/modules/vr/VRController.cpp b/third_party/WebKit/Source/modules/vr/VRController.cpp index 834f8f4..e397c763 100644 --- a/third_party/WebKit/Source/modules/vr/VRController.cpp +++ b/third_party/WebKit/Source/modules/vr/VRController.cpp
@@ -49,7 +49,7 @@ // Otherwise we're still waiting for the full list of displays to be populated // so queue up the promise for resolution when onDisplaysSynced is called. m_pendingGetDevicesCallbacks.append( - wrapUnique(new VRGetDevicesCallback(resolver))); + makeUnique<VRGetDevicesCallback>(resolver)); } // Each time a new VRDisplay is connected we'll recieve a VRDisplayPtr for it
diff --git a/third_party/WebKit/Source/modules/vr/VRDisplay.cpp b/third_party/WebKit/Source/modules/vr/VRDisplay.cpp index d068137..29f0f3bc 100644 --- a/third_party/WebKit/Source/modules/vr/VRDisplay.cpp +++ b/third_party/WebKit/Source/modules/vr/VRDisplay.cpp
@@ -70,6 +70,7 @@ m_depthNear(0.01), m_depthFar(10000.0), m_fullscreenCheckTimer(this, &VRDisplay::onFullscreenCheck), + m_contextGL(nullptr), m_animationCallbackRequested(false), m_inAnimationFrame(false), m_display(std::move(display)), @@ -115,6 +116,9 @@ bool VRDisplay::getFrameData(VRFrameData* frameData) { updatePose(); + if (!m_framePose) + return false; + if (!frameData) return false; @@ -137,6 +141,11 @@ } void VRDisplay::updatePose() { + if (m_displayBlurred) { + // WebVR spec says to return a null pose when the display is blurred. + m_framePose = nullptr; + return; + } if (m_canUpdateFramePose) { if (!m_display) return; @@ -186,11 +195,39 @@ m_scriptedAnimationController->cancelCallback(id); } +void VRDisplay::OnDisplayBlur() { + m_displayBlurred = true; + m_navigatorVR->fireVrDisplayOnBlur(this); +} + +void VRDisplay::OnDisplayFocus() { + m_displayBlurred = false; + // Restart our internal doc requestAnimationFrame callback, if it fired while + // the display was blurred. + // TODO(bajones): Don't use doc->requestAnimationFrame() at all. Animation + // frames should be tied to the presenting VR display (e.g. should be serviced + // by GVR library callbacks on Android), and not the doc frame rate. + if (!m_animationCallbackRequested) { + Document* doc = m_navigatorVR->document(); + if (!doc) + return; + doc->requestAnimationFrame(new VRDisplayFrameRequestCallback(this)); + } + m_navigatorVR->fireVrDisplayOnFocus(this); +} + void VRDisplay::serviceScriptedAnimations(double monotonicAnimationStartTime) { if (!m_scriptedAnimationController) return; AutoReset<bool> animating(&m_inAnimationFrame, true); m_animationCallbackRequested = false; + + // We use an internal rAF callback to run the animation loop at the display + // speed, and run the user's callback after our internal callback fires. + // However, when the display is blurred, we want to pause the animation loop, + // so we don't fire the user's callback until the display is focused. + if (m_displayBlurred) + return; m_scriptedAnimationController->serviceScriptedAnimations( monotonicAnimationStartTime); }
diff --git a/third_party/WebKit/Source/modules/vr/VRDisplay.h b/third_party/WebKit/Source/modules/vr/VRDisplay.h index 8c69834f..131c6951 100644 --- a/third_party/WebKit/Source/modules/vr/VRDisplay.h +++ b/third_party/WebKit/Source/modules/vr/VRDisplay.h
@@ -110,6 +110,8 @@ // VRDisplayClient void OnDisplayChanged(device::mojom::blink::VRDisplayInfoPtr) override; void OnExitPresent() override; + void OnDisplayBlur() override; + void OnDisplayFocus() override; ScriptedAnimationController& ensureScriptedAnimationController(Document*); @@ -119,7 +121,6 @@ bool m_isConnected; bool m_isPresenting; bool m_canUpdateFramePose; - unsigned m_compositorHandle; Member<VRDisplayCapabilities> m_capabilities; Member<VRStageParameters> m_stageParameters; Member<VREyeParameters> m_eyeParametersLeft; @@ -138,6 +139,7 @@ Member<ScriptedAnimationController> m_scriptedAnimationController; bool m_animationCallbackRequested; bool m_inAnimationFrame; + bool m_displayBlurred; device::mojom::blink::VRDisplayPtr m_display;
diff --git a/third_party/WebKit/Source/modules/vr/VRFrameData.cpp b/third_party/WebKit/Source/modules/vr/VRFrameData.cpp index f2c447b..6395e5d6 100644 --- a/third_party/WebKit/Source/modules/vr/VRFrameData.cpp +++ b/third_party/WebKit/Source/modules/vr/VRFrameData.cpp
@@ -47,14 +47,15 @@ } // Create a matrix from a rotation and translation. -void matrixfromRotationTranslation(DOMFloat32Array* outArray, - const mojo::WTFArray<float>& rotation, - const mojo::WTFArray<float>& translation) { +void matrixfromRotationTranslation( + DOMFloat32Array* outArray, + const WTF::Optional<WTF::Vector<float>>& rotation, + const WTF::Optional<WTF::Vector<float>>& translation) { // Quaternion math - float x = rotation.is_null() ? 0.0f : rotation[0]; - float y = rotation.is_null() ? 0.0f : rotation[1]; - float z = rotation.is_null() ? 0.0f : rotation[2]; - float w = rotation.is_null() ? 1.0f : rotation[3]; + float x = !rotation ? 0.0f : rotation.value()[0]; + float y = !rotation ? 0.0f : rotation.value()[1]; + float z = !rotation ? 0.0f : rotation.value()[2]; + float w = !rotation ? 1.0f : rotation.value()[3]; float x2 = x + x; float y2 = y + y; float z2 = z + z; @@ -82,9 +83,9 @@ out[9] = yz - wx; out[10] = 1 - (xx + yy); out[11] = 0; - out[12] = translation.is_null() ? 0.0f : translation[0]; - out[13] = translation.is_null() ? 0.0f : translation[1]; - out[14] = translation.is_null() ? 0.0f : translation[2]; + out[12] = !translation ? 0.0f : translation.value()[0]; + out[13] = !translation ? 0.0f : translation.value()[1]; + out[14] = !translation ? 0.0f : translation.value()[2]; out[15] = 1; }
diff --git a/third_party/WebKit/Source/modules/vr/VRPose.cpp b/third_party/WebKit/Source/modules/vr/VRPose.cpp index 3775522..8007fc5c 100644 --- a/third_party/WebKit/Source/modules/vr/VRPose.cpp +++ b/third_party/WebKit/Source/modules/vr/VRPose.cpp
@@ -8,11 +8,12 @@ namespace { -DOMFloat32Array* mojoArrayToFloat32Array(const mojo::WTFArray<float>& vec) { - if (vec.is_null()) +DOMFloat32Array* mojoArrayToFloat32Array( + const WTF::Optional<WTF::Vector<float>>& vec) { + if (!vec) return nullptr; - return DOMFloat32Array::create(&(vec.front()), vec.size()); + return DOMFloat32Array::create(&(vec.value().first()), vec.value().size()); } } // namespace
diff --git a/third_party/WebKit/Source/modules/vr/VRStageParameters.cpp b/third_party/WebKit/Source/modules/vr/VRStageParameters.cpp index 597ab4ef..db8c9f1 100644 --- a/third_party/WebKit/Source/modules/vr/VRStageParameters.cpp +++ b/third_party/WebKit/Source/modules/vr/VRStageParameters.cpp
@@ -18,7 +18,7 @@ void VRStageParameters::update( const device::mojom::blink::VRStageParametersPtr& stage) { m_standingTransform = - DOMFloat32Array::create(&(stage->standingTransform.front()), 16); + DOMFloat32Array::create(&(stage->standingTransform.first()), 16); m_sizeX = stage->sizeX; m_sizeZ = stage->sizeZ; }
diff --git a/third_party/WebKit/Source/modules/webaudio/AudioBasicProcessorHandlerTest.cpp b/third_party/WebKit/Source/modules/webaudio/AudioBasicProcessorHandlerTest.cpp index 6c7bde45..9d4f35a 100644 --- a/third_party/WebKit/Source/modules/webaudio/AudioBasicProcessorHandlerTest.cpp +++ b/third_party/WebKit/Source/modules/webaudio/AudioBasicProcessorHandlerTest.cpp
@@ -30,7 +30,7 @@ MockProcessorNode(BaseAudioContext& context) : AudioNode(context) { setHandler(AudioBasicProcessorHandler::create( AudioHandler::NodeTypeWaveShaper, *this, 48000, - wrapUnique(new MockAudioProcessor()))); + makeUnique<MockAudioProcessor>())); handler().initialize(); } };
diff --git a/third_party/WebKit/Source/modules/webaudio/BaseAudioContextTest.cpp b/third_party/WebKit/Source/modules/webaudio/BaseAudioContextTest.cpp index eb46576..cf60f794 100644 --- a/third_party/WebKit/Source/modules/webaudio/BaseAudioContextTest.cpp +++ b/third_party/WebKit/Source/modules/webaudio/BaseAudioContextTest.cpp
@@ -98,8 +98,7 @@ m_childFrame = LocalFrame::create( MockCrossOriginFrameLoaderClient::create(document().frame()), document().frame()->host(), m_dummyFrameOwner.get()); - m_childFrame->setView( - FrameView::create(m_childFrame.get(), IntSize(500, 500))); + m_childFrame->setView(FrameView::create(*m_childFrame, IntSize(500, 500))); m_childFrame->init(); m_childDocumentLoader = DocumentLoader::create( m_childFrame.get(), ResourceRequest("https://www.example.com"),
diff --git a/third_party/WebKit/Source/modules/webaudio/BiquadProcessor.cpp b/third_party/WebKit/Source/modules/webaudio/BiquadProcessor.cpp index 8cfd1d8..a91de7aa 100644 --- a/third_party/WebKit/Source/modules/webaudio/BiquadProcessor.cpp +++ b/third_party/WebKit/Source/modules/webaudio/BiquadProcessor.cpp
@@ -51,7 +51,7 @@ } std::unique_ptr<AudioDSPKernel> BiquadProcessor::createKernel() { - return wrapUnique(new BiquadDSPKernel(this)); + return makeUnique<BiquadDSPKernel>(this); } void BiquadProcessor::checkForDirtyCoefficients() { @@ -134,7 +134,7 @@ // thread on the main kernels. std::unique_ptr<BiquadDSPKernel> responseKernel = - wrapUnique(new BiquadDSPKernel(this)); + makeUnique<BiquadDSPKernel>(this); responseKernel->getFrequencyResponse(nFrequencies, frequencyHz, magResponse, phaseResponse); }
diff --git a/third_party/WebKit/Source/modules/webaudio/DelayProcessor.cpp b/third_party/WebKit/Source/modules/webaudio/DelayProcessor.cpp index 201085e..c2ac1f1 100644 --- a/third_party/WebKit/Source/modules/webaudio/DelayProcessor.cpp +++ b/third_party/WebKit/Source/modules/webaudio/DelayProcessor.cpp
@@ -44,7 +44,7 @@ } std::unique_ptr<AudioDSPKernel> DelayProcessor::createKernel() { - return wrapUnique(new DelayDSPKernel(this)); + return makeUnique<DelayDSPKernel>(this); } } // namespace blink
diff --git a/third_party/WebKit/Source/modules/webaudio/IIRProcessor.cpp b/third_party/WebKit/Source/modules/webaudio/IIRProcessor.cpp index 988f0a6..d099954b 100644 --- a/third_party/WebKit/Source/modules/webaudio/IIRProcessor.cpp +++ b/third_party/WebKit/Source/modules/webaudio/IIRProcessor.cpp
@@ -51,7 +51,7 @@ m_feedback[0] = 1; } - m_responseKernel = wrapUnique(new IIRDSPKernel(this)); + m_responseKernel = makeUnique<IIRDSPKernel>(this); } IIRProcessor::~IIRProcessor() { @@ -60,7 +60,7 @@ } std::unique_ptr<AudioDSPKernel> IIRProcessor::createKernel() { - return wrapUnique(new IIRDSPKernel(this)); + return makeUnique<IIRDSPKernel>(this); } void IIRProcessor::process(const AudioBus* source,
diff --git a/third_party/WebKit/Source/modules/webaudio/MediaElementAudioSourceNode.cpp b/third_party/WebKit/Source/modules/webaudio/MediaElementAudioSourceNode.cpp index c581d6150..df865355 100644 --- a/third_party/WebKit/Source/modules/webaudio/MediaElementAudioSourceNode.cpp +++ b/third_party/WebKit/Source/modules/webaudio/MediaElementAudioSourceNode.cpp
@@ -101,7 +101,7 @@ if (sourceSampleRate != sampleRate()) { double scaleFactor = sourceSampleRate / sampleRate(); m_multiChannelResampler = - wrapUnique(new MultiChannelResampler(scaleFactor, numberOfChannels)); + makeUnique<MultiChannelResampler>(scaleFactor, numberOfChannels); } else { // Bypass resampling. m_multiChannelResampler.reset();
diff --git a/third_party/WebKit/Source/modules/webaudio/PeriodicWave.cpp b/third_party/WebKit/Source/modules/webaudio/PeriodicWave.cpp index a2fe54e..cef86012 100644 --- a/third_party/WebKit/Source/modules/webaudio/PeriodicWave.cpp +++ b/third_party/WebKit/Source/modules/webaudio/PeriodicWave.cpp
@@ -297,7 +297,7 @@ // Create the band-limited table. unsigned waveSize = periodicWaveSize(); std::unique_ptr<AudioFloatArray> table = - wrapUnique(new AudioFloatArray(waveSize)); + makeUnique<AudioFloatArray>(waveSize); adjustV8ExternalMemory(waveSize * sizeof(float)); m_bandLimitedTables.append(std::move(table));
diff --git a/third_party/WebKit/Source/modules/webaudio/RealtimeAnalyser.cpp b/third_party/WebKit/Source/modules/webaudio/RealtimeAnalyser.cpp index 010f90fc..ab4f0e2 100644 --- a/third_party/WebKit/Source/modules/webaudio/RealtimeAnalyser.cpp +++ b/third_party/WebKit/Source/modules/webaudio/RealtimeAnalyser.cpp
@@ -57,7 +57,7 @@ m_minDecibels(DefaultMinDecibels), m_maxDecibels(DefaultMaxDecibels), m_lastAnalysisTime(-1) { - m_analysisFrame = wrapUnique(new FFTFrame(DefaultFFTSize)); + m_analysisFrame = makeUnique<FFTFrame>(DefaultFFTSize); } bool RealtimeAnalyser::setFftSize(size_t size) { @@ -71,7 +71,7 @@ return false; if (m_fftSize != size) { - m_analysisFrame = wrapUnique(new FFTFrame(size)); + m_analysisFrame = makeUnique<FFTFrame>(size); // m_magnitudeBuffer has size = fftSize / 2 because it contains floats // reduced from complex values in m_analysisFrame. m_magnitudeBuffer.allocate(size / 2);
diff --git a/third_party/WebKit/Source/modules/webaudio/ScriptProcessorNode.cpp b/third_party/WebKit/Source/modules/webaudio/ScriptProcessorNode.cpp index 2cc0098..1321578 100644 --- a/third_party/WebKit/Source/modules/webaudio/ScriptProcessorNode.cpp +++ b/third_party/WebKit/Source/modules/webaudio/ScriptProcessorNode.cpp
@@ -214,7 +214,7 @@ // If this node is in the offline audio context, use the // waitable event to synchronize to the offline rendering thread. std::unique_ptr<WaitableEvent> waitableEvent = - wrapUnique(new WaitableEvent()); + makeUnique<WaitableEvent>(); context()->getExecutionContext()->postTask( BLINK_FROM_HERE,
diff --git a/third_party/WebKit/Source/modules/webaudio/WaveShaperProcessor.cpp b/third_party/WebKit/Source/modules/webaudio/WaveShaperProcessor.cpp index 7952c4c..9c9b59db 100644 --- a/third_party/WebKit/Source/modules/webaudio/WaveShaperProcessor.cpp +++ b/third_party/WebKit/Source/modules/webaudio/WaveShaperProcessor.cpp
@@ -41,7 +41,7 @@ } std::unique_ptr<AudioDSPKernel> WaveShaperProcessor::createKernel() { - return wrapUnique(new WaveShaperDSPKernel(this)); + return makeUnique<WaveShaperDSPKernel>(this); } void WaveShaperProcessor::setCurve(const float* curveData, @@ -57,7 +57,7 @@ } // Copy the curve data, if any, to our internal buffer. - m_curve = wrapUnique(new Vector<float>(curveLength)); + m_curve = makeUnique<Vector<float>>(curveLength); memcpy(m_curve->data(), curveData, sizeof(float) * curveLength); }
diff --git a/third_party/WebKit/Source/modules/webdatabase/DatabaseThread.cpp b/third_party/WebKit/Source/modules/webdatabase/DatabaseThread.cpp index e82abdc4..05daa525 100644 --- a/third_party/WebKit/Source/modules/webdatabase/DatabaseThread.cpp +++ b/third_party/WebKit/Source/modules/webdatabase/DatabaseThread.cpp
@@ -43,7 +43,7 @@ namespace blink { DatabaseThread::DatabaseThread() - : m_transactionClient(wrapUnique(new SQLTransactionClient())), + : m_transactionClient(makeUnique<SQLTransactionClient>()), m_cleanupSync(nullptr), m_terminationRequested(false) { DCHECK(isMainThread());
diff --git a/third_party/WebKit/Source/modules/webgl/EXTDisjointTimerQuery.cpp b/third_party/WebKit/Source/modules/webgl/EXTDisjointTimerQuery.cpp index 1c3b496a4..4988bfc 100644 --- a/third_party/WebKit/Source/modules/webgl/EXTDisjointTimerQuery.cpp +++ b/third_party/WebKit/Source/modules/webgl/EXTDisjointTimerQuery.cpp
@@ -68,7 +68,8 @@ if (scoped.isLost()) return; - if (!query || query->isDeleted() || !query->validate(0, scoped.context())) { + DCHECK(query); + if (query->isDeleted() || !query->validate(0, scoped.context())) { scoped.context()->synthesizeGLError(GL_INVALID_OPERATION, "beginQueryEXT", "invalid query"); return; @@ -125,7 +126,8 @@ if (scoped.isLost()) return; - if (!query || query->isDeleted() || !query->validate(0, scoped.context())) { + DCHECK(query); + if (query->isDeleted() || !query->validate(0, scoped.context())) { scoped.context()->synthesizeGLError(GL_INVALID_OPERATION, "queryCounterEXT", "invalid query"); return; @@ -188,7 +190,8 @@ if (scoped.isLost()) return ScriptValue::createNull(scriptState); - if (!query || query->isDeleted() || !query->validate(0, scoped.context()) || + DCHECK(query); + if (query->isDeleted() || !query->validate(0, scoped.context()) || m_currentElapsedQuery == query) { scoped.context()->synthesizeGLError(GL_INVALID_OPERATION, "getQueryObjectEXT", "invalid query");
diff --git a/third_party/WebKit/Source/modules/webgl/EXTDisjointTimerQuery.idl b/third_party/WebKit/Source/modules/webgl/EXTDisjointTimerQuery.idl index f25f7c3..0232388 100644 --- a/third_party/WebKit/Source/modules/webgl/EXTDisjointTimerQuery.idl +++ b/third_party/WebKit/Source/modules/webgl/EXTDisjointTimerQuery.idl
@@ -18,11 +18,11 @@ const GLenum GPU_DISJOINT_EXT = 0x8FBB; WebGLTimerQueryEXT createQueryEXT(); - void deleteQueryEXT([Default=Undefined] WebGLTimerQueryEXT? query); - boolean isQueryEXT([Default=Undefined] WebGLTimerQueryEXT? query); - void beginQueryEXT(GLenum target, [Default=Undefined] WebGLTimerQueryEXT? query); + void deleteQueryEXT(WebGLTimerQueryEXT? query); + boolean isQueryEXT(WebGLTimerQueryEXT? query); + void beginQueryEXT(GLenum target, WebGLTimerQueryEXT query); void endQueryEXT(GLenum target); - void queryCounterEXT([Default=Undefined] WebGLTimerQueryEXT? query, GLenum target); + void queryCounterEXT(WebGLTimerQueryEXT query, GLenum target); [CallWith=ScriptState] any getQueryEXT(GLenum target, GLenum pname); - [CallWith=ScriptState] any getQueryObjectEXT([Default=Undefined] WebGLTimerQueryEXT? query, GLenum pname); + [CallWith=ScriptState] any getQueryObjectEXT(WebGLTimerQueryEXT query, GLenum pname); };
diff --git a/third_party/WebKit/Source/modules/webgl/EXTDisjointTimerQueryWebGL2.cpp b/third_party/WebKit/Source/modules/webgl/EXTDisjointTimerQueryWebGL2.cpp index c7f9c420..9c45d88 100644 --- a/third_party/WebKit/Source/modules/webgl/EXTDisjointTimerQueryWebGL2.cpp +++ b/third_party/WebKit/Source/modules/webgl/EXTDisjointTimerQueryWebGL2.cpp
@@ -38,7 +38,8 @@ if (scoped.isLost()) return; - if (!query || query->isDeleted() || + DCHECK(query); + if (query->isDeleted() || !query->validate(scoped.context()->contextGroup(), scoped.context())) { scoped.context()->synthesizeGLError(GL_INVALID_OPERATION, "queryCounterEXT", "invalid query");
diff --git a/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.cpp b/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.cpp index 7f02375..ea9a2c4 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.cpp +++ b/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.cpp
@@ -1315,7 +1315,7 @@ sourceImageRect.setLocation(IntPoint(m_unpackSkipPixels, m_unpackSkipRows)); sourceImageRect.setSize(IntSize(width, height)); texImageHelperImageData(TexImage2D, target, level, internalformat, 0, format, - type, 1, 0, 0, 0, pixels, sourceImageRect); + type, 1, 0, 0, 0, pixels, sourceImageRect, 0); } void WebGL2RenderingContextBase::texImage2D(GLenum target, @@ -1474,7 +1474,7 @@ sourceImageRect.setLocation(IntPoint(m_unpackSkipPixels, m_unpackSkipRows)); sourceImageRect.setSize(IntSize(width, height)); texImageHelperImageData(TexSubImage2D, target, level, 0, 0, format, type, 1, - xoffset, yoffset, 0, pixels, sourceImageRect); + xoffset, yoffset, 0, pixels, sourceImageRect, 0); } void WebGL2RenderingContextBase::texSubImage2D(GLenum target, @@ -1696,8 +1696,14 @@ GLint border, GLenum format, GLenum type, - ImageData* imageData) { - // TODO(zmo): To be implemented. + ImageData* pixels) { + DCHECK(pixels); + IntRect sourceImageRect; + sourceImageRect.setLocation(IntPoint(m_unpackSkipPixels, m_unpackSkipRows)); + sourceImageRect.setSize(IntSize(width, height)); + texImageHelperImageData(TexImage3D, target, level, internalformat, 0, format, + type, depth, 0, 0, 0, pixels, sourceImageRect, + m_unpackImageHeight); } void WebGL2RenderingContextBase::texImage3D(GLenum target, @@ -1824,7 +1830,13 @@ GLenum format, GLenum type, ImageData* pixels) { - // TODO(zmo): To be implemented. + DCHECK(pixels); + IntRect sourceImageRect; + sourceImageRect.setLocation(IntPoint(m_unpackSkipPixels, m_unpackSkipRows)); + sourceImageRect.setSize(IntSize(width, height)); + texImageHelperImageData(TexSubImage3D, target, level, 0, 0, format, type, + depth, xoffset, yoffset, zoffset, pixels, + sourceImageRect, m_unpackImageHeight); } void WebGL2RenderingContextBase::texSubImage3D(GLenum target, @@ -1902,19 +1914,6 @@ GLint zoffset, GLenum format, GLenum type, - ImageData* pixels) { - texImageHelperImageData(TexSubImage3D, target, level, 0, 0, format, type, 1, - xoffset, yoffset, zoffset, pixels, - getImageDataSize(pixels)); -} - -void WebGL2RenderingContextBase::texSubImage3D(GLenum target, - GLint level, - GLint xoffset, - GLint yoffset, - GLint zoffset, - GLenum format, - GLenum type, HTMLCanvasElement* canvas, ExceptionState& exceptionState) { texImageHelperHTMLCanvasElement(TexSubImage3D, target, level, 0, format, type, @@ -2010,6 +2009,7 @@ } else if (srcLengthOverride > data->byteLength() - srcOffset) { synthesizeGLError(GL_INVALID_VALUE, "compressedTexImage2D", "srcLengthOverride is out of range"); + return; } contextGL()->CompressedTexImage2D( target, level, internalformat, width, height, border, srcLengthOverride, @@ -2056,6 +2056,7 @@ } else if (srcLengthOverride > data->byteLength() - srcOffset) { synthesizeGLError(GL_INVALID_VALUE, "compressedTexImage2D", "srcLengthOverride is out of range"); + return; } contextGL()->CompressedTexSubImage2D( target, level, xoffset, yoffset, width, height, format, srcLengthOverride, @@ -2089,6 +2090,7 @@ } else if (srcLengthOverride > data->byteLength() - srcOffset) { synthesizeGLError(GL_INVALID_VALUE, "compressedTexImage3D", "srcLengthOverride is out of range"); + return; } contextGL()->CompressedTexImage3D( target, level, internalformat, width, height, depth, border, @@ -2125,6 +2127,7 @@ } else if (srcLengthOverride > data->byteLength() - srcOffset) { synthesizeGLError(GL_INVALID_VALUE, "compressedTexSubImage3D", "srcLengthOverride is out of range"); + return; } contextGL()->CompressedTexSubImage3D( target, level, xoffset, yoffset, zoffset, width, height, depth, format,
diff --git a/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.idl b/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.idl index b82610dd..8d438fa 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.idl +++ b/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.idl
@@ -330,7 +330,6 @@ void texSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, ArrayBufferView pixels, optional GLuint srcOffset = 0); // TODO(zmo): Obsolete, remove after WebGL2 conformance tests are updated. - void texSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLenum format, GLenum type, ImageData data); [RaisesException] void texSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLenum format, GLenum type, HTMLCanvasElement canvas); [RaisesException] void texSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLenum format, GLenum type, HTMLVideoElement video); [RaisesException] void texSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLenum format, GLenum type, ImageBitmap bitmap);
diff --git a/third_party/WebKit/Source/modules/webgl/WebGLDebugShaders.idl b/third_party/WebKit/Source/modules/webgl/WebGLDebugShaders.idl index 0790ee1b..28efeac0 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGLDebugShaders.idl +++ b/third_party/WebKit/Source/modules/webgl/WebGLDebugShaders.idl
@@ -27,5 +27,5 @@ NoInterfaceObject, SetWrapperReferenceFrom=canvas, ] interface WebGLDebugShaders { - DOMString? getTranslatedShaderSource(WebGLShader? shader); + DOMString? getTranslatedShaderSource(WebGLShader shader); };
diff --git a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp index ca13517..6a68b16 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp +++ b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp
@@ -700,7 +700,7 @@ return; } // no HTMLCanvas associated, thrown InvalidStateError - if (getOffscreenCanvas()->getAssociatedCanvasId() == -1) { + if (!getOffscreenCanvas()->hasPlaceholderCanvas()) { exceptionState.throwDOMException(InvalidStateError, "Commit() was called on a context whose " "OffscreenCanvas is not associated with a " @@ -729,7 +729,7 @@ OpacityMode opacityMode = creationAttributes().hasAlpha() ? NonOpaque : Opaque; std::unique_ptr<AcceleratedImageBufferSurface> surface = - wrapUnique(new AcceleratedImageBufferSurface(size, opacityMode)); + makeUnique<AcceleratedImageBufferSurface>(size, opacityMode); if (!surface->isValid()) return nullptr; std::unique_ptr<ImageBuffer> buffer = ImageBuffer::create(std::move(surface)); @@ -4366,33 +4366,12 @@ } bool selectingSubRectangle = false; - if (!validateTexImageSubRectangle(funcName, image, subRect, + if (!validateTexImageSubRectangle(funcName, functionID, image, subRect, depth, + unpackImageHeight, &selectingSubRectangle)) { return; } - if (functionID == TexImage3D || functionID == TexSubImage3D) { - DCHECK_GE(unpackImageHeight, 0); - - // Verify that the image data can cover the required depth. - CheckedNumeric<GLint> maxDepthSupported = 1; - if (unpackImageHeight) { - maxDepthSupported = subRect.height(); - maxDepthSupported /= unpackImageHeight; - } - - if (!maxDepthSupported.IsValid() || - maxDepthSupported.ValueOrDie() < depth) { - synthesizeGLError( - GL_INVALID_OPERATION, funcName, - "Not enough data supplied to upload to a 3D texture with depth > 1"); - return; - } - } else { - DCHECK_EQ(depth, 1); - DCHECK_EQ(unpackImageHeight, 0); - } - // Adjust the source image rectangle if doing a y-flip. IntRect adjustedSourceImageRect = subRect; if (flipY) { @@ -4706,7 +4685,8 @@ GLint yoffset, GLint zoffset, ImageData* pixels, - const IntRect& sourceImageRect) { + const IntRect& sourceImageRect, + GLint unpackImageHeight) { const char* funcName = getTexImageFunctionName(functionID); if (isContextLost()) return; @@ -4719,7 +4699,7 @@ if (!validateTexImageBinding(funcName, functionID, target)) return; TexImageFunctionType functionType; - if (functionID == TexImage2D) + if (functionID == TexImage2D || functionID == TexImage3D) functionType = TexImage; else functionType = TexSubImage; @@ -4729,7 +4709,8 @@ return; bool selectingSubRectangle = false; - if (!validateTexImageSubRectangle(funcName, pixels, sourceImageRect, + if (!validateTexImageSubRectangle(funcName, functionID, pixels, + sourceImageRect, depth, unpackImageHeight, &selectingSubRectangle)) { return; } @@ -4763,23 +4744,33 @@ } } resetUnpackParameters(); + const uint8_t* bytes = needConversion ? data.data() : pixels->data()->data(); if (functionID == TexImage2D) { - texImage2DBase(target, level, internalformat, - adjustedSourceImageRect.width(), - adjustedSourceImageRect.height(), border, format, type, - needConversion ? data.data() : pixels->data()->data()); + DCHECK_EQ(unpackImageHeight, 0); + texImage2DBase( + target, level, internalformat, adjustedSourceImageRect.width(), + adjustedSourceImageRect.height(), border, format, type, bytes); } else if (functionID == TexSubImage2D) { + DCHECK_EQ(unpackImageHeight, 0); contextGL()->TexSubImage2D( target, level, xoffset, yoffset, adjustedSourceImageRect.width(), - adjustedSourceImageRect.height(), format, type, - needConversion ? data.data() : pixels->data()->data()); + adjustedSourceImageRect.height(), format, type, bytes); } else { - DCHECK_EQ(functionID, TexSubImage3D); - contextGL()->TexSubImage3D( - target, level, xoffset, yoffset, zoffset, - adjustedSourceImageRect.width(), adjustedSourceImageRect.height(), - depth, format, type, - needConversion ? data.data() : pixels->data()->data()); + GLint uploadHeight = adjustedSourceImageRect.height(); + if (unpackImageHeight) { + // GL_UNPACK_IMAGE_HEIGHT overrides the passed-in height. + uploadHeight = unpackImageHeight; + } + if (functionID == TexImage3D) { + contextGL()->TexImage3D(target, level, internalformat, + adjustedSourceImageRect.width(), uploadHeight, + depth, border, format, type, bytes); + } else { + DCHECK_EQ(functionID, TexSubImage3D); + contextGL()->TexSubImage3D(target, level, xoffset, yoffset, zoffset, + adjustedSourceImageRect.width(), uploadHeight, + depth, format, type, bytes); + } } restoreUnpackParameters(); } @@ -4791,7 +4782,8 @@ GLenum type, ImageData* pixels) { texImageHelperImageData(TexImage2D, target, level, internalformat, 0, format, - type, 1, 0, 0, 0, pixels, getImageDataSize(pixels)); + type, 1, 0, 0, 0, pixels, getImageDataSize(pixels), + 0); } void WebGLRenderingContextBase::texImageHelperHTMLImageElement( @@ -5392,8 +5384,8 @@ GLenum type, ImageData* pixels) { texImageHelperImageData(TexSubImage2D, target, level, 0, 0, format, type, 1, - xoffset, yoffset, 0, pixels, - getImageDataSize(pixels)); + xoffset, yoffset, 0, pixels, getImageDataSize(pixels), + 0); } void WebGLRenderingContextBase::texSubImage2D(GLenum target,
diff --git a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.h b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.h index b459f9e..d50f46b6 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.h +++ b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.h
@@ -49,6 +49,7 @@ #include "public/platform/Platform.h" #include "public/platform/WebGraphicsContext3DProvider.h" #include "third_party/khronos/GLES2/gl2.h" +#include "wtf/CheckedNumeric.h" #include "wtf/text/WTFString.h" #include <memory> #include <set> @@ -1024,9 +1025,15 @@ GLint unpackImageHeight); template <typename T> bool validateTexImageSubRectangle(const char* functionName, + TexImageFunctionID functionID, T* image, const IntRect& subRect, + GLsizei depth, + GLint unpackImageHeight, bool* selectingSubRectangle) { + DCHECK(functionName); + DCHECK(selectingSubRectangle); + DCHECK(image); *selectingSubRectangle = image && !(subRect.x() == 0 && subRect.y() == 0 && subRect.width() == image->width() && @@ -1050,6 +1057,28 @@ "parameters is invalid"); return false; } + + if (functionID == TexImage3D || functionID == TexSubImage3D) { + DCHECK_GE(unpackImageHeight, 0); + + // Verify that the image data can cover the required depth. + WTF::CheckedNumeric<GLint> maxDepthSupported = 1; + if (unpackImageHeight) { + maxDepthSupported = subRect.height(); + maxDepthSupported /= unpackImageHeight; + } + + if (!maxDepthSupported.IsValid() || + maxDepthSupported.ValueOrDie() < depth) { + synthesizeGLError(GL_INVALID_OPERATION, functionName, + "Not enough data supplied to upload to a 3D texture " + "with depth > 1"); + return false; + } + } else { + DCHECK_EQ(depth, 1); + DCHECK_EQ(unpackImageHeight, 0); + } return true; } @@ -1511,7 +1540,8 @@ GLint, GLint, ImageData*, - const IntRect&); + const IntRect&, + GLint); void texImageHelperHTMLImageElement(TexImageFunctionID, GLenum, GLint,
diff --git a/third_party/WebKit/Source/modules/websockets/DocumentWebSocketChannelTest.cpp b/third_party/WebKit/Source/modules/websockets/DocumentWebSocketChannelTest.cpp index 758363e..1e91780 100644 --- a/third_party/WebKit/Source/modules/websockets/DocumentWebSocketChannelTest.cpp +++ b/third_party/WebKit/Source/modules/websockets/DocumentWebSocketChannelTest.cpp
@@ -277,7 +277,7 @@ Vector<char> fooVector; fooVector.append("foo", 3); - channel()->sendBinaryAsCharVector(wrapUnique(new Vector<char>(fooVector))); + channel()->sendBinaryAsCharVector(makeUnique<Vector<char>>(fooVector)); EXPECT_EQ(3ul, m_sumOfConsumedBufferedAmount); } @@ -302,22 +302,22 @@ { Vector<char> v; v.append("\0ar", 3); - channel()->sendBinaryAsCharVector(wrapUnique(new Vector<char>(v))); + channel()->sendBinaryAsCharVector(makeUnique<Vector<char>>(v)); } { Vector<char> v; v.append("b\0z", 3); - channel()->sendBinaryAsCharVector(wrapUnique(new Vector<char>(v))); + channel()->sendBinaryAsCharVector(makeUnique<Vector<char>>(v)); } { Vector<char> v; v.append("qu\0", 3); - channel()->sendBinaryAsCharVector(wrapUnique(new Vector<char>(v))); + channel()->sendBinaryAsCharVector(makeUnique<Vector<char>>(v)); } { Vector<char> v; v.append("\0\0\0", 3); - channel()->sendBinaryAsCharVector(wrapUnique(new Vector<char>(v))); + channel()->sendBinaryAsCharVector(makeUnique<Vector<char>>(v)); } EXPECT_EQ(12ul, m_sumOfConsumedBufferedAmount); @@ -333,7 +333,7 @@ Vector<char> v; v.append("\xe7\x8b\x90", 3); - channel()->sendBinaryAsCharVector(wrapUnique(new Vector<char>(v))); + channel()->sendBinaryAsCharVector(makeUnique<Vector<char>>(v)); EXPECT_EQ(3ul, m_sumOfConsumedBufferedAmount); } @@ -348,7 +348,7 @@ Vector<char> v; v.append("\x80\xff\xe7", 3); - channel()->sendBinaryAsCharVector(wrapUnique(new Vector<char>(v))); + channel()->sendBinaryAsCharVector(makeUnique<Vector<char>>(v)); EXPECT_EQ(3ul, m_sumOfConsumedBufferedAmount); } @@ -377,7 +377,7 @@ "\xe7\x8b\x90\xe7\x8b\x90\xe7\x8b\x90\xe7\x8b\x90\xe7\x8b\x90\xe7\x8b" "\x90", 18); - channel()->sendBinaryAsCharVector(wrapUnique(new Vector<char>(v))); + channel()->sendBinaryAsCharVector(makeUnique<Vector<char>>(v)); checkpoint.Call(1); handleClient()->didReceiveFlowControl(handle(), 16);
diff --git a/third_party/WebKit/Source/modules/websockets/WorkerWebSocketChannel.cpp b/third_party/WebKit/Source/modules/websockets/WorkerWebSocketChannel.cpp index ef62cda..97e2f00e 100644 --- a/third_party/WebKit/Source/modules/websockets/WorkerWebSocketChannel.cpp +++ b/third_party/WebKit/Source/modules/websockets/WorkerWebSocketChannel.cpp
@@ -436,7 +436,7 @@ DCHECK(m_peer); // ArrayBuffer isn't thread-safe, hence the content of ArrayBuffer is copied // into Vector<char>. - std::unique_ptr<Vector<char>> data = wrapUnique(new Vector<char>(byteLength)); + std::unique_ptr<Vector<char>> data = makeUnique<Vector<char>>(byteLength); if (binaryData.byteLength()) memcpy(data->data(), static_cast<const char*>(binaryData.data()) + byteOffset,
diff --git a/third_party/WebKit/Source/platform/BUILD.gn b/third_party/WebKit/Source/platform/BUILD.gn index 4aa2607..d504890 100644 --- a/third_party/WebKit/Source/platform/BUILD.gn +++ b/third_party/WebKit/Source/platform/BUILD.gn
@@ -837,6 +837,8 @@ "graphics/OffscreenCanvasFrameDispatcher.h", "graphics/OffscreenCanvasFrameDispatcherImpl.cpp", "graphics/OffscreenCanvasFrameDispatcherImpl.h", + "graphics/OffscreenCanvasPlaceholder.cpp", + "graphics/OffscreenCanvasPlaceholder.h", "graphics/PaintGeneratedImage.cpp", "graphics/PaintGeneratedImage.h", "graphics/PaintInvalidationReason.cpp",
diff --git a/third_party/WebKit/Source/platform/LifecycleObserver.h b/third_party/WebKit/Source/platform/LifecycleObserver.h index e9f591a..e6a9b9d 100644 --- a/third_party/WebKit/Source/platform/LifecycleObserver.h +++ b/third_party/WebKit/Source/platform/LifecycleObserver.h
@@ -32,6 +32,9 @@ namespace blink { template <typename Context, typename Observer> +class LifecycleNotifier; + +template <typename Context, typename Observer> class LifecycleObserver : public GarbageCollectedMixin { public: DEFINE_INLINE_VIRTUAL_TRACE() { visitor->trace(m_lifecycleContext); } @@ -55,13 +58,19 @@ template <typename Context, typename Observer> inline void LifecycleObserver<Context, Observer>::setContext(Context* context) { - if (m_lifecycleContext) - m_lifecycleContext->removeObserver(static_cast<Observer*>(this)); + using Notifier = LifecycleNotifier<Context, Observer>; + + if (m_lifecycleContext) { + static_cast<Notifier*>(m_lifecycleContext) + ->removeObserver(static_cast<Observer*>(this)); + } m_lifecycleContext = context; - if (m_lifecycleContext) - m_lifecycleContext->addObserver(static_cast<Observer*>(this)); + if (m_lifecycleContext) { + static_cast<Notifier*>(m_lifecycleContext) + ->addObserver(static_cast<Observer*>(this)); + } } } // namespace blink
diff --git a/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.in b/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.in index 23e4996..c8f30e04 100644 --- a/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.in +++ b/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.in
@@ -166,7 +166,7 @@ OverlayScrollbars PagePopup status=stable PaintUnderInvalidationChecking settable_from_internals=True -PassiveDocumentEventListeners status=experimental +PassiveDocumentEventListeners status=stable PassiveEventListenersDueToFling status=experimental PassPaintVisualRectToCompositor PaymentApp status=experimental @@ -234,7 +234,7 @@ // Chromium sets this conditionally (eg. based on the presence of a // touchscreen) in ApplyWebPreferences. Touch status=stable -TraceWrappables +TraceWrappables status=stable TrustedEventsDefaultAction status=stable UserSelectAll status=stable WebAnimationsAPI status=experimental
diff --git a/third_party/WebKit/Source/platform/WebThreadSupportingGC.cpp b/third_party/WebKit/Source/platform/WebThreadSupportingGC.cpp index f96ef83..3e034cc 100644 --- a/third_party/WebKit/Source/platform/WebThreadSupportingGC.cpp +++ b/third_party/WebKit/Source/platform/WebThreadSupportingGC.cpp
@@ -52,7 +52,7 @@ void WebThreadSupportingGC::initialize() { ThreadState::attachCurrentThread(m_threadHeapMode); - m_gcTaskRunner = wrapUnique(new GCTaskRunner(m_thread)); + m_gcTaskRunner = makeUnique<GCTaskRunner>(m_thread); } void WebThreadSupportingGC::shutdown() {
diff --git a/third_party/WebKit/Source/platform/audio/AudioBus.cpp b/third_party/WebKit/Source/platform/audio/AudioBus.cpp index a770460..611be8e 100644 --- a/third_party/WebKit/Source/platform/audio/AudioBus.cpp +++ b/third_party/WebKit/Source/platform/audio/AudioBus.cpp
@@ -524,7 +524,7 @@ if (framesToDezipper) { if (!m_dezipperGainValues.get() || m_dezipperGainValues->size() < framesToDezipper) - m_dezipperGainValues = wrapUnique(new AudioFloatArray(framesToDezipper)); + m_dezipperGainValues = makeUnique<AudioFloatArray>(framesToDezipper); float* gainValues = m_dezipperGainValues->data(); for (unsigned i = 0; i < framesToDezipper; ++i) {
diff --git a/third_party/WebKit/Source/platform/audio/AudioDestination.cpp b/third_party/WebKit/Source/platform/audio/AudioDestination.cpp index 4cccdd9..39903c6 100644 --- a/third_party/WebKit/Source/platform/audio/AudioDestination.cpp +++ b/third_party/WebKit/Source/platform/audio/AudioDestination.cpp
@@ -126,7 +126,7 @@ AudioUtilities::kRenderQuantumFrames)); // Input buffering. - m_inputFifo = wrapUnique(new AudioFIFO(numberOfInputChannels, fifoSize)); + m_inputFifo = makeUnique<AudioFIFO>(numberOfInputChannels, fifoSize); // If the callback size does not match the render size, then we need to // buffer some extra silence for the input. Otherwise, we can over-consume
diff --git a/third_party/WebKit/Source/platform/audio/AudioResampler.cpp b/third_party/WebKit/Source/platform/audio/AudioResampler.cpp index 8a64f5c1..6f7cc51 100644 --- a/third_party/WebKit/Source/platform/audio/AudioResampler.cpp +++ b/third_party/WebKit/Source/platform/audio/AudioResampler.cpp
@@ -33,13 +33,13 @@ const double AudioResampler::MaxRate = 8.0; AudioResampler::AudioResampler() : m_rate(1.0) { - m_kernels.append(wrapUnique(new AudioResamplerKernel(this))); + m_kernels.append(makeUnique<AudioResamplerKernel>(this)); m_sourceBus = AudioBus::create(1, 0, false); } AudioResampler::AudioResampler(unsigned numberOfChannels) : m_rate(1.0) { for (unsigned i = 0; i < numberOfChannels; ++i) - m_kernels.append(wrapUnique(new AudioResamplerKernel(this))); + m_kernels.append(makeUnique<AudioResamplerKernel>(this)); m_sourceBus = AudioBus::create(numberOfChannels, 0, false); } @@ -52,7 +52,7 @@ // First deal with adding or removing kernels. if (numberOfChannels > currentSize) { for (unsigned i = currentSize; i < numberOfChannels; ++i) - m_kernels.append(wrapUnique(new AudioResamplerKernel(this))); + m_kernels.append(makeUnique<AudioResamplerKernel>(this)); } else m_kernels.resize(numberOfChannels);
diff --git a/third_party/WebKit/Source/platform/audio/DynamicsCompressorKernel.cpp b/third_party/WebKit/Source/platform/audio/DynamicsCompressorKernel.cpp index e44afae..9ab32c3 100644 --- a/third_party/WebKit/Source/platform/audio/DynamicsCompressorKernel.cpp +++ b/third_party/WebKit/Source/platform/audio/DynamicsCompressorKernel.cpp
@@ -73,8 +73,7 @@ m_preDelayBuffers.clear(); for (unsigned i = 0; i < numberOfChannels; ++i) - m_preDelayBuffers.append( - wrapUnique(new AudioFloatArray(MaxPreDelayFrames))); + m_preDelayBuffers.append(makeUnique<AudioFloatArray>(MaxPreDelayFrames)); } void DynamicsCompressorKernel::setPreDelayTime(float preDelayTime) {
diff --git a/third_party/WebKit/Source/platform/audio/HRTFElevation.cpp b/third_party/WebKit/Source/platform/audio/HRTFElevation.cpp index 777c31b..f43e910 100644 --- a/third_party/WebKit/Source/platform/audio/HRTFElevation.cpp +++ b/third_party/WebKit/Source/platform/audio/HRTFElevation.cpp
@@ -261,9 +261,9 @@ return nullptr; std::unique_ptr<HRTFKernelList> kernelListL = - wrapUnique(new HRTFKernelList(NumberOfTotalAzimuths)); + makeUnique<HRTFKernelList>(NumberOfTotalAzimuths); std::unique_ptr<HRTFKernelList> kernelListR = - wrapUnique(new HRTFKernelList(NumberOfTotalAzimuths)); + makeUnique<HRTFKernelList>(NumberOfTotalAzimuths); // Load convolution kernels from HRTF files. int interpolatedIndex = 0; @@ -314,9 +314,9 @@ ASSERT(x >= 0.0 && x < 1.0); std::unique_ptr<HRTFKernelList> kernelListL = - wrapUnique(new HRTFKernelList(NumberOfTotalAzimuths)); + makeUnique<HRTFKernelList>(NumberOfTotalAzimuths); std::unique_ptr<HRTFKernelList> kernelListR = - wrapUnique(new HRTFKernelList(NumberOfTotalAzimuths)); + makeUnique<HRTFKernelList>(NumberOfTotalAzimuths); HRTFKernelList* kernelListL1 = hrtfElevation1->kernelListL(); HRTFKernelList* kernelListR1 = hrtfElevation1->kernelListR();
diff --git a/third_party/WebKit/Source/platform/audio/HRTFKernel.cpp b/third_party/WebKit/Source/platform/audio/HRTFKernel.cpp index 97fc2af..f8c29e2 100644 --- a/third_party/WebKit/Source/platform/audio/HRTFKernel.cpp +++ b/third_party/WebKit/Source/platform/audio/HRTFKernel.cpp
@@ -95,7 +95,7 @@ } } - m_fftFrame = wrapUnique(new FFTFrame(fftSize)); + m_fftFrame = makeUnique<FFTFrame>(fftSize); m_fftFrame->doPaddedFFT(impulseResponse, truncatedResponseLength); }
diff --git a/third_party/WebKit/Source/platform/audio/MultiChannelResampler.cpp b/third_party/WebKit/Source/platform/audio/MultiChannelResampler.cpp index 368c4ab..87197dd 100644 --- a/third_party/WebKit/Source/platform/audio/MultiChannelResampler.cpp +++ b/third_party/WebKit/Source/platform/audio/MultiChannelResampler.cpp
@@ -100,7 +100,7 @@ // Create each channel's resampler. for (unsigned channelIndex = 0; channelIndex < numberOfChannels; ++channelIndex) - m_kernels.append(wrapUnique(new SincResampler(scaleFactor))); + m_kernels.append(makeUnique<SincResampler>(scaleFactor)); } void MultiChannelResampler::process(AudioSourceProvider* provider,
diff --git a/third_party/WebKit/Source/platform/audio/Panner.cpp b/third_party/WebKit/Source/platform/audio/Panner.cpp index 9fde3eb5..1d002ea 100644 --- a/third_party/WebKit/Source/platform/audio/Panner.cpp +++ b/third_party/WebKit/Source/platform/audio/Panner.cpp
@@ -39,10 +39,10 @@ HRTFDatabaseLoader* databaseLoader) { switch (model) { case PanningModelEqualPower: - return wrapUnique(new EqualPowerPanner(sampleRate)); + return makeUnique<EqualPowerPanner>(sampleRate); case PanningModelHRTF: - return wrapUnique(new HRTFPanner(sampleRate, databaseLoader)); + return makeUnique<HRTFPanner>(sampleRate, databaseLoader); default: ASSERT_NOT_REACHED();
diff --git a/third_party/WebKit/Source/platform/audio/ReverbConvolverStage.cpp b/third_party/WebKit/Source/platform/audio/ReverbConvolverStage.cpp index 16914b80..70d741ca 100644 --- a/third_party/WebKit/Source/platform/audio/ReverbConvolverStage.cpp +++ b/third_party/WebKit/Source/platform/audio/ReverbConvolverStage.cpp
@@ -56,16 +56,16 @@ ASSERT(accumulationBuffer); if (!m_directMode) { - m_fftKernel = wrapUnique(new FFTFrame(fftSize)); + m_fftKernel = makeUnique<FFTFrame>(fftSize); m_fftKernel->doPaddedFFT(impulseResponse + stageOffset, stageLength); - m_fftConvolver = wrapUnique(new FFTConvolver(fftSize)); + m_fftConvolver = makeUnique<FFTConvolver>(fftSize); } else { ASSERT(!stageOffset); ASSERT(stageLength <= fftSize / 2); m_directKernel = wrapUnique(new AudioFloatArray(fftSize / 2)); m_directKernel->copyToRange(impulseResponse, 0, stageLength); - m_directConvolver = wrapUnique(new DirectConvolver(renderSliceSize)); + m_directConvolver = makeUnique<DirectConvolver>(renderSliceSize); } m_temporaryBuffer.allocate(renderSliceSize);
diff --git a/third_party/WebKit/Source/platform/exported/WebCredential.cpp b/third_party/WebKit/Source/platform/exported/WebCredential.cpp index bf97b8e..2c1cce04 100644 --- a/third_party/WebKit/Source/platform/exported/WebCredential.cpp +++ b/third_party/WebKit/Source/platform/exported/WebCredential.cpp
@@ -14,11 +14,11 @@ std::unique_ptr<WebCredential> WebCredential::create( PlatformCredential* credential) { if (credential->isPassword()) { - return wrapUnique(new WebPasswordCredential(credential)); + return makeUnique<WebPasswordCredential>(credential); } if (credential->isFederated()) { - return wrapUnique(new WebFederatedCredential(credential)); + return makeUnique<WebFederatedCredential>(credential); } ASSERT_NOT_REACHED();
diff --git a/third_party/WebKit/Source/platform/exported/WebCryptoKeyAlgorithm.cpp b/third_party/WebKit/Source/platform/exported/WebCryptoKeyAlgorithm.cpp index d110d3b6..12a70f9 100644 --- a/third_party/WebKit/Source/platform/exported/WebCryptoKeyAlgorithm.cpp +++ b/third_party/WebKit/Source/platform/exported/WebCryptoKeyAlgorithm.cpp
@@ -73,7 +73,7 @@ if (keyLengthBits != 128 && keyLengthBits != 192 && keyLengthBits != 256) return WebCryptoKeyAlgorithm(); return WebCryptoKeyAlgorithm( - id, wrapUnique(new WebCryptoAesKeyAlgorithmParams(keyLengthBits))); + id, makeUnique<WebCryptoAesKeyAlgorithmParams>(keyLengthBits)); } WebCryptoKeyAlgorithm WebCryptoKeyAlgorithm::createHmac( @@ -105,7 +105,7 @@ WebCryptoAlgorithmId id, WebCryptoNamedCurve namedCurve) { return WebCryptoKeyAlgorithm( - id, wrapUnique(new WebCryptoEcKeyAlgorithmParams(namedCurve))); + id, makeUnique<WebCryptoEcKeyAlgorithmParams>(namedCurve)); } WebCryptoKeyAlgorithm WebCryptoKeyAlgorithm::createWithoutParams(
diff --git a/third_party/WebKit/Source/platform/fonts/FontCache.cpp b/third_party/WebKit/Source/platform/fonts/FontCache.cpp index 1ac542a..94a6157 100644 --- a/third_party/WebKit/Source/platform/fonts/FontCache.cpp +++ b/third_party/WebKit/Source/platform/fonts/FontCache.cpp
@@ -201,7 +201,7 @@ #if OS(MACOSX) return createFontPlatformData(fontDescription, creationParams, fontSize); #else - return wrapUnique(new FontPlatformData(fontPlatformData, fontSize)); + return makeUnique<FontPlatformData>(fontPlatformData, fontSize); #endif }
diff --git a/third_party/WebKit/Source/platform/fonts/OrientationIterator.cpp b/third_party/WebKit/Source/platform/fonts/OrientationIterator.cpp index 72b3bfd2..48ead978 100644 --- a/third_party/WebKit/Source/platform/fonts/OrientationIterator.cpp +++ b/third_party/WebKit/Source/platform/fonts/OrientationIterator.cpp
@@ -11,7 +11,7 @@ OrientationIterator::OrientationIterator(const UChar* buffer, unsigned bufferSize, FontOrientation runOrientation) - : m_utf16Iterator(wrapUnique(new UTF16TextIterator(buffer, bufferSize))), + : m_utf16Iterator(makeUnique<UTF16TextIterator>(buffer, bufferSize)), m_bufferSize(bufferSize), m_atEnd(bufferSize == 0) { // There's not much point in segmenting by isUprightInVertical if the text
diff --git a/third_party/WebKit/Source/platform/fonts/SmallCapsIterator.cpp b/third_party/WebKit/Source/platform/fonts/SmallCapsIterator.cpp index d849a374e..a8db468c 100644 --- a/third_party/WebKit/Source/platform/fonts/SmallCapsIterator.cpp +++ b/third_party/WebKit/Source/platform/fonts/SmallCapsIterator.cpp
@@ -10,7 +10,7 @@ namespace blink { SmallCapsIterator::SmallCapsIterator(const UChar* buffer, unsigned bufferSize) - : m_utf16Iterator(wrapUnique(new UTF16TextIterator(buffer, bufferSize))), + : m_utf16Iterator(makeUnique<UTF16TextIterator>(buffer, bufferSize)), m_bufferSize(bufferSize), m_nextUChar32(0), m_atEnd(bufferSize == 0),
diff --git a/third_party/WebKit/Source/platform/fonts/SymbolsIterator.cpp b/third_party/WebKit/Source/platform/fonts/SymbolsIterator.cpp index 59d40e7..99807a3b 100644 --- a/third_party/WebKit/Source/platform/fonts/SymbolsIterator.cpp +++ b/third_party/WebKit/Source/platform/fonts/SymbolsIterator.cpp
@@ -13,7 +13,7 @@ using namespace WTF::Unicode; SymbolsIterator::SymbolsIterator(const UChar* buffer, unsigned bufferSize) - : m_utf16Iterator(wrapUnique(new UTF16TextIterator(buffer, bufferSize))), + : m_utf16Iterator(makeUnique<UTF16TextIterator>(buffer, bufferSize)), m_bufferSize(bufferSize), m_nextChar(0), m_atEnd(bufferSize == 0),
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/CachingWordShaperTest.cpp b/third_party/WebKit/Source/platform/fonts/shaping/CachingWordShaperTest.cpp index f0daa5b..d702836 100644 --- a/third_party/WebKit/Source/platform/fonts/shaping/CachingWordShaperTest.cpp +++ b/third_party/WebKit/Source/platform/fonts/shaping/CachingWordShaperTest.cpp
@@ -27,7 +27,7 @@ font.update(nullptr); ASSERT_TRUE(font.canShapeWordByWord()); fallbackFonts = nullptr; - cache = wrapUnique(new ShapeCache()); + cache = makeUnique<ShapeCache>(); } FontCachePurgePreventer fontCachePurgePreventer; @@ -120,7 +120,7 @@ GlyphBuffer glyphBuffer; shaper.fillGlyphBuffer(&font, textRun, fallbackFonts, &glyphBuffer, 0, 3); - std::unique_ptr<ShapeCache> referenceCache = wrapUnique(new ShapeCache()); + std::unique_ptr<ShapeCache> referenceCache = makeUnique<ShapeCache>(); CachingWordShaper referenceShaper(referenceCache.get()); GlyphBuffer referenceGlyphBuffer; font.setCanShapeWordByWordForTesting(false); @@ -144,7 +144,7 @@ GlyphBuffer glyphBuffer; shaper.fillGlyphBuffer(&font, textRun, fallbackFonts, &glyphBuffer, 1, 6); - std::unique_ptr<ShapeCache> referenceCache = wrapUnique(new ShapeCache()); + std::unique_ptr<ShapeCache> referenceCache = makeUnique<ShapeCache>(); CachingWordShaper referenceShaper(referenceCache.get()); GlyphBuffer referenceGlyphBuffer; font.setCanShapeWordByWordForTesting(false);
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzFace.cpp b/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzFace.cpp index 07fb9426..2f3a54a 100644 --- a/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzFace.cpp +++ b/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzFace.cpp
@@ -124,7 +124,7 @@ private: explicit HbFontCacheEntry(hb_font_t* font) : m_hbFont(HbFontUniquePtr(font)), - m_hbFontData(wrapUnique(new HarfBuzzFontData())){}; + m_hbFontData(makeUnique<HarfBuzzFontData>()){}; HbFontUniquePtr m_hbFont; std::unique_ptr<HarfBuzzFontData> m_hbFontData;
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/RunSegmenter.cpp b/third_party/WebKit/Source/platform/fonts/shaping/RunSegmenter.cpp index 034a700..35e8af38 100644 --- a/third_party/WebKit/Source/platform/fonts/shaping/RunSegmenter.cpp +++ b/third_party/WebKit/Source/platform/fonts/shaping/RunSegmenter.cpp
@@ -21,14 +21,13 @@ m_candidateRange({0, 0, USCRIPT_INVALID_CODE, OrientationIterator::OrientationKeep, FontFallbackPriority::Text}), - m_scriptRunIterator( - wrapUnique(new ScriptRunIterator(buffer, bufferSize))), + m_scriptRunIterator(makeUnique<ScriptRunIterator>(buffer, bufferSize)), m_orientationIterator( runOrientation == FontOrientation::VerticalMixed ? wrapUnique( new OrientationIterator(buffer, bufferSize, runOrientation)) : nullptr), - m_symbolsIterator(wrapUnique(new SymbolsIterator(buffer, bufferSize))), + m_symbolsIterator(makeUnique<SymbolsIterator>(buffer, bufferSize)), m_lastSplit(0), m_scriptRunIteratorPosition(0), m_orientationIteratorPosition(
diff --git a/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridgeTest.cpp b/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridgeTest.cpp index ec66ecd..b131652e 100644 --- a/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridgeTest.cpp +++ b/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridgeTest.cpp
@@ -347,7 +347,7 @@ Canvas2DLayerBridgeTest* testHost, WaitableEvent* doneEvent) { std::unique_ptr<FakeWebGraphicsContext3DProvider> contextProvider = - wrapUnique(new FakeWebGraphicsContext3DProvider(gl)); + makeUnique<FakeWebGraphicsContext3DProvider>(gl); *bridgePtr = testHost->makeBridge(std::move(contextProvider), IntSize(300, 300), Canvas2DLayerBridge::EnableAcceleration); @@ -364,7 +364,7 @@ gpu::gles2::GLES2Interface* gl, Canvas2DLayerBridgeTest* testHost) { std::unique_ptr<WaitableEvent> bridgeCreatedEvent = - wrapUnique(new WaitableEvent()); + makeUnique<WaitableEvent>(); testThread->getWebTaskRunner()->postTask( location, crossThreadBind( &runCreateBridgeTask, crossThreadUnretained(bridgePtr), @@ -392,7 +392,7 @@ WebThread* testThread, Canvas2DLayerBridgePtr* bridgePtr) { std::unique_ptr<WaitableEvent> bridgeDestroyedEvent = - wrapUnique(new WaitableEvent()); + makeUnique<WaitableEvent>(); testThread->getWebTaskRunner()->postTask( location, crossThreadBind(&runDestroyBridgeTask, crossThreadUnretained(bridgePtr), @@ -423,7 +423,7 @@ WebThread* testThread, Canvas2DLayerBridge* bridge, bool value) { - std::unique_ptr<WaitableEvent> doneEvent = wrapUnique(new WaitableEvent()); + std::unique_ptr<WaitableEvent> doneEvent = makeUnique<WaitableEvent>(); postSetIsHiddenTask(location, testThread, bridge, value, doneEvent.get()); doneEvent->wait(); } @@ -462,7 +462,7 @@ // Test entering hibernation std::unique_ptr<WaitableEvent> hibernationStartedEvent = - wrapUnique(new WaitableEvent()); + makeUnique<WaitableEvent>(); EXPECT_CALL(*mockLoggerPtr, reportHibernationEvent( Canvas2DLayerBridge::HibernationScheduled)); EXPECT_CALL(*mockLoggerPtr, didStartHibernating()) @@ -514,7 +514,7 @@ // Test entering hibernation std::unique_ptr<WaitableEvent> hibernationStartedEvent = - wrapUnique(new WaitableEvent()); + makeUnique<WaitableEvent>(); EXPECT_CALL(*mockLoggerPtr, reportHibernationEvent( Canvas2DLayerBridge::HibernationScheduled)); EXPECT_CALL(*mockLoggerPtr, didStartHibernating()) @@ -577,7 +577,7 @@ // Test entering hibernation std::unique_ptr<WaitableEvent> hibernationStartedEvent = - wrapUnique(new WaitableEvent()); + makeUnique<WaitableEvent>(); EXPECT_CALL(*mockLoggerPtr, reportHibernationEvent( Canvas2DLayerBridge::HibernationScheduled)); EXPECT_CALL(*mockLoggerPtr, didStartHibernating()) @@ -620,7 +620,7 @@ void postAndWaitRenderingTask(const WebTraceLocation& location, WebThread* testThread, Canvas2DLayerBridge* bridge) { - std::unique_ptr<WaitableEvent> doneEvent = wrapUnique(new WaitableEvent()); + std::unique_ptr<WaitableEvent> doneEvent = makeUnique<WaitableEvent>(); testThread->getWebTaskRunner()->postTask( location, crossThreadBind(&runRenderingTask, crossThreadUnretained(bridge), @@ -651,7 +651,7 @@ // Test entering hibernation std::unique_ptr<WaitableEvent> hibernationStartedEvent = - wrapUnique(new WaitableEvent()); + makeUnique<WaitableEvent>(); EXPECT_CALL(*mockLoggerPtr, reportHibernationEvent( Canvas2DLayerBridge::HibernationScheduled)); EXPECT_CALL(*mockLoggerPtr, didStartHibernating()) @@ -719,7 +719,7 @@ // Test entering hibernation std::unique_ptr<WaitableEvent> hibernationStartedEvent = - wrapUnique(new WaitableEvent()); + makeUnique<WaitableEvent>(); EXPECT_CALL(*mockLoggerPtr, reportHibernationEvent( Canvas2DLayerBridge::HibernationScheduled)); EXPECT_CALL(*mockLoggerPtr, didStartHibernating()) @@ -790,7 +790,7 @@ // Test entering hibernation std::unique_ptr<WaitableEvent> hibernationStartedEvent = - wrapUnique(new WaitableEvent()); + makeUnique<WaitableEvent>(); EXPECT_CALL(*mockLoggerPtr, reportHibernationEvent( Canvas2DLayerBridge::HibernationScheduled)); EXPECT_CALL(*mockLoggerPtr, didStartHibernating()) @@ -857,7 +857,7 @@ // Test entering hibernation std::unique_ptr<WaitableEvent> hibernationStartedEvent = - wrapUnique(new WaitableEvent()); + makeUnique<WaitableEvent>(); EXPECT_CALL(*mockLoggerPtr, reportHibernationEvent( Canvas2DLayerBridge::HibernationScheduled)); EXPECT_CALL(*mockLoggerPtr, didStartHibernating()) @@ -900,7 +900,7 @@ // Test entering hibernation std::unique_ptr<WaitableEvent> hibernationStartedEvent = - wrapUnique(new WaitableEvent()); + makeUnique<WaitableEvent>(); EXPECT_CALL(*mockLoggerPtr, reportHibernationEvent( Canvas2DLayerBridge::HibernationScheduled)); EXPECT_CALL(*mockLoggerPtr, didStartHibernating()) @@ -926,7 +926,7 @@ // End hibernation normally std::unique_ptr<WaitableEvent> hibernationEndedEvent = - wrapUnique(new WaitableEvent()); + makeUnique<WaitableEvent>(); EXPECT_CALL( *mockLoggerPtr, reportHibernationEvent(Canvas2DLayerBridge::HibernationEndedNormally)) @@ -962,7 +962,7 @@ // Test entering hibernation std::unique_ptr<WaitableEvent> hibernationScheduledEvent = - wrapUnique(new WaitableEvent()); + makeUnique<WaitableEvent>(); EXPECT_CALL(*mockLoggerPtr, reportHibernationEvent( Canvas2DLayerBridge::HibernationScheduled)); postSetIsHiddenTask(BLINK_FROM_HERE, testThread.get(), bridge.get(), true, @@ -979,7 +979,7 @@ // completion before the thread is destroyed. // This test passes by not crashing, which proves that the WeakPtr logic // is sound. - std::unique_ptr<WaitableEvent> fenceEvent = wrapUnique(new WaitableEvent()); + std::unique_ptr<WaitableEvent> fenceEvent = makeUnique<WaitableEvent>(); testThread->getWebTaskRunner()->postTask( BLINK_FROM_HERE, WTF::bind(&WaitableEvent::signal, unretained(fenceEvent.get()))); @@ -1009,7 +1009,7 @@ // Test entering hibernation std::unique_ptr<WaitableEvent> hibernationAbortedEvent = - wrapUnique(new WaitableEvent()); + makeUnique<WaitableEvent>(); EXPECT_CALL(*mockLoggerPtr, reportHibernationEvent( Canvas2DLayerBridge::HibernationScheduled)); EXPECT_CALL( @@ -1054,7 +1054,7 @@ // Test entering hibernation std::unique_ptr<WaitableEvent> hibernationAbortedEvent = - wrapUnique(new WaitableEvent()); + makeUnique<WaitableEvent>(); EXPECT_CALL(*mockLoggerPtr, reportHibernationEvent( Canvas2DLayerBridge::HibernationScheduled)); EXPECT_CALL(*mockLoggerPtr, @@ -1099,7 +1099,7 @@ gl.setIsContextLost(true); // Test entering hibernation std::unique_ptr<WaitableEvent> hibernationAbortedEvent = - wrapUnique(new WaitableEvent()); + makeUnique<WaitableEvent>(); EXPECT_CALL(*mockLoggerPtr, reportHibernationEvent( Canvas2DLayerBridge::HibernationScheduled)); EXPECT_CALL(*mockLoggerPtr, @@ -1140,7 +1140,7 @@ // Test entering hibernation std::unique_ptr<WaitableEvent> hibernationStartedEvent = - wrapUnique(new WaitableEvent()); + makeUnique<WaitableEvent>(); EXPECT_CALL(*mockLoggerPtr, reportHibernationEvent( Canvas2DLayerBridge::HibernationScheduled)); EXPECT_CALL(*mockLoggerPtr, didStartHibernating()) @@ -1188,7 +1188,7 @@ // Test entering hibernation std::unique_ptr<WaitableEvent> hibernationStartedEvent = - wrapUnique(new WaitableEvent()); + makeUnique<WaitableEvent>(); EXPECT_CALL(*mockLoggerPtr, reportHibernationEvent( Canvas2DLayerBridge::HibernationScheduled)); EXPECT_CALL(*mockLoggerPtr, didStartHibernating())
diff --git a/third_party/WebKit/Source/platform/graphics/CompositorElementId.h b/third_party/WebKit/Source/platform/graphics/CompositorElementId.h index 3f4d9f3..230d3dfc 100644 --- a/third_party/WebKit/Source/platform/graphics/CompositorElementId.h +++ b/third_party/WebKit/Source/platform/graphics/CompositorElementId.h
@@ -5,7 +5,7 @@ #ifndef CompositorElementId_h #define CompositorElementId_h -#include "cc/animation/element_id.h" +#include "cc/trees/element_id.h" #include "platform/PlatformExport.h" namespace blink {
diff --git a/third_party/WebKit/Source/platform/graphics/CompositorMutatorClientTest.cpp b/third_party/WebKit/Source/platform/graphics/CompositorMutatorClientTest.cpp index 4280bf4..6244e9c 100644 --- a/third_party/WebKit/Source/platform/graphics/CompositorMutatorClientTest.cpp +++ b/third_party/WebKit/Source/platform/graphics/CompositorMutatorClientTest.cpp
@@ -38,7 +38,7 @@ CompositorMutatorClient client(new StubCompositorMutator, &target); std::unique_ptr<CompositorMutations> mutations = - wrapUnique(new CompositorMutations()); + makeUnique<CompositorMutations>(); client.setMutationsForTesting(std::move(mutations)); EXPECT_CALL(target, applyMutations(_));
diff --git a/third_party/WebKit/Source/platform/graphics/ContiguousContainer.cpp b/third_party/WebKit/Source/platform/graphics/ContiguousContainer.cpp index 5c94d93..f3c65902 100644 --- a/third_party/WebKit/Source/platform/graphics/ContiguousContainer.cpp +++ b/third_party/WebKit/Source/platform/graphics/ContiguousContainer.cpp
@@ -170,8 +170,7 @@ size_t bufferSize, const char* typeName) { ASSERT(m_buffers.isEmpty() || m_endIndex == m_buffers.size() - 1); - std::unique_ptr<Buffer> newBuffer = - wrapUnique(new Buffer(bufferSize, typeName)); + std::unique_ptr<Buffer> newBuffer = makeUnique<Buffer>(bufferSize, typeName); Buffer* bufferToReturn = newBuffer.get(); m_buffers.append(std::move(newBuffer)); m_endIndex = m_buffers.size() - 1;
diff --git a/third_party/WebKit/Source/platform/graphics/DrawLooperBuilder.cpp b/third_party/WebKit/Source/platform/graphics/DrawLooperBuilder.cpp index ad13032..6b36340 100644 --- a/third_party/WebKit/Source/platform/graphics/DrawLooperBuilder.cpp +++ b/third_party/WebKit/Source/platform/graphics/DrawLooperBuilder.cpp
@@ -48,10 +48,6 @@ DrawLooperBuilder::~DrawLooperBuilder() {} -std::unique_ptr<DrawLooperBuilder> DrawLooperBuilder::create() { - return wrapUnique(new DrawLooperBuilder); -} - sk_sp<SkDrawLooper> DrawLooperBuilder::detachDrawLooper() { return m_skDrawLooperBuilder.detach(); }
diff --git a/third_party/WebKit/Source/platform/graphics/DrawLooperBuilder.h b/third_party/WebKit/Source/platform/graphics/DrawLooperBuilder.h index c28df37..b63e7dc 100644 --- a/third_party/WebKit/Source/platform/graphics/DrawLooperBuilder.h +++ b/third_party/WebKit/Source/platform/graphics/DrawLooperBuilder.h
@@ -49,7 +49,7 @@ // Implementing the copy constructor properly would require writing code to // copy the underlying SkLayerDrawLooper::Builder. WTF_MAKE_NONCOPYABLE(DrawLooperBuilder); - USING_FAST_MALLOC(DrawLooperBuilder); + STACK_ALLOCATED(); public: enum ShadowTransformMode { @@ -61,8 +61,6 @@ DrawLooperBuilder(); ~DrawLooperBuilder(); - static std::unique_ptr<DrawLooperBuilder> create(); - // Creates the SkDrawLooper and passes ownership to the caller. The builder // should not be used any more after calling this method. sk_sp<SkDrawLooper> detachDrawLooper();
diff --git a/third_party/WebKit/Source/platform/graphics/GraphicsContext.cpp b/third_party/WebKit/Source/platform/graphics/GraphicsContext.cpp index bac530d..fe833dd 100644 --- a/third_party/WebKit/Source/platform/graphics/GraphicsContext.cpp +++ b/third_party/WebKit/Source/platform/graphics/GraphicsContext.cpp
@@ -173,34 +173,30 @@ if (contextDisabled()) return; - std::unique_ptr<DrawLooperBuilder> drawLooperBuilder = - DrawLooperBuilder::create(); + DrawLooperBuilder drawLooperBuilder; if (!color.alpha()) { // When shadow-only but there is no shadow, we use an empty draw looper // to disable rendering of the source primitive. When not shadow-only, we // clear the looper. - if (shadowMode != DrawShadowOnly) - drawLooperBuilder.reset(); - - setDrawLooper(std::move(drawLooperBuilder)); + setDrawLooper(shadowMode != DrawShadowOnly + ? nullptr + : drawLooperBuilder.detachDrawLooper()); return; } - drawLooperBuilder->addShadow(offset, blur, color, shadowTransformMode, - shadowAlphaMode); + drawLooperBuilder.addShadow(offset, blur, color, shadowTransformMode, + shadowAlphaMode); if (shadowMode == DrawShadowAndForeground) { - drawLooperBuilder->addUnmodifiedContent(); + drawLooperBuilder.addUnmodifiedContent(); } - setDrawLooper(std::move(drawLooperBuilder)); + setDrawLooper(drawLooperBuilder.detachDrawLooper()); } -void GraphicsContext::setDrawLooper( - std::unique_ptr<DrawLooperBuilder> drawLooperBuilder) { +void GraphicsContext::setDrawLooper(sk_sp<SkDrawLooper> drawLooper) { if (contextDisabled()) return; - mutableState()->setDrawLooper( - drawLooperBuilder ? drawLooperBuilder->detachDrawLooper() : nullptr); + mutableState()->setDrawLooper(std::move(drawLooper)); } SkColorFilter* GraphicsContext::getColorFilter() const { @@ -451,12 +447,11 @@ clip(rect.rect()); } - std::unique_ptr<DrawLooperBuilder> drawLooperBuilder = - DrawLooperBuilder::create(); - drawLooperBuilder->addShadow(FloatSize(shadowOffset), shadowBlur, shadowColor, - DrawLooperBuilder::ShadowRespectsTransforms, - DrawLooperBuilder::ShadowIgnoresAlpha); - setDrawLooper(std::move(drawLooperBuilder)); + DrawLooperBuilder drawLooperBuilder; + drawLooperBuilder.addShadow(FloatSize(shadowOffset), shadowBlur, shadowColor, + DrawLooperBuilder::ShadowRespectsTransforms, + DrawLooperBuilder::ShadowIgnoresAlpha); + setDrawLooper(drawLooperBuilder.detachDrawLooper()); fillRectWithRoundedHole(outerRect, roundedHole, fillColor); }
diff --git a/third_party/WebKit/Source/platform/graphics/GraphicsContext.h b/third_party/WebKit/Source/platform/graphics/GraphicsContext.h index 7678209..3aa40b0 100644 --- a/third_party/WebKit/Source/platform/graphics/GraphicsContext.h +++ b/third_party/WebKit/Source/platform/graphics/GraphicsContext.h
@@ -299,10 +299,7 @@ DrawLooperBuilder::ShadowRespectsAlpha, ShadowMode = DrawShadowAndForeground); - // It is assumed that this draw looper is used only for shadows - // (i.e. a draw looper is set if and only if there is a shadow). - // The builder passed into this method will be destroyed. - void setDrawLooper(std::unique_ptr<DrawLooperBuilder>); + void setDrawLooper(sk_sp<SkDrawLooper>); void drawFocusRing(const Vector<IntRect>&, float width,
diff --git a/third_party/WebKit/Source/platform/graphics/GraphicsLayer.cpp b/third_party/WebKit/Source/platform/graphics/GraphicsLayer.cpp index 9157dd4..189f518 100644 --- a/third_party/WebKit/Source/platform/graphics/GraphicsLayer.cpp +++ b/third_party/WebKit/Source/platform/graphics/GraphicsLayer.cpp
@@ -116,7 +116,7 @@ m_client->verifyNotPainting(); #endif - m_contentLayerDelegate = wrapUnique(new ContentLayerDelegate(this)); + m_contentLayerDelegate = makeUnique<ContentLayerDelegate>(this); m_layer = Platform::current()->compositorSupport()->createContentLayer( m_contentLayerDelegate.get()); m_layer->layer()->setDrawsContent(m_drawsContent && m_contentsVisible); @@ -1307,11 +1307,11 @@ #ifndef NDEBUG void showGraphicsLayerTree(const blink::GraphicsLayer* layer) { if (!layer) { - fprintf(stderr, "Cannot showGraphicsLayerTree for (nil).\n"); + LOG(INFO) << "Cannot showGraphicsLayerTree for (nil)."; return; } String output = layer->layerTreeAsText(blink::LayerTreeIncludesDebugInfo); - fprintf(stderr, "%s\n", output.utf8().data()); + LOG(INFO) << output.utf8().data(); } #endif
diff --git a/third_party/WebKit/Source/platform/graphics/Image.h b/third_party/WebKit/Source/platform/graphics/Image.h index 61ae170..87f940d 100644 --- a/third_party/WebKit/Source/platform/graphics/Image.h +++ b/third_party/WebKit/Source/platform/graphics/Image.h
@@ -84,6 +84,7 @@ virtual bool currentFrameIsComplete() { return false; } virtual bool currentFrameIsLazyDecoded() { return false; } virtual bool isTextureBacked(); + virtual void transfer() {} // Derived classes should override this if they can assure that the current // image frame contains only resources from its own security origin.
diff --git a/third_party/WebKit/Source/platform/graphics/ImageBuffer.cpp b/third_party/WebKit/Source/platform/graphics/ImageBuffer.cpp index 7940699..378f932 100644 --- a/third_party/WebKit/Source/platform/graphics/ImageBuffer.cpp +++ b/third_party/WebKit/Source/platform/graphics/ImageBuffer.cpp
@@ -514,7 +514,7 @@ // Create and configure a recording (unaccelerated) surface. std::unique_ptr<RecordingImageBufferFallbackSurfaceFactory> surfaceFactory = - wrapUnique(new UnacceleratedSurfaceFactory()); + makeUnique<UnacceleratedSurfaceFactory>(); std::unique_ptr<ImageBufferSurface> surface = wrapUnique(new RecordingImageBufferSurface( m_surface->size(), std::move(surfaceFactory),
diff --git a/third_party/WebKit/Source/platform/graphics/ImageFrameGenerator.cpp b/third_party/WebKit/Source/platform/graphics/ImageFrameGenerator.cpp index 3f2bd86d..d9aaeec4 100644 --- a/third_party/WebKit/Source/platform/graphics/ImageFrameGenerator.cpp +++ b/third_party/WebKit/Source/platform/graphics/ImageFrameGenerator.cpp
@@ -182,7 +182,7 @@ ASSERT(decoder); std::unique_ptr<ImagePlanes> imagePlanes = - wrapUnique(new ImagePlanes(planes, rowBytes)); + makeUnique<ImagePlanes>(planes, rowBytes); decoder->setImagePlanes(std::move(imagePlanes)); ASSERT(decoder->canDecodeToYUV());
diff --git a/third_party/WebKit/Source/platform/graphics/OffscreenCanvasFrameDispatcher.h b/third_party/WebKit/Source/platform/graphics/OffscreenCanvasFrameDispatcher.h index 7f993fa..23de3e67 100644 --- a/third_party/WebKit/Source/platform/graphics/OffscreenCanvasFrameDispatcher.h +++ b/third_party/WebKit/Source/platform/graphics/OffscreenCanvasFrameDispatcher.h
@@ -7,6 +7,7 @@ #include "platform/PlatformExport.h" #include "wtf/RefPtr.h" +#include "wtf/WeakPtr.h" namespace blink { @@ -14,10 +15,19 @@ class PLATFORM_EXPORT OffscreenCanvasFrameDispatcher { public: - virtual ~OffscreenCanvasFrameDispatcher(){}; + OffscreenCanvasFrameDispatcher() : m_weakPtrFactory(this) {} + virtual ~OffscreenCanvasFrameDispatcher() {} virtual void dispatchFrame(RefPtr<StaticBitmapImage>, double commitStartTime, bool isWebGLSoftwareRendering = false) = 0; + virtual void reclaimResource(unsigned resourceId) = 0; + + WeakPtr<OffscreenCanvasFrameDispatcher> createWeakPtr() { + return m_weakPtrFactory.createWeakPtr(); + } + + private: + WeakPtrFactory<OffscreenCanvasFrameDispatcher> m_weakPtrFactory; }; } // namespace blink
diff --git a/third_party/WebKit/Source/platform/graphics/OffscreenCanvasFrameDispatcherImpl.cpp b/third_party/WebKit/Source/platform/graphics/OffscreenCanvasFrameDispatcherImpl.cpp index d67604b..7555ecd 100644 --- a/third_party/WebKit/Source/platform/graphics/OffscreenCanvasFrameDispatcherImpl.cpp +++ b/third_party/WebKit/Source/platform/graphics/OffscreenCanvasFrameDispatcherImpl.cpp
@@ -7,7 +7,10 @@ #include "cc/output/compositor_frame.h" #include "cc/quads/texture_draw_quad.h" #include "gpu/command_buffer/client/gles2_interface.h" +#include "platform/CrossThreadFunctional.h" #include "platform/Histogram.h" +#include "platform/WebTaskRunner.h" +#include "platform/graphics/OffscreenCanvasPlaceholder.h" #include "platform/graphics/gpu/SharedGpuContext.h" #include "public/platform/InterfaceProvider.h" #include "public/platform/Platform.h" @@ -30,6 +33,7 @@ uint32_t localId, uint64_t nonceHigh, uint64_t nonceLow, + int canvasId, int width, int height) : m_surfaceId( @@ -40,7 +44,8 @@ m_width(width), m_height(height), m_nextResourceId(1u), - m_binding(this) { + m_binding(this), + m_placeholderCanvasId(canvasId) { DCHECK(!m_sink.is_bound()); mojom::blink::OffscreenCanvasCompositorFrameSinkProviderPtr provider; Platform::current()->interfaceProvider()->getInterface( @@ -150,6 +155,25 @@ m_cachedImages.add(m_nextResourceId, std::move(image)); } +namespace { + +void updatePlaceholderImage(WeakPtr<OffscreenCanvasFrameDispatcher> dispatcher, + std::unique_ptr<WebTaskRunner> taskRunner, + int placeholderCanvasId, + RefPtr<blink::Image> image, + unsigned resourceId) { + DCHECK(isMainThread()); + OffscreenCanvasPlaceholder* placeholderCanvas = + OffscreenCanvasPlaceholder::getPlaceholderById(placeholderCanvasId); + if (placeholderCanvas) { + placeholderCanvas->setPlaceholderFrame(std::move(image), + std::move(dispatcher), + std::move(taskRunner), resourceId); + } +} + +} // namespace + void OffscreenCanvasFrameDispatcherImpl::dispatchFrame( RefPtr<StaticBitmapImage> image, double commitStartTime, @@ -215,6 +239,20 @@ setTransferableResourceToSharedBitmap(resource, image); } } + + // After this point, |image| can only be used on the main thread, until + // it is returned. + image->transfer(); + std::unique_ptr<WebTaskRunner> dispatcherTaskRunner = + Platform::current()->currentThread()->getWebTaskRunner()->clone(); + + Platform::current()->mainThread()->getWebTaskRunner()->postTask( + BLINK_FROM_HERE, + crossThreadBind(updatePlaceholderImage, this->createWeakPtr(), + passed(std::move(dispatcherTaskRunner)), + m_placeholderCanvasId, std::move(image), resource.id)); + m_spareResourceLocks.add(m_nextResourceId); + commitTypeHistogram.count(commitType); m_nextResourceId++; @@ -242,6 +280,10 @@ frame.render_pass_list.push_back(std::move(pass)); double elapsedTime = WTF::monotonicallyIncreasingTime() - commitStartTime; + + // TODO(crbug.com/663916): The off-main-thread metrics are commented-out + // because they cause thread check errors (static variable accessed in many + // threads) switch (commitType) { case CommitGPUCanvasGPUCompositing: if (isMainThread()) { @@ -250,13 +292,13 @@ ("Blink.Canvas.OffscreenCommit.GPUCanvasGPUCompositingMain", 0, 10000000, 50)); commitGPUCanvasGPUCompositingMainTimer.count(elapsedTime * 1000000.0); - } else { + } /* else { DEFINE_STATIC_LOCAL( CustomCountHistogram, commitGPUCanvasGPUCompositingWorkerTimer, ("Blink.Canvas.OffscreenCommit.GPUCanvasGPUCompositingWorker", 0, 10000000, 50)); commitGPUCanvasGPUCompositingWorkerTimer.count(elapsedTime * 1000000.0); - } + } */ break; case CommitGPUCanvasSoftwareCompositing: if (isMainThread()) { @@ -266,14 +308,14 @@ 10000000, 50)); commitGPUCanvasSoftwareCompositingMainTimer.count(elapsedTime * 1000000.0); - } else { + } /* else { DEFINE_STATIC_LOCAL( CustomCountHistogram, commitGPUCanvasSoftwareCompositingWorkerTimer, ("Blink.Canvas.OffscreenCommit.GPUCanvasSoftwareCompositingWorker", 0, 10000000, 50)); commitGPUCanvasSoftwareCompositingWorkerTimer.count(elapsedTime * 1000000.0); - } + } */ break; case CommitSoftwareCanvasGPUCompositing: if (isMainThread()) { @@ -283,14 +325,14 @@ 10000000, 50)); commitSoftwareCanvasGPUCompositingMainTimer.count(elapsedTime * 1000000.0); - } else { + } /* else { DEFINE_STATIC_LOCAL( CustomCountHistogram, commitSoftwareCanvasGPUCompositingWorkerTimer, ("Blink.Canvas.OffscreenCommit.SoftwareCanvasGPUCompositingWorker", 0, 10000000, 50)); commitSoftwareCanvasGPUCompositingWorkerTimer.count(elapsedTime * 1000000.0); - } + } */ break; case CommitSoftwareCanvasSoftwareCompositing: if (isMainThread()) { @@ -301,7 +343,7 @@ 0, 10000000, 50)); commitSoftwareCanvasSoftwareCompositingMainTimer.count(elapsedTime * 1000000.0); - } else { + } /* else { DEFINE_STATIC_LOCAL(CustomCountHistogram, commitSoftwareCanvasSoftwareCompositingWorkerTimer, ("Blink.Canvas.OffscreenCommit." @@ -309,7 +351,7 @@ 0, 10000000, 50)); commitSoftwareCanvasSoftwareCompositingWorkerTimer.count(elapsedTime * 1000000.0); - } + } */ break; case OffscreenCanvasCommitTypeCount: NOTREACHED(); @@ -331,12 +373,26 @@ RefPtr<StaticBitmapImage> image = m_cachedImages.get(resource.id); if (image) image->updateSyncToken(resource.sync_token); - m_cachedImages.remove(resource.id); - m_sharedBitmaps.remove(resource.id); - m_cachedTextureIds.remove(resource.id); + reclaimResource(resource.id); } } +void OffscreenCanvasFrameDispatcherImpl::reclaimResource(unsigned resourceId) { + // An image resource needs to be returned by both the + // CompositorFrameSink and the HTMLCanvasElement. These + // events can happen in any order. The first of the two + // to return a given resource will result in the spare + // resource lock being lifted, and the second will delete + // the resource for real. + if (m_spareResourceLocks.contains(resourceId)) { + m_spareResourceLocks.remove(resourceId); + return; + } + m_cachedImages.remove(resourceId); + m_sharedBitmaps.remove(resourceId); + m_cachedTextureIds.remove(resourceId); +} + bool OffscreenCanvasFrameDispatcherImpl::verifyImageSize( const IntSize imageSize) { if (imageSize.width() == m_width && imageSize.height() == m_height)
diff --git a/third_party/WebKit/Source/platform/graphics/OffscreenCanvasFrameDispatcherImpl.h b/third_party/WebKit/Source/platform/graphics/OffscreenCanvasFrameDispatcherImpl.h index eb015b8..e43b2c2 100644 --- a/third_party/WebKit/Source/platform/graphics/OffscreenCanvasFrameDispatcherImpl.h +++ b/third_party/WebKit/Source/platform/graphics/OffscreenCanvasFrameDispatcherImpl.h
@@ -26,6 +26,7 @@ uint32_t localId, uint64_t nonceHigh, uint64_t nonceLow, + int canvasId, int width, int height); @@ -34,6 +35,7 @@ void dispatchFrame(RefPtr<StaticBitmapImage>, double commitStartTime, bool isWebGLSoftwareRendering = false) override; + void reclaimResource(unsigned resourceId) override; // cc::mojom::blink::MojoCompositorFrameSinkClient implementation. void DidReceiveCompositorFrameAck() override; @@ -58,12 +60,15 @@ HashMap<unsigned, RefPtr<StaticBitmapImage>> m_cachedImages; HashMap<unsigned, std::unique_ptr<cc::SharedBitmap>> m_sharedBitmaps; HashMap<unsigned, GLuint> m_cachedTextureIds; + HashSet<unsigned> m_spareResourceLocks; bool verifyImageSize(const IntSize); cc::mojom::blink::MojoCompositorFrameSinkPtr m_sink; mojo::Binding<cc::mojom::blink::MojoCompositorFrameSinkClient> m_binding; + int m_placeholderCanvasId; + void setTransferableResourceToSharedBitmap(cc::TransferableResource&, RefPtr<StaticBitmapImage>); void setTransferableResourceToSharedGPUContext(cc::TransferableResource&,
diff --git a/third_party/WebKit/Source/platform/graphics/OffscreenCanvasPlaceholder.cpp b/third_party/WebKit/Source/platform/graphics/OffscreenCanvasPlaceholder.cpp new file mode 100644 index 0000000..e78f482 --- /dev/null +++ b/third_party/WebKit/Source/platform/graphics/OffscreenCanvasPlaceholder.cpp
@@ -0,0 +1,89 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "platform/graphics/OffscreenCanvasPlaceholder.h" + +#include "platform/CrossThreadFunctional.h" +#include "platform/WebTaskRunner.h" +#include "platform/graphics/Image.h" +#include "platform/graphics/OffscreenCanvasFrameDispatcher.h" +#include "wtf/HashMap.h" + +namespace { + +typedef HashMap<int, blink::OffscreenCanvasPlaceholder*> PlaceholderIdMap; + +PlaceholderIdMap& placeholderRegistry() { + DCHECK(isMainThread()); + DEFINE_STATIC_LOCAL(PlaceholderIdMap, s_placeholderRegistry, ()); + return s_placeholderRegistry; +} + +void releaseFrameToDispatcher( + WeakPtr<blink::OffscreenCanvasFrameDispatcher> dispatcher, + RefPtr<blink::Image> oldImage, + unsigned resourceId) { + oldImage = nullptr; // Needed to unref'ed on the right thread + if (dispatcher) { + dispatcher->reclaimResource(resourceId); + } +} + +} // unnamed namespace + +namespace blink { + +OffscreenCanvasPlaceholder::~OffscreenCanvasPlaceholder() { + unregisterPlaceholder(); +} + +OffscreenCanvasPlaceholder* OffscreenCanvasPlaceholder::getPlaceholderById( + unsigned placeholderId) { + PlaceholderIdMap::iterator it = placeholderRegistry().find(placeholderId); + if (it == placeholderRegistry().end()) + return nullptr; + return it->value; +} + +void OffscreenCanvasPlaceholder::registerPlaceholder(unsigned placeholderId) { + DCHECK(!placeholderRegistry().contains(placeholderId)); + DCHECK(!isPlaceholderRegistered()); + placeholderRegistry().add(placeholderId, this); + m_placeholderId = placeholderId; +} + +void OffscreenCanvasPlaceholder::unregisterPlaceholder() { + if (!isPlaceholderRegistered()) + return; + DCHECK(placeholderRegistry().find(m_placeholderId)->value == this); + placeholderRegistry().remove(m_placeholderId); + m_placeholderId = kNoPlaceholderId; +} + +void OffscreenCanvasPlaceholder::setPlaceholderFrame( + RefPtr<Image> newFrame, + WeakPtr<OffscreenCanvasFrameDispatcher> dispatcher, + std::unique_ptr<WebTaskRunner> taskRunner, + unsigned resourceId) { + DCHECK(isPlaceholderRegistered()); + releasePlaceholderFrame(); + m_placeholderFrame = std::move(newFrame); + m_frameDispatcher = std::move(dispatcher); + m_frameDispatcherTaskRunner = std::move(taskRunner); + m_placeholderFrameResourceId = resourceId; +} + +void OffscreenCanvasPlaceholder::releasePlaceholderFrame() { + DCHECK(isPlaceholderRegistered()); + if (m_placeholderFrame) { + m_placeholderFrame->transfer(); + m_frameDispatcherTaskRunner->postTask( + BLINK_FROM_HERE, + crossThreadBind(releaseFrameToDispatcher, std::move(m_frameDispatcher), + std::move(m_placeholderFrame), + m_placeholderFrameResourceId)); + } +} + +} // blink
diff --git a/third_party/WebKit/Source/platform/graphics/OffscreenCanvasPlaceholder.h b/third_party/WebKit/Source/platform/graphics/OffscreenCanvasPlaceholder.h new file mode 100644 index 0000000..f03040e --- /dev/null +++ b/third_party/WebKit/Source/platform/graphics/OffscreenCanvasPlaceholder.h
@@ -0,0 +1,53 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef OffscreenCanvasPlaceholder_h +#define OffscreenCanvasPlaceholder_h + +#include "platform/PlatformExport.h" +#include "wtf/RefPtr.h" +#include "wtf/WeakPtr.h" +#include <memory> + +namespace blink { + +class Image; +class OffscreenCanvasFrameDispatcher; +class WebTaskRunner; + +class PLATFORM_EXPORT OffscreenCanvasPlaceholder { + public: + ~OffscreenCanvasPlaceholder(); + + void setPlaceholderFrame(RefPtr<Image>, + WeakPtr<OffscreenCanvasFrameDispatcher>, + std::unique_ptr<WebTaskRunner>, + unsigned resourceId); + void releasePlaceholderFrame(); + + static OffscreenCanvasPlaceholder* getPlaceholderById(unsigned placeholderId); + + void registerPlaceholder(unsigned placeholderId); + void unregisterPlaceholder(); + const RefPtr<Image>& placeholderFrame() const { return m_placeholderFrame; } + + private: + bool isPlaceholderRegistered() const { + return m_placeholderId != kNoPlaceholderId; + } + + RefPtr<Image> m_placeholderFrame; + WeakPtr<OffscreenCanvasFrameDispatcher> m_frameDispatcher; + std::unique_ptr<WebTaskRunner> m_frameDispatcherTaskRunner; + unsigned m_placeholderFrameResourceId = 0; + + enum { + kNoPlaceholderId = -1, + }; + int m_placeholderId = kNoPlaceholderId; +}; + +} // blink + +#endif
diff --git a/third_party/WebKit/Source/platform/graphics/PictureSnapshot.cpp b/third_party/WebKit/Source/platform/graphics/PictureSnapshot.cpp index 608af47..085b12c 100644 --- a/third_party/WebKit/Source/platform/graphics/PictureSnapshot.cpp +++ b/third_party/WebKit/Source/platform/graphics/PictureSnapshot.cpp
@@ -142,7 +142,7 @@ canvas.resetStepCount(); m_picture->playback(&canvas, &canvas); } - std::unique_ptr<Vector<char>> base64Data = wrapUnique(new Vector<char>()); + std::unique_ptr<Vector<char>> base64Data = makeUnique<Vector<char>>(); Vector<char> encodedImage; sk_sp<SkImage> image = SkImage::MakeFromBitmap(bitmap); @@ -167,7 +167,7 @@ double minDuration, const FloatRect* clipRect) const { std::unique_ptr<PictureSnapshot::Timings> timings = - wrapUnique(new PictureSnapshot::Timings()); + makeUnique<PictureSnapshot::Timings>(); timings->reserveCapacity(minRepeatCount); const SkIRect bounds = m_picture->cullRect().roundOut(); SkBitmap bitmap;
diff --git a/third_party/WebKit/Source/platform/graphics/RecordingImageBufferSurfaceTest.cpp b/third_party/WebKit/Source/platform/graphics/RecordingImageBufferSurfaceTest.cpp index 646e23ce..f630f2d 100644 --- a/third_party/WebKit/Source/platform/graphics/RecordingImageBufferSurfaceTest.cpp +++ b/third_party/WebKit/Source/platform/graphics/RecordingImageBufferSurfaceTest.cpp
@@ -97,7 +97,7 @@ protected: RecordingImageBufferSurfaceTest() { std::unique_ptr<MockSurfaceFactory> surfaceFactory = - wrapUnique(new MockSurfaceFactory()); + makeUnique<MockSurfaceFactory>(); m_surfaceFactory = surfaceFactory.get(); std::unique_ptr<RecordingImageBufferSurface> testSurface = wrapUnique(new RecordingImageBufferSurface(
diff --git a/third_party/WebKit/Source/platform/graphics/StaticBitmapImage.h b/third_party/WebKit/Source/platform/graphics/StaticBitmapImage.h index 67d32a6..7753fa8 100644 --- a/third_party/WebKit/Source/platform/graphics/StaticBitmapImage.h +++ b/third_party/WebKit/Source/platform/graphics/StaticBitmapImage.h
@@ -38,7 +38,6 @@ // Methods that have a default implementation, and overrided by only one // sub-class virtual bool hasMailbox() { return false; } - virtual void transfer() {} // Methods overrided by AcceleratedStaticBitmapImage only virtual void copyToTexture(WebGraphicsContext3DProvider*,
diff --git a/third_party/WebKit/Source/platform/graphics/compositing/PaintArtifactCompositor.cpp b/third_party/WebKit/Source/platform/graphics/compositing/PaintArtifactCompositor.cpp index 20bdc54..c0e9d44 100644 --- a/third_party/WebKit/Source/platform/graphics/compositing/PaintArtifactCompositor.cpp +++ b/third_party/WebKit/Source/platform/graphics/compositing/PaintArtifactCompositor.cpp
@@ -673,7 +673,7 @@ // We currently create dummy layers to host effect nodes and corresponding // render surfaces. This should be removed once cc implements better support // for freestanding property trees. - scoped_refptr<cc::Layer> dummyLayer = cc::Layer::Create(); + scoped_refptr<cc::Layer> dummyLayer = nextEffect->ensureDummyLayer(); m_rootLayer->AddChild(dummyLayer); // Also cc assumes a clip node is always created by a layer that creates
diff --git a/third_party/WebKit/Source/platform/graphics/compositing/PaintArtifactCompositorTest.cpp b/third_party/WebKit/Source/platform/graphics/compositing/PaintArtifactCompositorTest.cpp index 6710c08..259d729 100644 --- a/third_party/WebKit/Source/platform/graphics/compositing/PaintArtifactCompositorTest.cpp +++ b/third_party/WebKit/Source/platform/graphics/compositing/PaintArtifactCompositorTest.cpp
@@ -68,7 +68,7 @@ settings.single_thread_proxy_scheduler = false; settings.use_layer_lists = true; m_webLayerTreeView = - wrapUnique(new WebLayerTreeViewWithCompositorFrameSink(settings)); + makeUnique<WebLayerTreeViewWithCompositorFrameSink>(settings); m_webLayerTreeView->setRootLayer(*m_paintArtifactCompositor->getWebLayer()); }
diff --git a/third_party/WebKit/Source/platform/graphics/paint/CompositingRecorder.cpp b/third_party/WebKit/Source/platform/graphics/paint/CompositingRecorder.cpp index 53c03d1..7930f26 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/CompositingRecorder.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/CompositingRecorder.cpp
@@ -63,6 +63,14 @@ // Re-record the last two DisplayItems into a new SkPicture. SkPictureBuilder pictureBuilder(cullRect, nullptr, &graphicsContext); { +#if DCHECK_IS_ON() + // The picture builder creates an internal paint controller that has been + // initialized with null paint properties. Painting into this controller + // without properties will not cause problems because the display item + // from this internal paint controller is immediately reunited with the + // correct properties. + DisableNullPaintPropertyChecks disabler; +#endif DrawingRecorder newRecorder(pictureBuilder.context(), displayItemClient, displayItemType, cullRect); DCHECK(!DrawingRecorder::useCachedDrawingIfPossible(
diff --git a/third_party/WebKit/Source/platform/graphics/paint/DisplayItem.cpp b/third_party/WebKit/Source/platform/graphics/paint/DisplayItem.cpp index f37ca39..ecaa5b61 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/DisplayItem.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/DisplayItem.cpp
@@ -68,6 +68,23 @@ return "Unknown" static WTF::String specialDrawingTypeAsDebugString(DisplayItem::Type type) { + if (type >= DisplayItem::kTableCollapsedBorderUnalignedBase) { + if (type <= DisplayItem::kTableCollapsedBorderBase) + return "TableCollapsedBorderAlignment"; + if (type <= DisplayItem::kTableCollapsedBorderLast) { + StringBuilder sb; + sb.append("TableCollapsedBorder"); + if (type & DisplayItem::TableCollapsedBorderTop) + sb.append("Top"); + if (type & DisplayItem::TableCollapsedBorderRight) + sb.append("Right"); + if (type & DisplayItem::TableCollapsedBorderBottom) + sb.append("Bottom"); + if (type & DisplayItem::TableCollapsedBorderLeft) + sb.append("Left"); + return sb.toString(); + } + } switch (type) { DEBUG_STRING_CASE(BoxDecorationBackground); DEBUG_STRING_CASE(Caret); @@ -109,7 +126,6 @@ DEBUG_STRING_CASE(TableCellBackgroundFromColumn); DEBUG_STRING_CASE(TableCellBackgroundFromSection); DEBUG_STRING_CASE(TableCellBackgroundFromRow); - DEBUG_STRING_CASE(TableCollapsedBorders); DEBUG_STRING_CASE(TableSectionBoxShadowInset); DEBUG_STRING_CASE(TableSectionBoxShadowNormal); DEBUG_STRING_CASE(TableRowBoxShadowInset);
diff --git a/third_party/WebKit/Source/platform/graphics/paint/DisplayItem.h b/third_party/WebKit/Source/platform/graphics/paint/DisplayItem.h index 591a3e7..69d0457 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/DisplayItem.h +++ b/third_party/WebKit/Source/platform/graphics/paint/DisplayItem.h
@@ -110,7 +110,15 @@ kTableCellBackgroundFromColumn, kTableCellBackgroundFromSection, kTableCellBackgroundFromRow, - kTableCollapsedBorders, + // Table collapsed borders can be painted together (e.g., left & top) but + // there are at most 4 phases of collapsed border painting for a single + // cell. To disambiguate these phases of collapsed border painting, a mask + // is used. TableCollapsedBorderBase can be larger than + // TableCollapsedBorderUnalignedBase to ensure the base lower bits are 0's. + kTableCollapsedBorderUnalignedBase, + kTableCollapsedBorderBase = + (((kTableCollapsedBorderUnalignedBase - 1) >> 4) + 1) << 4, + kTableCollapsedBorderLast = kTableCollapsedBorderBase + 0x0f, kTableSectionBoxShadowInset, kTableSectionBoxShadowNormal, kTableRowBoxShadowInset, @@ -194,6 +202,19 @@ kTypeLast = kUninitializedType }; + static_assert(kTableCollapsedBorderBase >= kTableCollapsedBorderUnalignedBase, + "TableCollapsedBorder types overlap with other types"); + static_assert((kTableCollapsedBorderBase & 0xf) == 0, + "The lowest 4 bits of TableCollapsedBorderBase should be zero"); + // Bits or'ed onto TableCollapsedBorderBase to generate a real table collapsed + // border type. + enum TableCollapsedBorderSides { + TableCollapsedBorderTop = 1 << 0, + TableCollapsedBorderRight = 1 << 1, + TableCollapsedBorderBottom = 1 << 2, + TableCollapsedBorderLeft = 1 << 3, + }; + DisplayItem(const DisplayItemClient& client, Type type, size_t derivedSize) : m_client(&client), m_type(type),
diff --git a/third_party/WebKit/Source/platform/graphics/paint/EffectPaintPropertyNode.cpp b/third_party/WebKit/Source/platform/graphics/paint/EffectPaintPropertyNode.cpp index 27a0201..a40586f0 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/EffectPaintPropertyNode.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/EffectPaintPropertyNode.cpp
@@ -15,4 +15,11 @@ return root; } +cc::Layer* EffectPaintPropertyNode::ensureDummyLayer() const { + if (m_dummyLayer) + return m_dummyLayer.get(); + m_dummyLayer = cc::Layer::Create(); + return m_dummyLayer.get(); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/platform/graphics/paint/EffectPaintPropertyNode.h b/third_party/WebKit/Source/platform/graphics/paint/EffectPaintPropertyNode.h index e2d6099ee..fd8a894e 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/EffectPaintPropertyNode.h +++ b/third_party/WebKit/Source/platform/graphics/paint/EffectPaintPropertyNode.h
@@ -5,6 +5,7 @@ #ifndef EffectPaintPropertyNode_h #define EffectPaintPropertyNode_h +#include "cc/layers/layer.h" #include "platform/PlatformExport.h" #include "platform/graphics/CompositorFilterOperations.h" #include "platform/graphics/paint/ClipPaintPropertyNode.h" @@ -64,6 +65,8 @@ const EffectPaintPropertyNode* parent() const { return m_parent.get(); } bool isRoot() const { return !m_parent; } + cc::Layer* ensureDummyLayer() const; + #if DCHECK_IS_ON() // The clone function is used by FindPropertiesNeedingUpdate.h for recording // an effect node before it has been updated, to later detect changes. @@ -112,6 +115,13 @@ CompositorFilterOperations m_filter; float m_opacity; // === End of effects === + + // TODO(trchen): Remove the dummy layer. + // The main purpose of the dummy layer is to maintain a permanent identity + // to associate with cc::RenderSurfaceImpl for damage tracking. This shall + // be removed in favor of a stable ID once cc::LayerImpl no longer owns + // RenderSurfaceImpl. + mutable scoped_refptr<cc::Layer> m_dummyLayer; }; // Redeclared here to avoid ODR issues.
diff --git a/third_party/WebKit/Source/platform/graphics/paint/GeometryMapper.h b/third_party/WebKit/Source/platform/graphics/paint/GeometryMapper.h index 720d222..6a84c56 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/GeometryMapper.h +++ b/third_party/WebKit/Source/platform/graphics/paint/GeometryMapper.h
@@ -27,7 +27,7 @@ HashMap<const ClipPaintPropertyNode*, FloatRect> toAncestorClipRects; static std::unique_ptr<PrecomputedDataForAncestor> create() { - return wrapUnique(new PrecomputedDataForAncestor()); + return makeUnique<PrecomputedDataForAncestor>(); } };
diff --git a/third_party/WebKit/Source/platform/graphics/paint/GeometryMapperTest.cpp b/third_party/WebKit/Source/platform/graphics/paint/GeometryMapperTest.cpp index ded4b9d..f40c28e 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/GeometryMapperTest.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/GeometryMapperTest.cpp
@@ -52,7 +52,7 @@ 1.0); rootScrollNode = ScrollPaintPropertyNode::create( nullptr, rootTransformNode, IntSize(), IntSize(), false, false); - geometryMapper = wrapUnique(new GeometryMapper()); + geometryMapper = makeUnique<GeometryMapper>(); } void TearDown() override { geometryMapper.reset(); }
diff --git a/third_party/WebKit/Source/platform/graphics/paint/PaintChunker.cpp b/third_party/WebKit/Source/platform/graphics/paint/PaintChunker.cpp index 33b273b..1a64e549 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/PaintChunker.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/PaintChunker.cpp
@@ -8,6 +8,12 @@ namespace blink { +#if DCHECK_IS_ON() +static bool gNullPaintPropertyChecksDisabled = false; +DisableNullPaintPropertyChecks::DisableNullPaintPropertyChecks() + : m_disabler(&gNullPaintPropertyChecksDisabled, true) {} +#endif + PaintChunker::PaintChunker() {} PaintChunker::~PaintChunker() {} @@ -26,6 +32,19 @@ bool PaintChunker::incrementDisplayItemIndex(const DisplayItem& item) { DCHECK(RuntimeEnabledFeatures::slimmingPaintV2Enabled()); +#if DCHECK_IS_ON() + if (!gNullPaintPropertyChecksDisabled) { + // Property nodes should never be null because they should either be set to + // properties created by a LayoutObject/FrameView, or be set to a non-null + // root node. If these DCHECKs are hit we are missing a call to update the + // properties. See: ScopedPaintChunkProperties. + DCHECK(m_currentProperties.transform); + DCHECK(m_currentProperties.clip); + DCHECK(m_currentProperties.effect); + DCHECK(m_currentProperties.scroll); + } +#endif + ItemBehavior behavior; Optional<PaintChunk::Id> newChunkId; if (DisplayItem::isForeignLayerType(item.getType())) {
diff --git a/third_party/WebKit/Source/platform/graphics/paint/PaintChunker.h b/third_party/WebKit/Source/platform/graphics/paint/PaintChunker.h index c96a059..acf1558 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/PaintChunker.h +++ b/third_party/WebKit/Source/platform/graphics/paint/PaintChunker.h
@@ -10,6 +10,7 @@ #include "platform/graphics/paint/PaintChunk.h" #include "platform/graphics/paint/PaintChunkProperties.h" #include "wtf/Allocator.h" +#include "wtf/AutoReset.h" #include "wtf/Noncopyable.h" #include "wtf/Vector.h" @@ -74,6 +75,19 @@ PaintChunkProperties m_currentProperties; }; +#if DCHECK_IS_ON() +class DisableNullPaintPropertyChecks { + STACK_ALLOCATED(); + WTF_MAKE_NONCOPYABLE(DisableNullPaintPropertyChecks); + + public: + DisableNullPaintPropertyChecks(); + + private: + AutoReset<bool> m_disabler; +}; +#endif // DCHECK_IS_ON() + } // namespace blink #endif // PaintChunker_h
diff --git a/third_party/WebKit/Source/platform/graphics/paint/PaintChunkerTest.cpp b/third_party/WebKit/Source/platform/graphics/paint/PaintChunkerTest.cpp index ff3e5c1a..d36cfce 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/PaintChunkerTest.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/PaintChunkerTest.cpp
@@ -18,7 +18,12 @@ #if defined(NDEBUG) || !OS(WIN) PaintChunkProperties rootPaintChunkProperties() { - return PaintChunkProperties(); + PaintChunkProperties rootProperties; + rootProperties.transform = TransformPaintPropertyNode::root(); + rootProperties.clip = ClipPaintPropertyNode::root(); + rootProperties.effect = EffectPaintPropertyNode::root(); + rootProperties.scroll = ScrollPaintPropertyNode::root(); + return rootProperties; } class PaintChunkerTest : public testing::Test { @@ -111,14 +116,14 @@ chunker.incrementDisplayItemIndex(NormalTestDisplayItem()); chunker.incrementDisplayItemIndex(NormalTestDisplayItem()); - PaintChunkProperties simpleTransform; + PaintChunkProperties simpleTransform = rootPaintChunkProperties(); simpleTransform.transform = TransformPaintPropertyNode::create( nullptr, TransformationMatrix(0, 1, 2, 3, 4, 5), FloatPoint3D(9, 8, 7)); chunker.updateCurrentPaintChunkProperties(nullptr, simpleTransform); chunker.incrementDisplayItemIndex(NormalTestDisplayItem()); - PaintChunkProperties anotherTransform; + PaintChunkProperties anotherTransform = rootPaintChunkProperties(); anotherTransform.transform = TransformPaintPropertyNode::create( nullptr, TransformationMatrix(0, 1, 2, 3, 4, 5), FloatPoint3D(9, 8, 7)); chunker.updateCurrentPaintChunkProperties(nullptr, anotherTransform); @@ -138,14 +143,14 @@ rootPaintChunkProperties()); chunker.incrementDisplayItemIndex(NormalTestDisplayItem()); - PaintChunkProperties simpleTransform; + PaintChunkProperties simpleTransform = rootPaintChunkProperties(); simpleTransform.transform = TransformPaintPropertyNode::create( nullptr, TransformationMatrix(0, 0, 0, 0, 0, 0), FloatPoint3D(9, 8, 7)); chunker.updateCurrentPaintChunkProperties(nullptr, simpleTransform); chunker.incrementDisplayItemIndex(NormalTestDisplayItem()); chunker.incrementDisplayItemIndex(NormalTestDisplayItem()); - PaintChunkProperties simpleTransformAndEffect; + PaintChunkProperties simpleTransformAndEffect = rootPaintChunkProperties(); simpleTransformAndEffect.transform = simpleTransform.transform; simpleTransformAndEffect.effect = EffectPaintPropertyNode::create( EffectPaintPropertyNode::root(), TransformPaintPropertyNode::root(), @@ -154,7 +159,8 @@ chunker.incrementDisplayItemIndex(NormalTestDisplayItem()); chunker.incrementDisplayItemIndex(NormalTestDisplayItem()); - PaintChunkProperties simpleTransformAndEffectWithUpdatedTransform; + PaintChunkProperties simpleTransformAndEffectWithUpdatedTransform = + rootPaintChunkProperties(); simpleTransformAndEffectWithUpdatedTransform.transform = TransformPaintPropertyNode::create(nullptr, TransformationMatrix(1, 1, 0, 0, 0, 0), @@ -197,7 +203,7 @@ rootPaintChunkProperties()); chunker.incrementDisplayItemIndex(NormalTestDisplayItem()); - PaintChunkProperties simpleTransform; + PaintChunkProperties simpleTransform = rootPaintChunkProperties(); simpleTransform.transform = TransformPaintPropertyNode::create( nullptr, TransformationMatrix(0, 1, 2, 3, 4, 5), FloatPoint3D(9, 8, 7)); chunker.updateCurrentPaintChunkProperties(nullptr, simpleTransform); @@ -224,12 +230,12 @@ rootPaintChunkProperties()); chunker.incrementDisplayItemIndex(NormalTestDisplayItem()); - PaintChunkProperties firstTransform; + PaintChunkProperties firstTransform = rootPaintChunkProperties(); firstTransform.transform = TransformPaintPropertyNode::create( nullptr, TransformationMatrix(0, 1, 2, 3, 4, 5), FloatPoint3D(9, 8, 7)); chunker.updateCurrentPaintChunkProperties(nullptr, firstTransform); - PaintChunkProperties secondTransform; + PaintChunkProperties secondTransform = rootPaintChunkProperties(); secondTransform.transform = TransformPaintPropertyNode::create( nullptr, TransformationMatrix(9, 8, 7, 6, 5, 4), FloatPoint3D(3, 2, 1)); chunker.updateCurrentPaintChunkProperties(nullptr, secondTransform); @@ -284,10 +290,12 @@ TestDisplayItemRequiringSeparateChunk i2; DisplayItem::Id id2 = i2.getId(); + chunker.updateCurrentPaintChunkProperties(nullptr, + rootPaintChunkProperties()); chunker.incrementDisplayItemIndex(NormalTestDisplayItem()); chunker.incrementDisplayItemIndex(NormalTestDisplayItem()); - PaintChunkProperties simpleTransform; + PaintChunkProperties simpleTransform = rootPaintChunkProperties(); simpleTransform.transform = TransformPaintPropertyNode::create( nullptr, TransformationMatrix(0, 1, 2, 3, 4, 5), FloatPoint3D(9, 8, 7)); chunker.updateCurrentPaintChunkProperties(&id1, simpleTransform); @@ -319,10 +327,12 @@ TestDisplayItemRequiringSeparateChunk i2; i2.setSkippedCache(); + chunker.updateCurrentPaintChunkProperties(nullptr, + rootPaintChunkProperties()); chunker.incrementDisplayItemIndex(NormalTestDisplayItem()); chunker.incrementDisplayItemIndex(NormalTestDisplayItem()); - PaintChunkProperties simpleTransform; + PaintChunkProperties simpleTransform = rootPaintChunkProperties(); simpleTransform.transform = TransformPaintPropertyNode::create( nullptr, TransformationMatrix(0, 1, 2, 3, 4, 5), FloatPoint3D(9, 8, 7)); chunker.updateCurrentPaintChunkProperties(&id1, simpleTransform);
diff --git a/third_party/WebKit/Source/platform/graphics/paint/PaintControllerTest.cpp b/third_party/WebKit/Source/platform/graphics/paint/PaintControllerTest.cpp index 7f4bf7333..870d850 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/PaintControllerTest.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/PaintControllerTest.cpp
@@ -54,6 +54,15 @@ RuntimeEnabledFeatures::Backup m_featuresBackup; }; +PaintChunkProperties rootPaintChunkProperties() { + PaintChunkProperties rootProperties; + rootProperties.transform = TransformPaintPropertyNode::root(); + rootProperties.clip = ClipPaintPropertyNode::root(); + rootProperties.effect = EffectPaintPropertyNode::root(); + rootProperties.scroll = ScrollPaintPropertyNode::root(); + return rootProperties; +} + const DisplayItem::Type foregroundDrawingType = static_cast<DisplayItem::Type>(DisplayItem::kDrawingPaintPhaseFirst + 4); const DisplayItem::Type backgroundDrawingType = @@ -166,9 +175,10 @@ TEST_P(PaintControllerTest, NestedRecorders) { GraphicsContext context(getPaintController()); FakeDisplayItemClient client("client", LayoutRect(100, 100, 200, 200)); - if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { getPaintController().updateCurrentPaintChunkProperties( - &m_rootPaintChunkId, PaintChunkProperties()); + &m_rootPaintChunkId, rootPaintChunkProperties()); + } drawClippedRect(context, client, clipType, backgroundDrawingType, FloatRect(100, 100, 200, 200)); @@ -191,9 +201,10 @@ FakeDisplayItemClient first("first", LayoutRect(100, 100, 300, 300)); FakeDisplayItemClient second("second", LayoutRect(100, 100, 200, 200)); GraphicsContext context(getPaintController()); - if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { getPaintController().updateCurrentPaintChunkProperties( - &m_rootPaintChunkId, PaintChunkProperties()); + &m_rootPaintChunkId, rootPaintChunkProperties()); + } drawRect(context, first, backgroundDrawingType, FloatRect(100, 100, 300, 300)); @@ -217,7 +228,7 @@ UnorderedElementsAre(FloatRect(LayoutRect::infiniteIntRect()))); getPaintController().updateCurrentPaintChunkProperties( - &m_rootPaintChunkId, PaintChunkProperties()); + &m_rootPaintChunkId, rootPaintChunkProperties()); } drawRect(context, first, backgroundDrawingType, @@ -252,9 +263,10 @@ FakeDisplayItemClient second("second", LayoutRect(100, 100, 50, 200)); FakeDisplayItemClient unaffected("unaffected", LayoutRect(300, 300, 10, 10)); GraphicsContext context(getPaintController()); - if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { getPaintController().updateCurrentPaintChunkProperties( - &m_rootPaintChunkId, PaintChunkProperties()); + &m_rootPaintChunkId, rootPaintChunkProperties()); + } drawRect(context, first, backgroundDrawingType, FloatRect(100, 100, 100, 100)); @@ -269,9 +281,6 @@ drawRect(context, unaffected, foregroundDrawingType, FloatRect(300, 300, 10, 10)); getPaintController().commitNewDisplayItems(); - if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) - getPaintController().updateCurrentPaintChunkProperties( - &m_rootPaintChunkId, PaintChunkProperties()); EXPECT_DISPLAY_LIST(getPaintController().getDisplayItemList(), 6, TestDisplayItem(first, backgroundDrawingType), @@ -281,6 +290,10 @@ TestDisplayItem(unaffected, backgroundDrawingType), TestDisplayItem(unaffected, foregroundDrawingType)); + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { + getPaintController().updateCurrentPaintChunkProperties( + &m_rootPaintChunkId, rootPaintChunkProperties()); + } drawRect(context, second, backgroundDrawingType, FloatRect(100, 100, 50, 200)); drawRect(context, second, foregroundDrawingType, @@ -324,9 +337,10 @@ FakeDisplayItemClient second("second", LayoutRect(100, 100, 50, 200)); FakeDisplayItemClient unaffected("unaffected", LayoutRect(300, 300, 10, 10)); GraphicsContext context(getPaintController()); - if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { getPaintController().updateCurrentPaintChunkProperties( - &m_rootPaintChunkId, PaintChunkProperties()); + &m_rootPaintChunkId, rootPaintChunkProperties()); + } drawRect(context, first, backgroundDrawingType, FloatRect(100, 100, 100, 100)); @@ -350,9 +364,10 @@ TestDisplayItem(unaffected, backgroundDrawingType), TestDisplayItem(unaffected, foregroundDrawingType)); - if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { getPaintController().updateCurrentPaintChunkProperties( - &m_rootPaintChunkId, PaintChunkProperties()); + &m_rootPaintChunkId, rootPaintChunkProperties()); + } first.setDisplayItemsUncached(); drawRect(context, second, backgroundDrawingType, @@ -401,9 +416,10 @@ FakeDisplayItemClient second("second", LayoutRect(100, 100, 50, 200)); FakeDisplayItemClient third("third", LayoutRect(125, 100, 200, 50)); GraphicsContext context(getPaintController()); - if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { getPaintController().updateCurrentPaintChunkProperties( - &m_rootPaintChunkId, PaintChunkProperties()); + &m_rootPaintChunkId, rootPaintChunkProperties()); + } drawRect(context, first, backgroundDrawingType, FloatRect(100, 100, 100, 100)); @@ -415,9 +431,10 @@ TestDisplayItem(first, backgroundDrawingType), TestDisplayItem(second, backgroundDrawingType)); - if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { getPaintController().updateCurrentPaintChunkProperties( - &m_rootPaintChunkId, PaintChunkProperties()); + &m_rootPaintChunkId, rootPaintChunkProperties()); + } drawRect(context, first, backgroundDrawingType, FloatRect(100, 100, 100, 100)); @@ -453,9 +470,10 @@ FakeDisplayItemClient second("second", LayoutRect(100, 100, 50, 200)); FakeDisplayItemClient third("third", LayoutRect(300, 100, 50, 50)); GraphicsContext context(getPaintController()); - if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { getPaintController().updateCurrentPaintChunkProperties( - &m_rootPaintChunkId, PaintChunkProperties()); + &m_rootPaintChunkId, rootPaintChunkProperties()); + } drawRect(context, first, backgroundDrawingType, FloatRect(100, 100, 100, 100)); @@ -477,9 +495,10 @@ TestDisplayItem(second, foregroundDrawingType), TestDisplayItem(third, foregroundDrawingType)); - if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { getPaintController().updateCurrentPaintChunkProperties( - &m_rootPaintChunkId, PaintChunkProperties()); + &m_rootPaintChunkId, rootPaintChunkProperties()); + } second.setDisplayItemsUncached(); drawRect(context, first, backgroundDrawingType, @@ -523,9 +542,10 @@ FakeDisplayItemClient first("first", LayoutRect(100, 100, 150, 150)); FakeDisplayItemClient second("second", LayoutRect(200, 200, 50, 50)); GraphicsContext context(getPaintController()); - if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { getPaintController().updateCurrentPaintChunkProperties( - &m_rootPaintChunkId, PaintChunkProperties()); + &m_rootPaintChunkId, rootPaintChunkProperties()); + } drawRect(context, second, backgroundDrawingType, FloatRect(200, 200, 50, 50)); drawRect(context, second, foregroundDrawingType, FloatRect(200, 200, 50, 50)); @@ -535,9 +555,10 @@ TestDisplayItem(second, backgroundDrawingType), TestDisplayItem(second, foregroundDrawingType)); - if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { getPaintController().updateCurrentPaintChunkProperties( - &m_rootPaintChunkId, PaintChunkProperties()); + &m_rootPaintChunkId, rootPaintChunkProperties()); + } first.setDisplayItemsUncached(); second.setDisplayItemsUncached(); @@ -569,7 +590,7 @@ FloatRect(150, 150, 100, 100))); // New bounds of |second|. getPaintController().updateCurrentPaintChunkProperties( - &m_rootPaintChunkId, PaintChunkProperties()); + &m_rootPaintChunkId, rootPaintChunkProperties()); } drawRect(context, second, backgroundDrawingType, @@ -603,9 +624,10 @@ FakeDisplayItemClient first("first", LayoutRect(100, 100, 150, 150)); FakeDisplayItemClient second("second", LayoutRect(200, 200, 50, 50)); GraphicsContext context(getPaintController()); - if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { getPaintController().updateCurrentPaintChunkProperties( - &m_rootPaintChunkId, PaintChunkProperties()); + &m_rootPaintChunkId, rootPaintChunkProperties()); + } drawRect(context, first, backgroundDrawingType, FloatRect(100, 100, 150, 150)); @@ -617,9 +639,10 @@ TestDisplayItem(first, backgroundDrawingType), TestDisplayItem(first, foregroundDrawingType)); - if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { getPaintController().updateCurrentPaintChunkProperties( - &m_rootPaintChunkId, PaintChunkProperties()); + &m_rootPaintChunkId, rootPaintChunkProperties()); + } first.setDisplayItemsUncached(); first.setVisualRect(LayoutRect(150, 150, 100, 100)); @@ -649,7 +672,7 @@ 50))); // |second| newly appeared in the chunk. getPaintController().updateCurrentPaintChunkProperties( - &m_rootPaintChunkId, PaintChunkProperties()); + &m_rootPaintChunkId, rootPaintChunkProperties()); } first.setDisplayItemsUncached(); @@ -685,7 +708,7 @@ { if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { PaintChunk::Id id(first, clipType); - PaintChunkProperties properties; + PaintChunkProperties properties = rootPaintChunkProperties(); properties.clip = ClipPaintPropertyNode::create( nullptr, nullptr, FloatRoundedRect(1, 1, 2, 2)); getPaintController().updateCurrentPaintChunkProperties(&id, properties); @@ -705,9 +728,10 @@ TestDisplayItem(second, backgroundDrawingType), TestDisplayItem(first, DisplayItem::clipTypeToEndClipType(clipType))); - if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { getPaintController().updateCurrentPaintChunkProperties( - &m_rootPaintChunkId, PaintChunkProperties()); + &m_rootPaintChunkId, rootPaintChunkProperties()); + } first.setDisplayItemsUncached(); drawRect(context, first, backgroundDrawingType, @@ -735,7 +759,7 @@ LayoutRect::infiniteIntRect()))); // This is a new chunk. getPaintController().updateCurrentPaintChunkProperties( - &m_rootPaintChunkId, PaintChunkProperties()); + &m_rootPaintChunkId, rootPaintChunkProperties()); } second.setDisplayItemsUncached(); @@ -744,7 +768,7 @@ { if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { PaintChunk::Id id(second, clipType); - PaintChunkProperties properties; + PaintChunkProperties properties = rootPaintChunkProperties(); properties.clip = ClipPaintPropertyNode::create( nullptr, nullptr, FloatRoundedRect(1, 1, 2, 2)); getPaintController().updateCurrentPaintChunkProperties(&id, properties); @@ -778,6 +802,10 @@ FakeDisplayItemClient first("first"); FakeDisplayItemClient second("second"); GraphicsContext context(getPaintController()); + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { + getPaintController().updateCurrentPaintChunkProperties( + &m_rootPaintChunkId, rootPaintChunkProperties()); + } drawRect(context, first, backgroundDrawingType, FloatRect(100, 100, 150, 150)); @@ -803,6 +831,10 @@ EXPECT_FALSE(getPaintController().clientCacheIsValid(first)); EXPECT_TRUE(getPaintController().clientCacheIsValid(second)); + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { + getPaintController().updateCurrentPaintChunkProperties( + &m_rootPaintChunkId, rootPaintChunkProperties()); + } drawRect(context, first, backgroundDrawingType, FloatRect(100, 100, 150, 150)); drawRect(context, second, backgroundDrawingType, @@ -837,9 +869,10 @@ LayoutRect(100, 200, 100, 100)); FakeDisplayItemClient content2("content2", LayoutRect(100, 200, 50, 200)); GraphicsContext context(getPaintController()); - if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { getPaintController().updateCurrentPaintChunkProperties( - &m_rootPaintChunkId, PaintChunkProperties()); + &m_rootPaintChunkId, rootPaintChunkProperties()); + } drawRect(context, container1, backgroundDrawingType, FloatRect(100, 100, 100, 100)); @@ -869,9 +902,10 @@ TestDisplayItem(content2, foregroundDrawingType), TestDisplayItem(container2, foregroundDrawingType)); - if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { getPaintController().updateCurrentPaintChunkProperties( - &m_rootPaintChunkId, PaintChunkProperties()); + &m_rootPaintChunkId, rootPaintChunkProperties()); + } // Simulate the situation when |container1| gets a z-index that is greater // than that of |container2|. @@ -923,9 +957,10 @@ LayoutRect(100, 200, 100, 100)); FakeDisplayItemClient content2("content2", LayoutRect(100, 200, 50, 200)); GraphicsContext context(getPaintController()); - if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { getPaintController().updateCurrentPaintChunkProperties( - &m_rootPaintChunkId, PaintChunkProperties()); + &m_rootPaintChunkId, rootPaintChunkProperties()); + } drawRect(context, container1, backgroundDrawingType, FloatRect(100, 100, 100, 100)); @@ -955,9 +990,10 @@ TestDisplayItem(content2, foregroundDrawingType), TestDisplayItem(container2, foregroundDrawingType)); - if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { getPaintController().updateCurrentPaintChunkProperties( - &m_rootPaintChunkId, PaintChunkProperties()); + &m_rootPaintChunkId, rootPaintChunkProperties()); + } // Simulate the situation when |container1| gets a z-index that is greater // than that of |container2|, and |container1| is invalidated. @@ -1013,8 +1049,8 @@ FakeDisplayItemClient content2("content2", LayoutRect(100, 200, 50, 200)); GraphicsContext context(getPaintController()); - PaintChunkProperties container1Properties; - PaintChunkProperties container2Properties; + PaintChunkProperties container1Properties = rootPaintChunkProperties(); + PaintChunkProperties container2Properties = rootPaintChunkProperties(); { if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { @@ -1185,8 +1221,8 @@ FakeDisplayItemClient content2("content2", LayoutRect(100, 200, 50, 200)); GraphicsContext context(getPaintController()); - PaintChunkProperties container1Properties; - PaintChunkProperties container2Properties; + PaintChunkProperties container1Properties = rootPaintChunkProperties(); + PaintChunkProperties container2Properties = rootPaintChunkProperties(); { if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { @@ -1297,6 +1333,10 @@ const DisplayItem::Type type4 = static_cast<DisplayItem::Type>(DisplayItem::kDrawingFirst + 3); + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { + getPaintController().updateCurrentPaintChunkProperties( + &m_rootPaintChunkId, rootPaintChunkProperties()); + } drawRect(context, client, type1, FloatRect(100, 100, 100, 100)); drawRect(context, client, type2, FloatRect(100, 100, 50, 200)); drawRect(context, client, type3, FloatRect(100, 100, 50, 200)); @@ -1304,6 +1344,10 @@ getPaintController().commitNewDisplayItems(); + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { + getPaintController().updateCurrentPaintChunkProperties( + &m_rootPaintChunkId, rootPaintChunkProperties()); + } drawRect(context, client, type2, FloatRect(100, 100, 50, 200)); drawRect(context, client, type3, FloatRect(100, 100, 50, 200)); drawRect(context, client, type1, FloatRect(100, 100, 100, 100)); @@ -1321,11 +1365,14 @@ FakeDisplayItemClient content2("content2", LayoutRect(100, 200, 50, 200)); GraphicsContext context(getPaintController()); - PaintChunkProperties container1BackgroundProperties; - PaintChunkProperties content1Properties; - PaintChunkProperties container1ForegroundProperties; - PaintChunkProperties container2BackgroundProperties; - PaintChunkProperties content2Properties; + PaintChunkProperties container1BackgroundProperties = + rootPaintChunkProperties(); + PaintChunkProperties content1Properties = rootPaintChunkProperties(); + PaintChunkProperties container1ForegroundProperties = + rootPaintChunkProperties(); + PaintChunkProperties container2BackgroundProperties = + rootPaintChunkProperties(); + PaintChunkProperties content2Properties = rootPaintChunkProperties(); { if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { @@ -1547,9 +1594,10 @@ FakeDisplayItemClient multicol("multicol", LayoutRect(100, 100, 200, 200)); FakeDisplayItemClient content("content", LayoutRect(100, 100, 100, 100)); GraphicsContext context(getPaintController()); - if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { getPaintController().updateCurrentPaintChunkProperties( - &m_rootPaintChunkId, PaintChunkProperties()); + &m_rootPaintChunkId, rootPaintChunkProperties()); + } FloatRect rect1(100, 100, 50, 50); FloatRect rect2(150, 100, 50, 50); @@ -1585,7 +1633,7 @@ UnorderedElementsAre(FloatRect(LayoutRect::infiniteIntRect()))); getPaintController().updateCurrentPaintChunkProperties( - &m_rootPaintChunkId, PaintChunkProperties()); + &m_rootPaintChunkId, rootPaintChunkProperties()); } // Draw again with nothing invalidated. @@ -1627,7 +1675,7 @@ FloatRect(100, 100, 100, 100))); // New bounds of |content|. getPaintController().updateCurrentPaintChunkProperties( - &m_rootPaintChunkId, PaintChunkProperties()); + &m_rootPaintChunkId, rootPaintChunkProperties()); } // Now the multicol becomes 3 columns and repaints. @@ -1676,6 +1724,10 @@ FloatRect rect2(150, 100, 50, 50); FloatRect rect3(200, 100, 50, 50); + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { + getPaintController().updateCurrentPaintChunkProperties( + &m_rootPaintChunkId, rootPaintChunkProperties()); + } drawRect(context, content, backgroundDrawingType, rect1); getPaintController().beginSkippingCache(); drawRect(context, content, foregroundDrawingType, rect2); @@ -1706,6 +1758,10 @@ EXPECT_FALSE(getPaintController().clientCacheIsValid(content)); EXPECT_EQ(PaintInvalidationFull, content.getPaintInvalidationReason()); + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { + getPaintController().updateCurrentPaintChunkProperties( + &m_rootPaintChunkId, rootPaintChunkProperties()); + } // Draw again with nothing invalidated. drawRect(context, content, backgroundDrawingType, rect1); getPaintController().beginSkippingCache(); @@ -1793,6 +1849,10 @@ RuntimeEnabledFeatures::setSlimmingPaintV2Enabled(true); FakeDisplayItemClient client("test client"); + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { + getPaintController().updateCurrentPaintChunkProperties( + nullptr, rootPaintChunkProperties()); + } GraphicsContext context(getPaintController()); drawRect(context, client, backgroundDrawingType, FloatRect(0, 0, 100, 100));
diff --git a/third_party/WebKit/Source/platform/graphics/test/MockImageDecoder.h b/third_party/WebKit/Source/platform/graphics/test/MockImageDecoder.h index 5eb7769b..5c9ad100 100644 --- a/third_party/WebKit/Source/platform/graphics/test/MockImageDecoder.h +++ b/third_party/WebKit/Source/platform/graphics/test/MockImageDecoder.h
@@ -62,7 +62,7 @@ public: static std::unique_ptr<MockImageDecoder> create( MockImageDecoderClient* client) { - return wrapUnique(new MockImageDecoder(client)); + return makeUnique<MockImageDecoder>(client); } MockImageDecoder(MockImageDecoderClient* client)
diff --git a/third_party/WebKit/Source/platform/heap/Heap.cpp b/third_party/WebKit/Source/platform/heap/Heap.cpp index 5388141..31b391c 100644 --- a/third_party/WebKit/Source/platform/heap/Heap.cpp +++ b/third_party/WebKit/Source/platform/heap/Heap.cpp
@@ -205,9 +205,9 @@ } ThreadHeap::ThreadHeap() - : m_regionTree(wrapUnique(new RegionTree())), + : m_regionTree(makeUnique<RegionTree>()), m_heapDoesNotContainCache(wrapUnique(new HeapDoesNotContainCache)), - m_safePointBarrier(wrapUnique(new SafePointBarrier())), + m_safePointBarrier(makeUnique<SafePointBarrier>()), m_freePagePool(wrapUnique(new FreePagePool)), m_orphanedPagePool(wrapUnique(new OrphanedPagePool)), m_markingStack(CallbackStack::create()),
diff --git a/third_party/WebKit/Source/platform/heap/HeapTest.cpp b/third_party/WebKit/Source/platform/heap/HeapTest.cpp index 40068ee..0cb7a06 100644 --- a/third_party/WebKit/Source/platform/heap/HeapTest.cpp +++ b/third_party/WebKit/Source/platform/heap/HeapTest.cpp
@@ -1291,11 +1291,12 @@ static ObserverMap& observe(Observable& target) { ObserverMap& map = observers(); ObserverMap::AddResult result = map.add(&target, nullptr); - if (result.isNewEntry) + if (result.isNewEntry) { result.storedValue->value = - wrapUnique(new FinalizationObserverWithHashMap(target)); - else + makeUnique<FinalizationObserverWithHashMap>(target); + } else { ASSERT(result.storedValue->value); + } return map; } @@ -6488,7 +6489,7 @@ TEST(HeapTest, WeakPersistent) { Persistent<IntWrapper> object = new IntWrapper(20); std::unique_ptr<WeakPersistentHolder> holder = - wrapUnique(new WeakPersistentHolder(object)); + makeUnique<WeakPersistentHolder>(object); preciselyCollectGarbage(); EXPECT_TRUE(holder->object()); object = nullptr;
diff --git a/third_party/WebKit/Source/platform/heap/ThreadState.cpp b/third_party/WebKit/Source/platform/heap/ThreadState.cpp index 9c2889ab..51f445f 100644 --- a/third_party/WebKit/Source/platform/heap/ThreadState.cpp +++ b/third_party/WebKit/Source/platform/heap/ThreadState.cpp
@@ -140,7 +140,7 @@ ThreadState::ThreadState(BlinkGC::ThreadHeapMode threadHeapMode) : m_thread(currentThread()), - m_persistentRegion(wrapUnique(new PersistentRegion())), + m_persistentRegion(makeUnique<PersistentRegion>()), #if OS(WIN) && COMPILER(MSVC) m_threadStackSize(0), #endif
diff --git a/third_party/WebKit/Source/platform/heap/Visitor.cpp b/third_party/WebKit/Source/platform/heap/Visitor.cpp index 8c01f390..9ec0785 100644 --- a/third_party/WebKit/Source/platform/heap/Visitor.cpp +++ b/third_party/WebKit/Source/platform/heap/Visitor.cpp
@@ -17,13 +17,13 @@ switch (gcType) { case BlinkGC::GCWithSweep: case BlinkGC::GCWithoutSweep: - return wrapUnique(new MarkingVisitor<Visitor::GlobalMarking>(state)); + return makeUnique<MarkingVisitor<Visitor::GlobalMarking>>(state); case BlinkGC::TakeSnapshot: - return wrapUnique(new MarkingVisitor<Visitor::SnapshotMarking>(state)); + return makeUnique<MarkingVisitor<Visitor::SnapshotMarking>>(state); case BlinkGC::ThreadTerminationGC: - return wrapUnique(new MarkingVisitor<Visitor::ThreadLocalMarking>(state)); + return makeUnique<MarkingVisitor<Visitor::ThreadLocalMarking>>(state); case BlinkGC::ThreadLocalWeakProcessing: - return wrapUnique(new MarkingVisitor<Visitor::WeakProcessing>(state)); + return makeUnique<MarkingVisitor<Visitor::WeakProcessing>>(state); default: ASSERT_NOT_REACHED(); }
diff --git a/third_party/WebKit/Source/platform/image-decoders/ImageDecoder.cpp b/third_party/WebKit/Source/platform/image-decoders/ImageDecoder.cpp index 327db4b..05b0a77 100644 --- a/third_party/WebKit/Source/platform/image-decoders/ImageDecoder.cpp +++ b/third_party/WebKit/Source/platform/image-decoders/ImageDecoder.cpp
@@ -209,9 +209,15 @@ if (m_frameBufferCache.size() <= 1) return 0; + return clearCacheExceptTwoFrames(clearExceptFrame, kNotFound); +} + +size_t ImageDecoder::clearCacheExceptTwoFrames(size_t clearExceptFrame1, + size_t clearExceptFrame2) { size_t frameBytesCleared = 0; for (size_t i = 0; i < m_frameBufferCache.size(); ++i) { - if (i != clearExceptFrame) { + if (m_frameBufferCache[i].getStatus() != ImageFrame::FrameEmpty && + i != clearExceptFrame1 && i != clearExceptFrame2) { frameBytesCleared += frameBytesAtIndex(i); clearFrameBuffer(i); } @@ -223,6 +229,30 @@ m_frameBufferCache[frameIndex].clearPixelData(); } +Vector<size_t> ImageDecoder::findFramesToDecode(size_t index) const { + DCHECK(index < m_frameBufferCache.size()); + + Vector<size_t> framesToDecode; + do { + framesToDecode.append(index); + index = m_frameBufferCache[index].requiredPreviousFrameIndex(); + } while (index != kNotFound && + m_frameBufferCache[index].getStatus() != ImageFrame::FrameComplete); + return framesToDecode; +} + +bool ImageDecoder::postDecodeProcessing(size_t index) { + DCHECK(index < m_frameBufferCache.size()); + + if (m_frameBufferCache[index].getStatus() != ImageFrame::FrameComplete) + return false; + + if (m_purgeAggressively) + clearCacheExceptFrame(index); + + return true; +} + void ImageDecoder::updateAggressivePurging(size_t index) { if (m_purgeAggressively) return;
diff --git a/third_party/WebKit/Source/platform/image-decoders/ImageDecoder.h b/third_party/WebKit/Source/platform/image-decoders/ImageDecoder.h index d6169b5..d052b386 100644 --- a/third_party/WebKit/Source/platform/image-decoders/ImageDecoder.h +++ b/third_party/WebKit/Source/platform/image-decoders/ImageDecoder.h
@@ -292,6 +292,9 @@ // ImageFrame::m_requiredPreviousFrameIndex. size_t findRequiredPreviousFrame(size_t frameIndex, bool frameRectIsOpaque); + // This is called by clearCacheExceptFrame() if that method decides it wants + // to preserve another frame, to avoid unnecessary redecoding. + size_t clearCacheExceptTwoFrames(size_t, size_t); virtual void clearFrameBuffer(size_t frameIndex); // Decodes the image sufficiently to determine the image size. @@ -308,6 +311,19 @@ // Decodes the requested frame. virtual void decode(size_t) = 0; + // This method is only required for animated images. It returns a vector with + // all frame indices that need to be decoded in order to succesfully decode + // the provided frame. The indices are returned in reverse order, so the + // last frame needs to be decoded first. Before calling this method, the + // caller must verify that the frame exists. + Vector<size_t> findFramesToDecode(size_t) const; + + // This is called by decode() after decoding a frame in an animated image. + // Before calling this method, the caller must verify that the frame exists. + // @return true if the frame was fully decoded, + // false otherwise. + bool postDecodeProcessing(size_t); + RefPtr<SegmentReader> m_data; // The encoded data. Vector<ImageFrame, 1> m_frameBufferCache; const bool m_premultiplyAlpha; @@ -326,7 +342,6 @@ // If that happens, m_purgeAggressively is set to true. This signals // future decodes to purge old frames as it goes. void updateAggressivePurging(size_t index); - bool m_purgeAggressively; private: enum class SniffResult { JPEG, PNG, GIF, WEBP, ICO, BMP, Invalid }; @@ -341,6 +356,8 @@ return total_size > ((1 << 29) - 1); } + bool m_purgeAggressively; + IntSize m_size; bool m_sizeAvailable = false; bool m_isAllDataReceived = false;
diff --git a/third_party/WebKit/Source/platform/image-decoders/ImageDecoderTest.cpp b/third_party/WebKit/Source/platform/image-decoders/ImageDecoderTest.cpp index 01e1291..f457240 100644 --- a/third_party/WebKit/Source/platform/image-decoders/ImageDecoderTest.cpp +++ b/third_party/WebKit/Source/platform/image-decoders/ImageDecoderTest.cpp
@@ -70,7 +70,7 @@ }; TEST(ImageDecoderTest, sizeCalculationMayOverflow) { - std::unique_ptr<TestImageDecoder> decoder(wrapUnique(new TestImageDecoder())); + std::unique_ptr<TestImageDecoder> decoder(makeUnique<TestImageDecoder>()); EXPECT_FALSE(decoder->setSize(1 << 29, 1)); EXPECT_FALSE(decoder->setSize(1, 1 << 29)); EXPECT_FALSE(decoder->setSize(1 << 15, 1 << 15)); @@ -80,7 +80,7 @@ } TEST(ImageDecoderTest, requiredPreviousFrameIndex) { - std::unique_ptr<TestImageDecoder> decoder(wrapUnique(new TestImageDecoder())); + std::unique_ptr<TestImageDecoder> decoder(makeUnique<TestImageDecoder>()); decoder->initFrames(6); Vector<ImageFrame, 1>& frameBuffers = decoder->frameBufferCache(); @@ -104,7 +104,7 @@ } TEST(ImageDecoderTest, requiredPreviousFrameIndexDisposeOverwriteBgcolor) { - std::unique_ptr<TestImageDecoder> decoder(wrapUnique(new TestImageDecoder())); + std::unique_ptr<TestImageDecoder> decoder(makeUnique<TestImageDecoder>()); decoder->initFrames(3); Vector<ImageFrame, 1>& frameBuffers = decoder->frameBufferCache(); @@ -122,7 +122,7 @@ } TEST(ImageDecoderTest, requiredPreviousFrameIndexForFrame1) { - std::unique_ptr<TestImageDecoder> decoder(wrapUnique(new TestImageDecoder())); + std::unique_ptr<TestImageDecoder> decoder(makeUnique<TestImageDecoder>()); decoder->initFrames(2); Vector<ImageFrame, 1>& frameBuffers = decoder->frameBufferCache(); @@ -150,7 +150,7 @@ } TEST(ImageDecoderTest, requiredPreviousFrameIndexBlendAtopBgcolor) { - std::unique_ptr<TestImageDecoder> decoder(wrapUnique(new TestImageDecoder())); + std::unique_ptr<TestImageDecoder> decoder(makeUnique<TestImageDecoder>()); decoder->initFrames(3); Vector<ImageFrame, 1>& frameBuffers = decoder->frameBufferCache(); @@ -180,7 +180,7 @@ } TEST(ImageDecoderTest, requiredPreviousFrameIndexKnownOpaque) { - std::unique_ptr<TestImageDecoder> decoder(wrapUnique(new TestImageDecoder())); + std::unique_ptr<TestImageDecoder> decoder(makeUnique<TestImageDecoder>()); decoder->initFrames(3); Vector<ImageFrame, 1>& frameBuffers = decoder->frameBufferCache(); @@ -207,7 +207,7 @@ } TEST(ImageDecoderTest, clearCacheExceptFrameDoNothing) { - std::unique_ptr<TestImageDecoder> decoder(wrapUnique(new TestImageDecoder())); + std::unique_ptr<TestImageDecoder> decoder(makeUnique<TestImageDecoder>()); decoder->clearCacheExceptFrame(0); // This should not crash. @@ -217,7 +217,7 @@ TEST(ImageDecoderTest, clearCacheExceptFrameAll) { const size_t numFrames = 10; - std::unique_ptr<TestImageDecoder> decoder(wrapUnique(new TestImageDecoder())); + std::unique_ptr<TestImageDecoder> decoder(makeUnique<TestImageDecoder>()); decoder->initFrames(numFrames); Vector<ImageFrame, 1>& frameBuffers = decoder->frameBufferCache(); for (size_t i = 0; i < numFrames; ++i) @@ -234,7 +234,7 @@ TEST(ImageDecoderTest, clearCacheExceptFramePreverveClearExceptFrame) { const size_t numFrames = 10; - std::unique_ptr<TestImageDecoder> decoder(wrapUnique(new TestImageDecoder())); + std::unique_ptr<TestImageDecoder> decoder(makeUnique<TestImageDecoder>()); decoder->initFrames(numFrames); Vector<ImageFrame, 1>& frameBuffers = decoder->frameBufferCache(); for (size_t i = 0; i < numFrames; ++i)
diff --git a/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageDecoder.cpp b/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageDecoder.cpp index 0a81003..b9cd8c1 100644 --- a/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageDecoder.cpp +++ b/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageDecoder.cpp
@@ -267,19 +267,6 @@ return clearCacheExceptTwoFrames(clearExceptFrame, clearExceptFrame2); } -size_t GIFImageDecoder::clearCacheExceptTwoFrames(size_t clearExceptFrame1, - size_t clearExceptFrame2) { - size_t frameBytesCleared = 0; - for (size_t i = 0; i < m_frameBufferCache.size(); ++i) { - if (m_frameBufferCache[i].getStatus() != ImageFrame::FrameEmpty && - i != clearExceptFrame1 && i != clearExceptFrame2) { - frameBytesCleared += frameBytesAtIndex(i); - clearFrameBuffer(i); - } - } - return frameBytesCleared; -} - void GIFImageDecoder::clearFrameBuffer(size_t frameIndex) { if (m_reader && m_frameBufferCache[frameIndex].getStatus() == ImageFrame::FramePartial) { @@ -318,28 +305,16 @@ updateAggressivePurging(index); - Vector<size_t> framesToDecode; - size_t frameToDecode = index; - do { - framesToDecode.append(frameToDecode); - frameToDecode = - m_frameBufferCache[frameToDecode].requiredPreviousFrameIndex(); - } while (frameToDecode != kNotFound && - m_frameBufferCache[frameToDecode].getStatus() != - ImageFrame::FrameComplete); - + Vector<size_t> framesToDecode = findFramesToDecode(index); for (auto i = framesToDecode.rbegin(); i != framesToDecode.rend(); ++i) { if (!m_reader->decode(*i)) { setFailed(); return; } - // We need more data to continue decoding. - if (m_frameBufferCache[*i].getStatus() != ImageFrame::FrameComplete) + // If this returns false, we need more data to continue decoding. + if (!postDecodeProcessing(*i)) break; - - if (m_purgeAggressively) - clearCacheExceptFrame(*i); } // It is also a fatal error if all data is received and we have decoded all @@ -354,7 +329,7 @@ return; if (!m_reader) { - m_reader = wrapUnique(new GIFImageReader(this)); + m_reader = makeUnique<GIFImageReader>(this); m_reader->setData(m_data); }
diff --git a/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageDecoder.h b/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageDecoder.h index 1987dfcf..96dad58 100644 --- a/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageDecoder.h +++ b/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageDecoder.h
@@ -87,9 +87,6 @@ // failure, this will mark the image as failed. bool initFrameBuffer(size_t frameIndex); - // Like clearCacheExceptFrame(), but preserves two frames instead of one. - size_t clearCacheExceptTwoFrames(size_t, size_t); - bool m_currentBufferSawAlpha; mutable int m_repetitionCount; std::unique_ptr<GIFImageReader> m_reader;
diff --git a/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageReader.cpp b/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageReader.cpp index d94b2e6..c475109c 100644 --- a/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageReader.cpp +++ b/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageReader.cpp
@@ -342,7 +342,7 @@ if (!isDataSizeDefined() || !isHeaderDefined()) return true; - m_lzwContext = wrapUnique(new GIFLZWContext(client, this)); + m_lzwContext = makeUnique<GIFLZWContext>(client, this); if (!m_lzwContext->prepareToDecode()) { m_lzwContext.reset(); return false;
diff --git a/third_party/WebKit/Source/platform/image-decoders/jpeg/JPEGImageDecoder.cpp b/third_party/WebKit/Source/platform/image-decoders/jpeg/JPEGImageDecoder.cpp index ab6bd20..06837708 100644 --- a/third_party/WebKit/Source/platform/image-decoders/jpeg/JPEGImageDecoder.cpp +++ b/third_party/WebKit/Source/platform/image-decoders/jpeg/JPEGImageDecoder.cpp
@@ -1008,7 +1008,7 @@ return; if (!m_reader) { - m_reader = wrapUnique(new JPEGImageReader(this)); + m_reader = makeUnique<JPEGImageReader>(this); m_reader->setData(m_data.get()); }
diff --git a/third_party/WebKit/Source/platform/image-decoders/jpeg/JPEGImageDecoderTest.cpp b/third_party/WebKit/Source/platform/image-decoders/jpeg/JPEGImageDecoderTest.cpp index aba6aade..8e6da23e 100644 --- a/third_party/WebKit/Source/platform/image-decoders/jpeg/JPEGImageDecoderTest.cpp +++ b/third_party/WebKit/Source/platform/image-decoders/jpeg/JPEGImageDecoderTest.cpp
@@ -89,7 +89,7 @@ // Setting a dummy ImagePlanes object signals to the decoder that we want to // do YUV decoding. - std::unique_ptr<ImagePlanes> dummyImagePlanes = wrapUnique(new ImagePlanes()); + std::unique_ptr<ImagePlanes> dummyImagePlanes = makeUnique<ImagePlanes>(); decoder->setImagePlanes(std::move(dummyImagePlanes)); bool sizeIsAvailable = decoder->isSizeAvailable(); @@ -125,7 +125,7 @@ planes[2] = ((char*)planes[1]) + rowBytes[1] * uSize.height(); std::unique_ptr<ImagePlanes> imagePlanes = - wrapUnique(new ImagePlanes(planes, rowBytes)); + makeUnique<ImagePlanes>(planes, rowBytes); decoder->setImagePlanes(std::move(imagePlanes)); ASSERT_TRUE(decoder->decodeToYUV()); @@ -263,7 +263,7 @@ std::unique_ptr<ImageDecoder> decoder = createDecoder(230 * 230 * 4); decoder->setData(data.get(), true); - std::unique_ptr<ImagePlanes> imagePlanes = wrapUnique(new ImagePlanes()); + std::unique_ptr<ImagePlanes> imagePlanes = makeUnique<ImagePlanes>(); decoder->setImagePlanes(std::move(imagePlanes)); ASSERT_TRUE(decoder->isSizeAvailable()); ASSERT_FALSE(decoder->canDecodeToYUV());
diff --git a/third_party/WebKit/Source/platform/image-decoders/png/PNGImageDecoder.cpp b/third_party/WebKit/Source/platform/image-decoders/png/PNGImageDecoder.cpp index 1aa5b1f..be94ce5 100644 --- a/third_party/WebKit/Source/platform/image-decoders/png/PNGImageDecoder.cpp +++ b/third_party/WebKit/Source/platform/image-decoders/png/PNGImageDecoder.cpp
@@ -375,7 +375,7 @@ return; if (!m_reader) - m_reader = wrapUnique(new PNGImageReader(this, m_offset)); + m_reader = makeUnique<PNGImageReader>(this, m_offset); // If we couldn't decode the image but have received all the data, decoding // has failed.
diff --git a/third_party/WebKit/Source/platform/image-decoders/webp/WEBPImageDecoder.cpp b/third_party/WebKit/Source/platform/image-decoders/webp/WEBPImageDecoder.cpp index b02c793..87a9677 100644 --- a/third_party/WebKit/Source/platform/image-decoders/webp/WEBPImageDecoder.cpp +++ b/third_party/WebKit/Source/platform/image-decoders/webp/WEBPImageDecoder.cpp
@@ -285,18 +285,32 @@ } size_t WEBPImageDecoder::clearCacheExceptFrame(size_t clearExceptFrame) { - // If |clearExceptFrame| has status FrameComplete, we preserve that frame. - // Otherwise, we preserve the most recent previous frame with status - // FrameComplete whose data will be required to decode |clearExceptFrame|, - // either in initFrameBuffer() or ApplyPostProcessing(). All other frames can - // be cleared. - while ((clearExceptFrame < m_frameBufferCache.size()) && - (m_frameBufferCache[clearExceptFrame].getStatus() != - ImageFrame::FrameComplete)) - clearExceptFrame = - m_frameBufferCache[clearExceptFrame].requiredPreviousFrameIndex(); + // Don't clear if there are no frames, or only one. + if (m_frameBufferCache.size() <= 1) + return 0; - return ImageDecoder::clearCacheExceptFrame(clearExceptFrame); + // If |clearExceptFrame| has status FrameComplete, we only preserve that + // frame. Otherwise, we *also* preserve the most recent previous frame with + // status FrameComplete whose data will be required to decode + // |clearExceptFrame|, either in initFrameBuffer() or ApplyPostProcessing(). + // This frame index is stored in |clearExceptFrame2|. All other frames can + // be cleared. + size_t clearExceptFrame2 = kNotFound; + if (clearExceptFrame < m_frameBufferCache.size() && + m_frameBufferCache[clearExceptFrame].getStatus() != + ImageFrame::FrameComplete) { + clearExceptFrame2 = + m_frameBufferCache[clearExceptFrame].requiredPreviousFrameIndex(); + } + + while ((clearExceptFrame2 < m_frameBufferCache.size()) && + (m_frameBufferCache[clearExceptFrame2].getStatus() != + ImageFrame::FrameComplete)) { + clearExceptFrame2 = + m_frameBufferCache[clearExceptFrame2].requiredPreviousFrameIndex(); + } + + return clearCacheExceptTwoFrames(clearExceptFrame, clearExceptFrame2); } void WEBPImageDecoder::clearFrameBuffer(size_t frameIndex) { @@ -447,15 +461,7 @@ if (failed()) return; - Vector<size_t> framesToDecode; - size_t frameToDecode = index; - do { - framesToDecode.append(frameToDecode); - frameToDecode = - m_frameBufferCache[frameToDecode].requiredPreviousFrameIndex(); - } while (frameToDecode != kNotFound && - m_frameBufferCache[frameToDecode].getStatus() != - ImageFrame::FrameComplete); + Vector<size_t> framesToDecode = findFramesToDecode(index); ASSERT(m_demux); for (auto i = framesToDecode.rbegin(); i != framesToDecode.rend(); ++i) { @@ -471,12 +477,9 @@ if (failed()) return; - // We need more data to continue decoding. - if (m_frameBufferCache[*i].getStatus() != ImageFrame::FrameComplete) + // If this returns false, we need more data to continue decoding. + if (!postDecodeProcessing(*i)) break; - - if (m_purgeAggressively) - clearCacheExceptFrame(*i); } // It is also a fatal error if all data is received and we have decoded all
diff --git a/third_party/WebKit/Source/platform/image-decoders/webp/WEBPImageDecoderTest.cpp b/third_party/WebKit/Source/platform/image-decoders/webp/WEBPImageDecoderTest.cpp index 265cd5c..3a0c9080 100644 --- a/third_party/WebKit/Source/platform/image-decoders/webp/WEBPImageDecoderTest.cpp +++ b/third_party/WebKit/Source/platform/image-decoders/webp/WEBPImageDecoderTest.cpp
@@ -550,6 +550,81 @@ false, 32000); } +TEST(AnimatedWEBPTests, clearCacheExceptFrameWithAncestors) { + std::unique_ptr<ImageDecoder> decoder = createDecoder(); + + RefPtr<SharedBuffer> fullData = + readFile("/LayoutTests/fast/images/resources/webp-animated.webp"); + ASSERT_TRUE(fullData.get()); + decoder->setData(fullData.get(), true); + + ASSERT_EQ(3u, decoder->frameCount()); + // We need to store pointers to the image frames, since calling + // frameBufferAtIndex will decode the frame if it is not FrameComplete, + // and we want to read the status of the frame without decoding it again. + ImageFrame* buffers[3]; + size_t bufferSizes[3]; + for (size_t i = 0; i < decoder->frameCount(); i++) { + buffers[i] = decoder->frameBufferAtIndex(i); + ASSERT_EQ(ImageFrame::FrameComplete, buffers[i]->getStatus()); + bufferSizes[i] = decoder->frameBytesAtIndex(i); + } + + // Explicitly set the required previous frame for the frames, since this test + // is designed on this chain. Whether the frames actually depend on each + // other is not important for this test - clearCacheExceptFrame just looks at + // the frame status and the required previous frame. + buffers[1]->setRequiredPreviousFrameIndex(0); + buffers[2]->setRequiredPreviousFrameIndex(1); + + // Clear the cache except for a single frame. All other frames should be + // cleared to FrameEmpty, since this frame is FrameComplete. + EXPECT_EQ(bufferSizes[0] + bufferSizes[2], decoder->clearCacheExceptFrame(1)); + EXPECT_EQ(ImageFrame::FrameEmpty, buffers[0]->getStatus()); + EXPECT_EQ(ImageFrame::FrameComplete, buffers[1]->getStatus()); + EXPECT_EQ(ImageFrame::FrameEmpty, buffers[2]->getStatus()); + + // Verify that the required previous frame is also preserved if the provided + // frame is not FrameComplete. The simulated situation is: + // + // Frame 0 <--------- Frame 1 <--------- Frame 2 + // FrameComplete depends on FrameComplete depends on FramePartial + // + // The expected outcome is that frame 1 and frame 2 are preserved, since + // frame 1 is necessary to fully decode frame 2. + for (size_t i = 0; i < decoder->frameCount(); i++) { + ASSERT_EQ(ImageFrame::FrameComplete, + decoder->frameBufferAtIndex(i)->getStatus()); + } + buffers[2]->setStatus(ImageFrame::FramePartial); + EXPECT_EQ(bufferSizes[0], decoder->clearCacheExceptFrame(2)); + EXPECT_EQ(ImageFrame::FrameEmpty, buffers[0]->getStatus()); + EXPECT_EQ(ImageFrame::FrameComplete, buffers[1]->getStatus()); + EXPECT_EQ(ImageFrame::FramePartial, buffers[2]->getStatus()); + + // Verify that the nearest FrameComplete required frame is preserved if + // earlier required frames in the ancestor list are not FrameComplete. The + // simulated situation is: + // + // Frame 0 <--------- Frame 1 <--------- Frame 2 + // FrameComplete depends on FrameEmpty depends on FramePartial + // + // The expected outcome is that frame 0 and frame 2 are preserved. Frame 2 + // should be preserved since it is the frame passed to clearCacheExceptFrame. + // Frame 0 should be preserved since it is the nearest FrameComplete ancestor. + // Thus, since frame 1 is FrameEmpty, no data is cleared in this case. + for (size_t i = 0; i < decoder->frameCount(); i++) { + ASSERT_EQ(ImageFrame::FrameComplete, + decoder->frameBufferAtIndex(i)->getStatus()); + } + buffers[1]->setStatus(ImageFrame::FrameEmpty); + buffers[2]->setStatus(ImageFrame::FramePartial); + EXPECT_EQ(0u, decoder->clearCacheExceptFrame(2)); + EXPECT_EQ(ImageFrame::FrameComplete, buffers[0]->getStatus()); + EXPECT_EQ(ImageFrame::FrameEmpty, buffers[1]->getStatus()); + EXPECT_EQ(ImageFrame::FramePartial, buffers[2]->getStatus()); +} + TEST(StaticWebPTests, truncatedImage) { // VP8 data is truncated. testInvalidImage("/LayoutTests/fast/images/resources/truncated.webp", false);
diff --git a/third_party/WebKit/Source/platform/image-encoders/JPEGImageEncoder.cpp b/third_party/WebKit/Source/platform/image-encoders/JPEGImageEncoder.cpp index 62d2ea2..91db3dc 100644 --- a/third_party/WebKit/Source/platform/image-encoders/JPEGImageEncoder.cpp +++ b/third_party/WebKit/Source/platform/image-encoders/JPEGImageEncoder.cpp
@@ -140,7 +140,7 @@ return nullptr; std::unique_ptr<JPEGImageEncoderStateImpl> encoderState = - wrapUnique(new JPEGImageEncoderStateImpl()); + makeUnique<JPEGImageEncoderStateImpl>(); jpeg_compress_struct* cinfo = encoderState->cinfo(); jpeg_error_mgr* error = encoderState->error();
diff --git a/third_party/WebKit/Source/platform/mojo/MojoHelper.h b/third_party/WebKit/Source/platform/mojo/MojoHelper.h index 8f0f00d..ff0ff0d 100644 --- a/third_party/WebKit/Source/platform/mojo/MojoHelper.h +++ b/third_party/WebKit/Source/platform/mojo/MojoHelper.h
@@ -6,26 +6,6 @@ #define MojoHelper_h #include "base/message_loop/message_loop.h" -#include "mojo/public/cpp/bindings/wtf_array.h" -#include "platform/heap/HeapAllocator.h" -#include <utility> - -namespace mojo { - -// A |TypeConverter| that will create a |WTFArray<T>| containing a copy of the -// contents of a |blink::HeapVector<E>|, using |TypeConverter<T, E>| to copy -// each element. The returned array will always be non-null. -template <typename T, typename E> -struct TypeConverter<WTFArray<T>, blink::HeapVector<E>> { - static WTFArray<T> Convert(const blink::HeapVector<E>& input) { - WTFArray<T> result(input.size()); - for (size_t i = 0; i < input.size(); ++i) - result[i] = TypeConverter<T, E>::Convert(input[i]); - return std::move(result); - } -}; - -} // namespace mojo namespace blink {
diff --git a/third_party/WebKit/Source/platform/network/HTTPHeaderMap.cpp b/third_party/WebKit/Source/platform/network/HTTPHeaderMap.cpp index 2c46a96f..487756ae 100644 --- a/third_party/WebKit/Source/platform/network/HTTPHeaderMap.cpp +++ b/third_party/WebKit/Source/platform/network/HTTPHeaderMap.cpp
@@ -41,7 +41,7 @@ std::unique_ptr<CrossThreadHTTPHeaderMapData> HTTPHeaderMap::copyData() const { std::unique_ptr<CrossThreadHTTPHeaderMapData> data = - wrapUnique(new CrossThreadHTTPHeaderMapData()); + makeUnique<CrossThreadHTTPHeaderMapData>(); data->reserveInitialCapacity(size()); HTTPHeaderMap::const_iterator endIt = end();
diff --git a/third_party/WebKit/Source/platform/network/ResourceRequest.cpp b/third_party/WebKit/Source/platform/network/ResourceRequest.cpp index 9ee48406..ce12ef5 100644 --- a/third_party/WebKit/Source/platform/network/ResourceRequest.cpp +++ b/third_party/WebKit/Source/platform/network/ResourceRequest.cpp
@@ -98,7 +98,7 @@ std::unique_ptr<CrossThreadResourceRequestData> ResourceRequest::copyData() const { std::unique_ptr<CrossThreadResourceRequestData> data = - wrapUnique(new CrossThreadResourceRequestData()); + makeUnique<CrossThreadResourceRequestData>(); data->m_url = url().copy(); data->m_cachePolicy = getCachePolicy(); data->m_timeoutInterval = timeoutInterval();
diff --git a/third_party/WebKit/Source/platform/scroll/ScrollbarTestSuite.h b/third_party/WebKit/Source/platform/scroll/ScrollbarTestSuite.h index 5ffaf654..2baed7f1 100644 --- a/third_party/WebKit/Source/platform/scroll/ScrollbarTestSuite.h +++ b/third_party/WebKit/Source/platform/scroll/ScrollbarTestSuite.h
@@ -87,7 +87,7 @@ TestingPlatformSupport::Config config; config.compositorSupport = Platform::current()->compositorSupport(); m_fakePlatform = - wrapUnique(new TestingPlatformSupportWithMockScheduler(config)); + makeUnique<TestingPlatformSupportWithMockScheduler>(config); } void TearDown() override { m_fakePlatform = nullptr; }
diff --git a/third_party/WebKit/Source/platform/testing/TestPaintArtifact.cpp b/third_party/WebKit/Source/platform/testing/TestPaintArtifact.cpp index f41adc6..5795259 100644 --- a/third_party/WebKit/Source/platform/testing/TestPaintArtifact.cpp +++ b/third_party/WebKit/Source/platform/testing/TestPaintArtifact.cpp
@@ -74,7 +74,7 @@ TestPaintArtifact& TestPaintArtifact::rectDrawing(const FloatRect& bounds, Color color) { std::unique_ptr<DummyRectClient> client = - wrapUnique(new DummyRectClient(bounds, color)); + makeUnique<DummyRectClient>(bounds, color); m_displayItemList.allocateAndConstruct<DrawingDisplayItem>( *client, DisplayItem::kDrawingFirst, client->makePicture()); m_dummyClients.append(std::move(client));
diff --git a/third_party/WebKit/Source/platform/testing/TestingPlatformSupport.cpp b/third_party/WebKit/Source/platform/testing/TestingPlatformSupport.cpp index da50eda..93a4be0 100644 --- a/third_party/WebKit/Source/platform/testing/TestingPlatformSupport.cpp +++ b/third_party/WebKit/Source/platform/testing/TestingPlatformSupport.cpp
@@ -71,7 +71,7 @@ mojo::ScopedMessagePipeHandle handle) override { if (std::string(name) == mojom::blink::MimeRegistry::Name_) { mojo::MakeStrongBinding( - wrapUnique(new MockMimeRegistry()), + makeUnique<MockMimeRegistry>(), mojo::MakeRequest<mojom::blink::MimeRegistry>(std::move(handle))); return; } @@ -330,7 +330,7 @@ m_compositorSupport = wrapUnique(new cc_blink::WebCompositorSupportImpl); m_testingPlatformConfig.compositorSupport = m_compositorSupport.get(); m_testingPlatformSupport = - wrapUnique(new TestingPlatformSupport(m_testingPlatformConfig)); + makeUnique<TestingPlatformSupport>(m_testingPlatformConfig); ProcessHeap::init(); ThreadState::attachMainThread();
diff --git a/third_party/WebKit/Source/platform/text/LocaleICU.cpp b/third_party/WebKit/Source/platform/text/LocaleICU.cpp index b846837..c9323634 100644 --- a/third_party/WebKit/Source/platform/text/LocaleICU.cpp +++ b/third_party/WebKit/Source/platform/text/LocaleICU.cpp
@@ -190,7 +190,7 @@ if (udat_countSymbols(dateFormat, type) != startIndex + size) return std::unique_ptr<Vector<String>>(); - std::unique_ptr<Vector<String>> labels = wrapUnique(new Vector<String>()); + std::unique_ptr<Vector<String>> labels = makeUnique<Vector<String>>(); labels->reserveCapacity(size); bool isStandAloneMonth = (type == UDAT_STANDALONE_MONTHS) || (type == UDAT_STANDALONE_SHORT_MONTHS); @@ -223,7 +223,7 @@ } static std::unique_ptr<Vector<String>> createFallbackWeekDayShortLabels() { - std::unique_ptr<Vector<String>> labels = wrapUnique(new Vector<String>()); + std::unique_ptr<Vector<String>> labels = makeUnique<Vector<String>>(); labels->reserveCapacity(7); labels->append("Sun"); labels->append("Mon"); @@ -255,7 +255,7 @@ } static std::unique_ptr<Vector<String>> createFallbackMonthLabels() { - std::unique_ptr<Vector<String>> labels = wrapUnique(new Vector<String>()); + std::unique_ptr<Vector<String>> labels = makeUnique<Vector<String>>(); labels->reserveCapacity(WTF_ARRAY_LENGTH(WTF::monthFullName)); for (unsigned i = 0; i < WTF_ARRAY_LENGTH(WTF::monthFullName); ++i) labels->append(WTF::monthFullName[i]); @@ -292,7 +292,7 @@ } static std::unique_ptr<Vector<String>> createFallbackAMPMLabels() { - std::unique_ptr<Vector<String>> labels = wrapUnique(new Vector<String>()); + std::unique_ptr<Vector<String>> labels = makeUnique<Vector<String>>(); labels->reserveCapacity(2); labels->append("AM"); labels->append("PM");
diff --git a/third_party/WebKit/Source/platform/threading/BackgroundTaskRunnerTest.cpp b/third_party/WebKit/Source/platform/threading/BackgroundTaskRunnerTest.cpp index e8c3935..6717d30a 100644 --- a/third_party/WebKit/Source/platform/threading/BackgroundTaskRunnerTest.cpp +++ b/third_party/WebKit/Source/platform/threading/BackgroundTaskRunnerTest.cpp
@@ -22,7 +22,7 @@ class BackgroundTaskRunnerTest : public testing::Test {}; TEST_F(BackgroundTaskRunnerTest, RunShortTaskOnBackgroundThread) { - std::unique_ptr<WaitableEvent> doneEvent = wrapUnique(new WaitableEvent()); + std::unique_ptr<WaitableEvent> doneEvent = makeUnique<WaitableEvent>(); BackgroundTaskRunner::postOnBackgroundThread( BLINK_FROM_HERE, crossThreadBind(&PingPongTask, crossThreadUnretained(doneEvent.get())), @@ -32,7 +32,7 @@ } TEST_F(BackgroundTaskRunnerTest, RunLongTaskOnBackgroundThread) { - std::unique_ptr<WaitableEvent> doneEvent = wrapUnique(new WaitableEvent()); + std::unique_ptr<WaitableEvent> doneEvent = makeUnique<WaitableEvent>(); BackgroundTaskRunner::postOnBackgroundThread( BLINK_FROM_HERE, crossThreadBind(&PingPongTask, crossThreadUnretained(doneEvent.get())),
diff --git a/third_party/WebKit/Source/platform/transforms/TransformationMatrix.h b/third_party/WebKit/Source/platform/transforms/TransformationMatrix.h index f2bc7d9..7aa2e72 100644 --- a/third_party/WebKit/Source/platform/transforms/TransformationMatrix.h +++ b/third_party/WebKit/Source/platform/transforms/TransformationMatrix.h
@@ -63,11 +63,11 @@ #endif static std::unique_ptr<TransformationMatrix> create() { - return wrapUnique(new TransformationMatrix()); + return makeUnique<TransformationMatrix>(); } static std::unique_ptr<TransformationMatrix> create( const TransformationMatrix& t) { - return wrapUnique(new TransformationMatrix(t)); + return makeUnique<TransformationMatrix>(t); } static std::unique_ptr<TransformationMatrix> create(double a, double b, @@ -75,7 +75,7 @@ double d, double e, double f) { - return wrapUnique(new TransformationMatrix(a, b, c, d, e, f)); + return makeUnique<TransformationMatrix>(a, b, c, d, e, f); } static std::unique_ptr<TransformationMatrix> create(double m11, double m12,
diff --git a/third_party/WebKit/Source/web/AssertMatchingEnums.cpp b/third_party/WebKit/Source/web/AssertMatchingEnums.cpp index 190f678..9294519 100644 --- a/third_party/WebKit/Source/web/AssertMatchingEnums.cpp +++ b/third_party/WebKit/Source/web/AssertMatchingEnums.cpp
@@ -86,6 +86,7 @@ #include "public/platform/WebFileSystem.h" #include "public/platform/WebFontDescription.h" #include "public/platform/WebHistoryScrollRestorationType.h" +#include "public/platform/WebInputEvent.h" #include "public/platform/WebMediaPlayer.h" #include "public/platform/WebMediaPlayerClient.h" #include "public/platform/WebMediaSource.h" @@ -118,7 +119,6 @@ #include "public/web/WebHistoryItem.h" #include "public/web/WebIconURL.h" #include "public/web/WebInputElement.h" -#include "public/web/WebInputEvent.h" #include "public/web/WebNavigationPolicy.h" #include "public/web/WebNavigatorContentUtilsClient.h" #include "public/web/WebRemoteFrameClient.h"
diff --git a/third_party/WebKit/Source/web/ChromeClientImpl.cpp b/third_party/WebKit/Source/web/ChromeClientImpl.cpp index d8a4928..1c0863b2 100644 --- a/third_party/WebKit/Source/web/ChromeClientImpl.cpp +++ b/third_party/WebKit/Source/web/ChromeClientImpl.cpp
@@ -74,6 +74,7 @@ #include "public/platform/WebCursorInfo.h" #include "public/platform/WebFloatRect.h" #include "public/platform/WebFrameScheduler.h" +#include "public/platform/WebInputEvent.h" #include "public/platform/WebRect.h" #include "public/platform/WebURLRequest.h" #include "public/platform/WebViewScheduler.h" @@ -84,7 +85,6 @@ #include "public/web/WebConsoleMessage.h" #include "public/web/WebFrameClient.h" #include "public/web/WebInputElement.h" -#include "public/web/WebInputEvent.h" #include "public/web/WebKit.h" #include "public/web/WebNode.h" #include "public/web/WebPageImportanceSignals.h"
diff --git a/third_party/WebKit/Source/web/FrameLoaderClientImpl.cpp b/third_party/WebKit/Source/web/FrameLoaderClientImpl.cpp index 3c728c67..2081e509 100644 --- a/third_party/WebKit/Source/web/FrameLoaderClientImpl.cpp +++ b/third_party/WebKit/Source/web/FrameLoaderClientImpl.cpp
@@ -520,7 +520,8 @@ NavigationType type, NavigationPolicy policy, bool replacesCurrentHistoryItem, - bool isClientRedirect) { + bool isClientRedirect, + HTMLFormElement* form) { if (!m_webFrame->client()) return NavigationPolicyIgnore; @@ -556,6 +557,8 @@ navigationInfo.isHistoryNavigationInNewChildFrame = isHistoryNavigationInNewChildFrame; navigationInfo.isClientRedirect = isClientRedirect; + if (form) + navigationInfo.form = WebFormElement(form); WebNavigationPolicy webPolicy = m_webFrame->client()->decidePolicyForNavigation(navigationInfo);
diff --git a/third_party/WebKit/Source/web/FrameLoaderClientImpl.h b/third_party/WebKit/Source/web/FrameLoaderClientImpl.h index 289f4db1..4993864 100644 --- a/third_party/WebKit/Source/web/FrameLoaderClientImpl.h +++ b/third_party/WebKit/Source/web/FrameLoaderClientImpl.h
@@ -112,7 +112,8 @@ NavigationType, NavigationPolicy, bool shouldReplaceCurrentEntry, - bool isClientRedirect) override; + bool isClientRedirect, + HTMLFormElement*) override; void dispatchWillSendSubmitEvent(HTMLFormElement*) override; void dispatchWillSubmitForm(HTMLFormElement*) override; void didStartLoading(LoadStartType) override;
diff --git a/third_party/WebKit/Source/web/InspectorOverlay.cpp b/third_party/WebKit/Source/web/InspectorOverlay.cpp index 5753a26..129080c 100644 --- a/third_party/WebKit/Source/web/InspectorOverlay.cpp +++ b/third_party/WebKit/Source/web/InspectorOverlay.cpp
@@ -559,7 +559,7 @@ LocalFrame* frame = LocalFrame::create(&dummyFrameLoaderClient, &m_overlayPage->frameHost(), 0); - frame->setView(FrameView::create(frame)); + frame->setView(FrameView::create(*frame)); frame->init(); FrameLoader& loader = frame->loader(); frame->view()->setCanHaveScrollbars(false);
diff --git a/third_party/WebKit/Source/web/InspectorOverlay.h b/third_party/WebKit/Source/web/InspectorOverlay.h index 6e5a686..55a0834 100644 --- a/third_party/WebKit/Source/web/InspectorOverlay.h +++ b/third_party/WebKit/Source/web/InspectorOverlay.h
@@ -37,7 +37,7 @@ #include "platform/geometry/LayoutRect.h" #include "platform/graphics/Color.h" #include "platform/heap/Handle.h" -#include "public/web/WebInputEvent.h" +#include "public/platform/WebInputEvent.h" #include "wtf/RefPtr.h" #include "wtf/text/WTFString.h" #include <memory>
diff --git a/third_party/WebKit/Source/web/LinkHighlightImplTest.cpp b/third_party/WebKit/Source/web/LinkHighlightImplTest.cpp index f4fe09d..b4fae65b 100644 --- a/third_party/WebKit/Source/web/LinkHighlightImplTest.cpp +++ b/third_party/WebKit/Source/web/LinkHighlightImplTest.cpp
@@ -36,12 +36,12 @@ #include "public/platform/Platform.h" #include "public/platform/WebContentLayer.h" #include "public/platform/WebFloatPoint.h" +#include "public/platform/WebInputEvent.h" #include "public/platform/WebSize.h" #include "public/platform/WebURLLoaderMockFactory.h" #include "public/web/WebCache.h" #include "public/web/WebFrame.h" #include "public/web/WebFrameClient.h" -#include "public/web/WebInputEvent.h" #include "public/web/WebViewClient.h" #include "testing/gtest/include/gtest/gtest.h" #include "web/WebInputEventConversion.h" @@ -185,7 +185,7 @@ // A lifetime test: delete LayerTreeView while running LinkHighlights. TEST(LinkHighlightImplTest, resetLayerTreeView) { std::unique_ptr<FakeCompositingWebViewClient> webViewClient = - wrapUnique(new FakeCompositingWebViewClient()); + makeUnique<FakeCompositingWebViewClient>(); const std::string baseURL("http://www.test.com/"); const std::string fileName("test_touch_link_highlight.html");
diff --git a/third_party/WebKit/Source/web/PageOverlayTest.cpp b/third_party/WebKit/Source/web/PageOverlayTest.cpp index 66c075e..eeb657ee 100644 --- a/third_party/WebKit/Source/web/PageOverlayTest.cpp +++ b/third_party/WebKit/Source/web/PageOverlayTest.cpp
@@ -85,9 +85,8 @@ WebViewImpl* webViewImpl() const { return m_helper.webView(); } std::unique_ptr<PageOverlay> createSolidYellowOverlay() { - return PageOverlay::create( - webViewImpl()->mainFrameImpl(), - wrapUnique(new SolidColorOverlay(SK_ColorYELLOW))); + return PageOverlay::create(webViewImpl()->mainFrameImpl(), + makeUnique<SolidColorOverlay>(SK_ColorYELLOW)); } template <typename OverlayType>
diff --git a/third_party/WebKit/Source/web/PageWidgetDelegate.cpp b/third_party/WebKit/Source/web/PageWidgetDelegate.cpp index 227bce08..081ec32 100644 --- a/third_party/WebKit/Source/web/PageWidgetDelegate.cpp +++ b/third_party/WebKit/Source/web/PageWidgetDelegate.cpp
@@ -43,7 +43,7 @@ #include "platform/graphics/paint/DrawingRecorder.h" #include "platform/graphics/paint/SkPictureBuilder.h" #include "platform/transforms/AffineTransform.h" -#include "public/web/WebInputEvent.h" +#include "public/platform/WebInputEvent.h" #include "web/WebInputEventConversion.h" #include "wtf/CurrentTime.h"
diff --git a/third_party/WebKit/Source/web/PageWidgetDelegate.h b/third_party/WebKit/Source/web/PageWidgetDelegate.h index d8dbe36..4a810b2 100644 --- a/third_party/WebKit/Source/web/PageWidgetDelegate.h +++ b/third_party/WebKit/Source/web/PageWidgetDelegate.h
@@ -32,7 +32,7 @@ #define PageWidgetDelegate_h #include "public/platform/WebCanvas.h" -#include "public/web/WebInputEvent.h" +#include "public/platform/WebInputEvent.h" #include "public/web/WebWidget.h" #include "web/WebExport.h"
diff --git a/third_party/WebKit/Source/web/WebDocument.cpp b/third_party/WebKit/Source/web/WebDocument.cpp index c3bc1c98..ca949a9 100644 --- a/third_party/WebKit/Source/web/WebDocument.cpp +++ b/third_party/WebKit/Source/web/WebDocument.cpp
@@ -206,6 +206,14 @@ CSSSelectorWatch::from(*document).watchCSSSelectors(selectors); } +bool WebDocument::unloadStartedDoNotUse() const { + return constUnwrap<Document>()->unloadStarted(); +} + +bool WebDocument::processingBeforeUnloadDoNotUse() const { + return constUnwrap<Document>()->processingBeforeUnload(); +} + WebReferrerPolicy WebDocument::referrerPolicy() const { return static_cast<WebReferrerPolicy>( constUnwrap<Document>()->getReferrerPolicy());
diff --git a/third_party/WebKit/Source/web/WebFrameWidgetBase.cpp b/third_party/WebKit/Source/web/WebFrameWidgetBase.cpp index 91a6560..26d39f40 100644 --- a/third_party/WebKit/Source/web/WebFrameWidgetBase.cpp +++ b/third_party/WebKit/Source/web/WebFrameWidgetBase.cpp
@@ -6,6 +6,7 @@ #include "core/frame/FrameHost.h" #include "core/frame/VisualViewport.h" +#include "core/input/EventHandler.h" #include "core/page/DragActions.h" #include "core/page/DragController.h" #include "core/page/DragData.h" @@ -91,6 +92,30 @@ m_currentDragData = nullptr; } +void WebFrameWidgetBase::dragSourceEndedAt(const WebPoint& pointInViewport, + const WebPoint& screenPoint, + WebDragOperation operation) { + WebPoint pointInRootFrame( + page()->frameHost().visualViewport().viewportToRootFrame( + pointInViewport)); + PlatformMouseEvent pme( + pointInRootFrame, screenPoint, WebPointerProperties::Button::Left, + PlatformEvent::MouseMoved, 0, PlatformEvent::NoModifiers, + PlatformMouseEvent::RealOrIndistinguishable, + WTF::monotonicallyIncreasingTime()); + page()->deprecatedLocalMainFrame()->eventHandler().dragSourceEndedAt( + pme, static_cast<DragOperation>(operation)); +} + +void WebFrameWidgetBase::dragSourceSystemDragEnded() { + // It's possible for us to get this callback while not doing a drag if it's + // from a previous page that got unloaded. + if (view()->doingDragAndDrop()) { + page()->dragController().dragEnded(); + view()->setDoingDragAndDrop(false); + } +} + WebDragOperation WebFrameWidgetBase::dragTargetDragEnterOrOver( const WebPoint& pointInViewport, const WebPoint& screenPoint,
diff --git a/third_party/WebKit/Source/web/WebFrameWidgetBase.h b/third_party/WebKit/Source/web/WebFrameWidgetBase.h index 9ac9110..ccd3ebb 100644 --- a/third_party/WebKit/Source/web/WebFrameWidgetBase.h +++ b/third_party/WebKit/Source/web/WebFrameWidgetBase.h
@@ -59,6 +59,10 @@ const WebPoint& pointInViewport, const WebPoint& screenPoint, int modifiers) override; + void dragSourceEndedAt(const WebPoint& pointInViewport, + const WebPoint& screenPoint, + WebDragOperation) override; + void dragSourceSystemDragEnded() override; protected: enum DragAction { DragEnter, DragOver };
diff --git a/third_party/WebKit/Source/web/WebFrameWidgetImpl.h b/third_party/WebKit/Source/web/WebFrameWidgetImpl.h index 5b50a371..68889493 100644 --- a/third_party/WebKit/Source/web/WebFrameWidgetImpl.h +++ b/third_party/WebKit/Source/web/WebFrameWidgetImpl.h
@@ -34,9 +34,9 @@ #include "platform/graphics/GraphicsLayer.h" #include "platform/heap/SelfKeepAlive.h" #include "platform/scroll/ScrollTypes.h" +#include "public/platform/WebInputEvent.h" #include "public/platform/WebPoint.h" #include "public/platform/WebSize.h" -#include "public/web/WebInputEvent.h" #include "public/web/WebInputMethodController.h" #include "web/PageWidgetDelegate.h" #include "web/WebFrameWidgetBase.h"
diff --git a/third_party/WebKit/Source/web/WebInputEvent.cpp b/third_party/WebKit/Source/web/WebInputEvent.cpp index 8523b4a9..60b965a2 100644 --- a/third_party/WebKit/Source/web/WebInputEvent.cpp +++ b/third_party/WebKit/Source/web/WebInputEvent.cpp
@@ -28,9 +28,10 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "public/web/WebInputEvent.h" +#include "public/platform/WebInputEvent.h" #include "platform/KeyboardCodes.h" +#include "public/platform/WebGestureEvent.h" #include "wtf/ASCIICType.h" #include "wtf/Assertions.h" #include "wtf/StringExtras.h"
diff --git a/third_party/WebKit/Source/web/WebInputEventConversion.h b/third_party/WebKit/Source/web/WebInputEventConversion.h index dc7b56d..39abbf5 100644 --- a/third_party/WebKit/Source/web/WebInputEventConversion.h +++ b/third_party/WebKit/Source/web/WebInputEventConversion.h
@@ -35,7 +35,8 @@ #include "platform/PlatformMouseEvent.h" #include "platform/PlatformTouchEvent.h" #include "platform/PlatformWheelEvent.h" -#include "public/web/WebInputEvent.h" +#include "public/platform/WebGestureEvent.h" +#include "public/platform/WebInputEvent.h" #include "web/WebExport.h" #include "wtf/Compiler.h"
diff --git a/third_party/WebKit/Source/web/WebNode.cpp b/third_party/WebKit/Source/web/WebNode.cpp index fb3dabc..a1359277 100644 --- a/third_party/WebKit/Source/web/WebNode.cpp +++ b/third_party/WebKit/Source/web/WebNode.cpp
@@ -169,7 +169,7 @@ void WebNode::simulateClick() { m_private->getExecutionContext()->postSuspendableTask( - wrapUnique(new NodeDispatchSimulatedClickTask(m_private))); + makeUnique<NodeDispatchSimulatedClickTask>(m_private)); } WebElementCollection WebNode::getElementsByHTMLTagName(
diff --git a/third_party/WebKit/Source/web/WebPagePopupImpl.cpp b/third_party/WebKit/Source/web/WebPagePopupImpl.cpp index e41a86be..2b83ad57 100644 --- a/third_party/WebKit/Source/web/WebPagePopupImpl.cpp +++ b/third_party/WebKit/Source/web/WebPagePopupImpl.cpp
@@ -289,13 +289,13 @@ m_page->settings().setScrollAnimatorEnabled( mainSettings.scrollAnimatorEnabled()); - provideContextFeaturesTo(*m_page, wrapUnique(new PagePopupFeaturesClient())); + provideContextFeaturesTo(*m_page, makeUnique<PagePopupFeaturesClient>()); DEFINE_STATIC_LOCAL(FrameLoaderClient, emptyFrameLoaderClient, (EmptyFrameLoaderClient::create())); LocalFrame* frame = LocalFrame::create(&emptyFrameLoaderClient, &m_page->frameHost(), 0); frame->setPagePopupOwner(m_popupClient->ownerElement()); - frame->setView(FrameView::create(frame)); + frame->setView(FrameView::create(*frame)); frame->init(); frame->view()->setParentVisible(true); frame->view()->setSelfVisible(true);
diff --git a/third_party/WebKit/Source/web/WebPepperSocket.cpp b/third_party/WebKit/Source/web/WebPepperSocket.cpp index 7f16a932..c4ef974 100644 --- a/third_party/WebKit/Source/web/WebPepperSocket.cpp +++ b/third_party/WebKit/Source/web/WebPepperSocket.cpp
@@ -42,7 +42,7 @@ return 0; std::unique_ptr<WebPepperSocketImpl> websocket = - wrapUnique(new WebPepperSocketImpl(document, client)); + makeUnique<WebPepperSocketImpl>(document, client); if (websocket && websocket->isNull()) return 0; return websocket.release();
diff --git a/third_party/WebKit/Source/web/WebPluginContainerImpl.cpp b/third_party/WebKit/Source/web/WebPluginContainerImpl.cpp index 99e6289e..30ac3e4 100644 --- a/third_party/WebKit/Source/web/WebPluginContainerImpl.cpp +++ b/third_party/WebKit/Source/web/WebPluginContainerImpl.cpp
@@ -87,6 +87,7 @@ #include "public/platform/WebCursorInfo.h" #include "public/platform/WebDragData.h" #include "public/platform/WebExternalTextureLayer.h" +#include "public/platform/WebInputEvent.h" #include "public/platform/WebRect.h" #include "public/platform/WebString.h" #include "public/platform/WebURL.h" @@ -96,7 +97,6 @@ #include "public/web/WebDocument.h" #include "public/web/WebElement.h" #include "public/web/WebFrameClient.h" -#include "public/web/WebInputEvent.h" #include "public/web/WebPlugin.h" #include "public/web/WebPrintParams.h" #include "public/web/WebPrintPresetOptions.h"
diff --git a/third_party/WebKit/Source/web/WebViewImpl.cpp b/third_party/WebKit/Source/web/WebViewImpl.cpp index 0f858659..bc2e404 100644 --- a/third_party/WebKit/Source/web/WebViewImpl.cpp +++ b/third_party/WebKit/Source/web/WebViewImpl.cpp
@@ -322,7 +322,7 @@ } void WebView::willEnterModalLoop() { - pageLoadDeferrerStack().append(wrapUnique(new ScopedPageLoadDeferrer())); + pageLoadDeferrerStack().append(makeUnique<ScopedPageLoadDeferrer>()); } void WebView::didExitModalLoop() { @@ -3400,30 +3400,6 @@ return hitTestResultForRootFramePos(pointInRootFrame); } -void WebViewImpl::dragSourceEndedAt(const WebPoint& pointInViewport, - const WebPoint& screenPoint, - WebDragOperation operation) { - WebPoint pointInRootFrame( - page()->frameHost().visualViewport().viewportToRootFrame( - pointInViewport)); - PlatformMouseEvent pme( - pointInRootFrame, screenPoint, WebPointerProperties::Button::Left, - PlatformEvent::MouseMoved, 0, PlatformEvent::NoModifiers, - PlatformMouseEvent::RealOrIndistinguishable, - WTF::monotonicallyIncreasingTime()); - m_page->deprecatedLocalMainFrame()->eventHandler().dragSourceEndedAt( - pme, static_cast<DragOperation>(operation)); -} - -void WebViewImpl::dragSourceSystemDragEnded() { - // It's possible for us to get this callback while not doing a drag if - // it's from a previous page that got unloaded. - if (m_doingDragAndDrop) { - m_page->dragController().dragEnded(); - m_doingDragAndDrop = false; - } -} - void WebViewImpl::spellingMarkers(WebVector<uint32_t>* markers) { Vector<uint32_t> result; for (Frame* frame = m_page->mainFrame(); frame; @@ -3785,7 +3761,7 @@ return; m_pageColorOverlay = - PageOverlay::create(mainFrameImpl(), wrapUnique(new ColorOverlay(color))); + PageOverlay::create(mainFrameImpl(), makeUnique<ColorOverlay>(color)); m_pageColorOverlay->update(); }
diff --git a/third_party/WebKit/Source/web/WebViewImpl.h b/third_party/WebKit/Source/web/WebViewImpl.h index 9a90f914..1071850e 100644 --- a/third_party/WebKit/Source/web/WebViewImpl.h +++ b/third_party/WebKit/Source/web/WebViewImpl.h
@@ -41,6 +41,8 @@ #include "public/platform/WebDisplayMode.h" #include "public/platform/WebFloatSize.h" #include "public/platform/WebGestureCurveTarget.h" +#include "public/platform/WebGestureEvent.h" +#include "public/platform/WebInputEvent.h" #include "public/platform/WebInputEventResult.h" #include "public/platform/WebLayer.h" #include "public/platform/WebPoint.h" @@ -49,7 +51,6 @@ #include "public/platform/WebSize.h" #include "public/platform/WebString.h" #include "public/platform/WebVector.h" -#include "public/web/WebInputEvent.h" #include "public/web/WebNavigationPolicy.h" #include "public/web/WebPageImportanceSignals.h" #include "public/web/WebView.h" @@ -239,10 +240,6 @@ WebHitTestResult hitTestResultAt(const WebPoint&) override; WebHitTestResult hitTestResultForTap(const WebPoint&, const WebSize&) override; - void dragSourceEndedAt(const WebPoint& pointInViewport, - const WebPoint& screenPoint, - WebDragOperation) override; - void dragSourceSystemDragEnded() override; void spellingMarkers(WebVector<uint32_t>* markers) override; void removeSpellingMarkersUnderWords( const WebVector<WebString>& words) override; @@ -506,6 +503,7 @@ ChromeClientImpl& chromeClient() const { return *m_chromeClientImpl.get(); } void setDoingDragAndDrop(bool doing) { m_doingDragAndDrop = doing; } + bool doingDragAndDrop() { return m_doingDragAndDrop; } // Returns the currently active WebInputMethodController which the one // corresponding to the focused frame. It will return nullptr if there are
diff --git a/third_party/WebKit/Source/web/tests/ChromeClientImplTest.cpp b/third_party/WebKit/Source/web/tests/ChromeClientImplTest.cpp index efdcdbb4..75871b82 100644 --- a/third_party/WebKit/Source/web/tests/ChromeClientImplTest.cpp +++ b/third_party/WebKit/Source/web/tests/ChromeClientImplTest.cpp
@@ -30,8 +30,8 @@ #include "core/loader/FrameLoadRequest.h" #include "core/page/Page.h" +#include "public/platform/WebInputEvent.h" #include "public/web/WebFrameClient.h" -#include "public/web/WebInputEvent.h" #include "public/web/WebLocalFrame.h" #include "public/web/WebView.h" #include "public/web/WebViewClient.h"
diff --git a/third_party/WebKit/Source/web/tests/ProgrammaticScrollTest.cpp b/third_party/WebKit/Source/web/tests/ProgrammaticScrollTest.cpp index b25f36b..db00e267 100644 --- a/third_party/WebKit/Source/web/tests/ProgrammaticScrollTest.cpp +++ b/third_party/WebKit/Source/web/tests/ProgrammaticScrollTest.cpp
@@ -3,12 +3,12 @@ #include "core/loader/FrameLoader.h" #include "platform/testing/URLTestHelpers.h" #include "public/platform/Platform.h" +#include "public/platform/WebInputEvent.h" #include "public/platform/WebURLLoaderMockFactory.h" #include "public/web/WebCache.h" #include "public/web/WebFrame.h" #include "public/web/WebFrameClient.h" #include "public/web/WebHistoryItem.h" -#include "public/web/WebInputEvent.h" #include "public/web/WebScriptSource.h" #include "public/web/WebSettings.h" #include "public/web/WebView.h"
diff --git a/third_party/WebKit/Source/web/tests/TouchActionTest.cpp b/third_party/WebKit/Source/web/tests/TouchActionTest.cpp index c62d107..455a51d 100644 --- a/third_party/WebKit/Source/web/tests/TouchActionTest.cpp +++ b/third_party/WebKit/Source/web/tests/TouchActionTest.cpp
@@ -44,12 +44,12 @@ #include "platform/testing/URLTestHelpers.h" #include "platform/testing/UnitTestHelpers.h" #include "public/platform/Platform.h" +#include "public/platform/WebInputEvent.h" #include "public/platform/WebURLLoaderMockFactory.h" #include "public/web/WebCache.h" #include "public/web/WebDocument.h" #include "public/web/WebFrame.h" #include "public/web/WebHitTestResult.h" -#include "public/web/WebInputEvent.h" #include "public/web/WebTouchAction.h" #include "public/web/WebView.h" #include "public/web/WebViewClient.h"
diff --git a/third_party/WebKit/Source/web/tests/VisualViewportTest.cpp b/third_party/WebKit/Source/web/tests/VisualViewportTest.cpp index 418e648..26d508ee 100644 --- a/third_party/WebKit/Source/web/tests/VisualViewportTest.cpp +++ b/third_party/WebKit/Source/web/tests/VisualViewportTest.cpp
@@ -25,13 +25,13 @@ #include "platform/testing/URLTestHelpers.h" #include "public/platform/Platform.h" #include "public/platform/WebCachePolicy.h" +#include "public/platform/WebInputEvent.h" #include "public/platform/WebLayerTreeView.h" #include "public/platform/WebURLLoaderMockFactory.h" #include "public/web/WebCache.h" #include "public/web/WebContextMenuData.h" #include "public/web/WebDocument.h" #include "public/web/WebFrameClient.h" -#include "public/web/WebInputEvent.h" #include "public/web/WebScriptSource.h" #include "public/web/WebSettings.h" #include "public/web/WebViewClient.h" @@ -2137,7 +2137,7 @@ std::unique_ptr<FrameTestHelpers::TestWebViewClient> fakeCompositingWebViewClient = - wrapUnique(new FrameTestHelpers::TestWebViewClient()); + makeUnique<FrameTestHelpers::TestWebViewClient>(); FrameTestHelpers::WebViewHelper webViewHelper; WebViewImpl* webViewImpl = webViewHelper.initialize( true, nullptr, fakeCompositingWebViewClient.get(), nullptr, @@ -2327,7 +2327,7 @@ std::unique_ptr<FrameTestHelpers::TestWebViewClient> fakeCompositingWebViewClient = - wrapUnique(new FrameTestHelpers::TestWebViewClient()); + makeUnique<FrameTestHelpers::TestWebViewClient>(); FrameTestHelpers::WebViewHelper webViewHelper; WebViewImpl* webViewImpl = webViewHelper.initialize( true, nullptr, fakeCompositingWebViewClient.get(), nullptr,
diff --git a/third_party/WebKit/Source/web/tests/WebFrameTest.cpp b/third_party/WebKit/Source/web/tests/WebFrameTest.cpp index bd83d42..bfd2ffa 100644 --- a/third_party/WebKit/Source/web/tests/WebFrameTest.cpp +++ b/third_party/WebKit/Source/web/tests/WebFrameTest.cpp
@@ -3108,7 +3108,7 @@ int viewHeight = 500; std::unique_ptr<FakeCompositingWebViewClient> fakeCompositingWebViewClient = - wrapUnique(new FakeCompositingWebViewClient()); + makeUnique<FakeCompositingWebViewClient>(); FrameTestHelpers::WebViewHelper webViewHelper; webViewHelper.initialize(true, nullptr, fakeCompositingWebViewClient.get(), nullptr, &configureCompositingWebView); @@ -4275,14 +4275,14 @@ int extensionGroup, int worldId) override { createNotifications.append( - wrapUnique(new Notification(frame, context, worldId))); + makeUnique<Notification>(frame, context, worldId)); } void willReleaseScriptContext(WebLocalFrame* frame, v8::Local<v8::Context> context, int worldId) override { releaseNotifications.append( - wrapUnique(new Notification(frame, context, worldId))); + makeUnique<Notification>(frame, context, worldId)); } }; @@ -5462,7 +5462,7 @@ ~CompositedSelectionBoundsTestLayerTreeView() override {} void registerSelection(const WebSelection& selection) override { - m_selection = wrapUnique(new WebSelection(selection)); + m_selection = makeUnique<WebSelection>(selection); } void clearSelection() override { @@ -7361,7 +7361,7 @@ TEST_F(WebFrameTest, overflowHiddenRewrite) { registerMockedHttpURLLoad("non-scrollable.html"); std::unique_ptr<FakeCompositingWebViewClient> fakeCompositingWebViewClient = - wrapUnique(new FakeCompositingWebViewClient()); + makeUnique<FakeCompositingWebViewClient>(); FrameTestHelpers::WebViewHelper webViewHelper; webViewHelper.initialize(true, nullptr, fakeCompositingWebViewClient.get(), nullptr, &configureCompositingWebView); @@ -10254,7 +10254,7 @@ } void addExpectedRequest(const KURL& url, WebURLRequest::Priority priority) { - m_expectedRequests.add(url, wrapUnique(new ExpectedRequest(url, priority))); + m_expectedRequests.add(url, makeUnique<ExpectedRequest>(url, priority)); } void verifyAllRequests() {
diff --git a/third_party/WebKit/Source/web/tests/WebPluginContainerTest.cpp b/third_party/WebKit/Source/web/tests/WebPluginContainerTest.cpp index 8ced299e..8528137 100644 --- a/third_party/WebKit/Source/web/tests/WebPluginContainerTest.cpp +++ b/third_party/WebKit/Source/web/tests/WebPluginContainerTest.cpp
@@ -734,6 +734,12 @@ static_cast<const CompositedPlugin*>(container->plugin()); std::unique_ptr<PaintController> paintController = PaintController::create(); + PaintChunkProperties properties; + properties.transform = TransformPaintPropertyNode::root(); + properties.clip = ClipPaintPropertyNode::root(); + properties.effect = EffectPaintPropertyNode::root(); + properties.scroll = ScrollPaintPropertyNode::root(); + paintController->updateCurrentPaintChunkProperties(nullptr, properties); GraphicsContext graphicsContext(*paintController); container->paint(graphicsContext, CullRect(IntRect(10, 10, 400, 300))); paintController->commitNewDisplayItems();
diff --git a/third_party/WebKit/Source/web/tests/WebViewTest.cpp b/third_party/WebKit/Source/web/tests/WebViewTest.cpp index 227304a..5d8f627 100644 --- a/third_party/WebKit/Source/web/tests/WebViewTest.cpp +++ b/third_party/WebKit/Source/web/tests/WebViewTest.cpp
@@ -70,6 +70,7 @@ #include "public/platform/WebDragData.h" #include "public/platform/WebDragOperation.h" #include "public/platform/WebFloatPoint.h" +#include "public/platform/WebInputEvent.h" #include "public/platform/WebLayerTreeView.h" #include "public/platform/WebMockClipboard.h" #include "public/platform/WebSize.h" @@ -85,7 +86,6 @@ #include "public/web/WebFrameClient.h" #include "public/web/WebFrameContentDumper.h" #include "public/web/WebHitTestResult.h" -#include "public/web/WebInputEvent.h" #include "public/web/WebInputMethodController.h" #include "public/web/WebScriptSource.h" #include "public/web/WebSettings.h" @@ -2616,7 +2616,7 @@ TEST_P(WebViewTest, ShowPressOnTransformedLink) { std::unique_ptr<FrameTestHelpers::TestWebViewClient> fakeCompositingWebViewClient = - wrapUnique(new FrameTestHelpers::TestWebViewClient()); + makeUnique<FrameTestHelpers::TestWebViewClient>(); FrameTestHelpers::WebViewHelper webViewHelper; WebViewImpl* webViewImpl = webViewHelper.initialize( true, nullptr, fakeCompositingWebViewClient.get(), nullptr,
diff --git a/third_party/WebKit/Source/wtf/FilePrintStream.cpp b/third_party/WebKit/Source/wtf/FilePrintStream.cpp index 70a0a45..fe7cb24e 100644 --- a/third_party/WebKit/Source/wtf/FilePrintStream.cpp +++ b/third_party/WebKit/Source/wtf/FilePrintStream.cpp
@@ -45,7 +45,7 @@ if (!file) return std::unique_ptr<FilePrintStream>(); - return wrapUnique(new FilePrintStream(file)); + return makeUnique<FilePrintStream>(file); } void FilePrintStream::vprintf(const char* format, va_list argList) {
diff --git a/third_party/WebKit/Source/wtf/FunctionalTest.cpp b/third_party/WebKit/Source/wtf/FunctionalTest.cpp index 8157975..174d26d4 100644 --- a/third_party/WebKit/Source/wtf/FunctionalTest.cpp +++ b/third_party/WebKit/Source/wtf/FunctionalTest.cpp
@@ -318,13 +318,13 @@ TEST(FunctionalTest, MemberFunctionBindByUniquePtr) { std::unique_ptr<Function<int()>> function1 = - WTF::bind(&A::f, wrapUnique(new A(10))); + WTF::bind(&A::f, makeUnique<A>(10)); EXPECT_EQ(10, (*function1)()); } TEST(FunctionalTest, MemberFunctionBindByPassedUniquePtr) { std::unique_ptr<Function<int()>> function1 = - WTF::bind(&A::f, passed(wrapUnique(new A(10)))); + WTF::bind(&A::f, passed(makeUnique<A>(10))); EXPECT_EQ(10, (*function1)()); }
diff --git a/third_party/WebKit/Source/wtf/HashMapTest.cpp b/third_party/WebKit/Source/wtf/HashMapTest.cpp index 8437fbf..2d47cd8 100644 --- a/third_party/WebKit/Source/wtf/HashMapTest.cpp +++ b/third_party/WebKit/Source/wtf/HashMapTest.cpp
@@ -249,7 +249,7 @@ result.storedValue->value = wrapUnique(simple1); EXPECT_EQ(simple1, map.get(1)); - IntSimpleMap::AddResult result2 = map.add(1, wrapUnique(new SimpleClass(2))); + IntSimpleMap::AddResult result2 = map.add(1, makeUnique<SimpleClass>(2)); EXPECT_FALSE(result2.isNewEntry); EXPECT_EQ(1, result.storedValue->key); EXPECT_EQ(1, result.storedValue->value->v());
diff --git a/third_party/WebKit/Source/wtf/HashSetTest.cpp b/third_party/WebKit/Source/wtf/HashSetTest.cpp index f560d35..bbe69902 100644 --- a/third_party/WebKit/Source/wtf/HashSetTest.cpp +++ b/third_party/WebKit/Source/wtf/HashSetTest.cpp
@@ -128,8 +128,8 @@ deleted2 = false; { OwnPtrSet set; - set.add(wrapUnique(new Dummy(deleted1))); - set.add(wrapUnique(new Dummy(deleted2))); + set.add(makeUnique<Dummy>(deleted1)); + set.add(makeUnique<Dummy>(deleted2)); } EXPECT_TRUE(deleted1); EXPECT_TRUE(deleted2);
diff --git a/third_party/WebKit/Source/wtf/ListHashSetTest.cpp b/third_party/WebKit/Source/wtf/ListHashSetTest.cpp index cfc6266..1c30944 100644 --- a/third_party/WebKit/Source/wtf/ListHashSetTest.cpp +++ b/third_party/WebKit/Source/wtf/ListHashSetTest.cpp
@@ -584,8 +584,8 @@ deleted2 = false; { OwnPtrSet set; - set.add(wrapUnique(new Dummy(deleted1))); - set.add(wrapUnique(new Dummy(deleted2))); + set.add(makeUnique<Dummy>(deleted1)); + set.add(makeUnique<Dummy>(deleted2)); } EXPECT_TRUE(deleted1); EXPECT_TRUE(deleted2);
diff --git a/third_party/WebKit/Source/wtf/text/StringImpl.cpp b/third_party/WebKit/Source/wtf/text/StringImpl.cpp index 190af7f2..c861abfd 100644 --- a/third_party/WebKit/Source/wtf/text/StringImpl.cpp +++ b/third_party/WebKit/Source/wtf/text/StringImpl.cpp
@@ -39,8 +39,6 @@ #include "wtf/text/StringToNumber.h" #include <algorithm> #include <memory> -#include <unicode/translit.h> -#include <unicode/unistr.h> #ifdef STRING_STATS #include "wtf/DataLog.h" @@ -803,7 +801,7 @@ } PassRefPtr<StringImpl> StringImpl::lower(const AtomicString& localeIdentifier) { - // Use the more-optimized code path most of the time. + // Use the more optimized code path most of the time. // Only Turkic (tr and az) languages and Lithuanian requires // locale-specific lowercasing rules. Even though CLDR has el-Lower, // it's identical to the locale-agnostic lowercasing. Context-dependent @@ -829,15 +827,14 @@ PassRefPtr<StringImpl> StringImpl::upper(const AtomicString& localeIdentifier) { // Use the more-optimized code path most of the time. - // Only Turkic (tr and az) languages and Greek require locale-specific - // lowercasing rules. - icu::UnicodeString transliteratorId; + // Only Turkic (tr and az) languages, Greek and Lithuanian require + // locale-specific uppercasing rules. const char* localeForConversion = 0; if (localeIdMatchesLang(localeIdentifier, "tr") || localeIdMatchesLang(localeIdentifier, "az")) localeForConversion = "tr"; else if (localeIdMatchesLang(localeIdentifier, "el")) - transliteratorId = UNICODE_STRING_SIMPLE("el-Upper"); + localeForConversion = "el"; else if (localeIdMatchesLang(localeIdentifier, "lt")) localeForConversion = "lt"; else @@ -850,23 +847,7 @@ RefPtr<StringImpl> upconverted = upconvertedString(); const UChar* source16 = upconverted->characters16(); - if (localeForConversion) - return caseConvert(source16, length, u_strToUpper, localeForConversion, - this); - - // TODO(jungshik): Cache transliterator if perf penaly warrants it for Greek. - UErrorCode status = U_ZERO_ERROR; - std::unique_ptr<icu::Transliterator> translit = - wrapUnique(icu::Transliterator::createInstance(transliteratorId, - UTRANS_FORWARD, status)); - if (U_FAILURE(status)) - return upper(); - - // target will be copy-on-write. - icu::UnicodeString target(false, source16, length); - translit->transliterate(target); - - return create(target.getBuffer(), target.length()); + return caseConvert(source16, length, u_strToUpper, localeForConversion, this); } PassRefPtr<StringImpl> StringImpl::fill(UChar character) {
diff --git a/third_party/WebKit/Source/wtf/text/TextCodecUTF16.cpp b/third_party/WebKit/Source/wtf/text/TextCodecUTF16.cpp index 3927890c..453a4f3 100644 --- a/third_party/WebKit/Source/wtf/text/TextCodecUTF16.cpp +++ b/third_party/WebKit/Source/wtf/text/TextCodecUTF16.cpp
@@ -53,13 +53,13 @@ static std::unique_ptr<TextCodec> newStreamingTextDecoderUTF16LE( const TextEncoding&, const void*) { - return wrapUnique(new TextCodecUTF16(true)); + return makeUnique<TextCodecUTF16>(true); } static std::unique_ptr<TextCodec> newStreamingTextDecoderUTF16BE( const TextEncoding&, const void*) { - return wrapUnique(new TextCodecUTF16(false)); + return makeUnique<TextCodecUTF16>(false); } void TextCodecUTF16::registerCodecs(TextCodecRegistrar registrar) {
diff --git a/third_party/WebKit/Source/wtf/text/TextPosition.cpp b/third_party/WebKit/Source/wtf/text/TextPosition.cpp index 075cafd7..46d157c 100644 --- a/third_party/WebKit/Source/wtf/text/TextPosition.cpp +++ b/third_party/WebKit/Source/wtf/text/TextPosition.cpp
@@ -33,7 +33,7 @@ namespace WTF { std::unique_ptr<Vector<unsigned>> lineEndings(const String& text) { - std::unique_ptr<Vector<unsigned>> result(wrapUnique(new Vector<unsigned>())); + std::unique_ptr<Vector<unsigned>> result(makeUnique<Vector<unsigned>>()); unsigned start = 0; while (start < text.length()) {
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/chromium_wpt.py b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/chromium_wpt.py index c1c091a..f447c3c5 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/chromium_wpt.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/chromium_wpt.py
@@ -10,6 +10,7 @@ from webkitpy.common.memoized import memoized from webkitpy.common.webkit_finder import WebKitFinder +from webkitpy.w3c.deps_updater import DepsUpdater class ChromiumWPT(object): @@ -41,8 +42,7 @@ '--name-only', '-r', chromium_commit ]).splitlines() - # TODO(jeffcarp): Use DepsUpdater.is_baseline - return any(f.startswith(CHROMIUM_WPT_DIR) and '-expected' not in f for f in files) + return any(f.startswith(CHROMIUM_WPT_DIR) and not DepsUpdater.is_baseline(f) for f in files) def chromium_commits_since(self, chromium_commit): return self.host.executive.run_command([
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/chromium_wpt_unittest.py b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/chromium_wpt_unittest.py index 7c8a84ad..aa1c26d5 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/chromium_wpt_unittest.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/chromium_wpt_unittest.py
@@ -39,7 +39,7 @@ def run_command_fn(_): return ("something/something.html\n" - "third_party/WebKit/LayoutTests/imported/wpt/something-expected.html\n" + "third_party/WebKit/LayoutTests/imported/wpt/something-expected.txt\n" "-expected.txt\n") host.executive = MockExecutive2(run_command_fn=run_command_fn)
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/deps_updater.py b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/deps_updater.py index f20de4f3..7306761 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/deps_updater.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/deps_updater.py
@@ -188,7 +188,8 @@ _log.info('Cleaning out tests from LayoutTests/imported/%s.', dest_dir_name) dest_path = self.path_from_webkit_base('LayoutTests', 'imported', dest_dir_name) - files_to_delete = self.fs.files_under(dest_path, file_filter=self.is_not_baseline) + is_not_baseline_filter = lambda fs, dirname, basename: not self.is_baseline(basename) + files_to_delete = self.fs.files_under(dest_path, file_filter=is_not_baseline_filter) for subpath in files_to_delete: self.remove('LayoutTests', 'imported', subpath) @@ -200,13 +201,17 @@ self.run(['git', 'add', '--all', 'LayoutTests/imported/%s' % dest_dir_name]) _log.info('Deleting any orphaned baselines.') - previous_baselines = self.fs.files_under(dest_path, file_filter=self.is_baseline) + + is_baseline_filter = lambda fs, dirname, basename: self.is_baseline(basename) + previous_baselines = self.fs.files_under(dest_path, file_filter=is_baseline_filter) + for subpath in previous_baselines: full_path = self.fs.join(dest_path, subpath) if self.fs.glob(full_path.replace('-expected.txt', '*')) == [full_path]: self.fs.remove(full_path) self._generate_manifest(temp_repo_path, dest_path) + if not keep_w3c_repos_around: _log.info('Deleting temp repo directory %s.', temp_repo_path) self.rmtree(temp_repo_path) @@ -236,13 +241,10 @@ _log.info('Done: no changes to import.') return False - # Callback for FileSystem.files_under; not all arguments used - pylint: disable=unused-argument - def is_baseline(self, fs, dirname, basename): + @staticmethod + def is_baseline(basename): return basename.endswith('-expected.txt') - def is_not_baseline(self, fs, dirname, basename): - return not self.is_baseline(fs, dirname, basename) - def run(self, cmd, exit_on_failure=True, cwd=None): _log.debug('Running command: %s', ' '.join(cmd))
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/sync_wpt.py b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/sync_wpt.py index 826eb3f..df10de310 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/sync_wpt.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/sync_wpt.py
@@ -27,6 +27,7 @@ host = Host() # TODO(jeffcarp): the script does not handle reverted changes right now + # TODO(jeffcarp): it also doesn't handle changes to -expected.html files local_wpt = LocalWPT(host, no_fetch=options.no_fetch, use_github=True) chromium_wpt = ChromiumWPT(host)
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/update_w3c_test_expectations.py b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/update_w3c_test_expectations.py index 09d2811..15e3a29 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/update_w3c_test_expectations.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/update_w3c_test_expectations.py
@@ -23,6 +23,8 @@ _log = logging.getLogger(__name__) +MARKER_COMMENT = '# ====== New tests from w3c-test-autoroller added here ======' + class W3CExpectationsLineAdder(object): @@ -267,14 +269,13 @@ _log.debug('Lines to write to TestExpectations: %r', line_list) port = self.host.port_factory.get() expectations_file_path = port.path_to_generic_test_expectations_file() - marker_comment = '# Tests added from W3C auto import bot' file_contents = self.host.filesystem.read_text_file(expectations_file_path) - marker_comment_index = file_contents.find(marker_comment) + marker_comment_index = file_contents.find(MARKER_COMMENT) line_list = [line for line in line_list if self._test_name_from_expectation_string(line) not in file_contents] if not line_list: return if marker_comment_index == -1: - file_contents += '\n%s\n' % marker_comment + file_contents += '\n%s\n' % MARKER_COMMENT file_contents += '\n'.join(line_list) else: end_of_marker_line = (file_contents[marker_comment_index:].find('\n')) + marker_comment_index
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/update_w3c_test_expectations_unittest.py b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/update_w3c_test_expectations_unittest.py index ee57843b..4d794cf 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/update_w3c_test_expectations_unittest.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/update_w3c_test_expectations_unittest.py
@@ -13,7 +13,7 @@ from webkitpy.common.system.logtesting import LoggingTestCase from webkitpy.common.system.executive_mock import MockExecutive2 from webkitpy.layout_tests.builder_list import BuilderList -from webkitpy.w3c.update_w3c_test_expectations import W3CExpectationsLineAdder +from webkitpy.w3c.update_w3c_test_expectations import W3CExpectationsLineAdder, MARKER_COMMENT class UpdateW3CTestExpectationsTest(LoggingTestCase): @@ -176,14 +176,14 @@ def test_write_to_test_expectations_with_marker_comment(self): expectations_path = '/mock-checkout/third_party/WebKit/LayoutTests/TestExpectations' - self.host.filesystem.files[expectations_path] = '# Tests added from W3C auto import bot\n' + self.host.filesystem.files[expectations_path] = MARKER_COMMENT + '\n' line_adder = W3CExpectationsLineAdder(self.host) line_list = ['crbug.com/123 [ FakePlatform ] fake/file/path.html [ Pass ]'] line_adder.write_to_test_expectations(line_list) value = line_adder.host.filesystem.read_text_file(expectations_path) self.assertMultiLineEqual( value, - ('# Tests added from W3C auto import bot\n' + (MARKER_COMMENT + '\n' 'crbug.com/123 [ FakePlatform ] fake/file/path.html [ Pass ]\n')) def test_write_to_test_expectations_with_no_marker_comment(self): @@ -196,8 +196,7 @@ self.assertMultiLineEqual( value, ('crbug.com/111 [ FakePlatform ]\n' - '\n' - '# Tests added from W3C auto import bot\n' + '\n' + MARKER_COMMENT + '\n' 'crbug.com/123 [ FakePlatform ] fake/file/path.html [ Pass ]')) def test_write_to_test_expectations_skips_existing_lines(self): @@ -213,21 +212,20 @@ self.assertEqual( value, ('crbug.com/111 dont/copy/me.html [ Failure ]\n' - '\n' - '# Tests added from W3C auto import bot\n' + '\n' + MARKER_COMMENT + '\n' 'crbug.com/222 do/copy/me.html [ Failure ]')) def test_write_to_test_expectations_with_marker_and_no_lines(self): expectations_path = '/mock-checkout/third_party/WebKit/LayoutTests/TestExpectations' self.host.filesystem.files[expectations_path] = ( - '# Tests added from W3C auto import bot\n' + MARKER_COMMENT + '\n' 'crbug.com/123 [ FakePlatform ] fake/file/path.html [ Pass ]\n') line_adder = W3CExpectationsLineAdder(self.host) line_adder.write_to_test_expectations([]) value = line_adder.host.filesystem.read_text_file(expectations_path) self.assertMultiLineEqual( value, - ('# Tests added from W3C auto import bot\n' + (MARKER_COMMENT + '\n' 'crbug.com/123 [ FakePlatform ] fake/file/path.html [ Pass ]\n')) def test_is_js_test_true(self):
diff --git a/third_party/WebKit/public/BUILD.gn b/third_party/WebKit/public/BUILD.gn index 39f1284..ab794f1f 100644 --- a/third_party/WebKit/public/BUILD.gn +++ b/third_party/WebKit/public/BUILD.gn
@@ -73,6 +73,7 @@ header = "public_features.h" flags = [ "DEBUG_DEVTOOLS=$debug_devtools", + "USE_DEFAULT_RENDER_THEME=$use_default_render_theme", "USE_MINIKIN_HYPHENATION=$use_minikin_hyphenation", ] } @@ -190,6 +191,7 @@ "platform/WebGestureCurve.h", "platform/WebGestureCurveTarget.h", "platform/WebGestureDevice.h", + "platform/WebGestureEvent.h", "platform/WebGraphicsContext3DProvider.h", "platform/WebHTTPBody.h", "platform/WebHTTPHeaderVisitor.h", @@ -489,7 +491,6 @@ "web/WebImageCache.h", "web/WebImageDecoder.h", "web/WebInputElement.h", - "web/WebInputEvent.h", "web/WebInputMethodController.h", "web/WebKit.h", "web/WebLabelElement.h",
diff --git a/third_party/WebKit/public/platform/WebGestureEvent.h b/third_party/WebKit/public/platform/WebGestureEvent.h new file mode 100644 index 0000000..791562f --- /dev/null +++ b/third_party/WebKit/public/platform/WebGestureEvent.h
@@ -0,0 +1,171 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef WebGestureEvent_h +#define WebGestureEvent_h + +#include "WebGestureDevice.h" +#include "WebInputEvent.h" + +namespace blink { + +// See WebInputEvent.h for details why this pack is here. +#pragma pack(push, 4) + +// WebGestureEvent --------------------------------------------------------- + +class WebGestureEvent : public WebInputEvent { + public: + enum ScrollUnits { + PrecisePixels = 0, // generated by high precision devices. + Pixels, // large pixel jump duration; should animate to delta. + Page // page (visible viewport) based scrolling. + }; + + enum InertialPhaseState { + UnknownMomentumPhase = 0, // No phase information. + NonMomentumPhase, // Regular scrolling phase. + MomentumPhase, // Momentum phase. + }; + + int x; + int y; + int globalX; + int globalY; + WebGestureDevice sourceDevice; + + // If the WebGestureEvent has sourceDevice=WebGestureDeviceTouchscreen, this + // field contains the unique identifier for the touch event that released + // this event at TouchDispositionGestureFilter. If the WebGestureEvents was + // not released through a touch event (e.g. timer-released gesture events or + // gesture events with sourceDevice!=WebGestureDeviceTouchscreen), the field + // contains 0. See crbug.com/618738. + uint32_t uniqueTouchEventId; + + // This field exists to allow BrowserPlugin to mark GestureScroll events as + // 'resent' to handle the case where an event is not consumed when first + // encountered; it should be handled differently by the plugin when it is + // sent for thesecond time. No code within Blink touches this, other than to + // plumb it through event conversions. + int resendingPluginId; + + union { + // Tap information must be set for GestureTap, GestureTapUnconfirmed, + // and GestureDoubleTap events. + struct { + int tapCount; + float width; + float height; + } tap; + + struct { + float width; + float height; + } tapDown; + + struct { + float width; + float height; + } showPress; + + struct { + float width; + float height; + } longPress; + + struct { + float firstFingerWidth; + float firstFingerHeight; + } twoFingerTap; + + struct { + // Initial motion that triggered the scroll. + // May be redundant with deltaX/deltaY in the first scrollUpdate. + float deltaXHint; + float deltaYHint; + // Default initialized to ScrollUnits::PrecisePixels. + ScrollUnits deltaHintUnits; + // If true, this event will skip hit testing to find a scroll + // target and instead just scroll the viewport. + bool targetViewport; + // The state of inertial phase scrolling. OSX has unique phases for normal + // and momentum scroll events. Should always be UnknownMomentumPhase for + // touch based input as it generates GestureFlingStart instead. + InertialPhaseState inertialPhase; + // True if this event was synthesized in order to force a hit test; + // avoiding scroll latching behavior until crbug.com/526463 is fully + // implemented. + bool synthetic; + + // number of pointers down. + int pointerCount; + } scrollBegin; + + struct { + float deltaX; + float deltaY; + float velocityX; + float velocityY; + // Whether any previous GestureScrollUpdate in the current scroll + // sequence was suppressed (e.g., the causal touchmove was + // preventDefault'ed). This bit is particularly useful for + // determining whether the observed scroll update sequence captures + // the entirety of the generative motion. + bool previousUpdateInSequencePrevented; + bool preventPropagation; + InertialPhaseState inertialPhase; + // Default initialized to ScrollUnits::PrecisePixels. + ScrollUnits deltaUnits; + } scrollUpdate; + + struct { + // The original delta units the scrollBegin and scrollUpdates + // were sent as. + ScrollUnits deltaUnits; + // The state of inertial phase scrolling. OSX has unique phases for normal + // and momentum scroll events. Should always be UnknownMomentumPhase for + // touch based input as it generates GestureFlingStart instead. + InertialPhaseState inertialPhase; + // True if this event was synthesized in order to generate the proper + // GSB/GSU/GSE matching sequences. This is a temporary so that a future + // GSB will generate a hit test so latching behavior is avoided + // until crbug.com/526463 is fully implemented. + bool synthetic; + } scrollEnd; + + struct { + float velocityX; + float velocityY; + // If true, this event will skip hit testing to find a scroll + // target and instead just scroll the viewport. + bool targetViewport; + } flingStart; + + struct { + // If set to true, don't treat flingCancel + // as a part of fling boost events sequence. + bool preventBoosting; + } flingCancel; + + struct { + bool zoomDisabled; + float scale; + } pinchUpdate; + } data; + + WebGestureEvent() + : WebInputEvent(sizeof(WebGestureEvent)), + x(0), + y(0), + globalX(0), + globalY(0), + sourceDevice(WebGestureDeviceUninitialized), + resendingPluginId(-1) {} +}; + +#pragma pack(pop) + +} // namespace blink + +#endif // WebGestureEvent_h
diff --git a/third_party/WebKit/public/platform/WebInputEvent.h b/third_party/WebKit/public/platform/WebInputEvent.h index d0d50a1..2133aae 100644 --- a/third_party/WebKit/public/platform/WebInputEvent.h +++ b/third_party/WebKit/public/platform/WebInputEvent.h
@@ -32,7 +32,6 @@ #define WebInputEvent_h #include "WebCommon.h" -#include "WebGestureDevice.h" #include "WebPointerProperties.h" #include "WebRect.h" #include "WebTouchPoint.h" @@ -333,8 +332,6 @@ nativeKeyCode(0), isSystemKey(false), isBrowserShortcut(false) { - memset(&text, 0, sizeof(text)); - memset(&unmodifiedText, 0, sizeof(unmodifiedText)); } // Please refer to bug http://b/issue?id=961192, which talks about Webkit @@ -460,158 +457,6 @@ dispatchType(Blocking) {} }; -// WebGestureEvent --------------------------------------------------------- - -class WebGestureEvent : public WebInputEvent { - public: - enum ScrollUnits { - PrecisePixels = 0, // generated by high precision devices. - Pixels, // large pixel jump duration; should animate to delta. - Page // page (visible viewport) based scrolling. - }; - - enum InertialPhaseState { - UnknownMomentumPhase = 0, // No phase information. - NonMomentumPhase, // Regular scrolling phase. - MomentumPhase, // Momentum phase. - }; - - int x; - int y; - int globalX; - int globalY; - WebGestureDevice sourceDevice; - - // If the WebGestureEvent has sourceDevice=WebGestureDeviceTouchscreen, this - // field contains the unique identifier for the touch event that released - // this event at TouchDispositionGestureFilter. If the WebGestureEvents was - // not released through a touch event (e.g. timer-released gesture events or - // gesture events with sourceDevice!=WebGestureDeviceTouchscreen), the field - // contains 0. See crbug.com/618738. - uint32_t uniqueTouchEventId; - - // This field exists to allow BrowserPlugin to mark GestureScroll events as - // 'resent' to handle the case where an event is not consumed when first - // encountered; it should be handled differently by the plugin when it is - // sent for thesecond time. No code within Blink touches this, other than to - // plumb it through event conversions. - int resendingPluginId; - - union { - // Tap information must be set for GestureTap, GestureTapUnconfirmed, - // and GestureDoubleTap events. - struct { - int tapCount; - float width; - float height; - } tap; - - struct { - float width; - float height; - } tapDown; - - struct { - float width; - float height; - } showPress; - - struct { - float width; - float height; - } longPress; - - struct { - float firstFingerWidth; - float firstFingerHeight; - } twoFingerTap; - - struct { - // Initial motion that triggered the scroll. - // May be redundant with deltaX/deltaY in the first scrollUpdate. - float deltaXHint; - float deltaYHint; - // Default initialized to ScrollUnits::PrecisePixels. - ScrollUnits deltaHintUnits; - // If true, this event will skip hit testing to find a scroll - // target and instead just scroll the viewport. - bool targetViewport; - // The state of inertial phase scrolling. OSX has unique phases for normal - // and momentum scroll events. Should always be UnknownMomentumPhase for - // touch based input as it generates GestureFlingStart instead. - InertialPhaseState inertialPhase; - // True if this event was synthesized in order to force a hit test; - // avoiding scroll latching behavior until crbug.com/526463 is fully - // implemented. - bool synthetic; - - // number of pointers down. - int pointerCount; - } scrollBegin; - - struct { - float deltaX; - float deltaY; - float velocityX; - float velocityY; - // Whether any previous GestureScrollUpdate in the current scroll - // sequence was suppressed (e.g., the causal touchmove was - // preventDefault'ed). This bit is particularly useful for - // determining whether the observed scroll update sequence captures - // the entirety of the generative motion. - bool previousUpdateInSequencePrevented; - bool preventPropagation; - InertialPhaseState inertialPhase; - // Default initialized to ScrollUnits::PrecisePixels. - ScrollUnits deltaUnits; - } scrollUpdate; - - struct { - // The original delta units the scrollBegin and scrollUpdates - // were sent as. - ScrollUnits deltaUnits; - // The state of inertial phase scrolling. OSX has unique phases for normal - // and momentum scroll events. Should always be UnknownMomentumPhase for - // touch based input as it generates GestureFlingStart instead. - InertialPhaseState inertialPhase; - // True if this event was synthesized in order to generate the proper - // GSB/GSU/GSE matching sequences. This is a temporary so that a future - // GSB will generate a hit test so latching behavior is avoided - // until crbug.com/526463 is fully implemented. - bool synthetic; - } scrollEnd; - - struct { - float velocityX; - float velocityY; - // If true, this event will skip hit testing to find a scroll - // target and instead just scroll the viewport. - bool targetViewport; - } flingStart; - - struct { - // If set to true, don't treat flingCancel - // as a part of fling boost events sequence. - bool preventBoosting; - } flingCancel; - - struct { - bool zoomDisabled; - float scale; - } pinchUpdate; - } data; - - WebGestureEvent() - : WebInputEvent(sizeof(WebGestureEvent)), - x(0), - y(0), - globalX(0), - globalY(0), - sourceDevice(WebGestureDeviceUninitialized), - resendingPluginId(-1) { - memset(&data, 0, sizeof(data)); - } -}; // WebTouchEvent --------------------------------------------------------------
diff --git a/third_party/WebKit/public/public_features.gni b/third_party/WebKit/public/public_features.gni index 2eb71d3..51bc577d 100644 --- a/third_party/WebKit/public/public_features.gni +++ b/third_party/WebKit/public/public_features.gni
@@ -2,6 +2,8 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import("//build/config/ui.gni") + declare_args() { # If debug_devtools is set to true, JavaScript files for DevTools are stored # as is and loaded from disk. Otherwise, a concatenated file is stored in @@ -10,5 +12,7 @@ debug_devtools = false } +use_default_render_theme = use_aura && !is_android + # Use Minikin hyphenation engine. use_minikin_hyphenation = is_android
diff --git a/third_party/WebKit/public/web/WebActiveWheelFlingParameters.h b/third_party/WebKit/public/web/WebActiveWheelFlingParameters.h index 17ad6d7..fa2dc05 100644 --- a/third_party/WebKit/public/web/WebActiveWheelFlingParameters.h +++ b/third_party/WebKit/public/web/WebActiveWheelFlingParameters.h
@@ -31,7 +31,6 @@ #include "../platform/WebGestureDevice.h" #include "../platform/WebPoint.h" #include "../platform/WebSize.h" -#include "WebInputEvent.h" namespace blink {
diff --git a/third_party/WebKit/public/web/WebDocument.h b/third_party/WebKit/public/web/WebDocument.h index 72ef282..4de2c0a 100644 --- a/third_party/WebKit/public/web/WebDocument.h +++ b/third_party/WebKit/public/web/WebDocument.h
@@ -136,6 +136,12 @@ // Each call to this method overrides any previous calls. BLINK_EXPORT void watchCSSSelectors(const WebVector<WebString>& selectors); + // These methods are exposed only as a temporary fix for a stable-blocker + // regression (crbug.com/660706), and should be removed pronto. + // TODO(devlin): Make it happen! + BLINK_EXPORT bool unloadStartedDoNotUse() const; + BLINK_EXPORT bool processingBeforeUnloadDoNotUse() const; + BLINK_EXPORT WebVector<WebDraggableRegion> draggableRegions() const; BLINK_EXPORT v8::Local<v8::Value> registerEmbedderCustomElement(
diff --git a/third_party/WebKit/public/web/WebFrameClient.h b/third_party/WebKit/public/web/WebFrameClient.h index a9d54539..d0039430 100644 --- a/third_party/WebKit/public/web/WebFrameClient.h +++ b/third_party/WebKit/public/web/WebFrameClient.h
@@ -36,6 +36,7 @@ #include "WebDOMMessageEvent.h" #include "WebDataSource.h" #include "WebFileChooserParams.h" +#include "WebFormElement.h" #include "WebFrame.h" #include "WebFrameOwnerProperties.h" #include "WebHistoryCommitType.h" @@ -81,7 +82,6 @@ class WebExternalPopupMenu; class WebExternalPopupMenuClient; class WebFileChooserCompletion; -class WebFormElement; class WebInstalledAppClient; class WebLocalFrame; class WebMediaPlayer; @@ -289,6 +289,7 @@ bool replacesCurrentHistoryItem; bool isHistoryNavigationInNewChildFrame; bool isClientRedirect; + WebFormElement form; NavigationPolicyInfo(WebURLRequest& urlRequest) : extraData(nullptr),
diff --git a/third_party/WebKit/public/web/WebFrameWidget.h b/third_party/WebKit/public/web/WebFrameWidget.h index 952132d..4dd0509 100644 --- a/third_party/WebKit/public/web/WebFrameWidget.h +++ b/third_party/WebKit/public/web/WebFrameWidget.h
@@ -89,7 +89,7 @@ const = 0; // Callback methods when a drag-and-drop operation is trying to drop something - // on the WebWidget. + // on the WebFrameWidget. virtual WebDragOperation dragTargetDragEnter( const WebDragData&, const WebPoint& pointInViewport, @@ -106,6 +106,15 @@ const WebPoint& pointInViewport, const WebPoint& screenPoint, int modifiers) = 0; + + // Notifies the WebFrameWidget that a drag has terminated. + virtual void dragSourceEndedAt(const WebPoint& pointInViewport, + const WebPoint& screenPoint, + WebDragOperation) = 0; + + // Notfies the WebFrameWidget that the system drag and drop operation has + // ended. + virtual void dragSourceSystemDragEnded() = 0; }; } // namespace blink
diff --git a/third_party/WebKit/public/web/WebInputElement.h b/third_party/WebKit/public/web/WebInputElement.h index c14fc8e..7872541 100644 --- a/third_party/WebKit/public/web/WebInputElement.h +++ b/third_party/WebKit/public/web/WebInputElement.h
@@ -65,7 +65,7 @@ BLINK_EXPORT bool isRadioButton() const; BLINK_EXPORT bool isCheckbox() const; // This has different behavior from 'maxLength' IDL attribute, it returns - // defaultMaxLengt() when no valid has been set, whereas 'maxLength' IDL + // defaultMaxLength() when no valid has been set, whereas 'maxLength' IDL // attribute returns -1. BLINK_EXPORT int maxLength() const; BLINK_EXPORT void setActivatedSubmit(bool);
diff --git a/third_party/WebKit/public/web/WebInputEvent.h b/third_party/WebKit/public/web/WebInputEvent.h deleted file mode 100644 index a1fef8b..0000000 --- a/third_party/WebKit/public/web/WebInputEvent.h +++ /dev/null
@@ -1,33 +0,0 @@ -/* - * Copyright (C) 2009 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -// TODO(dtapuska): This is a temporarily placeholder file -// while crbug.com/625684 is fixed. -#include "../platform/WebInputEvent.h"
diff --git a/third_party/WebKit/public/web/WebView.h b/third_party/WebKit/public/web/WebView.h index d1e98a7..06dba32 100644 --- a/third_party/WebKit/public/web/WebView.h +++ b/third_party/WebKit/public/web/WebView.h
@@ -368,14 +368,6 @@ virtual WebHitTestResult hitTestResultForTap(const WebPoint& tapPoint, const WebSize& tapArea) = 0; - // Notifies the WebView that a drag has terminated. - virtual void dragSourceEndedAt(const WebPoint& pointInViewport, - const WebPoint& screenPoint, - WebDragOperation operation) = 0; - - // Notfies the WebView that the system drag and drop operation has ended. - virtual void dragSourceSystemDragEnded() = 0; - // Retrieves a list of spelling markers. virtual void spellingMarkers(WebVector<uint32_t>* markers) = 0; virtual void removeSpellingMarkersUnderWords(
diff --git a/third_party/boringssl/BUILD.gn b/third_party/boringssl/BUILD.gn index ed3754ce..d9439e96 100644 --- a/third_party/boringssl/BUILD.gn +++ b/third_party/boringssl/BUILD.gn
@@ -41,11 +41,6 @@ defines = [ "OPENSSL_NO_ASM" ] } -config("fuzzer_config") { - visibility = [ ":*" ] # Only targets in this file can depend on this. - defines = [ "BORINGSSL_UNSAFE_FUZZER_MODE" ] -} - all_sources = crypto_sources + ssl_sources # Windows' assembly is built with Yasm. The other platforms use the platform @@ -156,6 +151,14 @@ } } + config("fuzzer_config") { + visibility = [ ":*" ] # Only targets in this file can depend on this. + defines = [ + "BORINGSSL_UNSAFE_FUZZER_MODE", + "BORINGSSL_UNSAFE_DETERMINISTIC_MODE", + ] + } + # The same as boringssl, but builds with BORINGSSL_UNSAFE_FUZZER_MODE. component("boringssl_fuzzer") { visibility = [ ":*" ] # Only targets in this file can depend on this. @@ -208,4 +211,52 @@ } } } + + config("fuzzer_no_fuzzer_mode_config") { + visibility = [ ":*" ] # Only targets in this file can depend on this. + defines = [ "BORINGSSL_UNSAFE_DETERMINISTIC_MODE" ] + } + + # The same as boringssl, but builds with BORINGSSL_UNSAFE_DETERMINISTIC_MODE. + component("boringssl_fuzzer_no_fuzzer_mode") { + visibility = [ ":*" ] # Only targets in this file can depend on this. + + sources = all_sources + deps = [ + ":boringssl_asm", + ] + + public_configs = [ + ":external_config", + ":fuzzer_no_fuzzer_mode_config", + ] + configs += [ ":internal_config" ] + + configs -= [ "//build/config/compiler:chromium_code" ] + configs += [ "//build/config/compiler:no_chromium_code" ] + + if (is_nacl) { + deps += [ "//native_client_sdk/src/libraries/nacl_io" ] + } + } + + fuzzer_test("boringssl_client_no_fuzzer_mode_fuzzer") { + sources = [ + "src/fuzz/client.cc", + ] + deps = [ + ":boringssl_fuzzer_no_fuzzer_mode", + ] + seed_corpus = "src/fuzz/client_corpus_no_fuzzer_mode" + } + + fuzzer_test("boringssl_server_no_fuzzer_mode_fuzzer") { + sources = [ + "src/fuzz/server.cc", + ] + deps = [ + ":boringssl_fuzzer_no_fuzzer_mode", + ] + seed_corpus = "src/fuzz/server_corpus_no_fuzzer_mode" + } }
diff --git a/third_party/boringssl/err_data.c b/third_party/boringssl/err_data.c index 001145d..7b70665 100644 --- a/third_party/boringssl/err_data.c +++ b/third_party/boringssl/err_data.c
@@ -178,42 +178,42 @@ 0x28340c19, 0x283480ac, 0x283500ea, - 0x2c322910, - 0x2c32a91e, - 0x2c332930, - 0x2c33a942, - 0x2c342956, - 0x2c34a968, - 0x2c352983, - 0x2c35a995, - 0x2c3629a8, + 0x2c32292c, + 0x2c32a93a, + 0x2c33294c, + 0x2c33a95e, + 0x2c342972, + 0x2c34a984, + 0x2c35299f, + 0x2c35a9b1, + 0x2c3629c4, 0x2c36832d, - 0x2c3729b5, - 0x2c37a9c7, - 0x2c3829da, - 0x2c38a9f1, - 0x2c3929ff, - 0x2c39aa0f, - 0x2c3a2a21, - 0x2c3aaa35, - 0x2c3b2a46, - 0x2c3baa65, - 0x2c3c2a79, - 0x2c3caa8f, - 0x2c3d2aa8, - 0x2c3daac5, - 0x2c3e2ad6, - 0x2c3eaae4, - 0x2c3f2afc, - 0x2c3fab14, - 0x2c402b21, + 0x2c3729d1, + 0x2c37a9e3, + 0x2c3829f6, + 0x2c38aa0d, + 0x2c392a1b, + 0x2c39aa2b, + 0x2c3a2a3d, + 0x2c3aaa51, + 0x2c3b2a62, + 0x2c3baa81, + 0x2c3c2a95, + 0x2c3caaab, + 0x2c3d2ac4, + 0x2c3daae1, + 0x2c3e2af2, + 0x2c3eab00, + 0x2c3f2b18, + 0x2c3fab30, + 0x2c402b3d, 0x2c4090e7, - 0x2c412b32, - 0x2c41ab45, + 0x2c412b4e, + 0x2c41ab61, 0x2c4210c0, - 0x2c42ab56, + 0x2c42ab72, 0x2c430720, - 0x2c43aa57, + 0x2c43aa73, 0x30320000, 0x30328015, 0x3033001f, @@ -438,65 +438,65 @@ 0x405f9f55, 0x40601f63, 0x40609f85, - 0x40611fad, - 0x40619fc2, - 0x40621fd9, - 0x40629fea, - 0x40631ffb, - 0x4063a010, - 0x40642027, - 0x4064a053, - 0x4065206e, - 0x4065a085, - 0x4066209d, - 0x4066a0c7, - 0x406720f2, - 0x4067a113, - 0x40682126, - 0x4068a147, - 0x40692179, - 0x4069a1a7, - 0x406a21c8, - 0x406aa1e8, - 0x406b2370, - 0x406ba393, - 0x406c23a9, - 0x406ca60b, - 0x406d263a, - 0x406da662, - 0x406e2690, - 0x406ea6a8, - 0x406f26c7, - 0x406fa6dc, - 0x407026ef, - 0x4070a70c, + 0x40611fc9, + 0x40619fde, + 0x40621ff5, + 0x4062a006, + 0x40632017, + 0x4063a02c, + 0x40642043, + 0x4064a06f, + 0x4065208a, + 0x4065a0a1, + 0x406620b9, + 0x4066a0e3, + 0x4067210e, + 0x4067a12f, + 0x40682142, + 0x4068a163, + 0x40692195, + 0x4069a1c3, + 0x406a21e4, + 0x406aa204, + 0x406b238c, + 0x406ba3af, + 0x406c23c5, + 0x406ca627, + 0x406d2656, + 0x406da67e, + 0x406e26ac, + 0x406ea6c4, + 0x406f26e3, + 0x406fa6f8, + 0x4070270b, + 0x4070a728, 0x40710800, - 0x4071a71e, - 0x40722731, - 0x4072a74a, - 0x40732762, + 0x4071a73a, + 0x4072274d, + 0x4072a766, + 0x4073277e, 0x4073936d, - 0x40742776, - 0x4074a790, - 0x407527a1, - 0x4075a7b5, - 0x407627c3, + 0x40742792, + 0x4074a7ac, + 0x407527bd, + 0x4075a7d1, + 0x407627df, 0x407691aa, - 0x407727e8, - 0x4077a80a, - 0x40782825, - 0x4078a85e, - 0x40792875, - 0x4079a88b, - 0x407a2897, - 0x407aa8aa, - 0x407b28bf, - 0x407ba8d1, - 0x407c28e6, - 0x407ca8ef, - 0x407d2162, + 0x40772804, + 0x4077a826, + 0x40782841, + 0x4078a87a, + 0x40792891, + 0x4079a8a7, + 0x407a28b3, + 0x407aa8c6, + 0x407b28db, + 0x407ba8ed, + 0x407c2902, + 0x407ca90b, + 0x407d217e, 0x407d9c57, - 0x407e283a, + 0x407e2856, 0x407e9e16, 0x407f1a67, 0x407f9887, @@ -504,45 +504,46 @@ 0x40809a8f, 0x40811cd9, 0x40819c08, - 0x4082267b, + 0x40822697, 0x4082986d, 0x40831df1, - 0x4083a038, + 0x4083a054, 0x40841aa3, 0x40849e4e, 0x40851ed3, - 0x41f4229b, - 0x41f9232d, - 0x41fe2220, - 0x41fea3fc, - 0x41ff24ed, - 0x420322b4, - 0x420822d6, - 0x4208a312, - 0x42092204, - 0x4209a34c, - 0x420a225b, - 0x420aa23b, - 0x420b227b, - 0x420ba2f4, - 0x420c2509, - 0x420ca3c9, - 0x420d23e3, - 0x420da41a, - 0x42122434, - 0x421724d0, - 0x4217a476, - 0x421c2498, - 0x421f2453, - 0x42212520, - 0x422624b3, - 0x422b25ef, - 0x422ba59d, - 0x422c25d7, - 0x422ca55c, - 0x422d253b, - 0x422da5bc, - 0x422e2582, + 0x40859fad, + 0x41f422b7, + 0x41f92349, + 0x41fe223c, + 0x41fea418, + 0x41ff2509, + 0x420322d0, + 0x420822f2, + 0x4208a32e, + 0x42092220, + 0x4209a368, + 0x420a2277, + 0x420aa257, + 0x420b2297, + 0x420ba310, + 0x420c2525, + 0x420ca3e5, + 0x420d23ff, + 0x420da436, + 0x42122450, + 0x421724ec, + 0x4217a492, + 0x421c24b4, + 0x421f246f, + 0x4221253c, + 0x422624cf, + 0x422b260b, + 0x422ba5b9, + 0x422c25f3, + 0x422ca578, + 0x422d2557, + 0x422da5d8, + 0x422e259e, 0x4432072b, 0x4432873a, 0x44330746, @@ -585,69 +586,69 @@ 0x4c3d136d, 0x4c3d937c, 0x4c3e1389, - 0x50322b68, - 0x5032ab77, - 0x50332b82, - 0x5033ab92, - 0x50342bab, - 0x5034abc5, - 0x50352bd3, - 0x5035abe9, - 0x50362bfb, - 0x5036ac11, - 0x50372c2a, - 0x5037ac3d, - 0x50382c55, - 0x5038ac66, - 0x50392c7b, - 0x5039ac8f, - 0x503a2caf, - 0x503aacc5, - 0x503b2cdd, - 0x503bacef, - 0x503c2d0b, - 0x503cad22, - 0x503d2d3b, - 0x503dad51, - 0x503e2d5e, - 0x503ead74, - 0x503f2d86, + 0x50322b84, + 0x5032ab93, + 0x50332b9e, + 0x5033abae, + 0x50342bc7, + 0x5034abe1, + 0x50352bef, + 0x5035ac05, + 0x50362c17, + 0x5036ac2d, + 0x50372c46, + 0x5037ac59, + 0x50382c71, + 0x5038ac82, + 0x50392c97, + 0x5039acab, + 0x503a2ccb, + 0x503aace1, + 0x503b2cf9, + 0x503bad0b, + 0x503c2d27, + 0x503cad3e, + 0x503d2d57, + 0x503dad6d, + 0x503e2d7a, + 0x503ead90, + 0x503f2da2, 0x503f8382, - 0x50402d99, - 0x5040ada9, - 0x50412dc3, - 0x5041add2, - 0x50422dec, - 0x5042ae09, - 0x50432e19, - 0x5043ae29, - 0x50442e38, + 0x50402db5, + 0x5040adc5, + 0x50412ddf, + 0x5041adee, + 0x50422e08, + 0x5042ae25, + 0x50432e35, + 0x5043ae45, + 0x50442e54, 0x5044843f, - 0x50452e4c, - 0x5045ae6a, - 0x50462e7d, - 0x5046ae93, - 0x50472ea5, - 0x5047aeba, - 0x50482ee0, - 0x5048aeee, - 0x50492f01, - 0x5049af16, - 0x504a2f2c, - 0x504aaf3c, - 0x504b2f5c, - 0x504baf6f, - 0x504c2f92, - 0x504cafc0, - 0x504d2fd2, - 0x504dafef, - 0x504e300a, - 0x504eb026, - 0x504f3038, - 0x504fb04f, - 0x5050305e, + 0x50452e68, + 0x5045ae86, + 0x50462e99, + 0x5046aeaf, + 0x50472ec1, + 0x5047aed6, + 0x50482efc, + 0x5048af0a, + 0x50492f1d, + 0x5049af32, + 0x504a2f48, + 0x504aaf58, + 0x504b2f78, + 0x504baf8b, + 0x504c2fae, + 0x504cafdc, + 0x504d2fee, + 0x504db00b, + 0x504e3026, + 0x504eb042, + 0x504f3054, + 0x504fb06b, + 0x5050307a, 0x505086ef, - 0x50513071, + 0x5051308d, 0x58320ec9, 0x68320e8b, 0x68328c25, @@ -1091,6 +1092,7 @@ "PATH_TOO_LONG\0" "PEER_DID_NOT_RETURN_A_CERTIFICATE\0" "PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE\0" + "PRE_SHARED_KEY_MUST_BE_LAST\0" "PROTOCOL_IS_SHUTDOWN\0" "PSK_IDENTITY_NOT_FOUND\0" "PSK_NO_CLIENT_CB\0"
diff --git a/third_party/custom_tabs_client/BUILD.gn b/third_party/custom_tabs_client/BUILD.gn index d73be4f..2ab6e0d 100644 --- a/third_party/custom_tabs_client/BUILD.gn +++ b/third_party/custom_tabs_client/BUILD.gn
@@ -20,14 +20,14 @@ apk_name = "CustomTabsClientExample" deps = [ ":chrome_tabs_client_example_apk_resources", - ":custom_tabs_client_shared_lib", - ":custom_tabs_support_lib", + ":custom_tabs_client_shared_java", + ":custom_tabs_support_java", "//third_party/android_tools:android_support_annotations_java", ] chromium_code = false } -android_library("custom_tabs_client_shared_lib") { +android_library("custom_tabs_client_shared_java") { java_files = [ "src/shared/src/main/java/org/chromium/customtabsclient/shared/CustomTabsHelper.java", "src/shared/src/main/java/org/chromium/customtabsclient/shared/KeepAliveService.java", @@ -36,12 +36,19 @@ ] deps = [ - ":custom_tabs_support_lib", + ":custom_tabs_support_java", ] chromium_code = true } -android_library("custom_tabs_support_lib") { +# TODO(agrieve): Delete once no longer referenced downstream. +java_group("custom_tabs_support_lib") { + deps = [ + ":custom_tabs_support_java", + ] +} + +android_library("custom_tabs_support_java") { java_files = [ "src/customtabs/src/android/support/customtabs/CustomTabsCallback.java", "src/customtabs/src/android/support/customtabs/CustomTabsClient.java", @@ -57,6 +64,7 @@ ] srcjar_deps = [ ":chrome_custom_tabs_service_aidl" ] chromium_code = true + run_findbugs_override = false } android_aidl("chrome_custom_tabs_service_aidl") {
diff --git a/third_party/haha/BUILD.gn b/third_party/haha/BUILD.gn index 6e7a2626..957ab24 100644 --- a/third_party/haha/BUILD.gn +++ b/third_party/haha/BUILD.gn
@@ -4,6 +4,6 @@ import("//build/config/android/rules.gni") -android_java_prebuilt("haha") { +android_java_prebuilt("haha_java") { jar_path = "haha-2.0.2.jar" }
diff --git a/third_party/leakcanary/BUILD.gn b/third_party/leakcanary/BUILD.gn index e88a64fa..c4de58a 100644 --- a/third_party/leakcanary/BUILD.gn +++ b/third_party/leakcanary/BUILD.gn
@@ -121,6 +121,6 @@ ] deps = [ ":leakcanary_resources", - "//third_party/haha", + "//third_party/haha:haha_java", ] }
diff --git a/third_party/netty-tcnative/BUILD.gn b/third_party/netty-tcnative/BUILD.gn index 2af63f5..6cf32a4 100644 --- a/third_party/netty-tcnative/BUILD.gn +++ b/third_party/netty-tcnative/BUILD.gn
@@ -54,7 +54,7 @@ } # Builds the Java part of netty-tcnative library. -android_library("netty-tcnative") { +android_library("netty-tcnative_java") { java_files = [ "src/java/src/org/apache/tomcat/Apr.java", "src/java/src/org/apache/tomcat/jni/Address.java", @@ -103,14 +103,3 @@ "//base:base_java", ] } - -# Builds both the Java and native parts of netty-tcnative library. -group("netty-tcnative_all") { - deps = [ - ":netty-tcnative", - ":netty-tcnative-so", - ] - public_deps = [ - ":netty-tcnative-so", - ] -}
diff --git a/third_party/netty4/BUILD.gn b/third_party/netty4/BUILD.gn index fddbd76f..8e72ddb 100644 --- a/third_party/netty4/BUILD.gn +++ b/third_party/netty4/BUILD.gn
@@ -6,6 +6,6 @@ import("//build/config/android/rules.gni") -android_java_prebuilt("netty_all") { +android_java_prebuilt("netty_all_java") { jar_path = "src/jar/all-in-one/netty-all-4.1.0.CR1-20160111.120759-50.jar" }
diff --git a/third_party/robolectric/BUILD.gn b/third_party/robolectric/BUILD.gn index 5d8691a..560e1db 100644 --- a/third_party/robolectric/BUILD.gn +++ b/third_party/robolectric/BUILD.gn
@@ -7,32 +7,32 @@ java_group("robolectric_all_java") { testonly = true deps = [ - ":android-all-5.0.0_r2-robolectric-1", + ":android-all-5.0.0_r2-robolectric-1_java", ":robolectric_annotations_java", ":robolectric_java", ":robolectric_resources_java", ":robolectric_utils_java", - ":shadows-core-3.0-21", - ":shadows-multidex-3.0", + ":shadows-core-3.0-21_java", + ":shadows-multidex-3.0_java", ] } -java_prebuilt("tagsoup-1.2") { +java_prebuilt("tagsoup-1.2_java") { testonly = true jar_path = "lib/tagsoup-1.2.jar" } -java_prebuilt("json-20080701") { +java_prebuilt("json-20080701_java") { testonly = true jar_path = "lib/json-20080701.jar" } -java_prebuilt("android-all-4.3_r2-robolectric-0") { +java_prebuilt("android-all-4.3_r2-robolectric-0_java") { testonly = true jar_path = "lib/android-all-4.3_r2-robolectric-0.jar" } -java_prebuilt("android-all-5.0.0_r2-robolectric-1") { +java_prebuilt("android-all-5.0.0_r2-robolectric-1_java") { testonly = true jar_path = "lib/android-all-5.0.0_r2-robolectric-1.jar" } @@ -40,15 +40,15 @@ java_library("robolectric_java") { testonly = true deps = [ - ":android-all-5.0.0_r2-robolectric-1", - ":json-20080701", + ":android-all-5.0.0_r2-robolectric-1_java", + ":json-20080701_java", ":robolectric_annotations_java", ":robolectric_resources_java", ":robolectric_utils_java", - ":shadows-core-3.0-18", - ":shadows-core-3.0-21", - ":shadows-multidex-3.0", - ":tagsoup-1.2", + ":shadows-core-3.0-18_java", + ":shadows-core-3.0-21_java", + ":shadows-multidex-3.0_java", + ":tagsoup-1.2_java", "//third_party/bouncycastle:bouncycastle_java", "//third_party/icu4j:icu4j_java", "//third_party/intellij:intellij_annotations_java", @@ -118,7 +118,7 @@ java_library("robolectric_annotations_java") { testonly = true deps = [ - ":android-all-5.0.0_r2-robolectric-1", + ":android-all-5.0.0_r2-robolectric-1_java", "//third_party/intellij:intellij_annotations_java", ] java_files = [ @@ -165,7 +165,7 @@ java_library("robolectric_resources_java") { testonly = true deps = [ - ":android-all-5.0.0_r2-robolectric-1", + ":android-all-5.0.0_r2-robolectric-1_java", ":robolectric_annotations_java", ":robolectric_utils_java", "//third_party/intellij:intellij_annotations_java", @@ -235,7 +235,7 @@ java_library("robolectric_utils_java") { testonly = true deps = [ - ":android-all-5.0.0_r2-robolectric-1", + ":android-all-5.0.0_r2-robolectric-1_java", ":robolectric_annotations_java", "//third_party/accessibility_test_framework:accessibility_test_framework_java", "//third_party/hamcrest:hamcrest_core_java", @@ -541,23 +541,19 @@ } template("shadows_core") { - forward_variables_from(invoker, - [ - "api_level", - "android_sdk_deps", - ]) testonly = true _shadows_core_java_files = invoker.shadows_core_java_files _template_files = invoker.template_files - _process_templates_target_name = "${target_name}__process_templates" + _process_templates_target_name = + "shadows_core_${invoker.api_level}__process_templates" _processed_template_files = [] _template_file_args = [] foreach(template_file, _template_files) { _gen_dir = get_path_info(template_file, "gen_dir") _name = get_path_info(template_file, "name") - _output_file = "$_gen_dir/$api_level/$_name" + _output_file = "$_gen_dir/${invoker.api_level}/$_name" _template_file_args += [ "--process-file", "$template_file", @@ -571,7 +567,7 @@ script = "$root_build_dir/bin/robolectric_template_processor" args = [ "--api-level", - "$api_level", + "${invoker.api_level}", "--base-template-dir", _base_template_dir, ] @@ -642,21 +638,21 @@ "//third_party/intellij:intellij_annotations_java", "//third_party/sqlite4java:sqlite4java_java", ] - deps += android_sdk_deps + deps += invoker.android_sdk_deps } } -shadows_core("shadows-core-3.0-21") { +shadows_core("shadows-core-3.0-21_java") { api_level = 21 - android_sdk_deps = [ ":android-all-5.0.0_r2-robolectric-1" ] + android_sdk_deps = [ ":android-all-5.0.0_r2-robolectric-1_java" ] } -shadows_core("shadows-core-3.0-18") { +shadows_core("shadows-core-3.0-18_java") { api_level = 18 - android_sdk_deps = [ ":android-all-4.3_r2-robolectric-0" ] + android_sdk_deps = [ ":android-all-4.3_r2-robolectric-0_java" ] } -java_library("shadows-multidex-3.0") { +java_library("shadows-multidex-3.0_java") { testonly = true processors_javac = [ "org.robolectric.annotation.processing.RobolectricProcessor" ] @@ -668,7 +664,7 @@ ] deps = [ - ":android-all-5.0.0_r2-robolectric-1", + ":android-all-5.0.0_r2-robolectric-1_java", ":robolectric_annotations_java", ":robolectric_processor_java", ":robolectric_utils_java",
diff --git a/third_party/sudden_motion_sensor/sudden_motion_sensor_mac.cc b/third_party/sudden_motion_sensor/sudden_motion_sensor_mac.cc index cd05e246..17d6888 100644 --- a/third_party/sudden_motion_sensor/sudden_motion_sensor_mac.cc +++ b/third_party/sudden_motion_sensor/sudden_motion_sensor_mac.cc
@@ -222,18 +222,20 @@ // Tested by avi on a 13" MacBook Pro. // Note: - // - MacBookPro10,1 (15" MacBook Pro with Retina display) + // - MacBookPro10,1 (15" MacBook Pro Retina, mid 2012) // has no accelerometer sensors. // MacBookPro10,2 handled by the generic case below. // Tested by avi on a 13" MacBook Pro with Retina display. // Note: - // - MacBookPro11,1 (13" MacBook Pro with Retina display) - // - MacBookPro11,2 (15" MacBook Pro with Retina display) - // - MacBookPro11,3 (15" MacBook Pro with Retina display) - // - MacBookPro11,4 (15" MacBook Pro with Retina display) - // - MacBookPro12,1 (13" MacBook Pro with Retina display) + // - MacBookPro11,1 (13" MacBook Pro, late 2013 - mid 2014) + // - MacBookPro11,2 (15" MacBook Pro, late 2013 - mid 2014) + // - MacBookPro11,3 (15" MacBook Pro, late 2013 - mid 2014) + // - MacBookPro11,4 (15" MacBook Pro, mid 2015) + // - MacBookPro11,5 (15" MacBook Pro, mid 2015) + // - MacBookPro12,1 (13" MacBook Pro, early 2015) + // - MacBookPro13,1 (13" MacBook Pro, late 2016) // have no accelerometer sensors. // Generic MacBook accelerometer sensor data, to be used for future models
diff --git a/tools/android/customtabs_benchmark/BUILD.gn b/tools/android/customtabs_benchmark/BUILD.gn index e1bd05e9c..ff365cab 100644 --- a/tools/android/customtabs_benchmark/BUILD.gn +++ b/tools/android/customtabs_benchmark/BUILD.gn
@@ -9,6 +9,6 @@ android_manifest = "java/AndroidManifest.xml" apk_name = "CustomTabsBenchmark" deps = [ - "//third_party/custom_tabs_client:custom_tabs_support_lib", + "//third_party/custom_tabs_client:custom_tabs_support_java", ] }
diff --git a/tools/battor_agent/battor_finder.cc b/tools/battor_agent/battor_finder.cc index 0aa54ac12..6137c3b 100644 --- a/tools/battor_agent/battor_finder.cc +++ b/tools/battor_agent/battor_finder.cc
@@ -38,7 +38,9 @@ // If we have no switch-specified path, look for a device with the right // display name. for (size_t i = 0; i < devices.size(); i++) { - std::string display_name = devices[i]->display_name.get(); + if (!devices[i]->display_name) + continue; + const auto& display_name = devices[i]->display_name.value(); if (display_name.find(kBattOrDisplayNamePrefix) != std::string::npos) { LOG(INFO) << "Found BattOr with display name " << display_name << " at path " << devices[i]->path;
diff --git a/tools/clang/scripts/test_tool.py b/tools/clang/scripts/test_tool.py index 728db47..18031f68 100755 --- a/tools/clang/scripts/test_tool.py +++ b/tools/clang/scripts/test_tool.py
@@ -49,6 +49,7 @@ sys.exit(1) tool_to_test = argv[0] + print '\nTesting %s\n' % tool_to_test tools_clang_scripts_directory = os.path.dirname(os.path.realpath(__file__)) tools_clang_directory = os.path.dirname(tools_clang_scripts_directory) test_directory_for_tool = os.path.join( @@ -71,6 +72,10 @@ '../..', 'testing/gtest/include'))) + if len(actual_files) == 0: + print 'Tool "%s" does not have compatible test files.' % tool_to_test + return 1 + try: # Set up the test environment. for source, actual in zip(source_files, actual_files): @@ -93,7 +98,7 @@ stdout, _ = run_tool.communicate() if run_tool.returncode != 0: print 'run_tool failed:\n%s' % stdout - sys.exit(1) + return 1 args = ['cl', 'format'] args.extend(actual_files) @@ -130,6 +135,7 @@ print '[ PASSED ] %s.' % _NumberOfTestsToString(passed) if failed > 0: print '[ FAILED ] %s.' % _NumberOfTestsToString(failed) + return 1 finally: # No matter what, unstage the git changes we made earlier to avoid polluting # the index.
diff --git a/tools/clang/scripts/update.py b/tools/clang/scripts/update.py index 157abbf0d..96d45b4 100755 --- a/tools/clang/scripts/update.py +++ b/tools/clang/scripts/update.py
@@ -34,7 +34,7 @@ CLANG_REVISION = 'HEAD' # This is incremented when pushing a new build of Clang at the same revision. -CLANG_SUB_REVISION=1 +CLANG_SUB_REVISION=2 PACKAGE_VERSION = "%s-%s" % (CLANG_REVISION, CLANG_SUB_REVISION)
diff --git a/tools/gn/docs/cookbook.md b/tools/gn/docs/cookbook.md index 9a1b259..390fbf1b 100644 --- a/tools/gn/docs/cookbook.md +++ b/tools/gn/docs/cookbook.md
@@ -275,7 +275,6 @@ | `use_athena` (0/1) | `use_athena` (true/false) | `//build/config/ui.gni` | | `use_aura` (0/1) | `use_aura` (true/false) | `//build/config/ui.gni` | | `use_cairo` (0/1) | `use_cairo` (true/false) | `//build/config/ui.gni` | -| `use_clipboard_aurax11` (0/1) | `use_aura && use_x11` | | | `use_cups` (0/1) | `use_cups` (true/false) | `//build/config/features.gni` | | `use_dbus` (0/1) | `use_dbus` (true/false) | `//build/config/features.gni` | | `use_gconf` (0/1) | `use_gconf` (true/false) | `//build/config/features.gni` |
diff --git a/tools/mb/mb.py b/tools/mb/mb.py index 364671f..07ad4a2 100755 --- a/tools/mb/mb.py +++ b/tools/mb/mb.py
@@ -1056,19 +1056,23 @@ return ret def GetIsolateCommand(self, target, vals): + isolate_map = self.ReadIsolateMap() + android = 'target_os="android"' in vals['gn_args'] + ozone = 'use_ozone=true' in vals['gn_args'] + ozone_x11 = (ozone and 'args' in isolate_map[target] and + '--ozone-platform=x11' in isolate_map[target]['args']) # This needs to mirror the settings in //build/config/ui.gni: - # use_x11 = is_linux && !use_ozone. + # use_x11 = is_linux && !use_ozone || use_ozone && --ozone-platform=x11 use_x11 = (self.platform == 'linux2' and not android and - not 'use_ozone=true' in vals['gn_args']) + (ozone_x11 or not ozone)) asan = 'is_asan=true' in vals['gn_args'] msan = 'is_msan=true' in vals['gn_args'] tsan = 'is_tsan=true' in vals['gn_args'] - isolate_map = self.ReadIsolateMap() test_type = isolate_map[target]['type'] executable = isolate_map[target].get('executable', target)
diff --git a/tools/mb/mb_config.pyl b/tools/mb/mb_config.pyl index 144223d..d86b4aa 100644 --- a/tools/mb/mb_config.pyl +++ b/tools/mb/mb_config.pyl
@@ -81,6 +81,7 @@ 'Android Builder Goma Canary (dbg)': 'android_debug_bot', 'Android deterministic': 'android_without_codecs_release_bot_minimal_symbols', 'Android deterministic (dbg)': 'android_debug_bot', + 'Android x64 Tests': 'android_shared_release_bot_x64', 'Blimp Android Client': '//build/args/bots/chromium.fyi/blimp_client_rel.gn', 'Blimp Linux Engine': @@ -834,6 +835,10 @@ 'android', 'release_bot', 'minimal_symbols', ], + 'android_shared_release_bot_x64': [ + 'android_without_codecs', 'shared_release_bot', 'x64', 'dcheck_always_on', + ], + 'android_release_trybot': [ 'android', 'release_trybot', ],
diff --git a/tools/md_browser/md_browser.py b/tools/md_browser/md_browser.py index f7a32e7b..d423c66 100755 --- a/tools/md_browser/md_browser.py +++ b/tools/md_browser/md_browser.py
@@ -17,11 +17,12 @@ import threading import time import webbrowser +from xml.etree import ElementTree THIS_DIR = os.path.realpath(os.path.dirname(__file__)) SRC_DIR = os.path.dirname(os.path.dirname(THIS_DIR)) -sys.path.append(os.path.join(SRC_DIR, 'third_party', 'Python-Markdown')) +sys.path.insert(0, os.path.join(SRC_DIR, 'third_party', 'Python-Markdown')) import markdown @@ -155,10 +156,19 @@ } contents = self._Read(path[1:]) - md_fragment = markdown.markdown(contents, - extensions=extensions, - extension_configs=extension_configs, - output_format='html4').encode('utf-8') + + md = markdown.Markdown(extensions=extensions, + extension_configs=extension_configs, + output_format='html4') + + has_a_single_h1 = (len([line for line in contents.splitlines() + if (line.startswith('#') and + not line.startswith('##'))]) == 1) + + md.treeprocessors['adjust_toc'] = _AdjustTOC(has_a_single_h1) + + md_fragment = md.convert(contents).encode('utf-8') + try: self._WriteHeader('text/html') self._WriteTemplate('header.html') @@ -199,5 +209,64 @@ self.wfile.write(contents.encode('utf-8')) +class _AdjustTOC(markdown.treeprocessors.Treeprocessor): + def __init__(self, has_a_single_h1): + super(_AdjustTOC, self).__init__() + self.has_a_single_h1 = has_a_single_h1 + + def run(self, tree): + # Given + # + # # H1 + # + # [TOC] + # + # ## first H2 + # + # ## second H2 + # + # the markdown.extensions.toc extension generates: + # + # <div class='toc'> + # <ul><li><a>H1</a> + # <ul><li>first H2 + # <li>second H2</li></ul></li><ul></div> + # + # for [TOC]. But, we want the TOC to have its own subheading, so + # we rewrite <div class='toc'><ul>...</ul></div> to: + # + # <div class='toc'> + # <h2>Contents</h2> + # <div class='toc-aux'> + # <ul>...</ul></div></div> + # + # In addition, if the document only has a single H1, it is usually the + # title, and we don't want the title to be in the TOC. So, we remove it + # and shift all of the title's children up a level, leaving: + # + # <div class='toc'> + # <h2>Contents</h2> + # <div class='toc-aux'> + # <ul><li>first H2 + # <li>second H2</li></ul></div></div> + + for toc_node in tree.findall(".//*[@class='toc']"): + toc_ul = toc_node[0] + if self.has_a_single_h1: + toc_ul_li = toc_ul[0] + ul_with_the_desired_toc_entries = toc_ul_li[1] + else: + ul_with_the_desired_toc_entries = toc_ul + + toc_node.remove(toc_ul) + contents = ElementTree.SubElement(toc_node, 'h2') + contents.text = 'Contents' + contents.tail = '\n' + toc_aux = ElementTree.SubElement(toc_node, 'div', {'class': 'toc-aux'}) + toc_aux.text = '\n' + toc_aux.append(ul_with_the_desired_toc_entries) + toc_aux.tail = '\n' + + if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 7e94067..4e1dd217 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -16877,6 +16877,18 @@ <summary>The manifest version of each loaded extension.</summary> </histogram> +<histogram name="Extensions.Messaging.ExtensionPortsCreated" + units="number of ports"> + <owner>rdevlin.cronin@chromium.org</owner> + <summary> + The number of ports created in a given script context at a specific time. + Recorded once at the destruction of the script context (when no more ports + could be created) if and only if at least one port was created in the + context. Only includes ports to extension contexts (i.e., not ports created + to tabs or native apps). + </summary> +</histogram> + <histogram name="Extensions.Messaging.GetPortIdAsyncTime" units="ms"> <owner>rdevlin.cronin@chromium.org</owner> <summary> @@ -21977,6 +21989,13 @@ </summary> </histogram> +<histogram name="JSDialogs.IsForemost" enum="BooleanForemost"> + <owner>avi@chromium.org</owner> + <summary> + For dialogs, whether or not they were spawned by a tab that was foremost. + </summary> +</histogram> + <histogram name="JSDialogs.OnBeforeUnloadStayVsLeave" enum="StayVsLeave"> <owner>avi@chromium.org</owner> <summary> @@ -38309,6 +38328,15 @@ </summary> </histogram> +<histogram name="NewTabPage.Snippets.EnteredState" enum="NTPSnippetsState"> + <owner>knn@chromium.org</owner> + <summary> + Android: The state of the RemoteSuggestionsProvider. Recorded when the state + changes, typically once at startup and rarely afterwards, e.g. on database + errors. + </summary> +</histogram> + <histogram name="NewTabPage.Snippets.FetchHttpResponseOrErrorCode" enum="CombinedHttpResponseAndNetErrorCode"> <owner>mastiz@chromium.org</owner> @@ -40226,6 +40254,14 @@ </summary> </histogram> +<histogram name="Omnibox.PaintTime" units="ms"> + <owner>asvitkine@chromium.org</owner> + <summary> + Records the time to paint the omnibox contents. This is a subcomponent of + Omnibox.CharTypedToRepaintLatency. Implemented on desktop platforms. + </summary> +</histogram> + <histogram name="Omnibox.Paste" units="count"> <owner>mpearson@chromium.org</owner> <summary> @@ -42910,6 +42946,13 @@ </summary> </histogram> +<histogram name="Pepper.Graphics3DHasShareGroup" units="BooleanShareGroup"> + <owner>jbauman@chromium.org</owner> + <summary> + True if a non-flash Pepper Graphics3D context has a share group. + </summary> +</histogram> + <histogram name="Pepper.InterfaceUsed" enum="PepperInterface"> <owner>sehr@chromium.org</owner> <owner>bradnelson@chromium.org</owner> @@ -71339,6 +71382,18 @@ </summary> </histogram> +<histogram name="WebRTC.Audio.ResidualEchoDetector.EchoLikelihood" units="%"> + <owner>hlundin@chromium.org</owner> + <owner>ivoc@chromium.org</owner> + <summary> + The estimated likelihood percentage of echo as detected by the residual echo + detector. The residual echo detector can be used to detect cases where the + AEC (hardware or software) is not functioning properly. The detector can be + non-causal and operates on larger timescales with more delay than the + regular AEC. + </summary> +</histogram> + <histogram name="WebRTC.Audio.TargetBitrateInKbps" units="kbps"> <owner>hlundin@chromium.org</owner> <summary> @@ -75673,6 +75728,11 @@ <int value="1" label="Force Disabled"/> </enum> +<enum name="BooleanForemost" type="int"> + <int value="0" label="Tab was not foremost"/> + <int value="1" label="Tab was foremost"/> +</enum> + <enum name="BooleanFormatChanged" type="int"> <int value="0" label="Any Codec Initialized"/> <int value="1" label="Missing FORMAT_CHANGED message"/> @@ -75968,6 +76028,11 @@ <int value="1" label="Selected"/> </enum> +<enum name="BooleanShareGroup" type="int"> + <int value="0" label="No share group"/> + <int value="1" label="Using share group"/> +</enum> + <enum name="BooleanShown" type="int"> <int value="0" label="Not Shown"/> <int value="1" label="Shown"/> @@ -85762,6 +85827,8 @@ <int value="1682" label="TouchEventPreventedNoTouchAction"/> <int value="1683" label="TouchEventPreventedForcedDocumentPassiveNoTouchAction"/> + <int value="1684" label="V8Event_StopPropagation_Method"/> + <int value="1685" label="V8Event_StopImmediatePropagation_Method"/> </enum> <enum name="FetchRequestMode" type="int"> @@ -94339,6 +94406,18 @@ <int value="8" label="Out of non-interactive quota"/> </enum> +<enum name="NTPSnippetsState" type="int"> + <summary> + The state of the RemoteSuggestionsProvider (formerly known as + NTPSnippetsService). + </summary> +<!-- Note: 0 corresponds to NOT_INITED, which should never be recorded. --> + + <int value="1" label="Ready"/> + <int value="2" label="Disabled"/> + <int value="3" label="Error"/> +</enum> + <enum name="NtpSuggestionsType" type="int"> <int value="0" label="Client suggestion"/> <int value="1" label="Server suggestion"/> @@ -107068,6 +107147,17 @@ <affected-histogram name="Extensions.Functions.SucceededTime"/> </histogram_suffixes> +<histogram_suffixes name="ExtensionMessagingPortCreationTime" separator="."> + <suffix name="Normal" + label="Created during any time other than the 'unload' or + 'beforeunload' handlers."/> + <suffix name="InBeforeUnload" + label="Created during an event handler for the 'beforeunload' event."/> + <suffix name="InUnload" + label="Created during an event handler for the 'unload' event."/> + <affected-histogram name="Extensions.Messaging.ExtensionPortsCreated"/> +</histogram_suffixes> + <histogram_suffixes name="ExtensionMessagingPortType" separator="."> <suffix name="Extension" label="A port opened to an extension context."/> <suffix name="NativeApp" label="A port opened to a native application."/> @@ -107677,12 +107767,10 @@ </histogram_suffixes> <histogram_suffixes name="JSDialogs.DialogType" separator="."> - <obsolete> - Deprecated 2016-10. - </obsolete> <suffix name="Alert"/> <suffix name="Confirm"/> <suffix name="Prompt"/> + <affected-histogram name="JSDialogs.IsForemost"/> <affected-histogram name="JSDialogs.SiteEngagementOfDialogs"/> </histogram_suffixes>
diff --git a/tools/perf/page_sets/idle_after_loading_stories.py b/tools/perf/page_sets/idle_after_loading_stories.py index 6f19739c..8054cc2 100644 --- a/tools/perf/page_sets/idle_after_loading_stories.py +++ b/tools/perf/page_sets/idle_after_loading_stories.py
@@ -6,10 +6,6 @@ # Chrome has high idle CPU usage on these sites, even after they have quiesced. SITES = [ - # https://bugs.chromium.org/p/chromium/issues/detail?id=638365 - 'http://www.labradortraininghq.com/labrador-training/how-to-crate-train' - '-a-puppy/#How_Long_DoesIt_Take_To_Crate_Train_A_Puppy', - # https://bugs.chromium.org/p/chromium/issues/detail?id=505990 # TODO(charliea): Temporarily disable this site, since it causes tracing to # explode from too much data. https://crbug.com/647398 @@ -18,42 +14,20 @@ # https://bugs.chromium.org/p/chromium/issues/detail?id=505601 'http://www.slideshare.net/patrickmeenan', - # https://bugs.chromium.org/p/chromium/issues/detail?id=505577 - 'http://tumblr.all-that-is-interesting.com/', - # https://bugs.chromium.org/p/chromium/issues/detail?id=505553 'https://instagram.com/cnn/', # https://bugs.chromium.org/p/chromium/issues/detail?id=505544 'http://www.sina.com.cn', - # https://bugs.chromium.org/p/chromium/issues/detail?id=505056 - 'http://bbc.com/news/uk/', - # https://bugs.chromium.org/p/chromium/issues/detail?id=505054 'http://www.uol.com.br', # https://bugs.chromium.org/p/chromium/issues/detail?id=505052 'http://www.indiatimes.com', - # https://bugs.chromium.org/p/chromium/issues/detail?id=505044 - 'http://www.w3schools.com/html/default.asp', - # https://bugs.chromium.org/p/chromium/issues/detail?id=505002 'http://www.microsoft.com', - - # https://bugs.chromium.org/p/chromium/issues/detail?id=489936 - 'http://capitalone.com', - - # https://bugs.chromium.org/p/chromium/issues/detail?id=481225 - 'https://twitter.com/katyperry', - - # https://bugs.chromium.org/p/chromium/issues/detail?id=476158 - 'http://bgr.com', - - # https://bugs.chromium.org/p/chromium/issues/detail?id=425474 - 'http://www.androidpolice.com/2014/10/20/animation-bonanza-android' - '-5-0-lollipop-in-gifs/', ] # TODO(rnephew): Move to seperate file and merge with mac_gpu_sites BasePage.
diff --git a/tools/perf/page_sets/system_health/blank_stories.py b/tools/perf/page_sets/system_health/blank_stories.py index ffe0ecc..dbfd385d 100644 --- a/tools/perf/page_sets/system_health/blank_stories.py +++ b/tools/perf/page_sets/system_health/blank_stories.py
@@ -4,7 +4,9 @@ from page_sets.system_health import system_health_story +from telemetry import decorators +@decorators.Disabled('win') # crbug.com/656040 class BlankAboutBlankStory(system_health_story.SystemHealthStory): """Story that loads the about:blank page."""
diff --git a/tools/perf/page_sets/system_health/browsing_stories.py b/tools/perf/page_sets/system_health/browsing_stories.py index 2a68155..e5cd356 100644 --- a/tools/perf/page_sets/system_health/browsing_stories.py +++ b/tools/perf/page_sets/system_health/browsing_stories.py
@@ -126,6 +126,7 @@ SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY +@decorators.Disabled('mac') # crbug.com/663025 class FlipboardDesktopStory(_NewsBrowsingStory): NAME = 'browse:news:flipboard' URL = 'https://flipboard.com/explore' @@ -194,7 +195,8 @@ SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY -@decorators.Disabled('win') # crbug.com/662971 +@decorators.Disabled('win', # crbug.com/662971 + 'mac') # crbug.com/664661, crbug.com/663025 class TwitterDesktopStory(_NewsBrowsingStory): NAME = 'browse:social:twitter' URL = 'https://www.twitter.com/nasa'
diff --git a/tools/perf/page_sets/system_health/loading_stories.py b/tools/perf/page_sets/system_health/loading_stories.py index 5dfef74..3b0532d 100644 --- a/tools/perf/page_sets/system_health/loading_stories.py +++ b/tools/perf/page_sets/system_health/loading_stories.py
@@ -8,6 +8,8 @@ from page_sets.login_helpers import dropbox_login from page_sets.login_helpers import google_login +from telemetry import decorators + class _LoadingStory(system_health_story.SystemHealthStory): """Abstract base class for single-page System Health user stories.""" @@ -381,6 +383,7 @@ 'document.querySelector("#game canvas").style.background !== ""') +@decorators.Disabled('mac') # crbug.com/664661 class LoadMiniclipStory(_LoadingStory): NAME = 'load:games:miniclip' # Using "https://" causes "404 Not Found" during WPR recording.
diff --git a/ui/accessibility/platform/ax_platform_node_delegate.h b/ui/accessibility/platform/ax_platform_node_delegate.h index 998168a7..8569e7f 100644 --- a/ui/accessibility/platform/ax_platform_node_delegate.h +++ b/ui/accessibility/platform/ax_platform_node_delegate.h
@@ -94,6 +94,9 @@ // Whether SetStringValue() is callable, i.e. if the string value is not read // only and if the callback exists. virtual bool CanSetStringValue() = 0; + + // Focus or unfocus a View, checking if the View is focusable first. + virtual bool SetFocused(bool focused) = 0; }; } // namespace ui
diff --git a/ui/accessibility/platform/ax_platform_node_mac.mm b/ui/accessibility/platform/ax_platform_node_mac.mm index 5814956..a30b4200 100644 --- a/ui/accessibility/platform/ax_platform_node_mac.mm +++ b/ui/accessibility/platform/ax_platform_node_mac.mm
@@ -382,9 +382,8 @@ return node_->GetDelegate()->CanSetStringValue(); if ([attributeName isEqualToString:NSAccessibilityFocusedAttribute]) { - if (ui::AXNodeData::IsFlagSet(node_->GetData().state, - ui::AX_STATE_FOCUSABLE)) - return NO; + return ui::AXNodeData::IsFlagSet(node_->GetData().state, + ui::AX_STATE_FOCUSABLE); } // TODO(patricialor): Add callbacks for updating the above attributes except @@ -393,13 +392,19 @@ } - (void)accessibilitySetValue:(id)value forAttribute:(NSString*)attribute { - if ([attribute isEqualToString:NSAccessibilityValueAttribute] && - [value isKindOfClass:[NSString class]]) { - node_->GetDelegate()->SetStringValue(base::SysNSStringToUTF16(value), true); - } else if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute] && - [value isKindOfClass:[NSString class]]) { - node_->GetDelegate()->SetStringValue(base::SysNSStringToUTF16(value), - false); + if ([value isKindOfClass:[NSString class]]) { + if ([attribute isEqualToString:NSAccessibilityValueAttribute]) { + node_->GetDelegate()->SetStringValue(base::SysNSStringToUTF16(value), + true); + } else if ([attribute + isEqualToString:NSAccessibilitySelectedTextAttribute]) { + node_->GetDelegate()->SetStringValue(base::SysNSStringToUTF16(value), + false); + } + } else if ([value isKindOfClass:[NSNumber class]]) { + if ([attribute isEqualToString:NSAccessibilityFocusedAttribute]) { + node_->GetDelegate()->SetFocused([value boolValue]); + } } // TODO(patricialor): Plumb through all the other writable attributes as
diff --git a/ui/accessibility/platform/test_ax_node_wrapper.cc b/ui/accessibility/platform/test_ax_node_wrapper.cc index 1c6aefa..7388fd35 100644 --- a/ui/accessibility/platform/test_ax_node_wrapper.cc +++ b/ui/accessibility/platform/test_ax_node_wrapper.cc
@@ -128,6 +128,10 @@ return false; } +bool TestAXNodeWrapper::SetFocused(bool focused) { + return false; +} + TestAXNodeWrapper::TestAXNodeWrapper(AXTree* tree, AXNode* node) : tree_(tree), node_(node),
diff --git a/ui/accessibility/platform/test_ax_node_wrapper.h b/ui/accessibility/platform/test_ax_node_wrapper.h index f2a12f0..a52dd537 100644 --- a/ui/accessibility/platform/test_ax_node_wrapper.h +++ b/ui/accessibility/platform/test_ax_node_wrapper.h
@@ -42,6 +42,7 @@ bool SetStringValue(const base::string16& new_value, bool clear_first) override; bool CanSetStringValue() override; + bool SetFocused(bool focused) override; private: TestAXNodeWrapper(AXTree* tree, AXNode* node);
diff --git a/ui/base/BUILD.gn b/ui/base/BUILD.gn index e50e4029..04909bb 100644 --- a/ui/base/BUILD.gn +++ b/ui/base/BUILD.gn
@@ -598,7 +598,7 @@ # Aura clipboard. if (use_aura) { - if (use_clipboard_aurax11) { + if (use_x11 && is_desktop_linux) { sources += [ "clipboard/clipboard_aurax11.cc", "clipboard/clipboard_aurax11.h",
diff --git a/ui/chromeos/BUILD.gn b/ui/chromeos/BUILD.gn index f20011e..e5844a5 100644 --- a/ui/chromeos/BUILD.gn +++ b/ui/chromeos/BUILD.gn
@@ -23,6 +23,8 @@ "ime/input_method_menu_manager.h", "ime/mode_indicator_view.cc", "ime/mode_indicator_view.h", + "touch_accessibility_enabler.cc", + "touch_accessibility_enabler.h", "touch_exploration_controller.cc", "touch_exploration_controller.h", "user_activity_power_manager_notifier.cc", @@ -61,6 +63,7 @@ "ime/input_method_menu_item_unittest.cc", "ime/input_method_menu_manager_unittest.cc", "run_all_unittests.cc", + "touch_accessibility_enabler_unittest.cc", "touch_exploration_controller_unittest.cc", ] deps = [
diff --git a/ui/chromeos/touch_accessibility_enabler.cc b/ui/chromeos/touch_accessibility_enabler.cc new file mode 100644 index 0000000..675f396 --- /dev/null +++ b/ui/chromeos/touch_accessibility_enabler.cc
@@ -0,0 +1,147 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/chromeos/touch_accessibility_enabler.h" + +#include <math.h> + +#include <utility> + +#include "base/logging.h" +#include "base/time/default_tick_clock.h" +#include "ui/aura/window.h" +#include "ui/aura/window_event_dispatcher.h" +#include "ui/aura/window_tree_host.h" +#include "ui/events/event.h" +#include "ui/events/event_processor.h" +#include "ui/events/event_utils.h" + +namespace ui { + +namespace { + +// Delay between timer callbacks. Each one plays a tick sound. +constexpr int kTimerDelayInMS = 500; + +// The number of ticks of the timer before toggling spoken feedback. +constexpr int kTimerTicksToToggleSpokenFeedback = 7; + +} // namespace + +TouchAccessibilityEnabler::TouchAccessibilityEnabler( + aura::Window* root_window, + TouchAccessibilityEnablerDelegate* delegate) + : root_window_(root_window), + delegate_(delegate), + state_(NO_FINGERS_DOWN), + tick_clock_(NULL) { + DCHECK(root_window); + DCHECK(delegate); + root_window_->AddPreTargetHandler(this); +} + +TouchAccessibilityEnabler::~TouchAccessibilityEnabler() { + root_window_->RemovePreTargetHandler(this); +} + +void TouchAccessibilityEnabler::OnTouchEvent(ui::TouchEvent* event) { + // Skip events rewritten by TouchExplorationController, it will hand + // us the unrewritten events directly. + if (!(event->flags() & ui::EF_TOUCH_ACCESSIBILITY)) + HandleTouchEvent(*event); +} + +void TouchAccessibilityEnabler::HandleTouchEvent(const ui::TouchEvent& event) { + DCHECK(!(event.flags() & ui::EF_TOUCH_ACCESSIBILITY)); + const ui::EventType type = event.type(); + const gfx::PointF& location = event.location_f(); + const int touch_id = event.touch_id(); + + if (type == ui::ET_TOUCH_PRESSED) { + touch_locations_.insert(std::pair<int, gfx::PointF>(touch_id, location)); + } else if (type == ui::ET_TOUCH_RELEASED || type == ui::ET_TOUCH_CANCELLED) { + auto iter = touch_locations_.find(touch_id); + + // Can happen if this object is constructed while fingers were down. + if (iter == touch_locations_.end()) + return; + + touch_locations_.erase(touch_id); + } else if (type == ui::ET_TOUCH_MOVED) { + auto iter = touch_locations_.find(touch_id); + + // Can happen if this object is constructed while fingers were down. + if (iter == touch_locations_.end()) + return; + + float delta = (location - iter->second).Length(); + if (delta > gesture_detector_config_.double_tap_slop) { + state_ = WAIT_FOR_NO_FINGERS; + CancelTimer(); + return; + } + } else { + NOTREACHED() << "Unexpected event type received: " << event.name(); + return; + } + + if (touch_locations_.size() == 0) { + state_ = NO_FINGERS_DOWN; + CancelTimer(); + return; + } + + if (touch_locations_.size() > 2) { + state_ = WAIT_FOR_NO_FINGERS; + CancelTimer(); + return; + } + + if (state_ == NO_FINGERS_DOWN && event.type() == ui::ET_TOUCH_PRESSED) { + state_ = ONE_FINGER_DOWN; + } else if (state_ == ONE_FINGER_DOWN && + event.type() == ui::ET_TOUCH_PRESSED) { + state_ = TWO_FINGERS_DOWN; + two_finger_start_time_ = Now(); + StartTimer(); + } +} + +base::TimeTicks TouchAccessibilityEnabler::Now() { + if (tick_clock_) { + // This is the same as what EventTimeForNow() does, but here we do it + // with a clock that can be replaced with a simulated clock for tests. + return tick_clock_->NowTicks(); + } + return ui::EventTimeForNow(); +} + +void TouchAccessibilityEnabler::StartTimer() { + if (timer_.IsRunning()) + return; + + timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(kTimerDelayInMS), + this, &ui::TouchAccessibilityEnabler::OnTimer); +} + +void TouchAccessibilityEnabler::CancelTimer() { + if (timer_.IsRunning()) + timer_.Stop(); +} + +void TouchAccessibilityEnabler::OnTimer() { + base::TimeTicks now = Now(); + double tick_count_f = + (now - two_finger_start_time_).InMillisecondsF() / kTimerDelayInMS; + int tick_count = roundf(tick_count_f); + if (tick_count >= 1 && tick_count < kTimerTicksToToggleSpokenFeedback) { + delegate_->PlaySpokenFeedbackToggleCountdown(tick_count); + } + if (tick_count == kTimerTicksToToggleSpokenFeedback) { + delegate_->ToggleSpokenFeedback(); + state_ = WAIT_FOR_NO_FINGERS; + } +} + +} // namespace ui
diff --git a/ui/chromeos/touch_accessibility_enabler.h b/ui/chromeos/touch_accessibility_enabler.h new file mode 100644 index 0000000..1b25990a --- /dev/null +++ b/ui/chromeos/touch_accessibility_enabler.h
@@ -0,0 +1,119 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef UI_CHROMEOS_TOUCH_ACCESSIBILITY_ENABLER_H_ +#define UI_CHROMEOS_TOUCH_ACCESSIBILITY_ENABLER_H_ + +#include "base/macros.h" +#include "base/time/tick_clock.h" +#include "base/timer/timer.h" +#include "base/values.h" +#include "ui/chromeos/ui_chromeos_export.h" +#include "ui/events/event.h" +#include "ui/events/event_handler.h" +#include "ui/events/gesture_detection/gesture_detector.h" + +namespace aura { +class Window; +} + +namespace ui { + +class Event; +class EventHandler; +class TouchEvent; + +// A delegate to handle commands in response to detected accessibility gesture +// events. +class TouchAccessibilityEnablerDelegate { + public: + virtual ~TouchAccessibilityEnablerDelegate() {} + + // While the user holds down two fingers on a touch screen, which is the + // gesture to enable spoken feedback (if held down long enough), play a sound + // every "tick" (approximately every half-second) to warn the user something + // is about to happen. + virtual void PlaySpokenFeedbackToggleCountdown(int tick_count) {} + + // Toggles spoken feedback. + virtual void ToggleSpokenFeedback() {} +}; + +// TouchAccessibilityEnabler triggers turning spoken feedback on or off +// by holding down two fingers on the touch screen for several seconds. +class UI_CHROMEOS_EXPORT TouchAccessibilityEnabler : public ui::EventHandler { + public: + TouchAccessibilityEnabler(aura::Window* root_window, + ui::TouchAccessibilityEnablerDelegate* delegate); + ~TouchAccessibilityEnabler() override; + + bool IsInNoFingersDownForTesting() { return state_ == NO_FINGERS_DOWN; } + bool IsInOneFingerDownForTesting() { return state_ == ONE_FINGER_DOWN; } + bool IsInTwoFingersDownForTesting() { return state_ == TWO_FINGERS_DOWN; } + bool IsInWaitForNoFingersForTesting() { + return state_ == WAIT_FOR_NO_FINGERS; + } + void TriggerOnTimerForTesting() { OnTimer(); } + + void HandleTouchEvent(const ui::TouchEvent& event); + + private: + // Overridden from ui::EventHandler + void OnTouchEvent(ui::TouchEvent* event) override; + + void StartTimer(); + void CancelTimer(); + void OnTimer(); + + // Returns the current time of the tick clock. + base::TimeTicks Now(); + + enum State { + // No fingers are down. + NO_FINGERS_DOWN, + + // One finger is down and it's possible this could be a two-finger-hold. + ONE_FINGER_DOWN, + + // Two fingers are down and stationary and we will trigger enabling + // spoken feedback after a delay. + TWO_FINGERS_DOWN, + + // This is the "reject" state when we get anything other than two fingers + // held down and stationary. Stay in this state until all fingers are + // removed. + WAIT_FOR_NO_FINGERS + }; + + aura::Window* root_window_; + + // Called when we detect a long-press of two fingers. Not owned. + ui::TouchAccessibilityEnablerDelegate* delegate_; + + // The current state. + State state_; + + // The time when we entered the two finger state. + base::TimeTicks two_finger_start_time_; + + // Map of touch ids to their initial locations. + std::map<int, gfx::PointF> touch_locations_; + + // A timer that triggers repeatedly while two fingers are held down. + base::RepeatingTimer timer_; + + // A default gesture detector config, so we can share the same + // timeout and pixel slop constants. + ui::GestureDetector::Config gesture_detector_config_; + + // When touch_accessibility_enabler gets time relative to real time during + // testing, this clock is set to the simulated clock and used. + base::TickClock* tick_clock_; + + DISALLOW_COPY_AND_ASSIGN(TouchAccessibilityEnabler); +}; + +} // namespace ui + +#endif // UI_CHROMEOS_TOUCH_ACCESSIBILITY_ENABLER_H_
diff --git a/ui/chromeos/touch_accessibility_enabler_unittest.cc b/ui/chromeos/touch_accessibility_enabler_unittest.cc new file mode 100644 index 0000000..1de53357 --- /dev/null +++ b/ui/chromeos/touch_accessibility_enabler_unittest.cc
@@ -0,0 +1,181 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/chromeos/touch_accessibility_enabler.h" + +#include "base/macros.h" +#include "base/test/simple_test_tick_clock.h" +#include "base/time/time.h" +#include "ui/aura/test/aura_test_base.h" +#include "ui/aura/window.h" +#include "ui/events/event.h" +#include "ui/events/event_utils.h" +#include "ui/events/gestures/gesture_provider_aura.h" +#include "ui/events/test/event_generator.h" +#include "ui/events/test/events_test_utils.h" +#include "ui/gfx/geometry/point.h" + +namespace ui { + +namespace { + +class MockTouchAccessibilityEnablerDelegate + : public ui::TouchAccessibilityEnablerDelegate { + public: + MockTouchAccessibilityEnablerDelegate() {} + ~MockTouchAccessibilityEnablerDelegate() override {} + + void PlaySpokenFeedbackToggleCountdown(int tick_count) override { + ++feedback_progress_sound_count_; + } + void ToggleSpokenFeedback() override { toggle_spoken_feedback_ = true; } + + size_t feedback_progress_sound_count() const { + return feedback_progress_sound_count_; + } + bool toggle_spoken_feedback() const { return toggle_spoken_feedback_; } + + private: + size_t feedback_progress_sound_count_ = 0; + bool toggle_spoken_feedback_ = false; + + DISALLOW_COPY_AND_ASSIGN(MockTouchAccessibilityEnablerDelegate); +}; + +class TouchAccessibilityEnablerTest : public aura::test::AuraTestBase { + public: + TouchAccessibilityEnablerTest() {} + ~TouchAccessibilityEnablerTest() override {} + + void SetUp() override { + aura::test::AuraTestBase::SetUp(); + + generator_.reset(new test::EventGenerator(root_window())); + + simulated_clock_ = new base::SimpleTestTickClock(); + // Tests fail if time is ever 0. + simulated_clock_->Advance(base::TimeDelta::FromMilliseconds(10)); + // ui takes ownership of the tick clock. + ui::SetEventTickClockForTesting( + std::unique_ptr<base::TickClock>(simulated_clock_)); + + enabler_.reset(new TouchAccessibilityEnabler(root_window(), &delegate_)); + } + + void TearDown() override { + enabler_.reset(nullptr); + ui::SetEventTickClockForTesting(nullptr); + aura::test::AuraTestBase::TearDown(); + } + + protected: + base::TimeTicks Now() { + // This is the same as what EventTimeForNow() does, but here we do it + // with our simulated clock. + return simulated_clock_->NowTicks(); + } + + std::unique_ptr<test::EventGenerator> generator_; + // Owned by |ui|. + base::SimpleTestTickClock* simulated_clock_ = nullptr; + MockTouchAccessibilityEnablerDelegate delegate_; + std::unique_ptr<TouchAccessibilityEnabler> enabler_; + ui::GestureDetector::Config gesture_detector_config_; + + DISALLOW_COPY_AND_ASSIGN(TouchAccessibilityEnablerTest); +}; + +} // namespace + +TEST_F(TouchAccessibilityEnablerTest, EntersOneFingerDownMode) { + EXPECT_TRUE(enabler_->IsInNoFingersDownForTesting()); + EXPECT_FALSE(enabler_->IsInOneFingerDownForTesting()); + generator_->set_current_location(gfx::Point(11, 12)); + generator_->PressTouch(); + + EXPECT_FALSE(enabler_->IsInNoFingersDownForTesting()); + EXPECT_TRUE(enabler_->IsInOneFingerDownForTesting()); +} + +TEST_F(TouchAccessibilityEnablerTest, EntersTwoFingersDownMode) { + EXPECT_TRUE(enabler_->IsInNoFingersDownForTesting()); + generator_->set_current_location(gfx::Point(11, 12)); + generator_->PressTouchId(1); + + generator_->set_current_location(gfx::Point(22, 34)); + generator_->PressTouchId(2); + + EXPECT_TRUE(enabler_->IsInTwoFingersDownForTesting()); +} + +TEST_F(TouchAccessibilityEnablerTest, PlaysProgressSound) { + EXPECT_TRUE(enabler_->IsInNoFingersDownForTesting()); + generator_->set_current_location(gfx::Point(11, 12)); + generator_->PressTouchId(1); + + generator_->set_current_location(gfx::Point(22, 34)); + generator_->PressTouchId(2); + + EXPECT_TRUE(enabler_->IsInTwoFingersDownForTesting()); + EXPECT_EQ(0U, delegate_.feedback_progress_sound_count()); + + enabler_->TriggerOnTimerForTesting(); + EXPECT_EQ(0U, delegate_.feedback_progress_sound_count()); + + simulated_clock_->Advance(base::TimeDelta::FromMilliseconds(500)); + enabler_->TriggerOnTimerForTesting(); + EXPECT_EQ(1U, delegate_.feedback_progress_sound_count()); +} + +TEST_F(TouchAccessibilityEnablerTest, TogglesSpokenFeedback) { + EXPECT_TRUE(enabler_->IsInNoFingersDownForTesting()); + generator_->set_current_location(gfx::Point(11, 12)); + generator_->PressTouchId(1); + + generator_->set_current_location(gfx::Point(22, 34)); + generator_->PressTouchId(2); + + EXPECT_TRUE(enabler_->IsInTwoFingersDownForTesting()); + EXPECT_FALSE(delegate_.toggle_spoken_feedback()); + + enabler_->TriggerOnTimerForTesting(); + EXPECT_FALSE(delegate_.toggle_spoken_feedback()); + + simulated_clock_->Advance(base::TimeDelta::FromMilliseconds(3500)); + enabler_->TriggerOnTimerForTesting(); + EXPECT_TRUE(delegate_.toggle_spoken_feedback()); +} + +TEST_F(TouchAccessibilityEnablerTest, ThreeFingersCancelsDetection) { + EXPECT_TRUE(enabler_->IsInNoFingersDownForTesting()); + generator_->set_current_location(gfx::Point(11, 12)); + generator_->PressTouchId(1); + + generator_->set_current_location(gfx::Point(22, 34)); + generator_->PressTouchId(2); + + EXPECT_TRUE(enabler_->IsInTwoFingersDownForTesting()); + + generator_->set_current_location(gfx::Point(33, 56)); + generator_->PressTouchId(3); + + EXPECT_TRUE(enabler_->IsInWaitForNoFingersForTesting()); +} + +TEST_F(TouchAccessibilityEnablerTest, MovingFingerPastSlopCancelsDetection) { + EXPECT_TRUE(enabler_->IsInNoFingersDownForTesting()); + generator_->set_current_location(gfx::Point(11, 12)); + generator_->PressTouch(); + + int slop = gesture_detector_config_.double_tap_slop; + int half_slop = slop / 2; + + generator_->MoveTouch(gfx::Point(11 + half_slop, 12)); + EXPECT_TRUE(enabler_->IsInOneFingerDownForTesting()); + + generator_->MoveTouch(gfx::Point(11 + slop + 1, 12)); + EXPECT_TRUE(enabler_->IsInWaitForNoFingersForTesting()); +} + +} // namespace ui
diff --git a/ui/chromeos/touch_exploration_controller.cc b/ui/chromeos/touch_exploration_controller.cc index 985779f..f2d0c83 100644 --- a/ui/chromeos/touch_exploration_controller.cc +++ b/ui/chromeos/touch_exploration_controller.cc
@@ -13,6 +13,7 @@ #include "ui/aura/window.h" #include "ui/aura/window_event_dispatcher.h" #include "ui/aura/window_tree_host.h" +#include "ui/chromeos/touch_accessibility_enabler.h" #include "ui/events/event.h" #include "ui/events/event_processor.h" #include "ui/events/event_utils.h" @@ -40,14 +41,16 @@ TouchExplorationController::TouchExplorationController( aura::Window* root_window, - TouchExplorationControllerDelegate* delegate) + TouchExplorationControllerDelegate* delegate, + TouchAccessibilityEnabler* touch_accessibility_enabler) : root_window_(root_window), delegate_(delegate), state_(NO_FINGERS_DOWN), anchor_point_state_(ANCHOR_POINT_NONE), gesture_provider_(new GestureProviderAura(this, this)), prev_state_(NO_FINGERS_DOWN), - VLOG_on_(true) { + VLOG_on_(true), + touch_accessibility_enabler_(touch_accessibility_enabler) { DCHECK(root_window); root_window->GetHost()->GetEventSource()->AddEventRewriter(this); } @@ -84,6 +87,10 @@ } const ui::TouchEvent& touch_event = static_cast<const ui::TouchEvent&>(event); + // Let TouchAccessibilityEnabler process the unrewritten event. + if (touch_accessibility_enabler_) + touch_accessibility_enabler_->HandleTouchEvent(touch_event); + if (!exclude_bounds_.IsEmpty()) { gfx::Point location = touch_event.location(); root_window_->GetHost()->ConvertPointFromNativeScreen(&location);
diff --git a/ui/chromeos/touch_exploration_controller.h b/ui/chromeos/touch_exploration_controller.h index 0af2d079..6727c2a 100644 --- a/ui/chromeos/touch_exploration_controller.h +++ b/ui/chromeos/touch_exploration_controller.h
@@ -25,6 +25,7 @@ class Event; class GestureEvent; class GestureProviderAura; +class TouchAccessibilityEnabler; class TouchEvent; // A delegate to handle commands in response to detected accessibility gesture @@ -180,7 +181,8 @@ public: explicit TouchExplorationController( aura::Window* root_window, - ui::TouchExplorationControllerDelegate* delegate); + ui::TouchExplorationControllerDelegate* delegate, + TouchAccessibilityEnabler* touch_accessibility_enabler); ~TouchExplorationController() override; // Make synthesized touch events are anchored at this point. This is @@ -506,6 +508,12 @@ // LocatedEvents within this area should be left alone. gfx::Rect exclude_bounds_; + // Code that detects a touch-screen gesture to enable or disable + // accessibility. That handler is always running, whereas this is not, + // but events need to be sent to TouchAccessibilityEnabler before being + // rewritten when TouchExplorationController is running. + TouchAccessibilityEnabler* touch_accessibility_enabler_; + DISALLOW_COPY_AND_ASSIGN(TouchExplorationController); };
diff --git a/ui/chromeos/touch_exploration_controller_unittest.cc b/ui/chromeos/touch_exploration_controller_unittest.cc index 02acee7..14b7a247 100644 --- a/ui/chromeos/touch_exploration_controller_unittest.cc +++ b/ui/chromeos/touch_exploration_controller_unittest.cc
@@ -298,7 +298,8 @@ } else if (on && !touch_exploration_controller_.get()) { touch_exploration_controller_.reset( new ui::TouchExplorationControllerTestApi( - new TouchExplorationController(root_window(), &delegate_))); + new TouchExplorationController(root_window(), &delegate_, + nullptr))); cursor_client()->ShowCursor(); cursor_client()->DisableMouseEvents(); }
diff --git a/ui/content_accelerators/DEPS b/ui/content_accelerators/DEPS index 4329266..9e6e70d 100644 --- a/ui/content_accelerators/DEPS +++ b/ui/content_accelerators/DEPS
@@ -2,5 +2,5 @@ "+content/public", "+ui/base", "+ui/events", - "+third_party/WebKit/public/web/WebInputEvent.h", + "+third_party/WebKit/public/platform/WebInputEvent.h", ]
diff --git a/ui/content_accelerators/accelerator_util.cc b/ui/content_accelerators/accelerator_util.cc index f7d627d..f6c99fa 100644 --- a/ui/content_accelerators/accelerator_util.cc +++ b/ui/content_accelerators/accelerator_util.cc
@@ -5,7 +5,7 @@ #include "ui/content_accelerators/accelerator_util.h" #include "build/build_config.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/event.h" #include "ui/events/event_constants.h"
diff --git a/ui/events/blink/DEPS b/ui/events/blink/DEPS index 94532ab..198f59ef 100644 --- a/ui/events/blink/DEPS +++ b/ui/events/blink/DEPS
@@ -8,6 +8,7 @@ "+third_party/WebKit/public/platform/WebGestureCurveTarget.h", "+third_party/WebKit/public/platform/WebFloatPoint.h", "+third_party/WebKit/public/platform/WebFloatSize.h", + "+third_party/WebKit/public/platform/WebGestureEvent.h", "+third_party/WebKit/public/platform/WebInputEvent.h", "+third_party/WebKit/public/platform/WebPoint.h", "+third_party/WebKit/public/web/WebActiveWheelFlingParameters.h",
diff --git a/ui/events/blink/blink_event_util.cc b/ui/events/blink/blink_event_util.cc index f0bb1247..360ca65 100644 --- a/ui/events/blink/blink_event_util.cc +++ b/ui/events/blink/blink_event_util.cc
@@ -14,6 +14,7 @@ #include "base/time/time.h" #include "build/build_config.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" #include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/base_event_utils.h" #include "ui/events/event_constants.h"
diff --git a/ui/events/blink/blink_event_util_unittest.cc b/ui/events/blink/blink_event_util_unittest.cc index fbf2fc8..e4dab10 100644 --- a/ui/events/blink/blink_event_util_unittest.cc +++ b/ui/events/blink/blink_event_util_unittest.cc
@@ -6,6 +6,7 @@ #include "base/time/time.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" #include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/gesture_event_details.h"
diff --git a/ui/events/blink/input_handler_proxy.h b/ui/events/blink/input_handler_proxy.h index 546cc11..a74be1c 100644 --- a/ui/events/blink/input_handler_proxy.h +++ b/ui/events/blink/input_handler_proxy.h
@@ -12,6 +12,7 @@ #include "cc/input/input_handler.h" #include "third_party/WebKit/public/platform/WebGestureCurve.h" #include "third_party/WebKit/public/platform/WebGestureCurveTarget.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" #include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/web/WebActiveWheelFlingParameters.h" #include "ui/events/blink/input_scroll_elasticity_controller.h"
diff --git a/ui/events/blink/input_scroll_elasticity_controller.h b/ui/events/blink/input_scroll_elasticity_controller.h index 23ca00b..4e44584b 100644 --- a/ui/events/blink/input_scroll_elasticity_controller.h +++ b/ui/events/blink/input_scroll_elasticity_controller.h
@@ -8,6 +8,7 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "cc/input/scroll_elasticity_helper.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" #include "third_party/WebKit/public/platform/WebInputEvent.h" // InputScrollElasticityController is based on
diff --git a/ui/events/blink/web_input_event.h b/ui/events/blink/web_input_event.h index 4f1fe95..caac517c 100644 --- a/ui/events/blink/web_input_event.h +++ b/ui/events/blink/web_input_event.h
@@ -6,6 +6,7 @@ #define UI_EVENTS_BLINK_WEB_INPUT_EVENT_H_ #include "base/callback.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" #include "third_party/WebKit/public/platform/WebInputEvent.h" namespace gfx {
diff --git a/ui/events/blink/web_input_event_traits.h b/ui/events/blink/web_input_event_traits.h index ea076bef8..88ab04f 100644 --- a/ui/events/blink/web_input_event_traits.h +++ b/ui/events/blink/web_input_event_traits.h
@@ -5,6 +5,7 @@ #ifndef UI_EVENTS_BLINK_WEB_INPUT_EVENT_TRAITS_H_ #define UI_EVENTS_BLINK_WEB_INPUT_EVENT_TRAITS_H_ +#include "third_party/WebKit/public/platform/WebGestureEvent.h" #include "third_party/WebKit/public/platform/WebInputEvent.h" #include "ui/events/blink/scoped_web_input_event.h" #include "ui/events/latency_info.h"
diff --git a/ui/file_manager/audio_player/elements/repeat_button.css b/ui/file_manager/audio_player/elements/repeat_button.css index 7003cffa..0e9772e 100644 --- a/ui/file_manager/audio_player/elements/repeat_button.css +++ b/ui/file_manager/audio_player/elements/repeat_button.css
@@ -34,3 +34,8 @@ top: 2px; width: 28px; } + +:host(.keyboard-focus) { + /* We use box-shadow rather than outline to make it rounded. */ + box-shadow: 0 0 0 1px rgba(66, 133, 244, 0.5); +}
diff --git a/ui/file_manager/audio_player/elements/repeat_button.js b/ui/file_manager/audio_player/elements/repeat_button.js index 51f5b9c..48e68d52 100644 --- a/ui/file_manager/audio_player/elements/repeat_button.js +++ b/ui/file_manager/audio_player/elements/repeat_button.js
@@ -10,6 +10,16 @@ Polymer({ is: 'repeat-button', + hostAttributes: { + role: 'button', + tabindex: 0 + }, + + behaviors: [ + Polymer.IronButtonState, + Polymer.IronControlState + ], + properties: { 'repeatMode': { type: String, @@ -22,6 +32,18 @@ tap: '_tapHandler' }, + observers: [ + '_focusedChanged(receivedFocusFromKeyboard)' + ], + + _focusedChanged: function(receivedFocusFromKeyboard) { + if (receivedFocusFromKeyboard) { + this.classList.add('keyboard-focus'); + } else { + this.classList.remove('keyboard-focus'); + } + }, + /** * Initialize member variables. */
diff --git a/ui/gfx/vector_icons/media_router_error.icon b/ui/gfx/vector_icons/media_router_error.icon index 0b2b0d6..eb1fccd 100644 --- a/ui/gfx/vector_icons/media_router_error.icon +++ b/ui/gfx/vector_icons/media_router_error.icon
@@ -47,10 +47,10 @@ H_LINE_TO, 8, CUBIC_TO, 8, 10.11f, 4.41f, 6.56f, 0, 6.56f, CLOSE, -MOVE_TO, 12.58f, 6.74f, +MOVE_TO, 12.94f, 6, R_LINE_TO, -1.69f, 1.69f, -LINE_TO, 9.73f, 6.74f, -LINE_TO, 8.84f, 7.63f, +LINE_TO, 9.56f, 6, +LINE_TO, 8.5f, 7.06f, R_LINE_TO, 1.69f, 1.69f, R_LINE_TO, -1.69f, 1.69f, R_LINE_TO, 1.06f, 1.06f,
diff --git a/ui/gl/BUILD.gn b/ui/gl/BUILD.gn index 69262b4..df83289 100644 --- a/ui/gl/BUILD.gn +++ b/ui/gl/BUILD.gn
@@ -404,6 +404,22 @@ ] } +group("gl_unittests_ozonex") { + testonly = true + data_deps = [ + ":gl_unittests", + ] +} + +# TODO(GYP_GONE): Delete this after we've converted everything to GN. +# The _run targets exist only for compatibility w/ GYP. +group("gl_unittests_ozonex_run") { + testonly = true + deps = [ + ":gl_unittests_ozonex", + ] +} + if (is_android) { generate_jar_jni("surface_jni_headers") { jni_package = "ui/gl"
diff --git a/ui/ozone/demo/gl_renderer.cc b/ui/ozone/demo/gl_renderer.cc index 3921a090..970a299 100644 --- a/ui/ozone/demo/gl_renderer.cc +++ b/ui/ozone/demo/gl_renderer.cc
@@ -24,7 +24,7 @@ bool GlRenderer::Initialize() { context_ = gl::init::CreateGLContext(nullptr, surface_.get(), - gl::PreferIntegratedGpu); + gl::GLContextAttribs()); if (!context_.get()) { LOG(ERROR) << "Failed to create GL context"; return false;
diff --git a/ui/views/BUILD.gn b/ui/views/BUILD.gn index c742f9c..5004c47 100644 --- a/ui/views/BUILD.gn +++ b/ui/views/BUILD.gn
@@ -24,6 +24,7 @@ "animation/bounds_animator.h", "animation/flood_fill_ink_drop_ripple.cc", "animation/flood_fill_ink_drop_ripple.h", + "animation/ink_drop.cc", "animation/ink_drop.h", "animation/ink_drop_animation_ended_reason.cc", "animation/ink_drop_animation_ended_reason.h", @@ -35,6 +36,8 @@ "animation/ink_drop_host_view.h", "animation/ink_drop_impl.cc", "animation/ink_drop_impl.h", + "animation/ink_drop_mask.cc", + "animation/ink_drop_mask.h", "animation/ink_drop_painted_layer_delegates.cc", "animation/ink_drop_painted_layer_delegates.h", "animation/ink_drop_ripple.cc", @@ -855,6 +858,7 @@ "focus/focus_manager_unittest.cc", "focus/focus_traversal_unittest.cc", "layout/box_layout_unittest.cc", + "layout/fill_layout_unittest.cc", "layout/grid_layout_unittest.cc", "rect_based_targeting_utils_unittest.cc", "view_model_unittest.cc",
diff --git a/ui/views/accessibility/native_view_accessibility.cc b/ui/views/accessibility/native_view_accessibility.cc index db1c1c4..04a0fa5af 100644 --- a/ui/views/accessibility/native_view_accessibility.cc +++ b/ui/views/accessibility/native_view_accessibility.cc
@@ -217,6 +217,17 @@ return !ui::AXNodeData::IsFlagSet(GetData().state, ui::AX_STATE_READ_ONLY); } +bool NativeViewAccessibility::SetFocused(bool focused) { + if (!ui::AXNodeData::IsFlagSet(GetData().state, ui::AX_STATE_FOCUSABLE)) + return false; + + if (focused) + view_->RequestFocus(); + else if (view_->HasFocus()) + view_->GetFocusManager()->ClearFocus(); + return true; +} + void NativeViewAccessibility::OnWidgetDestroying(Widget* widget) { if (parent_widget_ == widget) { parent_widget_->RemoveObserver(this);
diff --git a/ui/views/accessibility/native_view_accessibility.h b/ui/views/accessibility/native_view_accessibility.h index c4a07edaf..46752135 100644 --- a/ui/views/accessibility/native_view_accessibility.h +++ b/ui/views/accessibility/native_view_accessibility.h
@@ -59,6 +59,7 @@ bool SetStringValue(const base::string16& new_value, bool clear_first) override; bool CanSetStringValue() override; + bool SetFocused(bool focused) override; // WidgetObserver void OnWidgetDestroying(Widget* widget) override;
diff --git a/ui/views/accessibility/native_view_accessibility_auralinux.cc b/ui/views/accessibility/native_view_accessibility_auralinux.cc index a18c0b17..3ed2c2d 100644 --- a/ui/views/accessibility/native_view_accessibility_auralinux.cc +++ b/ui/views/accessibility/native_view_accessibility_auralinux.cc
@@ -116,6 +116,8 @@ bool CanSetStringValue() override { return false; } + bool SetFocused(bool focused) override { return false; } + private: friend struct base::DefaultSingletonTraits<AuraLinuxApplication>;
diff --git a/ui/views/accessibility/native_view_accessibility_unittest.cc b/ui/views/accessibility/native_view_accessibility_unittest.cc index 88d92168..4fd1b1e5 100644 --- a/ui/views/accessibility/native_view_accessibility_unittest.cc +++ b/ui/views/accessibility/native_view_accessibility_unittest.cc
@@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" #include "ui/accessibility/ax_node_data.h" #include "ui/gfx/geometry/rect_conversions.h" @@ -34,7 +35,7 @@ widget_ = new views::Widget; views::Widget::InitParams params = - CreateParams(views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); + CreateParams(views::Widget::InitParams::TYPE_WINDOW); params.bounds = gfx::Rect(0, 0, 200, 200); widget_->Init(params); @@ -46,7 +47,7 @@ button_->AddChildView(label_); label_accessibility_ = NativeViewAccessibility::Create(label_); - widget_->SetContentsView(button_); + widget_->GetContentsView()->AddChildView(button_); } void TearDown() override { @@ -87,6 +88,21 @@ label_accessibility_->GetParent()); } +TEST_F(NativeViewAccessibilityTest, WritableFocus) { + widget_->Show(); + // Make |button_| focusable, and focus/unfocus it via NativeViewAccessibility. + button_->SetFocusBehavior(View::FocusBehavior::ALWAYS); + EXPECT_EQ(nullptr, button_->GetFocusManager()->GetFocusedView()); + EXPECT_EQ(nullptr, button_accessibility_->GetFocus()); + EXPECT_TRUE(button_accessibility_->SetFocused(true)); + EXPECT_EQ(button_, button_->GetFocusManager()->GetFocusedView()); + EXPECT_EQ(button_->GetNativeViewAccessible(), + button_accessibility_->GetFocus()); + EXPECT_TRUE(button_accessibility_->SetFocused(false)); + EXPECT_EQ(nullptr, button_->GetFocusManager()->GetFocusedView()); + EXPECT_EQ(nullptr, button_accessibility_->GetFocus()); +} + // Subclass of NativeViewAccessibility that destroys itself when its // parent widget is destroyed, for the purposes of making sure this // doesn't lead to a crash.
diff --git a/ui/views/animation/ink_drop.cc b/ui/views/animation/ink_drop.cc new file mode 100644 index 0000000..a82f4c51 --- /dev/null +++ b/ui/views/animation/ink_drop.cc
@@ -0,0 +1,29 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/views/animation/ink_drop.h" + +namespace views { + +InkDropContainerView::InkDropContainerView() {} + +void InkDropContainerView::AddInkDropLayer(ui::Layer* ink_drop_layer) { + SetPaintToLayer(true); + SetVisible(true); + layer()->SetFillsBoundsOpaquely(false); + layer()->Add(ink_drop_layer); +} + +void InkDropContainerView::RemoveInkDropLayer(ui::Layer* ink_drop_layer) { + layer()->Remove(ink_drop_layer); + SetVisible(false); + SetPaintToLayer(false); +} + +bool InkDropContainerView::CanProcessEventsWithinSubtree() const { + // Ensure the container View is found as the EventTarget instead of this. + return false; +} + +} // namespace views
diff --git a/ui/views/animation/ink_drop.h b/ui/views/animation/ink_drop.h index 1de593f..0eb419e 100644 --- a/ui/views/animation/ink_drop.h +++ b/ui/views/animation/ink_drop.h
@@ -14,6 +14,7 @@ #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" #include "ui/views/animation/ink_drop_state.h" +#include "ui/views/view.h" #include "ui/views/views_export.h" namespace views { @@ -24,6 +25,9 @@ public: virtual ~InkDrop() {} + // Called by ink drop hosts when their size is changed. + virtual void HostSizeChanged(const gfx::Size& new_size) = 0; + // Gets the target state of the ink drop. virtual InkDropState GetTargetInkDropState() const = 0; @@ -49,6 +53,24 @@ DISALLOW_COPY_AND_ASSIGN(InkDrop); }; +// A View which can be used to parent ink drop layers. Typically this is used +// as a non-ancestor view to labels so that the labels can paint on an opaque +// canvas. This is used to avoid ugly text renderings when labels with subpixel +// rendering enabled are painted onto a non-opaque canvas. +class VIEWS_EXPORT InkDropContainerView : public views::View { + public: + InkDropContainerView(); + + void AddInkDropLayer(ui::Layer* ink_drop_layer); + void RemoveInkDropLayer(ui::Layer* ink_drop_layer); + + // View: + bool CanProcessEventsWithinSubtree() const override; + + private: + DISALLOW_COPY_AND_ASSIGN(InkDropContainerView); +}; + } // namespace views #endif // UI_VIEWS_ANIMATION_INK_DROP_H_
diff --git a/ui/views/animation/ink_drop_host_view.cc b/ui/views/animation/ink_drop_host_view.cc index a082ef1b..e12fc8a 100644 --- a/ui/views/animation/ink_drop_host_view.cc +++ b/ui/views/animation/ink_drop_host_view.cc
@@ -12,6 +12,7 @@ #include "ui/views/animation/ink_drop.h" #include "ui/views/animation/ink_drop_highlight.h" #include "ui/views/animation/ink_drop_impl.h" +#include "ui/views/animation/ink_drop_mask.h" #include "ui/views/animation/ink_drop_stub.h" #include "ui/views/animation/square_ink_drop_ripple.h" @@ -128,6 +129,9 @@ old_paint_to_layer_ = layer() != nullptr; SetPaintToLayer(true); layer()->SetFillsBoundsOpaquely(false); + ink_drop_mask_ = CreateInkDropMask(); + if (ink_drop_mask_) + ink_drop_layer->SetMaskLayer(ink_drop_mask_->layer()); layer()->Add(ink_drop_layer); layer()->StackAtBottom(ink_drop_layer); } @@ -139,6 +143,8 @@ if (destroying_) return; layer()->Remove(ink_drop_layer); + ink_drop_layer->SetMaskLayer(nullptr); + ink_drop_mask_.reset(); SetPaintToLayer(old_paint_to_layer_); } @@ -211,6 +217,11 @@ GetInkDrop()->AnimateToState(state); } +void InkDropHostView::OnBoundsChanged(const gfx::Rect& previous_bounds) { + if (ink_drop_) + ink_drop_->HostSizeChanged(size()); +} + void InkDropHostView::VisibilityChanged(View* starting_from, bool is_visible) { View::VisibilityChanged(starting_from, is_visible); if (GetWidget() && !is_visible) { @@ -251,6 +262,10 @@ return gfx::kPlaceholderColor; } +std::unique_ptr<views::InkDropMask> InkDropHostView::CreateInkDropMask() const { + return nullptr; +} + InkDrop* InkDropHostView::GetInkDrop() { if (!ink_drop_) { if (ink_drop_mode_ == InkDropMode::OFF) @@ -262,7 +277,8 @@ } std::unique_ptr<InkDropImpl> InkDropHostView::CreateDefaultInkDropImpl() { - std::unique_ptr<InkDropImpl> ink_drop = base::MakeUnique<InkDropImpl>(this); + std::unique_ptr<InkDropImpl> ink_drop = + base::MakeUnique<InkDropImpl>(this, size()); ink_drop->SetAutoHighlightMode( views::InkDropImpl::AutoHighlightMode::HIDE_ON_RIPPLE); return ink_drop;
diff --git a/ui/views/animation/ink_drop_host_view.h b/ui/views/animation/ink_drop_host_view.h index 3419e531..eb442da 100644 --- a/ui/views/animation/ink_drop_host_view.h +++ b/ui/views/animation/ink_drop_host_view.h
@@ -16,6 +16,7 @@ namespace views { class InkDropImpl; +class InkDropMask; namespace test { class InkDropHostViewTestApi; @@ -87,6 +88,7 @@ void AnimateInkDrop(InkDropState state, const ui::LocatedEvent* event); // View: + void OnBoundsChanged(const gfx::Rect& previous_bounds) override; void VisibilityChanged(View* starting_from, bool is_visible) override; void OnFocus() override; void OnBlur() override; @@ -96,6 +98,10 @@ // ink drop. virtual SkColor GetInkDropBaseColor() const; + // Subclasses can override to return a mask for the ink drop. By default, + // returns nullptr (i.e no mask). + virtual std::unique_ptr<views::InkDropMask> CreateInkDropMask() const; + // Provides access to |ink_drop_|. Implements lazy initialization of // |ink_drop_| so as to avoid virtual method calls during construction since // subclasses should be able to call SetInkDropMode() during construction. @@ -137,6 +143,8 @@ bool destroying_; + std::unique_ptr<views::InkDropMask> ink_drop_mask_; + DISALLOW_COPY_AND_ASSIGN(InkDropHostView); }; } // namespace views
diff --git a/ui/views/animation/ink_drop_impl.cc b/ui/views/animation/ink_drop_impl.cc index b61932f..01b3928 100644 --- a/ui/views/animation/ink_drop_impl.cc +++ b/ui/views/animation/ink_drop_impl.cc
@@ -575,7 +575,7 @@ return nullptr; } -InkDropImpl::InkDropImpl(InkDropHost* ink_drop_host) +InkDropImpl::InkDropImpl(InkDropHost* ink_drop_host, const gfx::Size& host_size) : ink_drop_host_(ink_drop_host), root_layer_(new ui::Layer(ui::LAYER_NOT_DRAWN)), root_layer_added_to_host_(false), @@ -585,6 +585,7 @@ is_focused_(false), exiting_highlight_state_(false), destroying_(false) { + root_layer_->SetBounds(gfx::Rect(host_size)); SetAutoHighlightMode(AutoHighlightMode::NONE); root_layer_->set_name("InkDropImpl:RootLayer"); } @@ -620,6 +621,13 @@ SetHighlightState(highlight_state_factory_->CreateStartState()); } +void InkDropImpl::HostSizeChanged(const gfx::Size& new_size) { + // |root_layer_| should fill the entire host because it affects the clipping + // when a mask layer is applied to it. This will not affect clipping if no + // mask layer is set. + root_layer_->SetBounds(gfx::Rect(new_size)); +} + InkDropState InkDropImpl::GetTargetInkDropState() const { if (!ink_drop_ripple_) return InkDropState::HIDDEN;
diff --git a/ui/views/animation/ink_drop_impl.h b/ui/views/animation/ink_drop_impl.h index 698e44c..961f80b 100644 --- a/ui/views/animation/ink_drop_impl.h +++ b/ui/views/animation/ink_drop_impl.h
@@ -45,11 +45,11 @@ }; // Constructs an ink drop that will attach the ink drop to the given - // |ink_drop_host|. + // |ink_drop_host|. |host_size| is used to set the size of the ink drop layer. // // By default the highlight will be made visible while |this| is hovered but // not focused and the NONE AutoHighlightMode will be used. - explicit InkDropImpl(InkDropHost* ink_drop_host); + InkDropImpl(InkDropHost* ink_drop_host, const gfx::Size& host_size); ~InkDropImpl() override; void SetShowHighlightOnHover(bool show_highlight_on_hover); @@ -66,6 +66,7 @@ void SetAutoHighlightMode(AutoHighlightMode auto_highlight_mode); // InkDrop: + void HostSizeChanged(const gfx::Size& new_size) override; InkDropState GetTargetInkDropState() const override; void AnimateToState(InkDropState ink_drop_state) override; void SnapToActivated() override;
diff --git a/ui/views/animation/ink_drop_impl_unittest.cc b/ui/views/animation/ink_drop_impl_unittest.cc index cf5801af..c0725ff9 100644 --- a/ui/views/animation/ink_drop_impl_unittest.cc +++ b/ui/views/animation/ink_drop_impl_unittest.cc
@@ -64,7 +64,8 @@ thread_task_runner_handle_( new base::ThreadTaskRunnerHandle(task_runner_)), ink_drop_host_(base::MakeUnique<TestInkDropHost>()), - ink_drop_(base::MakeUnique<InkDropImpl>(ink_drop_host_.get())), + ink_drop_( + base::MakeUnique<InkDropImpl>(ink_drop_host_.get(), gfx::Size())), test_api_(base::MakeUnique<test::InkDropImplTestApi>(ink_drop_.get())) { ink_drop_host_->set_disable_timers_for_test(true); }
diff --git a/ui/views/animation/ink_drop_mask.cc b/ui/views/animation/ink_drop_mask.cc new file mode 100644 index 0000000..3b64ac0 --- /dev/null +++ b/ui/views/animation/ink_drop_mask.cc
@@ -0,0 +1,68 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/views/animation/ink_drop_mask.h" + +#include "third_party/skia/include/core/SkPaint.h" +#include "ui/compositor/paint_recorder.h" +#include "ui/gfx/canvas.h" + +namespace views { + +// InkDropMask + +InkDropMask::InkDropMask(const gfx::Rect& layer_bounds) + : layer_(ui::LAYER_TEXTURED) { + layer_.set_delegate(this); + layer_.SetBounds(layer_bounds); + layer_.SetFillsBoundsOpaquely(false); + layer_.set_name("InkDropMaskLayer"); +} + +InkDropMask::~InkDropMask() { + layer_.set_delegate(nullptr); +} + +void InkDropMask::OnDelegatedFrameDamage(const gfx::Rect& damage_rect_in_dip) {} + +void InkDropMask::OnDeviceScaleFactorChanged(float device_scale_factor) {} + +// RoundRectInkDropMask + +RoundRectInkDropMask::RoundRectInkDropMask(const gfx::Rect& layer_bounds, + const gfx::Rect& mask_bounds, + int corner_radius) + : InkDropMask(layer_bounds), + mask_bounds_(mask_bounds), + corner_radius_(corner_radius) {} + +void RoundRectInkDropMask::OnPaintLayer(const ui::PaintContext& context) { + SkPaint paint; + paint.setAlpha(255); + paint.setStyle(SkPaint::kFill_Style); + paint.setAntiAlias(true); + + ui::PaintRecorder recorder(context, layer()->size()); + recorder.canvas()->DrawRoundRect(mask_bounds_, corner_radius_, paint); +} + +// CircleInkDropMask + +CircleInkDropMask::CircleInkDropMask(const gfx::Rect& layer_bounds, + const gfx::Point& mask_center, + int mask_radius) + : InkDropMask(layer_bounds), + mask_center_(mask_center), + mask_radius_(mask_radius) {} + +void CircleInkDropMask::OnPaintLayer(const ui::PaintContext& context) { + SkPaint paint; + paint.setAlpha(255); + paint.setStyle(SkPaint::kFill_Style); + + ui::PaintRecorder recorder(context, layer()->size()); + recorder.canvas()->DrawCircle(mask_center_, mask_radius_, paint); +} + +} // namespace views
diff --git a/ui/views/animation/ink_drop_mask.h b/ui/views/animation/ink_drop_mask.h new file mode 100644 index 0000000..2e1b91a --- /dev/null +++ b/ui/views/animation/ink_drop_mask.h
@@ -0,0 +1,75 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef UI_VIEWS_ANIMATION_INK_DROP_MASK_H_ +#define UI_VIEWS_ANIMATION_INK_DROP_MASK_H_ + +#include "base/macros.h" +#include "ui/compositor/layer.h" +#include "ui/compositor/layer_delegate.h" +#include "ui/gfx/geometry/point.h" +#include "ui/gfx/geometry/rect.h" +#include "ui/views/views_export.h" + +namespace views { + +// Base class for different ink drop masks. It is responsible for creating the +// ui::Layer that can be set as the mask layer for ink drop layer. +class VIEWS_EXPORT InkDropMask : public ui::LayerDelegate { + public: + ~InkDropMask() override; + + ui::Layer* layer() { return &layer_; } + + protected: + explicit InkDropMask(const gfx::Rect& layer_bounds); + + private: + // Overriden from ui::LayerDelegate: + void OnDelegatedFrameDamage(const gfx::Rect& damage_rect_in_dip) override; + + void OnDeviceScaleFactorChanged(float device_scale_factor) override; + + ui::Layer layer_; + + DISALLOW_COPY_AND_ASSIGN(InkDropMask); +}; + +// A rectangular ink drop mask with rounded corners. +class VIEWS_EXPORT RoundRectInkDropMask : public InkDropMask { + public: + RoundRectInkDropMask(const gfx::Rect& layer_bounds, + const gfx::Rect& mask_bounds, + int corner_radius); + + private: + // Overriden from InkDropMask: + void OnPaintLayer(const ui::PaintContext& context) override; + + gfx::Rect mask_bounds_; + int corner_radius_; + + DISALLOW_COPY_AND_ASSIGN(RoundRectInkDropMask); +}; + +// A circular ink drop mask. +class VIEWS_EXPORT CircleInkDropMask : public InkDropMask { + public: + CircleInkDropMask(const gfx::Rect& layer_bounds, + const gfx::Point& mask_center, + int mask_radius); + + private: + // Overriden from InkDropMask: + void OnPaintLayer(const ui::PaintContext& context) override; + + gfx::Point mask_center_; + int mask_radius_; + + DISALLOW_COPY_AND_ASSIGN(CircleInkDropMask); +}; + +} // namespace views + +#endif // UI_VIEWS_ANIMATION_INK_DROP_MASK_H_
diff --git a/ui/views/animation/ink_drop_stub.cc b/ui/views/animation/ink_drop_stub.cc index 300c72a..734173f4 100644 --- a/ui/views/animation/ink_drop_stub.cc +++ b/ui/views/animation/ink_drop_stub.cc
@@ -10,6 +10,8 @@ InkDropStub::~InkDropStub() {} +void InkDropStub::HostSizeChanged(const gfx::Size& new_size) {} + InkDropState InkDropStub::GetTargetInkDropState() const { return InkDropState::HIDDEN; }
diff --git a/ui/views/animation/ink_drop_stub.h b/ui/views/animation/ink_drop_stub.h index 00fb490..63a422679 100644 --- a/ui/views/animation/ink_drop_stub.h +++ b/ui/views/animation/ink_drop_stub.h
@@ -16,6 +16,7 @@ ~InkDropStub() override; // InkDrop: + void HostSizeChanged(const gfx::Size& new_size) override; InkDropState GetTargetInkDropState() const override; void AnimateToState(InkDropState state) override; void SnapToActivated() override;
diff --git a/ui/views/animation/ink_drop_unittest.cc b/ui/views/animation/ink_drop_unittest.cc index 4866bc5..4cee71e 100644 --- a/ui/views/animation/ink_drop_unittest.cc +++ b/ui/views/animation/ink_drop_unittest.cc
@@ -57,7 +57,7 @@ ink_drop_.reset(new InkDropStub()); break; case INK_DROP_IMPL: - ink_drop_.reset(new InkDropImpl(&test_ink_drop_host_)); + ink_drop_.reset(new InkDropImpl(&test_ink_drop_host_, gfx::Size())); // The Timer's used by the InkDropImpl class require a // base::ThreadTaskRunnerHandle instance. scoped_refptr<base::TestMockTimeTaskRunner> task_runner(
diff --git a/ui/views/animation/test/test_ink_drop.cc b/ui/views/animation/test/test_ink_drop.cc index 523c9ad6..061cb7e 100644 --- a/ui/views/animation/test/test_ink_drop.cc +++ b/ui/views/animation/test/test_ink_drop.cc
@@ -10,6 +10,8 @@ TestInkDrop::TestInkDrop() : state_(InkDropState::HIDDEN), is_hovered_(false) {} TestInkDrop::~TestInkDrop() {} +void TestInkDrop::HostSizeChanged(const gfx::Size& new_size) {} + InkDropState TestInkDrop::GetTargetInkDropState() const { return state_; }
diff --git a/ui/views/animation/test/test_ink_drop.h b/ui/views/animation/test/test_ink_drop.h index c34b79b..a9440e85 100644 --- a/ui/views/animation/test/test_ink_drop.h +++ b/ui/views/animation/test/test_ink_drop.h
@@ -21,6 +21,7 @@ bool is_hovered() const { return is_hovered_; } + void HostSizeChanged(const gfx::Size& new_size) override; InkDropState GetTargetInkDropState() const override; void AnimateToState(InkDropState ink_drop_state) override; void SnapToActivated() override;
diff --git a/ui/views/controls/button/custom_button_unittest.cc b/ui/views/controls/button/custom_button_unittest.cc index 6532653..889bc7be 100644 --- a/ui/views/controls/button/custom_button_unittest.cc +++ b/ui/views/controls/button/custom_button_unittest.cc
@@ -147,7 +147,7 @@ delete button_; button_ = new TestCustomButton(false); InkDropHostViewTestApi(button_).SetInkDrop( - base::MakeUnique<InkDropImpl>(button_)); + base::MakeUnique<InkDropImpl>(button_, button_->size())); widget_->SetContentsView(button_); }
diff --git a/ui/views/controls/button/label_button.cc b/ui/views/controls/button/label_button.cc index 52457b7..9c47167 100644 --- a/ui/views/controls/button/label_button.cc +++ b/ui/views/controls/button/label_button.cc
@@ -19,6 +19,7 @@ #include "ui/gfx/geometry/vector2d.h" #include "ui/native_theme/native_theme.h" #include "ui/views/animation/flood_fill_ink_drop_ripple.h" +#include "ui/views/animation/ink_drop.h" #include "ui/views/animation/ink_drop_highlight.h" #include "ui/views/animation/ink_drop_impl.h" #include "ui/views/animation/square_ink_drop_ripple.h" @@ -71,21 +72,6 @@ return font_list.Get(); } -// Ink drop container view that does not capture any events. -class InkDropContainerView : public views::View { - public: - InkDropContainerView() {} - - // View: - bool CanProcessEventsWithinSubtree() const override { - // Ensure the container View is found as the EventTarget instead of this. - return false; - } - - private: - DISALLOW_COPY_AND_ASSIGN(InkDropContainerView); -}; - } // namespace namespace views { @@ -438,14 +424,12 @@ void LabelButton::AddInkDropLayer(ui::Layer* ink_drop_layer) { image()->SetPaintToLayer(true); image()->layer()->SetFillsBoundsOpaquely(false); - ink_drop_container_->SetVisible(true); - ink_drop_container_->layer()->Add(ink_drop_layer); + ink_drop_container_->AddInkDropLayer(ink_drop_layer); } void LabelButton::RemoveInkDropLayer(ui::Layer* ink_drop_layer) { image()->SetPaintToLayer(false); - ink_drop_container_->layer()->Remove(ink_drop_layer); - ink_drop_container_->SetVisible(false); + ink_drop_container_->RemoveInkDropLayer(ink_drop_layer); } std::unique_ptr<InkDrop> LabelButton::CreateInkDrop() {
diff --git a/ui/views/controls/button/label_button.h b/ui/views/controls/button/label_button.h index 7baf940d2..a78ccb0 100644 --- a/ui/views/controls/button/label_button.h +++ b/ui/views/controls/button/label_button.h
@@ -19,6 +19,7 @@ namespace views { +class InkDropContainerView; class LabelButtonBorder; class Painter; @@ -191,7 +192,7 @@ // A separate view is necessary to hold the ink drop layer so that it can // be stacked below |image_| and on top of |label_|, without resorting to // drawing |label_| on a layer (which can mess with subpixel anti-aliasing). - View* ink_drop_container_; + InkDropContainerView* ink_drop_container_; // The cached font lists in the normal and bold style. gfx::FontList cached_normal_font_list_;
diff --git a/ui/views/layout/fill_layout.cc b/ui/views/layout/fill_layout.cc index 2137546..731504e2 100644 --- a/ui/views/layout/fill_layout.cc +++ b/ui/views/layout/fill_layout.cc
@@ -4,7 +4,7 @@ #include "ui/views/layout/fill_layout.h" -#include "base/logging.h" +#include <algorithm> namespace views { @@ -16,15 +16,18 @@ if (!host->has_children()) return; - View* frame_view = host->child_at(0); - frame_view->SetBoundsRect(host->GetContentsBounds()); + for (int i = 0; i < host->child_count(); ++i) + host->child_at(i)->SetBoundsRect(host->GetContentsBounds()); } gfx::Size FillLayout::GetPreferredSize(const View* host) const { if (!host->has_children()) return gfx::Size(); - DCHECK_EQ(1, host->child_count()); - gfx::Rect rect(host->child_at(0)->GetPreferredSize()); + + gfx::Size preferred_size; + for (int i = 0; i < host->child_count(); ++i) + preferred_size.SetToMax(host->child_at(i)->GetPreferredSize()); + gfx::Rect rect(preferred_size); rect.Inset(-host->GetInsets()); return rect.size(); } @@ -32,10 +35,17 @@ int FillLayout::GetPreferredHeightForWidth(const View* host, int width) const { if (!host->has_children()) return 0; - DCHECK_EQ(1, host->child_count()); + const gfx::Insets insets = host->GetInsets(); - return host->child_at(0)->GetHeightForWidth(width - insets.width()) + - insets.height(); + int preferred_height = 0; + for (int i = 0; i < host->child_count(); ++i) { + int cur_preferred_height = 0; + cur_preferred_height = + host->child_at(i)->GetHeightForWidth(width - insets.width()) + + insets.height(); + preferred_height = std::max(preferred_height, cur_preferred_height); + } + return preferred_height; } } // namespace views
diff --git a/ui/views/layout/fill_layout.h b/ui/views/layout/fill_layout.h index 11a56838..b248139 100644 --- a/ui/views/layout/fill_layout.h +++ b/ui/views/layout/fill_layout.h
@@ -15,8 +15,9 @@ /////////////////////////////////////////////////////////////////////////////// // // FillLayout -// A simple LayoutManager that causes the associated view's one child to be -// sized to match the bounds of its parent. +// A simple LayoutManager that causes the associated view's children to be +// sized to match the bounds of its parent. The preferred size/height is +// is calculated as the maximum values across all child views of the host. // /////////////////////////////////////////////////////////////////////////////// class VIEWS_EXPORT FillLayout : public LayoutManager {
diff --git a/ui/views/layout/fill_layout_unittest.cc b/ui/views/layout/fill_layout_unittest.cc new file mode 100644 index 0000000..93a6681 --- /dev/null +++ b/ui/views/layout/fill_layout_unittest.cc
@@ -0,0 +1,189 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/views/layout/fill_layout.h" + +#include "testing/gtest/include/gtest/gtest.h" +#include "ui/views/border.h" +#include "ui/views/test/test_views.h" +#include "ui/views/view.h" + +namespace views { + +namespace { + +class FillLayoutTest : public testing::Test { + public: + static const int kDefaultHostWidth = 100; + static const int kDefaultHostHeight = 200; + + FillLayoutTest() : layout_(new FillLayout), host_(new View) { + host_->SetLayoutManager(layout_); + SetHostSize(kDefaultHostWidth, kDefaultHostHeight); + } + + protected: + // Convenience function to get the preferred size from |layout_|. + gfx::Size GetPreferredSize() const { + return layout_->GetPreferredSize(host_.get()); + } + + // Convenience function to get the preferred height for width from |layout_|. + int GetPreferredHeightForWidth(int width) const { + return layout_->GetPreferredHeightForWidth(host_.get(), width); + } + + // Creates a View with the given |width| and |height| and adds it to |host_|. + View* AddChildView(int width, int height) { + View* child_view = new StaticSizedView(gfx::Size(width, height)); + host_->AddChildView(child_view); + return child_view; + } + + void SetHostSize(int width, int height) { + host_->SetSize(gfx::Size(width, height)); + } + + void SetHostInsets(int top, int left, int bottom, int right) { + host_->SetBorder(CreateEmptyBorder(gfx::Insets(top, left, bottom, right))); + } + + // The test target. + FillLayout* layout_; + + std::unique_ptr<View> host_; + + private: + DISALLOW_COPY_AND_ASSIGN(FillLayoutTest); +}; + +} // namespace + +TEST_F(FillLayoutTest, GetPreferredSizeWithNoChildren) { + EXPECT_EQ(gfx::Size(0, 0), GetPreferredSize()); + + SetHostSize(0, 0); + EXPECT_EQ(gfx::Size(0, 0), GetPreferredSize()); +} + +TEST_F(FillLayoutTest, GetPreferredSizeWithOneChild) { + AddChildView(25, 50); + EXPECT_EQ(gfx::Size(25, 50), GetPreferredSize()); +} + +TEST_F(FillLayoutTest, GetPreferredSizeWithInsets) { + const int kChildWidth = 25; + const int kChildHeight = 50; + const int kTopInset = 2; + const int kLeftInset = 3; + const int kBottomInset = 8; + const int kRightInset = 7; + + AddChildView(kChildWidth, kChildHeight); + SetHostInsets(kTopInset, kLeftInset, kBottomInset, kRightInset); + + EXPECT_EQ(gfx::Size(kChildWidth + kLeftInset + kRightInset, + kChildHeight + kTopInset + kBottomInset), + GetPreferredSize()); +} + +TEST_F(FillLayoutTest, GetPreferredSizeWithMultipleChildren) { + AddChildView(10, 50); + AddChildView(5, 5); + AddChildView(25, 10); + + EXPECT_EQ(gfx::Size(25, 50), GetPreferredSize()); +} + +TEST_F(FillLayoutTest, GetPreferredHeightForWidthWithNoChildren) { + EXPECT_EQ(0, GetPreferredHeightForWidth(0)); + EXPECT_EQ(0, GetPreferredHeightForWidth(100)); + + SetHostSize(0, 0); + EXPECT_EQ(0, GetPreferredHeightForWidth(0)); + EXPECT_EQ(0, GetPreferredHeightForWidth(100)); +} + +TEST_F(FillLayoutTest, GetPreferredHeightForWidthWithOneChild) { + AddChildView(25, 50); + + EXPECT_EQ(50, GetPreferredHeightForWidth(0)); + EXPECT_EQ(50, GetPreferredHeightForWidth(25)); + EXPECT_EQ(50, GetPreferredHeightForWidth(100)); +} + +TEST_F(FillLayoutTest, GetPreferredHeightForWidthWithInsets) { + const int kChildWidth = 25; + const int kChildHeight = 50; + const int kTopInset = 2; + const int kLeftInset = 3; + const int kBottomInset = 8; + const int kRightInset = 7; + + const int kExpectedHeight = kChildHeight + kTopInset + kBottomInset; + + AddChildView(kChildWidth, kChildHeight); + SetHostInsets(kTopInset, kLeftInset, kBottomInset, kRightInset); + + EXPECT_EQ(kExpectedHeight, GetPreferredHeightForWidth(0)); + EXPECT_EQ(kExpectedHeight, GetPreferredHeightForWidth(25)); + EXPECT_EQ(kExpectedHeight, GetPreferredHeightForWidth(100)); +} + +TEST_F(FillLayoutTest, GetPreferredHeightForWidthWithMultipleChildren) { + AddChildView(10, 50); + AddChildView(5, 5); + AddChildView(25, 10); + + EXPECT_EQ(50, GetPreferredHeightForWidth(0)); + EXPECT_EQ(50, GetPreferredHeightForWidth(25)); + EXPECT_EQ(50, GetPreferredHeightForWidth(100)); +} + +TEST_F(FillLayoutTest, LayoutWithNoChildren) { + host_->Layout(); + // Makes sure there is no crash. +} + +TEST_F(FillLayoutTest, LayoutWithOneChild) { + View* child = AddChildView(25, 50); + host_->Layout(); + + EXPECT_EQ(gfx::Rect(0, 0, kDefaultHostWidth, kDefaultHostHeight), + child->bounds()); +} + +TEST_F(FillLayoutTest, LayoutWithInsets) { + const int kChildWidth = 25; + const int kChildHeight = 50; + const int kTopInset = 2; + const int kLeftInset = 3; + const int kBottomInset = 8; + const int kRightInset = 7; + + View* child = AddChildView(kChildWidth, kChildHeight); + SetHostInsets(kTopInset, kLeftInset, kBottomInset, kRightInset); + host_->Layout(); + + EXPECT_EQ(gfx::Rect(kLeftInset, kTopInset, + kDefaultHostWidth - kLeftInset - kRightInset, + kDefaultHostHeight - kTopInset - kBottomInset), + child->bounds()); +} + +TEST_F(FillLayoutTest, LayoutMultipleChildren) { + View* child_1 = AddChildView(10, 50); + View* child_2 = AddChildView(5, 5); + View* child_3 = AddChildView(25, 10); + + const gfx::Rect kExpectedBounds(0, 0, kDefaultHostWidth, kDefaultHostHeight); + + host_->Layout(); + + EXPECT_EQ(kExpectedBounds, child_1->bounds()); + EXPECT_EQ(kExpectedBounds, child_2->bounds()); + EXPECT_EQ(kExpectedBounds, child_3->bounds()); +} + +} // namespace views
diff --git a/ui/views/widget/native_widget_mac_accessibility_unittest.mm b/ui/views/widget/native_widget_mac_accessibility_unittest.mm index f87d0dbf..3d641d19 100644 --- a/ui/views/widget/native_widget_mac_accessibility_unittest.mm +++ b/ui/views/widget/native_widget_mac_accessibility_unittest.mm
@@ -304,11 +304,42 @@ NSAccessibilityVisibleCharacterRangeAttribute) rangeValue])); } -// Test writing accessibility attributes via an accessibility client. +// Test writing accessibility attributes via an accessibility client for normal +// Views. +TEST_F(NativeWidgetMacAccessibilityTest, ViewWritableAttributes) { + FlexibleRoleTestView* view = new FlexibleRoleTestView(ui::AX_ROLE_GROUP); + view->SetSize(GetWidgetBounds().size()); + widget()->GetContentsView()->AddChildView(view); + + // Get the FlexibleRoleTestView accessibility object. + NSPoint midpoint = gfx::ScreenPointToNSPoint(GetWidgetBounds().CenterPoint()); + id ax_node = [widget()->GetNativeWindow() accessibilityHitTest:midpoint]; + EXPECT_TRUE(ax_node); + + // Make sure it's the correct accessibility object. + id value = [ax_node accessibilityAttributeValue:NSAccessibilityRoleAttribute]; + EXPECT_NSEQ(NSAccessibilityGroupRole, value); + + // Make sure |view| is focusable, then focus/unfocus it. + view->SetFocusBehavior(View::FocusBehavior::ALWAYS); + EXPECT_FALSE(view->HasFocus()); + EXPECT_FALSE( + [AttributeValueAtMidpoint(NSAccessibilityFocusedAttribute) boolValue]); + EXPECT_TRUE([ax_node + accessibilityIsAttributeSettable:NSAccessibilityFocusedAttribute]); + [ax_node accessibilitySetValue:[NSNumber numberWithBool:YES] + forAttribute:NSAccessibilityFocusedAttribute]; + EXPECT_TRUE( + [AttributeValueAtMidpoint(NSAccessibilityFocusedAttribute) boolValue]); + EXPECT_TRUE(view->HasFocus()); +} + +// Test writing accessibility attributes via an accessibility client for +// editable controls (in this case, views::Textfields). TEST_F(NativeWidgetMacAccessibilityTest, TextfieldWritableAttributes) { Textfield* textfield = AddChildTextfield(GetWidgetBounds().size()); - // Get the textfield accessibility object. + // Get the Textfield accessibility object. NSPoint midpoint = gfx::ScreenPointToNSPoint(GetWidgetBounds().CenterPoint()); id ax_node = [widget()->GetNativeWindow() accessibilityHitTest:midpoint]; EXPECT_TRUE(ax_node);
diff --git a/ui/views/win/hwnd_message_handler.cc b/ui/views/win/hwnd_message_handler.cc index 020d0a1..6f80d3e 100644 --- a/ui/views/win/hwnd_message_handler.cc +++ b/ui/views/win/hwnd_message_handler.cc
@@ -2227,12 +2227,47 @@ } } else if (!GetParent(hwnd())) { RECT window_rect; + const bool have_new_window_rect = + !(window_pos->flags & SWP_NOMOVE) && !(window_pos->flags & SWP_NOSIZE); + if (have_new_window_rect) { + // We should use new window rect for detecting monitor and it's + // parameters, if it is available. If we use |GetWindowRect()| instead, + // we can break our same monitor detection logic (see |same_monitor| + // below) and consequently Windows "Move to other monitor" shortcuts + // (Win+Shift+Arrows). See crbug.com/656001. + window_rect.left = window_pos->x; + window_rect.top = window_pos->y; + window_rect.right = window_pos->x + window_pos->cx - 1; + window_rect.bottom = window_pos->y + window_pos->cy - 1; + } + HMONITOR monitor; gfx::Rect monitor_rect, work_area; - if (GetWindowRect(hwnd(), &window_rect) && + if ((have_new_window_rect || GetWindowRect(hwnd(), &window_rect)) && GetMonitorAndRects(window_rect, &monitor, &monitor_rect, &work_area)) { bool work_area_changed = (monitor_rect == last_monitor_rect_) && (work_area != last_work_area_); + const bool same_monitor = monitor && (monitor == last_monitor_); + + gfx::Rect expected_maximized_bounds = work_area; + if (IsMaximized()) { + // Windows automatically adds a standard width border to all sides when + // window is maximized. We should take this into account. + gfx::Insets client_area_insets; + if (GetClientAreaInsets(&client_area_insets)) + expected_maximized_bounds.Inset(client_area_insets.Scale(-1)); + } + // Sometimes Windows incorrectly changes bounds of maximized windows after + // attaching or detaching additional displays. In this case user can see + // non-client area of the window (that should be hidden in normal case). + // We should restore window position if problem occurs. + const bool incorrect_maximized_bounds = + IsMaximized() && have_new_window_rect && + (expected_maximized_bounds.x() != window_pos->x || + expected_maximized_bounds.y() != window_pos->y || + expected_maximized_bounds.width() != window_pos->cx || + expected_maximized_bounds.height() != window_pos->cy); + // If the size of a background fullscreen window changes again, then we // should reset the |background_fullscreen_hack_| flag. if (background_fullscreen_hack_ && @@ -2240,8 +2275,11 @@ (monitor_rect.height() - window_pos->cy != 1))) { background_fullscreen_hack_ = false; } - if (monitor && (monitor == last_monitor_) && - ((IsFullscreen() && !background_fullscreen_hack_) || + const bool fullscreen_without_hack = + IsFullscreen() && !background_fullscreen_hack_; + + if (same_monitor && + (incorrect_maximized_bounds || fullscreen_without_hack || work_area_changed)) { // A rect for the monitor we're on changed. Normally Windows notifies // us about this (and thus we're reaching here due to the SetWindowPos() @@ -2255,9 +2293,7 @@ if (IsFullscreen()) { new_window_rect = monitor_rect; } else if (IsMaximized()) { - new_window_rect = work_area; - int border_thickness = GetSystemMetrics(SM_CXSIZEFRAME); - new_window_rect.Inset(-border_thickness, -border_thickness); + new_window_rect = expected_maximized_bounds; } else { new_window_rect = gfx::Rect(window_rect); new_window_rect.AdjustToFit(work_area);
diff --git a/ui/web_dialogs/DEPS b/ui/web_dialogs/DEPS index fb76c16..0c30349 100644 --- a/ui/web_dialogs/DEPS +++ b/ui/web_dialogs/DEPS
@@ -1,6 +1,7 @@ include_rules = [ "+content/public", - "+third_party/WebKit/public/web/WebInputEvent.h", + "+third_party/WebKit/public/platform/WebGestureEvent.h", + "+third_party/WebKit/public/platform/WebInputEvent.h", "+ui/base", "+ui/gfx", ]
diff --git a/ui/web_dialogs/web_dialog_web_contents_delegate.cc b/ui/web_dialogs/web_dialog_web_contents_delegate.cc index 0493e415..36baa4c8 100644 --- a/ui/web_dialogs/web_dialog_web_contents_delegate.cc +++ b/ui/web_dialogs/web_dialog_web_contents_delegate.cc
@@ -6,7 +6,7 @@ #include "base/logging.h" #include "content/public/browser/web_contents.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/platform/WebGestureEvent.h" using content::BrowserContext; using content::OpenURLParams;
diff --git a/ui/webui/resources/cr_elements/cr_dialog/cr_dialog.html b/ui/webui/resources/cr_elements/cr_dialog/cr_dialog.html index fffe3dd..9b8b675 100644 --- a/ui/webui/resources/cr_elements/cr_dialog/cr_dialog.html +++ b/ui/webui/resources/cr_elements/cr_dialog/cr_dialog.html
@@ -92,7 +92,8 @@ </style> <div class="title-container"> <content select=".title"></content> - <paper-icon-button icon="cr:clear" on-tap="cancel" id="close"> + <paper-icon-button icon="cr:clear" on-tap="cancel" id="close" + aria-label$="[[closeText]]"> </paper-icon-button> </div> <div class="body-container">
diff --git a/ui/webui/resources/cr_elements/cr_dialog/cr_dialog.js b/ui/webui/resources/cr_elements/cr_dialog/cr_dialog.js index 3f906ef..d15ed9b 100644 --- a/ui/webui/resources/cr_elements/cr_dialog/cr_dialog.js +++ b/ui/webui/resources/cr_elements/cr_dialog/cr_dialog.js
@@ -17,6 +17,11 @@ properties: { /** + * Alt-text for the dialog close button. + */ + closeText: String, + + /** * True if the dialog should remain open on 'popstate' events. This is used * for navigable dialogs that have their separate navigation handling code. */