diff --git a/BUILD.gn b/BUILD.gn index 8a6bb8d..36cd8ac 100644 --- a/BUILD.gn +++ b/BUILD.gn
@@ -276,7 +276,6 @@ "//ui/message_center:test_support", ] deps -= [ - "//chrome/test:unit_tests", # TODO(GYP) "//net:net_perftests", "//url:url_unittests", ]
diff --git a/DEPS b/DEPS index 3973fb1..b122956 100644 --- a/DEPS +++ b/DEPS
@@ -39,11 +39,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': 'c2e2977014c4581aed5da435fc2b7eba38e777b6', + 'skia_revision': '2d9c59fa8caefa48d46c8c9f880e54a7a6ad3945', # 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': 'b8500e4dc91d04675e9a044317576359290dff2b', + 'v8_revision': '9f1869d3eac26e7a9594471c255f3348a0d45e37', # 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. @@ -55,7 +55,7 @@ # 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. - 'buildtools_revision': 'acafdaa4e81adae617177d57e3c1261cc3565469', + 'buildtools_revision': 'c2f259809d5ede3275df5ea0842f0431990c4f98', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. @@ -187,7 +187,7 @@ Var('chromium_git') + '/external/selenium/py.git' + '@' + '5fd78261a75fe08d27ca4835fb6c5ce4b42275bd', 'src/third_party/libvpx_new/source/libvpx': - Var('chromium_git') + '/webm/libvpx.git' + '@' + 'dc9d36c0a6c749616d5543aa208864d7b0181fea', + Var('chromium_git') + '/webm/libvpx.git' + '@' + '9645cd4826de5a469e163838b997fccfd7907b91', 'src/third_party/ffmpeg': Var('chromium_git') + '/chromium/third_party/ffmpeg.git' + '@' + 'd2733b2c43f65f0e779d5d014777fb8ea1e89873', @@ -226,7 +226,7 @@ Var('chromium_git') + '/external/github.com/open-source-parsers/jsoncpp.git' + '@' + 'f572e8e42e22cfcf5ab0aea26574f408943edfa4', # from svn 248 'src/third_party/libyuv': - Var('chromium_git') + '/libyuv/libyuv.git' + '@' + '2844662e1c9733c2a064b740c27accbd49e1f755', # from version 1523 + Var('chromium_git') + '/libyuv/libyuv.git' + '@' + '5d97b9336922eaee34c342a00c8e370933938703', # from version 1527 'src/third_party/smhasher/src': Var('chromium_git') + '/external/smhasher.git' + '@' + 'e87738e57558e0ec472b2fc3a643b838e5b6e88f',
diff --git a/android_webview/android_webview.gyp b/android_webview/android_webview.gyp index 542b0e90..de442b5 100644 --- a/android_webview/android_webview.gyp +++ b/android_webview/android_webview.gyp
@@ -126,6 +126,24 @@ '<@(_outputs)', ], }, + { + 'action_name': 'generate_webview_license_notice', + 'inputs': [ + '<!@(python <(DEPTH)/android_webview/tools/webview_licenses.py notice_deps)', + '<(DEPTH)/android_webview/tools/licenses_notice.tmpl', + '<(DEPTH)/android_webview/tools/webview_licenses.py', + ], + 'outputs': [ + '<(webview_licenses_path)', + ], + 'action': [ + 'python', + '<(DEPTH)/android_webview/tools/webview_licenses.py', + 'notice', + '<(webview_licenses_path)', + ], + 'message': 'Generating WebView license notice', + }, ], }, # GN version: //android_webview/locale_paks
diff --git a/android_webview/apk/java/proguard.flags b/android_webview/apk/java/proguard.flags index 4e571c4..ddca320f 100644 --- a/android_webview/apk/java/proguard.flags +++ b/android_webview/apk/java/proguard.flags
@@ -103,8 +103,3 @@ public static **[] values(); public static ** valueOf(java.lang.String); } - -# Remove when ViewStructure is no longer duplicated (crbug.com/513229) --dontwarn android.view.* --dontwarn android.app.assist.* --dontwarn android.webkit.*
diff --git a/android_webview/apk/system_webview_apk_common.gypi b/android_webview/apk/system_webview_apk_common.gypi index f18211f9..b396652 100644 --- a/android_webview/apk/system_webview_apk_common.gypi +++ b/android_webview/apk/system_webview_apk_common.gypi
@@ -46,7 +46,8 @@ { 'destination': '<(asset_location)', 'files': [ - '<(PRODUCT_DIR)/android_webview_assets/webviewchromium.pak', + '<(webview_licenses_path)', + '<(webview_chromium_pak_path)', '<@(snapshot_copy_files)', ], 'conditions': [ @@ -58,27 +59,8 @@ ], }, ], - 'actions': [ - { - 'action_name': 'generate_webview_license_notice', - 'inputs': [ - '<!@(python <(DEPTH)/android_webview/tools/webview_licenses.py notice_deps)', - '<(DEPTH)/android_webview/tools/licenses_notice.tmpl', - '<(DEPTH)/android_webview/tools/webview_licenses.py', - ], - 'outputs': [ - '<(asset_location)/webview_licenses.notice', - ], - 'action': [ - 'python', - '<(DEPTH)/android_webview/tools/webview_licenses.py', - 'notice', - '<(asset_location)/webview_licenses.notice', - ], - 'message': 'Generating WebView license notice', - }, - ], 'includes': [ + 'system_webview_paks.gypi', '../../build/java_apk.gypi', '../../build/android/jinja_template.gypi', ],
diff --git a/android_webview/apk/system_webview_paks.gypi b/android_webview/apk/system_webview_paks.gypi index 1320f451..931c5af 100644 --- a/android_webview/apk/system_webview_paks.gypi +++ b/android_webview/apk/system_webview_paks.gypi
@@ -9,6 +9,7 @@ # once Chrome includes all the locales that the WebView needs. { 'variables': { + 'webview_licenses_path': '<(PRODUCT_DIR)/android_webview_assets/webview_licenses.notice', 'webview_chromium_pak_path': '<(PRODUCT_DIR)/android_webview_assets/webviewchromium.pak', 'webview_locales_input_paks_folder': '<(PRODUCT_DIR)/android_webview_assets/locales/', # The list of locale are only supported by WebView.
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index 8aaa1c0..6f5e693 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -27,7 +27,6 @@ "//base/third_party/dynamic_annotations", "//cc", "//components/device_event_log", - "//components/signin/core/account_id", "//components/user_manager", "//components/wallpaper", "//content/public/browser",
diff --git a/ash/DEPS b/ash/DEPS index 0e0ff3d..8952c301 100644 --- a/ash/DEPS +++ b/ash/DEPS
@@ -2,7 +2,6 @@ "+device/bluetooth", "+cc/debug", "+chromeos", - "+components/signin/core/account_id", "+components/user_manager", "+components/wallpaper", "+gpu/config",
diff --git a/ash/ash.gyp b/ash/ash.gyp index a775584..20960ee 100644 --- a/ash/ash.gyp +++ b/ash/ash.gyp
@@ -949,7 +949,6 @@ '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../cc/cc.gyp:cc', '../components/components.gyp:device_event_log_component', - '../components/components.gyp:signin_core_account_id', '../components/components.gyp:user_manager', '../components/components.gyp:wallpaper', '../content/content.gyp:content_browser', @@ -1146,7 +1145,6 @@ '../base/base.gyp:base', '../base/base.gyp:test_support_base', '../chrome/chrome_resources.gyp:packed_resources', - '../components/components.gyp:signin_core_account_id', '../components/components.gyp:user_manager', '../content/content.gyp:content_browser', '../content/content_shell_and_tests.gyp:test_support_content',
diff --git a/ash/display/display_color_manager_chromeos.cc b/ash/display/display_color_manager_chromeos.cc index 1ee0a51..1ae844f 100644 --- a/ash/display/display_color_manager_chromeos.cc +++ b/ash/display/display_color_manager_chromeos.cc
@@ -44,6 +44,7 @@ qcms_profile_get_vcgt_channel_length(display_profile); if (!vcgt_channel_length) { LOG(WARNING) << "No vcgt table in ICC file: " << path.value(); + qcms_profile_release(display_profile); return false; }
diff --git a/ash/frame/default_header_painter.cc b/ash/frame/default_header_painter.cc index ab9dd18..62a8465 100644 --- a/ash/frame/default_header_painter.cc +++ b/ash/frame/default_header_painter.cc
@@ -18,6 +18,7 @@ #include "ui/gfx/font_list.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/image/image.h" +#include "ui/gfx/scoped_canvas.h" #include "ui/gfx/skia_util.h" #include "ui/views/view.h" #include "ui/views/widget/native_widget_aura.h" @@ -262,13 +263,13 @@ } void DefaultHeaderPainter::PaintHeaderContentSeparator(gfx::Canvas* canvas) { - const float scale = canvas->SaveAndUnscale(); + gfx::ScopedCanvas scoped_canvas(canvas); + const float scale = canvas->UndoDeviceScaleFactor(); gfx::RectF rect(0, painted_height_ * scale - 1, view_->width() * scale, 1); SkPaint paint; paint.setColor((mode_ == MODE_ACTIVE) ? kHeaderContentSeparatorColor : kHeaderContentSeparatorInactiveColor); canvas->sk_canvas()->drawRect(gfx::RectFToSkRect(rect), paint); - canvas->Restore(); } void DefaultHeaderPainter::LayoutLeftHeaderView() {
diff --git a/ash/system/DEPS b/ash/system/DEPS index 1121c69..abf5b5f 100644 --- a/ash/system/DEPS +++ b/ash/system/DEPS
@@ -1,4 +1,3 @@ include_rules = [ "-chromeos", - "+components/signin/core/account_id", ]
diff --git a/ash/system/user/tray_user.cc b/ash/system/user/tray_user.cc index 06d1823..fd101e7 100644 --- a/ash/system/user/tray_user.cc +++ b/ash/system/user/tray_user.cc
@@ -20,7 +20,6 @@ #include "ash/system/user/user_view.h" #include "base/logging.h" #include "base/strings/string16.h" -#include "components/signin/core/account_id/account_id.h" #include "components/user_manager/user_info.h" #include "grit/ash_strings.h" #include "ui/aura/window.h" @@ -113,13 +112,13 @@ } views::View* TrayUser::CreateDetailedView(user::LoginStatus status) { - const AccountId account_id = Shell::GetInstance() - ->session_state_delegate() - ->GetUserInfo(0) - ->GetAccountId(); + std::string user_id = Shell::GetInstance() + ->session_state_delegate() + ->GetUserInfo(0) + ->GetUserID(); tray::UserAccountsDelegate* delegate = Shell::GetInstance()->system_tray_delegate()->GetUserAccountsDelegate( - account_id.GetUserEmail()); + user_id); if (!delegate) return nullptr; return new tray::AccountsDetailedView(this, status, delegate);
diff --git a/ash/system/user/tray_user_unittest.cc b/ash/system/user/tray_user_unittest.cc index ee1a92a..5d9d3d3 100644 --- a/ash/system/user/tray_user_unittest.cc +++ b/ash/system/user/tray_user_unittest.cc
@@ -17,7 +17,6 @@ #include "ash/test/test_session_state_delegate.h" #include "ash/test/test_shell_delegate.h" #include "base/strings/utf_string_conversions.h" -#include "components/signin/core/account_id/account_id.h" #include "components/user_manager/user_info.h" #include "ui/accessibility/ax_view_state.h" #include "ui/events/test/event_generator.h" @@ -273,11 +272,10 @@ ClickUserItem(&generator, 1); const user_manager::UserInfo* active_user = delegate()->GetActiveUserInfo(); const user_manager::UserInfo* second_user = delegate()->GetUserInfo(1); - EXPECT_EQ(active_user->GetAccountId(), second_user->GetAccountId()); + EXPECT_EQ(active_user->GetUserID(), second_user->GetUserID()); // Since the name is capitalized, the email should be different then the // user_id. - EXPECT_NE(active_user->GetAccountId().GetUserEmail(), - second_user->GetEmail()); + EXPECT_NE(active_user->GetUserID(), second_user->GetEmail()); tray()->CloseSystemBubble(); }
diff --git a/ash/system/user/user_view.cc b/ash/system/user/user_view.cc index 0c48ca99..7f7ece5 100644 --- a/ash/system/user/user_view.cc +++ b/ash/system/user/user_view.cc
@@ -19,7 +19,6 @@ #include "ash/system/user/config.h" #include "ash/system/user/rounded_image_view.h" #include "ash/system/user/user_card_view.h" -#include "components/signin/core/account_id/account_id.h" #include "components/user_manager/user_info.h" #include "grit/ash_resources.h" #include "grit/ash_strings.h" @@ -78,8 +77,7 @@ ash::Shell::GetInstance()->session_state_delegate(); ash::MultiProfileUMA::RecordSwitchActiveUser( ash::MultiProfileUMA::SWITCH_ACTIVE_USER_BY_TRAY); - delegate->SwitchActiveUser( - delegate->GetUserInfo(user_index)->GetAccountId().GetUserEmail()); + delegate->SwitchActiveUser(delegate->GetUserInfo(user_index)->GetUserID()); } class LogoutButton : public TrayPopupLabelButton {
diff --git a/ash/test/test_session_state_delegate.cc b/ash/test/test_session_state_delegate.cc index bd0bdd3..7f2e648d 100644 --- a/ash/test/test_session_state_delegate.cc +++ b/ash/test/test_session_state_delegate.cc
@@ -12,7 +12,6 @@ #include "base/stl_util.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" -#include "components/signin/core/account_id/account_id.h" #include "components/user_manager/user_info.h" #include "testing/gtest/include/gtest/gtest.h" @@ -21,20 +20,18 @@ namespace { -// The the "canonicalized" Account ID from a given |email| address. -AccountId GetAccountIdFromEmail(const std::string& email) { +// The the "canonicalized" user ID from a given |email| address. +std::string GetUserIDFromEmail(const std::string& email) { std::string user_id = email; std::transform(user_id.begin(), user_id.end(), user_id.begin(), ::tolower); - return AccountId::FromUserEmail(user_id); + return user_id; } } // namespace class MockUserInfo : public user_manager::UserInfo { public: - explicit MockUserInfo(const std::string& display_email) - : display_email_(display_email), - account_id_(GetAccountIdFromEmail(display_email)) {} + explicit MockUserInfo(const std::string& id) : email_(id) {} ~MockUserInfo() override {} void SetUserImage(const gfx::ImageSkia& user_image) { @@ -49,17 +46,18 @@ return base::UTF8ToUTF16("Über Über Über Über"); } - std::string GetEmail() const override { return display_email_; } + std::string GetEmail() const override { return email_; } - AccountId GetAccountId() const override { return account_id_; } + std::string GetUserID() const override { + return GetUserIDFromEmail(GetEmail()); + } const gfx::ImageSkia& GetImage() const override { return user_image_; } // A test user image. gfx::ImageSkia user_image_; - std::string display_email_; - const AccountId account_id_; + std::string email_; DISALLOW_COPY_AND_ASSIGN(MockUserInfo); }; @@ -217,19 +215,18 @@ } void TestSessionStateDelegate::SwitchActiveUser(const std::string& user_id) { - const AccountId account_id(GetAccountIdFromEmail(user_id)); // Make sure this is a user id and not an email address. - EXPECT_EQ(user_id, account_id.GetUserEmail()); + EXPECT_EQ(user_id, GetUserIDFromEmail(user_id)); active_user_index_ = 0; for (std::vector<MockUserInfo*>::iterator iter = user_list_.begin(); iter != user_list_.end(); ++iter) { - if ((*iter)->GetAccountId() == account_id) { + if ((*iter)->GetUserID() == user_id) { active_user_index_ = iter - user_list_.begin(); return; } } - NOTREACHED() << "Unknown user:" << account_id.GetUserEmail(); + NOTREACHED() << "Unknown user:" << user_id; } void TestSessionStateDelegate::CycleActiveUser(CycleUser cycle_user) {
diff --git a/base/android/jni_array.cc b/base/android/jni_array.cc index 0b7ce5d1..e419b34 100644 --- a/base/android/jni_array.cc +++ b/base/android/jni_array.cc
@@ -245,9 +245,7 @@ for (size_t i = 0; i < len; ++i) { ScopedJavaLocalRef<jintArray> int_array( env, static_cast<jintArray>(env->GetObjectArrayElement(array, i))); - jint* ints = env->GetIntArrayElements(int_array.obj(), nullptr); JavaIntArrayToIntVector(env, int_array.obj(), &((*out)[i])); - env->ReleaseIntArrayElements(int_array.obj(), ints, JNI_ABORT); } }
diff --git a/base/callback_list.h b/base/callback_list.h index aeed5f1..5f263f8 100644 --- a/base/callback_list.h +++ b/base/callback_list.h
@@ -185,10 +185,10 @@ } else { ++it; } - - if (updated && !removal_callback_.is_null()) - removal_callback_.Run(); } + + if (updated && !removal_callback_.is_null()) + removal_callback_.Run(); } private:
diff --git a/base/callback_list_unittest.cc b/base/callback_list_unittest.cc index 9adbabb..1cae827 100644 --- a/base/callback_list_unittest.cc +++ b/base/callback_list_unittest.cc
@@ -98,6 +98,19 @@ DISALLOW_COPY_AND_ASSIGN(Summer); }; +class Counter { + public: + Counter() : value_(0) {} + + void Increment() { value_++; } + + int value() const { return value_; } + + private: + int value_; + DISALLOW_COPY_AND_ASSIGN(Counter); +}; + // Sanity check that we can instantiate a CallbackList for each arity. TEST(CallbackListTest, ArityTest) { Summer s; @@ -287,5 +300,37 @@ cb_reg.Notify(); } +TEST(CallbackList, RemovalCallback) { + Counter remove_count; + CallbackList<void(void)> cb_reg; + cb_reg.set_removal_callback( + Bind(&Counter::Increment, Unretained(&remove_count))); + + scoped_ptr<CallbackList<void(void)>::Subscription> subscription = + cb_reg.Add(Bind(&DoNothing)); + + // Removing a subscription outside of iteration signals the callback. + EXPECT_EQ(0, remove_count.value()); + subscription.reset(); + EXPECT_EQ(1, remove_count.value()); + + // Configure two subscriptions to remove themselves. + Remover remover_1, remover_2; + scoped_ptr<CallbackList<void(void)>::Subscription> remover_1_sub = + cb_reg.Add(Bind(&Remover::IncrementTotalAndRemove, + Unretained(&remover_1))); + scoped_ptr<CallbackList<void(void)>::Subscription> remover_2_sub = + cb_reg.Add(Bind(&Remover::IncrementTotalAndRemove, + Unretained(&remover_2))); + remover_1.SetSubscriptionToRemove(remover_1_sub.Pass()); + remover_2.SetSubscriptionToRemove(remover_2_sub.Pass()); + + // The callback should be signaled exactly once. + EXPECT_EQ(1, remove_count.value()); + cb_reg.Notify(); + EXPECT_EQ(2, remove_count.value()); + EXPECT_TRUE(cb_reg.empty()); +} + } // namespace } // namespace base
diff --git a/base/files/file.h b/base/files/file.h index 8b3934d..66b78fa5 100644 --- a/base/files/file.h +++ b/base/files/file.h
@@ -85,6 +85,7 @@ FLAG_TERMINAL_DEVICE = 1 << 16, // Serial port flags. FLAG_BACKUP_SEMANTICS = 1 << 17, // Used on Windows only. FLAG_EXECUTE = 1 << 18, // Used on Windows only. + FLAG_SEQUENTIAL_SCAN = 1 << 19, // Used on Windows only. }; // This enum has been recorded in multiple histograms. If the order of the
diff --git a/base/files/file_win.cc b/base/files/file_win.cc index ce38d0b..2d75ca2 100644 --- a/base/files/file_win.cc +++ b/base/files/file_win.cc
@@ -375,6 +375,8 @@ create_flags |= FILE_FLAG_DELETE_ON_CLOSE; if (flags & FLAG_BACKUP_SEMANTICS) create_flags |= FILE_FLAG_BACKUP_SEMANTICS; + if (flags & FLAG_SEQUENTIAL_SCAN) + create_flags |= FILE_FLAG_SEQUENTIAL_SCAN; file_.Set(CreateFile(path.value().c_str(), access, sharing, NULL, disposition, create_flags, NULL));
diff --git a/base/memory/shared_memory.h b/base/memory/shared_memory.h index 5cdcb0d..18416c0 100644 --- a/base/memory/shared_memory.h +++ b/base/memory/shared_memory.h
@@ -140,10 +140,6 @@ // http://crbug.com/466437. bool CreateAndMapAnonymousPosix(size_t size); bool CreateAnonymousPosix(size_t size); - - // This method is an analog of CreateAndMapAnonymous that forces the - // underlying OS primitive to be a Mach memory object. - bool CreateAndMapAnonymousMach(size_t size); #endif // defined(OS_MACOSX) && !defined(OS_IOS) // Creates an anonymous shared memory segment of size size.
diff --git a/base/memory/shared_memory_handle.h b/base/memory/shared_memory_handle.h index 49398a4..b3dfc8f 100644 --- a/base/memory/shared_memory_handle.h +++ b/base/memory/shared_memory_handle.h
@@ -75,15 +75,12 @@ #else class BASE_EXPORT SharedMemoryHandle { public: - // The values of these enums must not change, as they are used by the - // histogram OSX.SharedMemory.Mechanism. enum Type { // The SharedMemoryHandle is backed by a POSIX fd. POSIX, // The SharedMemoryHandle is backed by the Mach primitive "memory object". MACH, }; - static const int TypeMax = 2; // The format that should be used to transmit |Type| over the wire. typedef int TypeWireFormat;
diff --git a/base/memory/shared_memory_mac.cc b/base/memory/shared_memory_mac.cc index 8f198dc..799b8e3 100644 --- a/base/memory/shared_memory_mac.cc +++ b/base/memory/shared_memory_mac.cc
@@ -13,10 +13,7 @@ #include "base/files/file_util.h" #include "base/files/scoped_file.h" #include "base/logging.h" -#include "base/mac/mac_util.h" #include "base/mac/scoped_mach_vm.h" -#include "base/metrics/field_trial.h" -#include "base/metrics/histogram_macros.h" #include "base/posix/eintr_wrapper.h" #include "base/posix/safe_strerror.h" #include "base/process/process_metrics.h" @@ -32,38 +29,6 @@ namespace { -const char kTrialName[] = "MacMemoryMechanism"; -const char kTrialMach[] = "Mach"; -const char kTrialPosix[] = "Posix"; - -SharedMemoryHandle::Type GetABTestMechanism() { - static bool found_group = false; - static SharedMemoryHandle::Type group = SharedMemoryHandle::MACH; - - if (found_group) - return group; - - const std::string group_name = - base::FieldTrialList::FindFullName(kTrialName); - if (group_name == kTrialMach) { - group = SharedMemoryHandle::MACH; - found_group = true; - } else if (group_name == kTrialPosix) { - group = SharedMemoryHandle::POSIX; - found_group = true; - } else { - group = SharedMemoryHandle::MACH; - } - - return group; -} - -// Emits a histogram entry indicating which type of SharedMemory was created. -void EmitMechanism(SharedMemoryHandle::Type type) { - UMA_HISTOGRAM_ENUMERATION("OSX.SharedMemory.Mechanism", type, - SharedMemoryHandle::TypeMax); -} - // Returns whether the operation succeeded. // |new_handle| is an output variable, populated on success. The caller takes // ownership of the underlying memory object. @@ -262,22 +227,6 @@ return Create(options); } -bool SharedMemory::CreateAndMapAnonymousMach(size_t size) { - SharedMemoryCreateOptions options; - - if (mac::IsOSLionOrLater()) { - // A/B test the mechanism. Once the experiment is over, this will always be - // set to SharedMemoryHandle::MACH. - // http://crbug.com/547261 - options.type = GetABTestMechanism(); - } else { - // Mach shared memory isn't supported on OSX 10.6 or older. - options.type = SharedMemoryHandle::POSIX; - } - options.size = size; - return Create(options) && Map(size); -} - // static bool SharedMemory::GetSizeFromSharedMemoryHandle( const SharedMemoryHandle& handle, @@ -299,8 +248,6 @@ if (options.size > static_cast<size_t>(std::numeric_limits<int>::max())) return false; - EmitMechanism(options.type); - if (options.type == SharedMemoryHandle::MACH) { shm_ = SharedMemoryHandle(options.size); requested_size_ = options.size;
diff --git a/base/trace_event/malloc_dump_provider.cc b/base/trace_event/malloc_dump_provider.cc index 6f15a04..914c684 100644 --- a/base/trace_event/malloc_dump_provider.cc +++ b/base/trace_event/malloc_dump_provider.cc
@@ -40,23 +40,13 @@ if (get_property_function) { // If the function is not null then tcmalloc is used. See // MallocExtension::getNumericProperty. - size_t pageheap_unmapped_bytes = 0; bool res = get_property_function("generic.heap_size", &total_virtual_size); DCHECK(res); - res = get_property_function("tcmalloc.pageheap_unmapped_bytes", - &pageheap_unmapped_bytes); + res = get_property_function("generic.total_physical_bytes", &resident_size); DCHECK(res); res = get_property_function("generic.current_allocated_bytes", &allocated_objects_size); DCHECK(res); - - // Please see TCMallocImplementation::GetStats implementation for - // explanation - // about this math. - // TODO(ssid): Usage of metadata is not included in page heap bytes - // (crbug.com/546491). MallocExtension::GetNumericProperty will be extended - // to get this value. - resident_size = total_virtual_size - pageheap_unmapped_bytes; } else { struct mallinfo info = mallinfo(); DCHECK_GE(info.arena + info.hblkhd, info.uordblks);
diff --git a/base/trace_event/trace_event_etw_export_win.cc b/base/trace_event/trace_event_etw_export_win.cc index 0fee10d..6822eff6 100644 --- a/base/trace_event/trace_event_etw_export_win.cc +++ b/base/trace_event/trace_event_etw_export_win.cc
@@ -336,20 +336,12 @@ } // static -void TraceEventETWExport::AddCustomEvent(const char* name, - char const* phase, - const char* arg_name_1, - const char* arg_value_1, - const char* arg_name_2, - const char* arg_value_2, - const char* arg_name_3, - const char* arg_value_3) { +void TraceEventETWExport::AddCompleteEndEvent(const char* name) { auto* instance = GetInstance(); if (!instance || !instance->etw_export_enabled_ || !EventEnabledChromeEvent()) return; - EventWriteChromeEvent(name, phase, arg_name_1, arg_value_1, arg_name_2, - arg_value_2, arg_name_3, arg_value_3); + EventWriteChromeEvent(name, "Complete End", "", "", "", "", "", ""); } // static
diff --git a/base/trace_event/trace_event_etw_export_win.h b/base/trace_event/trace_event_etw_export_win.h index 7a1c0296..5c3ae60 100644 --- a/base/trace_event/trace_event_etw_export_win.h +++ b/base/trace_event/trace_event_etw_export_win.h
@@ -49,17 +49,8 @@ const unsigned long long* arg_values, const scoped_refptr<ConvertableToTraceFormat>* convertable_values); - // Exports an event to ETW. This should be used when exporting an event only - // to ETW. Supports three arguments to be passed to ETW. - // TODO(georgesak): Allow different providers. - static void AddCustomEvent(const char* name, - const char* phase, - const char* arg_name_1, - const char* arg_value_1, - const char* arg_name_2, - const char* arg_value_2, - const char* arg_name_3, - const char* arg_value_3); + // Exports an ETW event that marks the end of a complete event. + static void AddCompleteEndEvent(const char* name); // Returns true if any category in the group is enabled. static bool IsCategoryGroupEnabled(const char* category_group_name);
diff --git a/base/trace_event/trace_log.cc b/base/trace_event/trace_log.cc index 70dec1d..a8d50caf 100644 --- a/base/trace_event/trace_log.cc +++ b/base/trace_event/trace_log.cc
@@ -1410,6 +1410,10 @@ const unsigned char* category_group_enabled, const char* name, TraceEventHandle handle) { + char category_group_enabled_local = *category_group_enabled; + if (!category_group_enabled_local) + return; + // Avoid re-entrance of AddTraceEvent. This may happen in GPU process when // ECHO_TO_CONSOLE is enabled: AddTraceEvent -> LOG(ERROR) -> // GpuProcessLogMessageHandler -> PostPendingTask -> TRACE_EVENT ... @@ -1421,8 +1425,14 @@ ThreadTicks thread_now = ThreadNow(); TraceTicks now = OffsetNow(); +#if defined(OS_WIN) + // Generate an ETW event that marks the end of a complete event. + if (category_group_enabled_local & ENABLED_FOR_ETW_EXPORT) + TraceEventETWExport::AddCompleteEndEvent(name); +#endif // OS_WIN + std::string console_message; - if (*category_group_enabled & ENABLED_FOR_RECORDING) { + if (category_group_enabled_local & ENABLED_FOR_RECORDING) { OptionalAutoLock lock(&lock_); TraceEvent* trace_event = GetEventByHandleInternal(handle, &lock); @@ -1448,7 +1458,7 @@ if (console_message.size()) LOG(ERROR) << console_message; - if (*category_group_enabled & ENABLED_FOR_EVENT_CALLBACK) { + if (category_group_enabled_local & ENABLED_FOR_EVENT_CALLBACK) { EventCallback event_callback = reinterpret_cast<EventCallback>( subtle::NoBarrier_Load(&event_callback_)); if (event_callback) {
diff --git a/blimp/OWNERS b/blimp/OWNERS index 4cd9769..4b161fe5 100644 --- a/blimp/OWNERS +++ b/blimp/OWNERS
@@ -2,3 +2,5 @@ kmarshall@chromium.org nyquist@chromium.org wez@chromium.org +haibinlu@chromium.org +
diff --git a/build/android/buildbot/bb_device_status_check.py b/build/android/buildbot/bb_device_status_check.py index dcfd8dc..6dd5ca5 100755 --- a/build/android/buildbot/bb_device_status_check.py +++ b/build/android/buildbot/bb_device_status_check.py
@@ -182,7 +182,7 @@ blacklist.Extend([serial], reason='status_check_timeout') elif blacklist: - blacklist.Extend([serial], reason='offline') + blacklist.Extend([serial], reason=adb_status) device_status['blacklisted'] = _IsBlacklisted(serial, blacklist)
diff --git a/build/android/devil/android/battery_utils.py b/build/android/devil/android/battery_utils.py index 5d5f19d..10dc49a 100644 --- a/build/android/devil/android/battery_utils.py +++ b/build/android/devil/android/battery_utils.py
@@ -323,37 +323,6 @@ return True return False - @decorators.WithTimeoutAndRetriesFromInstance() - def SetCharging(self, enabled, timeout=None, retries=None): - """Enables or disables charging on the device. - - Args: - enabled: A boolean indicating whether charging should be enabled or - disabled. - timeout: timeout in seconds - retries: number of retries - - Raises: - device_errors.CommandFailedError: If method of disabling charging cannot - be determined. - """ - self._DiscoverDeviceProfile() - if not self._cache['profile']['enable_command']: - raise device_errors.CommandFailedError( - 'Unable to find charging commands.') - - if enabled: - command = self._cache['profile']['enable_command'] - else: - command = self._cache['profile']['disable_command'] - - def verify_charging(): - return self.GetCharging() == enabled - - self._device.RunShellCommand( - command, check_return=True, as_root=True, large_output=True) - timeout_retry.WaitFor(verify_charging, wait_period=1) - # TODO(rnephew): Make private when all use cases can use the context manager. @decorators.WithTimeoutAndRetriesFromInstance() def DisableBatteryUpdates(self, timeout=None, retries=None): @@ -453,14 +422,14 @@ 'high. Cannot discharge phone %s percent.', percent) return - self.SetCharging(False) + self._HardwareSetCharging(False) def device_discharged(): - self.SetCharging(True) + self._HardwareSetCharging(True) current_level = int(self.GetBatteryInfo().get('level')) logging.info('current battery level: %s', current_level) if battery_level - current_level >= percent: return True - self.SetCharging(False) + self._HardwareSetCharging(False) return False timeout_retry.WaitFor(device_discharged, wait_period=wait_period) @@ -513,7 +482,7 @@ timeout_retry.WaitFor(cool_device, wait_period=wait_period) @decorators.WithTimeoutAndRetriesFromInstance() - def TieredSetCharging(self, enabled, timeout=None, retries=None): + def SetCharging(self, enabled, timeout=None, retries=None): """Enables or disables charging on the device. Args: @@ -529,7 +498,7 @@ self._DiscoverDeviceProfile() if enabled: if self._cache['profile']['enable_command']: - self.SetCharging(enabled) + self._HardwareSetCharging(enabled) else: logging.info('Unable to enable charging via hardware. ' 'Falling back to software enabling.') @@ -537,12 +506,40 @@ else: if self._cache['profile']['enable_command']: self._ClearPowerData() - self.SetCharging(enabled) + self._HardwareSetCharging(enabled) else: logging.info('Unable to disable charging via hardware. ' 'Falling back to software disabling.') self.DisableBatteryUpdates() + def _HardwareSetCharging(self, enabled, timeout=None, retries=None): + """Enables or disables charging on the device. + + Args: + enabled: A boolean indicating whether charging should be enabled or + disabled. + timeout: timeout in seconds + retries: number of retries + + Raises: + device_errors.CommandFailedError: If method of disabling charging cannot + be determined. + """ + self._DiscoverDeviceProfile() + if not self._cache['profile']['enable_command']: + raise device_errors.CommandFailedError( + 'Unable to find charging commands.') + + command = (self._cache['profile']['enable_command'] if enabled + else self._cache['profile']['disable_command']) + + def verify_charging(): + return self.GetCharging() == enabled + + self._device.RunShellCommand( + command, check_return=True, as_root=True, large_output=True) + timeout_retry.WaitFor(verify_charging, wait_period=1) + @contextlib.contextmanager def PowerMeasurement(self, timeout=None, retries=None): """Context manager that enables battery power collection. @@ -565,10 +562,10 @@ retries: number of retries """ try: - self.TieredSetCharging(False, timeout=timeout, retries=retries) + self.SetCharging(False, timeout=timeout, retries=retries) yield finally: - self.TieredSetCharging(True, timeout=timeout, retries=retries) + self.SetCharging(True, timeout=timeout, retries=retries) def _ClearPowerData(self): """Resets battery data and makes device appear like it is not
diff --git a/build/android/devil/android/battery_utils_test.py b/build/android/devil/android/battery_utils_test.py index 64253a5..af18e89 100755 --- a/build/android/devil/android/battery_utils_test.py +++ b/build/android/devil/android/battery_utils_test.py
@@ -104,36 +104,34 @@ with self.assertRaises(TypeError): battery_utils.BatteryUtils('') - class BatteryUtilsSetChargingTest(BatteryUtilsTest): - @mock.patch('time.sleep', mock.Mock()) - def testSetCharging_enabled(self): + def testHardwareSetCharging_enabled(self): self.battery._cache['profile'] = self._NEXUS_5 with self.assertCalls( (self.call.device.RunShellCommand( mock.ANY, check_return=True, as_root=True, large_output=True), []), (self.call.battery.GetCharging(), False), (self.call.battery.GetCharging(), True)): - self.battery.SetCharging(True) + self.battery._HardwareSetCharging(True) - def testSetCharging_alreadyEnabled(self): + def testHardwareSetCharging_alreadyEnabled(self): self.battery._cache['profile'] = self._NEXUS_5 with self.assertCalls( (self.call.device.RunShellCommand( mock.ANY, check_return=True, as_root=True, large_output=True), []), (self.call.battery.GetCharging(), True)): - self.battery.SetCharging(True) + self.battery._HardwareSetCharging(True) @mock.patch('time.sleep', mock.Mock()) - def testSetCharging_disabled(self): + def testHardwareSetCharging_disabled(self): self.battery._cache['profile'] = self._NEXUS_5 with self.assertCalls( (self.call.device.RunShellCommand( mock.ANY, check_return=True, as_root=True, large_output=True), []), (self.call.battery.GetCharging(), True), (self.call.battery.GetCharging(), False)): - self.battery.SetCharging(False) + self.battery._HardwareSetCharging(False) class BatteryUtilsSetBatteryMeasurementTest(BatteryUtilsTest): @@ -263,8 +261,8 @@ def testDischargeDevice_exact(self): with self.assertCalls( (self.call.battery.GetBatteryInfo(), {'level': '100'}), - (self.call.battery.SetCharging(False)), - (self.call.battery.SetCharging(True)), + (self.call.battery._HardwareSetCharging(False)), + (self.call.battery._HardwareSetCharging(True)), (self.call.battery.GetBatteryInfo(), {'level': '99'})): self.battery._DischargeDevice(1) @@ -272,8 +270,8 @@ def testDischargeDevice_over(self): with self.assertCalls( (self.call.battery.GetBatteryInfo(), {'level': '100'}), - (self.call.battery.SetCharging(False)), - (self.call.battery.SetCharging(True)), + (self.call.battery._HardwareSetCharging(False)), + (self.call.battery._HardwareSetCharging(True)), (self.call.battery.GetBatteryInfo(), {'level': '50'})): self.battery._DischargeDevice(1) @@ -281,17 +279,17 @@ def testDischargeDevice_takeslong(self): with self.assertCalls( (self.call.battery.GetBatteryInfo(), {'level': '100'}), - (self.call.battery.SetCharging(False)), - (self.call.battery.SetCharging(True)), + (self.call.battery._HardwareSetCharging(False)), + (self.call.battery._HardwareSetCharging(True)), (self.call.battery.GetBatteryInfo(), {'level': '100'}), - (self.call.battery.SetCharging(False)), - (self.call.battery.SetCharging(True)), + (self.call.battery._HardwareSetCharging(False)), + (self.call.battery._HardwareSetCharging(True)), (self.call.battery.GetBatteryInfo(), {'level': '99'}), - (self.call.battery.SetCharging(False)), - (self.call.battery.SetCharging(True)), + (self.call.battery._HardwareSetCharging(False)), + (self.call.battery._HardwareSetCharging(True)), (self.call.battery.GetBatteryInfo(), {'level': '98'}), - (self.call.battery.SetCharging(False)), - (self.call.battery.SetCharging(True)), + (self.call.battery._HardwareSetCharging(False)), + (self.call.battery._HardwareSetCharging(True)), (self.call.battery.GetBatteryInfo(), {'level': '97'})): self.battery._DischargeDevice(3) @@ -493,10 +491,10 @@ self.assertEqual(self.battery.GetFuelGaugeChargeCounter(), 123) -class BatteryUtilsTieredSetCharging(BatteryUtilsTest): +class BatteryUtilsSetCharging(BatteryUtilsTest): @mock.patch('time.sleep', mock.Mock()) - def testTieredSetCharging_softwareSetTrue(self): + def testSetCharging_softwareSetTrue(self): self.battery._cache['profile'] = self._NEXUS_6 with self.assertCalls( (self.call.battery.GetCharging(), False), @@ -506,10 +504,10 @@ (self.call.device.RunShellCommand( ['dumpsys', 'battery'], check_return=True), ['UPDATES STOPPED']), (self.call.battery.GetCharging(), True)): - self.battery.TieredSetCharging(True) + self.battery.SetCharging(True) @mock.patch('time.sleep', mock.Mock()) - def testTieredSetCharging_softwareSetFalse(self): + def testSetCharging_softwareSetFalse(self): self.battery._cache['profile'] = self._NEXUS_6 with self.assertCalls( (self.call.battery.GetCharging(), True), @@ -519,32 +517,32 @@ (self.call.device.RunShellCommand( ['dumpsys', 'battery', 'set', 'usb', '0'], check_return=True), []), (self.call.battery.GetCharging(), False)): - self.battery.TieredSetCharging(False) + self.battery.SetCharging(False) @mock.patch('time.sleep', mock.Mock()) - def testTieredSetCharging_hardwareSetTrue(self): + def testSetCharging_hardwareSetTrue(self): self.battery._cache['profile'] = self._NEXUS_5 with self.assertCalls( (self.call.battery.GetCharging(), False), - (self.call.battery.SetCharging(True))): - self.battery.TieredSetCharging(True) + (self.call.battery._HardwareSetCharging(True))): + self.battery.SetCharging(True) @mock.patch('time.sleep', mock.Mock()) - def testTieredSetCharging_hardwareSetFalse(self): + def testSetCharging_hardwareSetFalse(self): self.battery._cache['profile'] = self._NEXUS_5 with self.assertCalls( (self.call.battery.GetCharging(), True), (self.call.battery._ClearPowerData(), True), - (self.call.battery.SetCharging(False))): - self.battery.TieredSetCharging(False) + (self.call.battery._HardwareSetCharging(False))): + self.battery.SetCharging(False) - def testTieredSetCharging_expectedStateAlreadyTrue(self): + def testSetCharging_expectedStateAlreadyTrue(self): with self.assertCalls((self.call.battery.GetCharging(), True)): - self.battery.TieredSetCharging(True) + self.battery.SetCharging(True) - def testTieredSetCharging_expectedStateAlreadyFalse(self): + def testSetCharging_expectedStateAlreadyFalse(self): with self.assertCalls((self.call.battery.GetCharging(), False)): - self.battery.TieredSetCharging(False) + self.battery.SetCharging(False) class BatteryUtilsPowerMeasurement(BatteryUtilsTest): @@ -554,9 +552,9 @@ with self.assertCalls( (self.call.battery.GetCharging(), True), (self.call.battery._ClearPowerData(), True), - (self.call.battery.SetCharging(False)), + (self.call.battery._HardwareSetCharging(False)), (self.call.battery.GetCharging(), False), - (self.call.battery.SetCharging(True))): + (self.call.battery._HardwareSetCharging(True))): with self.battery.PowerMeasurement(): pass
diff --git a/build/android/gyp/jinja_template.py b/build/android/gyp/jinja_template.py index e7c9a343..a3633ae 100755 --- a/build/android/gyp/jinja_template.py +++ b/build/android/gyp/jinja_template.py
@@ -11,10 +11,12 @@ import os import sys +sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir)) +from pylib import constants from util import build_utils # Import jinja2 from third_party/jinja2 -sys.path.append(os.path.join(os.path.dirname(__file__), '../../../third_party')) +sys.path.append(os.path.join(constants.DIR_SOURCE_ROOT, 'third_party')) import jinja2 # pylint: disable=F0401 @@ -76,8 +78,8 @@ 'input. Required if --output-zip is given.') parser.add_option('--loader-base-dir', help='Base path used by the template ' 'loader. Must be a common ancestor directory of ' - 'the inputs. Defaults to CHROMIUM_SRC.', - default=build_utils.CHROMIUM_SRC) + 'the inputs. Defaults to DIR_SOURCE_ROOT.', + default=constants.DIR_SOURCE_ROOT) parser.add_option('--variables', help='Variables to be made available in the ' 'template processing environment, as a GYP list (e.g. ' '--variables "channel=beta mstone=39")', default='')
diff --git a/build/android/gyp/util/build_utils.py b/build/android/gyp/util/build_utils.py index f69401b..dcaa7e9 100644 --- a/build/android/gyp/util/build_utils.py +++ b/build/android/gyp/util/build_utils.py
@@ -19,10 +19,10 @@ # Some clients do not add //build/android/gyp to PYTHONPATH. import md5_check # pylint: disable=relative-import -CHROMIUM_SRC = os.path.normpath( - os.path.join(os.path.dirname(__file__), - os.pardir, os.pardir, os.pardir, os.pardir)) -COLORAMA_ROOT = os.path.join(CHROMIUM_SRC, +sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)) +from pylib import constants + +COLORAMA_ROOT = os.path.join(constants.DIR_SOURCE_ROOT, 'third_party', 'colorama', 'src') # aapt should ignore OWNERS files in addition the default ignore pattern. AAPT_IGNORE_PATTERN = ('!OWNERS:!.svn:!.git:!.ds_store:!*.scc:.*:<dir>_*:' + @@ -339,8 +339,9 @@ abs_module_paths = map(os.path.abspath, module_paths) + assert os.path.isabs(constants.DIR_SOURCE_ROOT) non_system_module_paths = [ - p for p in abs_module_paths if p.startswith(CHROMIUM_SRC)] + p for p in abs_module_paths if p.startswith(constants.DIR_SOURCE_ROOT)] def ConvertPycToPy(s): if s.endswith('.pyc'): return s[:-1]
diff --git a/build/gn_migration.gypi b/build/gn_migration.gypi index b4377bda..520188e 100644 --- a/build/gn_migration.gypi +++ b/build/gn_migration.gypi
@@ -241,7 +241,6 @@ ], 'dependencies!': [ # TODO(GYP): All of these targets need to be ported over. - '../chrome/chrome.gyp:unit_tests', '../url/url.gyp:url_unittests', ], }], @@ -250,6 +249,7 @@ '../chrome/android/chrome_apk.gyp:chrome_public_apk', '../chrome/android/chrome_apk.gyp:chrome_public_test_apk', '../chrome/chrome.gyp:chromedriver_webview_shell_apk', + '../chrome/chrome.gyp:unit_tests_apk', '../third_party/custom_tabs_client/custom_tabs_client.gyp:custom_tabs_client_example_apk', ], }], @@ -774,8 +774,6 @@ '../chrome/android/chrome_apk.gyp:chrome_sync_shell_apk', '../chrome/android/chrome_apk.gyp:chrome_sync_shell_test_apk', '../chrome/chrome.gyp:chrome_junit_tests', - '../chrome/chrome.gyp:unit_tests', - '../chrome/chrome.gyp:unit_tests_apk', '../remoting/remoting.gyp:remoting_apk', ], }],
diff --git a/cc/output/direct_renderer.cc b/cc/output/direct_renderer.cc index b219fd9..0083427 100644 --- a/cc/output/direct_renderer.cc +++ b/cc/output/direct_renderer.cc
@@ -240,27 +240,7 @@ // otherwise the framebuffer will be missing the overlay contents. if (root_render_pass->copy_requests.empty()) { overlay_processor_->ProcessForOverlays( - resource_provider_, render_passes_in_draw_order, &frame.overlay_list, - &frame.root_damage_rect); - - // No need to render in case the damage rect is completely composited using - // overlays and dont have any copy requests. - if (frame.root_damage_rect.IsEmpty()) { - bool handle_copy_requests = false; - for (auto* pass : *render_passes_in_draw_order) { - if (!pass->copy_requests.empty()) { - handle_copy_requests = true; - break; - } - } - - if (!handle_copy_requests) { - BindFramebufferToOutputSurface(&frame); - FinishDrawingFrame(&frame); - render_passes_in_draw_order->clear(); - return; - } - } + resource_provider_, render_passes_in_draw_order, &frame.overlay_list); } for (size_t i = 0; i < render_passes_in_draw_order->size(); ++i) {
diff --git a/cc/output/overlay_candidate.cc b/cc/output/overlay_candidate.cc index 5931e7da..658f153 100644 --- a/cc/output/overlay_candidate.cc +++ b/cc/output/overlay_candidate.cc
@@ -175,7 +175,6 @@ use_output_surface_for_resource(false), resource_id(0), plane_z_order(0), - needs_blending(false), overlay_handled(false) {} OverlayCandidate::~OverlayCandidate() {} @@ -197,8 +196,6 @@ candidate->format = RGBA_8888; candidate->clip_rect = quad->shared_quad_state->clip_rect; candidate->is_clipped = quad->shared_quad_state->is_clipped; - candidate->needs_blending = - quad->shared_quad_state->opacity < 1.0f || quad->needs_blending; switch (quad->material) { case DrawQuad::TEXTURE_CONTENT:
diff --git a/cc/output/overlay_candidate.h b/cc/output/overlay_candidate.h index 8033dca7..aa42ba11 100644 --- a/cc/output/overlay_candidate.h +++ b/cc/output/overlay_candidate.h
@@ -66,8 +66,6 @@ // Stacking order of the overlay plane relative to the main surface, // which is 0. Signed to allow for "underlays". int plane_z_order; - // If the overlay needs blending support. - bool needs_blending; // To be modified by the implementer if this candidate can go into // an overlay.
diff --git a/cc/output/overlay_processor.cc b/cc/output/overlay_processor.cc index 59434b01..69368a1 100644 --- a/cc/output/overlay_processor.cc +++ b/cc/output/overlay_processor.cc
@@ -12,14 +12,6 @@ namespace cc { -namespace { - -bool SortByZOrder(const OverlayCandidate& a, const OverlayCandidate& b) { - return (a.plane_z_order < b.plane_z_order); -} - -} // namespace - OverlayProcessor::OverlayProcessor(OutputSurface* surface) : surface_(surface) { } @@ -35,21 +27,10 @@ void OverlayProcessor::ProcessForOverlays(ResourceProvider* resource_provider, RenderPassList* render_passes, - OverlayCandidateList* candidates, - gfx::Rect* damage_rect) { + OverlayCandidateList* candidates) { for (auto strategy : strategies_) { - if (strategy->Attempt(resource_provider, render_passes, candidates)) { - std::sort(candidates->begin(), candidates->end(), SortByZOrder); - - for (const OverlayCandidate& overlay : *candidates) { - if (overlay.plane_z_order <= 0 || overlay.needs_blending) - continue; - - damage_rect->Subtract(ToEnclosedRect(overlay.display_rect)); - } - + if (strategy->Attempt(resource_provider, render_passes, candidates)) return; - } } }
diff --git a/cc/output/overlay_processor.h b/cc/output/overlay_processor.h index b4448d3..48ffe6b 100644 --- a/cc/output/overlay_processor.h +++ b/cc/output/overlay_processor.h
@@ -37,8 +37,7 @@ void ProcessForOverlays(ResourceProvider* resource_provider, RenderPassList* render_passes, - OverlayCandidateList* candidates, - gfx::Rect* damage_rect); + OverlayCandidateList* candidates); protected: StrategyList strategies_;
diff --git a/cc/output/overlay_unittest.cc b/cc/output/overlay_unittest.cc index 659e5050..722002e 100644 --- a/cc/output/overlay_unittest.cc +++ b/cc/output/overlay_unittest.cc
@@ -366,7 +366,6 @@ scoped_ptr<SharedBitmapManager> shared_bitmap_manager_; scoped_ptr<ResourceProvider> resource_provider_; scoped_ptr<OverlayProcessor> overlay_processor_; - gfx::Rect damage_rect_; }; typedef OverlayTest<SingleOnTopOverlayValidator> SingleOverlayOnTopTest; @@ -420,7 +419,7 @@ // Check for potential candidates. OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); ASSERT_EQ(1U, pass_list.size()); ASSERT_EQ(1U, candidate_list.size()); @@ -462,7 +461,7 @@ // Check for potential candidates. OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); // Ensure that the display and uv rects have cropping applied to them. ASSERT_EQ(1U, pass_list.size()); @@ -491,7 +490,7 @@ pass_list.push_back(pass.Pass()); OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); // Both candidates should become overlays. EXPECT_EQ(1u, pass_list.size()); @@ -525,7 +524,7 @@ pass_list.push_back(pass.Pass()); OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); // Only one of the candidates should become an overlay. EXPECT_EQ(1u, pass_list.size()); @@ -560,7 +559,8 @@ // Check for potential candidates. OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); + ASSERT_EQ(1U, pass_list.size()); ASSERT_EQ(2U, candidate_list.size()); @@ -615,7 +615,7 @@ OverlayCandidateList candidate_list; EXPECT_EQ(4U, main_pass->quad_list.size()); overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); ASSERT_EQ(1U, pass_list.size()); ASSERT_EQ(3U, candidate_list.size()); @@ -667,7 +667,7 @@ // Check for potential candidates. OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); ASSERT_EQ(1U, pass_list.size()); ASSERT_EQ(1U, candidate_list.size()); @@ -686,29 +686,6 @@ EXPECT_EQ(original_resource_id, candidate_list.back().resource_id); } -TEST_F(SingleOverlayOnTopTest, DamageRect) { - scoped_ptr<RenderPass> pass = CreateRenderPass(); - CreateFullscreenCandidateQuad(resource_provider_.get(), - pass->shared_quad_state_list.back(), - pass.get()); - damage_rect_ = kOverlayRect; - - // Add something behind it. - CreateFullscreenOpaqueQuad(resource_provider_.get(), - pass->shared_quad_state_list.back(), pass.get()); - CreateFullscreenOpaqueQuad(resource_provider_.get(), - pass->shared_quad_state_list.back(), pass.get()); - - RenderPassList pass_list; - pass_list.push_back(pass.Pass()); - - // Check for potential candidates. - OverlayCandidateList candidate_list; - overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); - DCHECK(damage_rect_.IsEmpty()); -} - TEST_F(SingleOverlayOnTopTest, NoCandidates) { scoped_ptr<RenderPass> pass = CreateRenderPass(); CreateFullscreenOpaqueQuad(resource_provider_.get(), @@ -724,7 +701,7 @@ OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); EXPECT_EQ(0U, candidate_list.size()); // There should be nothing new here. CompareRenderPassLists(pass_list, original_pass_list); @@ -749,7 +726,7 @@ OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); EXPECT_EQ(0U, candidate_list.size()); // There should be nothing new here. CompareRenderPassLists(pass_list, original_pass_list); @@ -779,7 +756,7 @@ // Check for potential candidates. OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); EXPECT_EQ(1U, candidate_list.size()); // This should be the same. @@ -798,7 +775,7 @@ pass_list.push_back(pass.Pass()); OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); EXPECT_EQ(1U, pass_list.size()); EXPECT_EQ(0U, candidate_list.size()); } @@ -815,7 +792,7 @@ pass_list.push_back(pass.Pass()); OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); ASSERT_EQ(1U, pass_list.size()); EXPECT_EQ(0U, candidate_list.size()); } @@ -832,7 +809,7 @@ pass_list.push_back(pass.Pass()); OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); ASSERT_EQ(1U, pass_list.size()); EXPECT_EQ(0U, candidate_list.size()); } @@ -848,7 +825,7 @@ pass_list.push_back(pass.Pass()); OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); ASSERT_EQ(1U, pass_list.size()); EXPECT_EQ(0U, candidate_list.size()); } @@ -864,7 +841,7 @@ pass_list.push_back(pass.Pass()); OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); ASSERT_EQ(1U, pass_list.size()); EXPECT_EQ(0U, candidate_list.size()); } @@ -881,7 +858,7 @@ pass_list.push_back(pass.Pass()); OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); ASSERT_EQ(1U, pass_list.size()); EXPECT_EQ(0U, candidate_list.size()); } @@ -898,7 +875,7 @@ pass_list.push_back(pass.Pass()); OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); ASSERT_EQ(1U, pass_list.size()); EXPECT_EQ(1U, candidate_list.size()); } @@ -917,7 +894,7 @@ pass_list.push_back(pass.Pass()); OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); ASSERT_EQ(1U, pass_list.size()); ASSERT_EQ(1U, candidate_list.size()); EXPECT_EQ(gfx::OVERLAY_TRANSFORM_FLIP_VERTICAL, @@ -938,7 +915,7 @@ pass_list.push_back(pass.Pass()); OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); ASSERT_EQ(1U, pass_list.size()); ASSERT_EQ(1U, candidate_list.size()); EXPECT_EQ(gfx::OVERLAY_TRANSFORM_FLIP_HORIZONTAL, @@ -958,7 +935,7 @@ pass_list.push_back(pass.Pass()); OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); ASSERT_EQ(1U, pass_list.size()); EXPECT_EQ(1U, candidate_list.size()); } @@ -976,7 +953,7 @@ pass_list.push_back(pass.Pass()); OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); ASSERT_EQ(1U, pass_list.size()); ASSERT_EQ(1U, candidate_list.size()); EXPECT_EQ(gfx::OVERLAY_TRANSFORM_ROTATE_90, candidate_list.back().transform); @@ -995,7 +972,7 @@ pass_list.push_back(pass.Pass()); OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); ASSERT_EQ(1U, pass_list.size()); ASSERT_EQ(1U, candidate_list.size()); EXPECT_EQ(gfx::OVERLAY_TRANSFORM_ROTATE_180, candidate_list.back().transform); @@ -1014,7 +991,7 @@ pass_list.push_back(pass.Pass()); OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); ASSERT_EQ(1U, pass_list.size()); ASSERT_EQ(1U, candidate_list.size()); EXPECT_EQ(gfx::OVERLAY_TRANSFORM_ROTATE_270, candidate_list.back().transform); @@ -1038,7 +1015,7 @@ OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); EXPECT_EQ(1U, pass_list.size()); EXPECT_EQ(1U, candidate_list.size()); } @@ -1062,7 +1039,7 @@ OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); EXPECT_EQ(1U, pass_list.size()); EXPECT_EQ(1U, candidate_list.size()); } @@ -1084,7 +1061,7 @@ OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); EXPECT_EQ(1U, pass_list.size()); EXPECT_EQ(1U, candidate_list.size()); } @@ -1108,7 +1085,7 @@ OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); EXPECT_EQ(1U, pass_list.size()); EXPECT_EQ(0U, candidate_list.size()); } @@ -1130,7 +1107,7 @@ OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); EXPECT_EQ(1U, pass_list.size()); EXPECT_EQ(0U, candidate_list.size()); } @@ -1145,7 +1122,7 @@ pass_list.push_back(pass.Pass()); OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); ASSERT_EQ(1U, pass_list.size()); EXPECT_EQ(0U, candidate_list.size()); } @@ -1160,7 +1137,7 @@ pass_list.push_back(pass.Pass()); OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); ASSERT_EQ(1U, pass_list.size()); EXPECT_EQ(1U, candidate_list.size()); } @@ -1175,7 +1152,7 @@ pass_list.push_back(pass.Pass()); OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); ASSERT_EQ(1U, pass_list.size()); EXPECT_EQ(1U, candidate_list.size()); } @@ -1190,7 +1167,7 @@ pass_list.push_back(pass.Pass()); OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); ASSERT_EQ(1U, pass_list.size()); EXPECT_EQ(1U, candidate_list.size()); } @@ -1205,7 +1182,7 @@ pass_list.push_back(pass.Pass()); OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); ASSERT_EQ(1U, pass_list.size()); EXPECT_EQ(1U, candidate_list.size()); } @@ -1223,7 +1200,7 @@ OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); EXPECT_EQ(1U, pass_list.size()); ASSERT_EQ(1U, candidate_list.size()); EXPECT_EQ(-1, candidate_list[0].plane_z_order); @@ -1246,7 +1223,7 @@ OverlayCandidateList candidate_list; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidate_list, &damage_rect_); + &candidate_list); EXPECT_EQ(1U, pass_list.size()); ASSERT_EQ(1U, candidate_list.size()); EXPECT_EQ(-1, candidate_list[0].plane_z_order); @@ -1269,14 +1246,14 @@ pass_list.push_back(pass.Pass()); OverlayCandidateList candidates; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidates, &damage_rect_); + &candidates); // Both quads should become overlays. EXPECT_EQ(2u, candidates.size()); - EXPECT_EQ(-2, candidates[0].plane_z_order); - EXPECT_EQ(-1, candidates[1].plane_z_order); - EXPECT_EQ(gfx::RectF(kOverlayTopLeftRect), candidates[1].display_rect); - EXPECT_EQ(gfx::RectF(kOverlayRect), candidates[0].display_rect); + EXPECT_EQ(-1, candidates[0].plane_z_order); + EXPECT_EQ(-2, candidates[1].plane_z_order); + EXPECT_EQ(gfx::RectF(kOverlayTopLeftRect), candidates[0].display_rect); + EXPECT_EQ(gfx::RectF(kOverlayRect), candidates[1].display_rect); // All quads should be gone. EXPECT_TRUE(pass_list.back()->quad_list.empty()); @@ -1300,7 +1277,7 @@ pass_list.push_back(pass.Pass()); OverlayCandidateList candidates; overlay_processor_->ProcessForOverlays(resource_provider_.get(), &pass_list, - &candidates, &damage_rect_); + &candidates); // No quads should become overlays. EXPECT_EQ(0u, candidates.size()); @@ -1337,7 +1314,7 @@ } ASSERT_EQ(2U, frame->overlay_list.size()); - EXPECT_GE(frame->overlay_list.back().resource_id, 0U); + EXPECT_NE(0U, frame->overlay_list.back().resource_id); } void set_expect_overlays(bool expect_overlays) { @@ -1408,44 +1385,6 @@ scoped_ptr<RenderPass> pass = CreateRenderPass(); - CreateCandidateQuadAt(resource_provider_.get(), - pass->shared_quad_state_list.back(), pass.get(), - kOverlayBottomRightRect); - CreateFullscreenOpaqueQuad(resource_provider_.get(), - pass->shared_quad_state_list.back(), pass.get()); - CreateFullscreenOpaqueQuad(resource_provider_.get(), - pass->shared_quad_state_list.back(), pass.get()); - - RenderPassList pass_list; - pass_list.push_back(pass.Pass()); - - // Candidate pass was taken out and extra skipped pass added, - // so only draw 2 quads. - EXPECT_CALL(*renderer_, DoDrawQuad(_, _, _)).Times(2); - EXPECT_CALL(scheduler_, - Schedule(0, gfx::OVERLAY_TRANSFORM_NONE, _, - gfx::Rect(kDisplaySize), gfx::RectF(0, 0, 1, 1))) - .Times(1); - EXPECT_CALL(scheduler_, Schedule(1, gfx::OVERLAY_TRANSFORM_NONE, _, - kOverlayBottomRightRect, - BoundingRect(kUVTopLeft, kUVBottomRight))) - .Times(1); - renderer_->DrawFrame(&pass_list, 1.f, viewport_rect, viewport_rect, false); - - SwapBuffers(); - - Mock::VerifyAndClearExpectations(renderer_.get()); - Mock::VerifyAndClearExpectations(&scheduler_); -} - -TEST_F(GLRendererWithOverlaysTest, OccludedQuadNotDrawn) { - bool use_validator = true; - Init(use_validator); - renderer_->set_expect_overlays(true); - gfx::Rect viewport_rect(16, 16); - - scoped_ptr<RenderPass> pass = CreateRenderPass(); - CreateFullscreenCandidateQuad(resource_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); @@ -1458,8 +1397,9 @@ RenderPassList pass_list; pass_list.push_back(pass.Pass()); - // Candidate covers all the quads, so we shouldn't have any draw quad calls. - EXPECT_CALL(*renderer_, DoDrawQuad(_, _, _)).Times(0); + // Candidate pass was taken out and extra skipped pass added, + // so only draw 2 quads. + EXPECT_CALL(*renderer_, DoDrawQuad(_, _, _)).Times(2); EXPECT_CALL(scheduler_, Schedule(0, gfx::OVERLAY_TRANSFORM_NONE, _, gfx::Rect(kDisplaySize), gfx::RectF(0, 0, 1, 1)))
diff --git a/cc/trees/layer_tree_host.cc b/cc/trees/layer_tree_host.cc index baf0c0ee..7bedcdda 100644 --- a/cc/trees/layer_tree_host.cc +++ b/cc/trees/layer_tree_host.cc
@@ -99,6 +99,7 @@ top_controls_height_(0.f), top_controls_shown_ratio_(0.f), device_scale_factor_(1.f), + painted_device_scale_factor_(1.f), visible_(false), page_scale_factor_(1.f), min_page_scale_factor_(1.f), @@ -311,6 +312,7 @@ // properties are set, since those trigger an update of GPU rasterization // status, which depends on the device scale factor. (crbug.com/535700) sync_tree->SetDeviceScaleFactor(device_scale_factor_); + sync_tree->set_painted_device_scale_factor(painted_device_scale_factor_); host_impl->SetDebugState(debug_state_); if (pending_page_scale_animation_) { sync_tree->SetPendingPageScaleAnimation( @@ -880,6 +882,15 @@ SetNeedsCommit(); } +void LayerTreeHost::SetPaintedDeviceScaleFactor( + float painted_device_scale_factor) { + if (painted_device_scale_factor == painted_device_scale_factor_) + return; + painted_device_scale_factor_ = painted_device_scale_factor; + + SetNeedsCommit(); +} + void LayerTreeHost::UpdateTopControlsState(TopControlsState constraints, TopControlsState current, bool animate) {
diff --git a/cc/trees/layer_tree_host.h b/cc/trees/layer_tree_host.h index 27cc3e3..a9063ff 100644 --- a/cc/trees/layer_tree_host.h +++ b/cc/trees/layer_tree_host.h
@@ -238,6 +238,8 @@ void SetImplTransform(const gfx::Transform& transform); void SetDeviceScaleFactor(float device_scale_factor); + void SetPaintedDeviceScaleFactor(float painted_device_scale_factor); + float device_scale_factor() const { return device_scale_factor_; } void UpdateTopControlsState(TopControlsState constraints, @@ -444,6 +446,7 @@ float top_controls_height_; float top_controls_shown_ratio_; float device_scale_factor_; + float painted_device_scale_factor_; bool visible_;
diff --git a/cc/trees/layer_tree_host_impl.cc b/cc/trees/layer_tree_host_impl.cc index 71eb92af..f69ae73 100644 --- a/cc/trees/layer_tree_host_impl.cc +++ b/cc/trees/layer_tree_host_impl.cc
@@ -1532,7 +1532,9 @@ CompositorFrameMetadata LayerTreeHostImpl::MakeCompositorFrameMetadata() const { CompositorFrameMetadata metadata; - metadata.device_scale_factor = active_tree_->device_scale_factor(); + metadata.device_scale_factor = active_tree_->painted_device_scale_factor() * + active_tree_->device_scale_factor(); + metadata.page_scale_factor = active_tree_->current_page_scale_factor(); metadata.scrollable_viewport_size = active_tree_->ScrollableViewportSize(); metadata.root_layer_size = active_tree_->ScrollableSize();
diff --git a/cc/trees/layer_tree_host_unittest.cc b/cc/trees/layer_tree_host_unittest.cc index cad9857..477f29ab 100644 --- a/cc/trees/layer_tree_host_unittest.cc +++ b/cc/trees/layer_tree_host_unittest.cc
@@ -6381,5 +6381,28 @@ MULTI_THREAD_TEST_F(LayerTreeHostTestDestroyWhileInitializingOutputSurface); +// Makes sure that painted_device_scale_factor is propagated to the +// frame's metadata. +class LayerTreeHostTestPaintedDeviceScaleFactor : public LayerTreeHostTest { + protected: + void BeginTest() override { + layer_tree_host()->SetPaintedDeviceScaleFactor(2.0f); + EXPECT_EQ(1.0f, layer_tree_host()->device_scale_factor()); + PostSetNeedsCommitToMainThread(); + } + + void SwapBuffersOnThread(LayerTreeHostImpl* host_impl, bool result) override { + EXPECT_EQ(2.0f, + output_surface()->last_sent_frame().metadata.device_scale_factor); + EXPECT_EQ(2.0f, host_impl->active_tree()->painted_device_scale_factor()); + EXPECT_EQ(1.0f, host_impl->active_tree()->device_scale_factor()); + EndTest(); + } + + void AfterTest() override {} +}; + +SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostTestPaintedDeviceScaleFactor); + } // namespace } // namespace cc
diff --git a/cc/trees/layer_tree_impl.cc b/cc/trees/layer_tree_impl.cc index 6d59e19f..6ba1153b 100644 --- a/cc/trees/layer_tree_impl.cc +++ b/cc/trees/layer_tree_impl.cc
@@ -58,6 +58,7 @@ min_page_scale_factor_(0), max_page_scale_factor_(0), device_scale_factor_(1.f), + painted_device_scale_factor_(1.f), elastic_overscroll_(elastic_overscroll), viewport_size_invalid_(false), needs_update_draw_properties_(true), @@ -315,6 +316,7 @@ target_tree->PushPageScaleFactorAndLimits(nullptr, min_page_scale_factor(), max_page_scale_factor()); target_tree->SetDeviceScaleFactor(device_scale_factor()); + target_tree->set_painted_device_scale_factor(painted_device_scale_factor()); target_tree->elastic_overscroll()->PushPendingToActive(); target_tree->pending_page_scale_animation_ =
diff --git a/cc/trees/layer_tree_impl.h b/cc/trees/layer_tree_impl.h index e642e9b..60ef91e 100644 --- a/cc/trees/layer_tree_impl.h +++ b/cc/trees/layer_tree_impl.h
@@ -198,6 +198,13 @@ void SetDeviceScaleFactor(float device_scale_factor); float device_scale_factor() const { return device_scale_factor_; } + void set_painted_device_scale_factor(float painted_device_scale_factor) { + painted_device_scale_factor_ = painted_device_scale_factor; + } + float painted_device_scale_factor() const { + return painted_device_scale_factor_; + } + SyncedElasticOverscroll* elastic_overscroll() { return elastic_overscroll_.get(); } @@ -437,6 +444,7 @@ float max_page_scale_factor_; float device_scale_factor_; + float painted_device_scale_factor_; scoped_refptr<SyncedElasticOverscroll> elastic_overscroll_;
diff --git a/chrome/android/java/res/layout/playback_notification_bar.xml b/chrome/android/java/res/layout/playback_notification_bar.xml index 0a79741..d52bc7c6 100644 --- a/chrome/android/java/res/layout/playback_notification_bar.xml +++ b/chrome/android/java/res/layout/playback_notification_bar.xml
@@ -4,13 +4,28 @@ found in the LICENSE file. --> <!-- - Notification layout for media controls. + Notification layout for media controls. Could have one or two buttons + depending on the corresponding media. + Local playback notification has one play/pause button on L+ but two buttons, + play/pause and stop button, on earlier Android versions as the notification + can't be dismissed by the swiping gesture. + Cast notification always has the stop button that stops casting but only has + the play/pause button if the Cast application controlled by the notification + supports play/pause. + The notification button ids are numbered from the right, so "R.id.button1" is + always present and "R.id.button2" may have the visibility GONE. _______________________________________________________ | | | | - | | Playing [media title] | | - | ICON | =====0============================= | || | + | | [media title] | | + | ICON |======================================| || | | | [www.example.com] | | |________|______________________________________|_____| + _______________________________________________________ + | | | | | + | | [Cast device name] | | | + | ICON |================================| || | X | + | | [www.example.com] | | | + |________|________________________________|_____|_____| --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" @@ -64,28 +79,28 @@ </LinearLayout> <ImageButton - android:id="@+id/playpause" + android:id="@+id/button2" android:src="@drawable/ic_vidcontrol_play" - android:layout_width="wrap_content" + android:layout_width="40dp" + android:layout_height="match_parent" + android:layout_marginStart="8dp" + android:gravity="center" + android:padding="8dp" + android:scaleType="center" + android:background="?android:attr/selectableItemBackground" + android:contentDescription="@null" + android:visibility="gone"/> + + <ImageButton + android:id="@+id/button1" + android:src="@drawable/ic_vidcontrol_stop" + android:layout_width="40dp" android:layout_height="match_parent" android:layout_marginEnd="8dp" android:gravity="center" - android:padding="12dp" + android:padding="8dp" android:scaleType="center" android:background="?android:attr/selectableItemBackground" android:contentDescription="@null"/> - <ImageButton - android:id="@+id/stop" - android:src="@drawable/ic_vidcontrol_stop" - android:layout_width="wrap_content" - android:layout_height="match_parent" - android:layout_marginEnd="8dp" - android:gravity="center" - android:padding="12dp" - android:scaleType="center" - android:background="?android:attr/selectableItemBackground" - android:contentDescription="@string/accessibility_stop" - android:visibility="gone"/> - </LinearLayout>
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ChromeSwitches.java b/chrome/android/java/src/org/chromium/chrome/browser/ChromeSwitches.java index 5cb64672..3cc027c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ChromeSwitches.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ChromeSwitches.java
@@ -131,18 +131,6 @@ "use-fake-device-for-media-stream"; /** - * Disables the new icon-centric NTP design. - * Native switch - switches::kDisableIconNtp - */ - public static final String DISABLE_ICON_NTP = "disable-icon-ntp"; - - /** - * Enables the new icon-centric NTP design. - * Native switch - switches::kEnableIconNtp - */ - public static final String ENABLE_ICON_NTP = "enable-icon-ntp"; - - /** * Disable domain reliability * Native switch - switches::kDisableDomainReliability */
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanelContent.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanelContent.java index 3d74cb9..88cdcb5a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanelContent.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanelContent.java
@@ -156,6 +156,15 @@ // ============================================================================================ /** + * Creates a ContentViewCore. This method will be overridden by tests. + * @param activity The ChromeActivity. + * @return The newly created ContentViewCore. + */ + protected ContentViewCore createContentViewCore(ChromeActivity activity) { + return new ContentViewCore(activity); + } + + /** * Create a new ContentViewCore that will be managed by this panel. */ private void createNewContentView() { @@ -167,7 +176,7 @@ destroyContentView(); } - mContentViewCore = new ContentViewCore(mActivity); + mContentViewCore = createContentViewCore(mActivity); if (mContentViewClient == null) { mContentViewClient = new ContentViewClient(); @@ -248,14 +257,6 @@ } /** - * @return Whether the ContentViewCore was created. - */ - @VisibleForTesting - public boolean didCreateContentView() { - return mContentViewCore != null; - } - - /** * Load a URL, this will trigger creation of a new ContentViewCore. * @param url The URL that should be loaded. */
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/contextualsearch/ContextualSearchPanelBase.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/contextualsearch/ContextualSearchPanelBase.java index 390bf36..7af52d2a4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/contextualsearch/ContextualSearchPanelBase.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/contextualsearch/ContextualSearchPanelBase.java
@@ -810,8 +810,6 @@ * @param reason The reason for a change in the panel's state. */ public void setPanelState(PanelState state, StateChangeReason reason) { - mPanelState = state; - if (state == PanelState.CLOSED) { mIsShowing = false; onClosed(reason); @@ -819,6 +817,12 @@ || (state == PanelState.MAXIMIZED && !isFullscreenSizePanel())) { showPromoViewAtYPosition(getPromoYPx()); } + + // We should only set the state at the end of this method, in oder to make sure that + // all callbacks will be fired before changing the state of the Panel. This prevents + // some flakiness on tests since they rely on changes of state to determine when a + // particular action has been completed. + mPanelState = state; } /**
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchTabHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchTabHelper.java index 0947286c..4081bf2 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchTabHelper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchTabHelper.java
@@ -4,6 +4,8 @@ package org.chromium.chrome.browser.contextualsearch; +import android.app.Activity; + import org.chromium.base.annotations.CalledByNative; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.compositor.bottombar.OverlayPanel.StateChangeReason; @@ -43,6 +45,8 @@ private long mNativeHelper = 0; + private final Tab mTab; + /** * Creates a contextual search tab helper for the given tab. * @param tab The tab whose contextual search actions will be handled by this helper. @@ -52,6 +56,7 @@ } private ContextualSearchTabHelper(Tab tab) { + mTab = tab; tab.addObserver(this); } @@ -161,7 +166,7 @@ /** * @return whether Contextual Search is enabled and active in this tab. */ - private static boolean isContextualSearchActive(ContentViewCore cvc) { + private boolean isContextualSearchActive(ContentViewCore cvc) { return !cvc.getWebContents().isIncognito() && getContextualSearchManager(cvc) != null && !PrefServiceBridge.getInstance().isContextualSearchDisabled() && TemplateUrlService.getInstance().isDefaultSearchEngineGoogle() @@ -175,10 +180,10 @@ /** * @return the Contextual Search manager. */ - private static ContextualSearchManager getContextualSearchManager(ContentViewCore cvc) { - // TODO(yfriedman): Decouple this from the activity. - if (cvc.getContext() instanceof ChromeActivity) { - return ((ChromeActivity) cvc.getContext()).getContextualSearchManager(); + private ContextualSearchManager getContextualSearchManager(ContentViewCore cvc) { + Activity activity = mTab.getWindowAndroid().getActivity().get(); + if (activity instanceof ChromeActivity) { + return ((ChromeActivity) activity).getContextualSearchManager(); } return null; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/media/router/cast/CastRequestIdGenerator.java b/chrome/android/java/src/org/chromium/chrome/browser/media/router/cast/CastRequestIdGenerator.java new file mode 100644 index 0000000..c753a83 --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/media/router/cast/CastRequestIdGenerator.java
@@ -0,0 +1,37 @@ +// 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. + +package org.chromium.chrome.browser.media.router.cast; + +/** + * Returns a request id in a range that is considered fairly unique. These request ids are used to + * communicate with the cast device and identify messages and their responses. + */ +public class CastRequestIdGenerator { + private static final Object LOCK = new Object(); + private static CastRequestIdGenerator sInstance; + + private int mRequestId; + + /** Returns the next requestId in the range allocated to communicate with the device. */ + public static int getNextRequestId() { + CastRequestIdGenerator instance = getInstance(); + + // Return the current |mRequestId| then increment. Never return 0 because it is reserved. + if (instance.mRequestId == 0) ++instance.mRequestId; + return instance.mRequestId++; + } + + /** Returns the Singleton instance of the CastRequestIdGenerator. */ + private static CastRequestIdGenerator getInstance() { + synchronized (LOCK) { + if (sInstance == null) sInstance = new CastRequestIdGenerator(); + } + return sInstance; + } + + private CastRequestIdGenerator() { + mRequestId = (int) Math.floor(Math.random() * 100000.0) * 1000; + } +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/media/router/cast/CastRouteController.java b/chrome/android/java/src/org/chromium/chrome/browser/media/router/cast/CastRouteController.java index e776aeb..411134d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/media/router/cast/CastRouteController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/media/router/cast/CastRouteController.java
@@ -5,10 +5,13 @@ package org.chromium.chrome.browser.media.router.cast; import android.content.Context; +import android.util.SparseIntArray; import com.google.android.gms.cast.ApplicationMetadata; import com.google.android.gms.cast.Cast; import com.google.android.gms.cast.CastDevice; +import com.google.android.gms.cast.MediaStatus; +import com.google.android.gms.cast.RemoteMediaPlayer; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; @@ -46,17 +49,15 @@ "LOAD", "PAUSE", "SEEK", - "GET_STATUS", "STOP_MEDIA", - "SET_VOLUME", - "GET_STATUS", + "MEDIA_SET_VOLUME", + "MEDIA_GET_STATUS", "EDIT_TRACKS_INFO", "QUEUE_LOAD", "QUEUE_INSERT", "QUEUE_UPDATE", "QUEUE_REMOVE", "QUEUE_REORDER", - "MEDIA_STATUS", }; private static final String MEDIA_SUPPORTED_COMMANDS[] = { @@ -66,7 +67,16 @@ "stream_mute", }; - // Map associating overloaded types with the types they represent. + // Sequence number used when no sequence number is required or was initially passed. + private static final int INVALID_SEQUENCE_NUMBER = -1; + // Sequence number use instead of no sequence number when a sequence number was expected from + // the client. + private static final int OPTIONAL_SEQUENCE_NUMBER = 0; + + // Map associating types that have a different names outside of the media namespace and inside. + // In other words, some types are sent as MEDIA_FOO or FOO_MEDIA by the client by the Cast + // expect them to be named FOO. The reason being that FOO might exist in multiple namespaces + // but the client isn't aware of namespacing. private static Map<String, String> sMediaOverloadedMessageTypes; // Lock used to lazy initialize sMediaOverloadedMessageTypes. @@ -85,7 +95,18 @@ + "\" message=\"" + message + "\""); if (MEDIA_NAMESPACE.equals(namespace) || RECEIVER_NAMESPACE.equals(namespace)) { - mSession.onMessage("v2_message", message); + int sequenceNumber = INVALID_SEQUENCE_NUMBER; + try { + JSONObject jsonMessage = new JSONObject(message); + int requestId = jsonMessage.getInt("requestId"); + if (mSession.mRequests.indexOfKey(requestId) >= 0) { + sequenceNumber = mSession.mRequests.get(requestId); + mSession.mRequests.delete(requestId); + } + } catch (JSONException e) { + } finally { + mSession.onMessage("v2_message", message, namespace, sequenceNumber); + } } else { mSession.onAppMessage(namespace, message); } @@ -131,10 +152,12 @@ private String mSessionId; private String mApplicationStatus; private ApplicationMetadata mApplicationMetadata; - private int mSequenceNumber; private boolean mStoppingApplication; private boolean mDetached; private MediaNotificationInfo.Builder mNotificationBuilder; + private RemoteMediaPlayer mMediaPlayer; + + private SparseIntArray mRequests; /** * Initializes a new {@link CastRouteController} instance. @@ -167,15 +190,40 @@ mApplicationMetadata = metadata; mApplicationStatus = applicationStatus; mCastDevice = castDevice; + mRequests = new SparseIntArray(); mMessageChannel = new CastMessagingChannel(this); addNamespace(RECEIVER_NAMESPACE); addNamespace(MEDIA_NAMESPACE); - Context context = ApplicationStatus.getApplicationContext(); + final Context context = ApplicationStatus.getApplicationContext(); + + if (mNamespaces.contains(MEDIA_NAMESPACE)) { + mMediaPlayer = new RemoteMediaPlayer(); + mMediaPlayer.setOnStatusUpdatedListener( + new RemoteMediaPlayer.OnStatusUpdatedListener() { + @Override + public void onStatusUpdated() { + MediaStatus mediaStatus = mMediaPlayer.getMediaStatus(); + if (mediaStatus == null) return; + + int playerState = mediaStatus.getPlayerState(); + if (playerState == MediaStatus.PLAYER_STATE_PAUSED + || playerState == MediaStatus.PLAYER_STATE_PLAYING) { + mNotificationBuilder.setPaused( + playerState != MediaStatus.PLAYER_STATE_PLAYING); + mNotificationBuilder.setActions(MediaNotificationInfo.ACTION_STOP + | MediaNotificationInfo.ACTION_PLAY_PAUSE); + } else { + mNotificationBuilder.setActions(MediaNotificationInfo.ACTION_STOP); + } + MediaNotificationManager.show(context, mNotificationBuilder); + } + }); + } + mNotificationBuilder = new MediaNotificationInfo.Builder() - .setTitle(context.getString( - R.string.cast_casting_video, mCastDevice.getFriendlyName())) + .setTitle(mCastDevice.getFriendlyName()) .setPaused(false) .setOrigin(origin) .setTabId(tabId) @@ -193,7 +241,7 @@ sMediaOverloadedMessageTypes = new HashMap<String, String>(); sMediaOverloadedMessageTypes.put("STOP_MEDIA", "STOP"); sMediaOverloadedMessageTypes.put("MEDIA_SET_VOLUME", "SET_VOLUME"); - sMediaOverloadedMessageTypes.put("MEDIA_GET_STATUS", "MEDIA_STATUS"); + sMediaOverloadedMessageTypes.put("MEDIA_GET_STATUS", "GET_STATUS"); } } } @@ -217,37 +265,7 @@ @Override public void close() { - if (mStoppingApplication) return; - - if (isApiClientInvalid()) return; - - mStoppingApplication = true; - Cast.CastApi.stopApplication(mApiClient, mSessionId) - .setResultCallback(new ResultCallback<Status>() { - @Override - public void onResult(Status status) { - onMessage("remove_session", mSessionId); - // TODO(avayvod): handle a failure to stop the application. - // https://crbug.com/535577 - - for (String namespace : mNamespaces) unregisterNamespace(namespace); - mNamespaces.clear(); - - mClients.clear(); - mSessionId = null; - mApiClient = null; - - mRouteDelegate.onRouteClosed(CastRouteController.this); - mStoppingApplication = false; - - // The detached route will be closed only if another route joined - // the same session so it will take over the notification. - if (!mDetached) { - MediaNotificationManager.hide( - mTabId, R.id.presentation_notification); - } - } - }); + stopApplication(INVALID_SEQUENCE_NUMBER); } @Override @@ -304,15 +322,21 @@ @Override public void onPlay(int actionSource) { + if (mMediaPlayer == null || isApiClientInvalid()) return; + + mMediaPlayer.play(mApiClient); } @Override public void onPause(int actionSource) { + if (mMediaPlayer == null || isApiClientInvalid()) return; + + mMediaPlayer.pause(mApiClient); } @Override public void onStop(int actionSource) { - close(); + stopApplication(INVALID_SEQUENCE_NUMBER); } @@ -320,13 +344,17 @@ * Sends the internal Cast message to the Cast clients on the page via the media router. * @param type The type of the message (e.g. "new_session" or "v2_message") * @param message The message itself (encoded JSON). + * @param namespace The namespace for the message. */ - public void onMessage(String type, String message) { + public void onMessage(String type, String message, String namespace, int sequenceNumber) { + if (MEDIA_NAMESPACE.equals(namespace) && mMediaPlayer != null) { + mMediaPlayer.onMessageReceived(mCastDevice, namespace, message); + } + for (String client : mClients) { mRouteDelegate.onMessage(mMediaRouteId, - buildInternalMessage(type, message, client, mSequenceNumber)); + buildInternalMessage(type, message, client, sequenceNumber)); } - mSequenceNumber++; } /** @@ -340,12 +368,47 @@ jsonMessage.put("sessionId", mSessionId); jsonMessage.put("namespaceName", namespace); jsonMessage.put("message", message); - onMessage("app_message", jsonMessage.toString()); + onMessage("app_message", jsonMessage.toString(), null, INVALID_SEQUENCE_NUMBER); } catch (JSONException e) { Log.e(TAG, "Failed to create the message wrapper", e); } } + private void stopApplication(final int sequenceNumber) { + if (mStoppingApplication) return; + + if (isApiClientInvalid()) return; + + mStoppingApplication = true; + Cast.CastApi.stopApplication(mApiClient, mSessionId) + .setResultCallback(new ResultCallback<Status>() { + @Override + public void onResult(Status status) { + onMessage("remove_session", mSessionId, null, sequenceNumber); + + // TODO(avayvod): handle a failure to stop the application. + // https://crbug.com/535577 + + for (String namespace : mNamespaces) unregisterNamespace(namespace); + mNamespaces.clear(); + + mClients.clear(); + mSessionId = null; + mApiClient = null; + + mRouteDelegate.onRouteClosed(CastRouteController.this); + mStoppingApplication = false; + + // The detached route will be closed only if another route joined + // the same session so it will take over the notification. + if (!mDetached) { + MediaNotificationManager.hide( + mTabId, R.id.presentation_notification); + } + } + }); + } + private void addNamespace(String namespace) { assert !mNamespaces.contains(namespace); @@ -393,6 +456,7 @@ return false; } } catch (JSONException e) { + Log.e(TAG, "JSONException while handling internal message: " + e); return false; } @@ -408,8 +472,8 @@ mClients.add(clientId); - mRouteDelegate.onMessage(mMediaRouteId, - buildInternalMessage("new_session", buildSessionMessage(), clientId, -1)); + mRouteDelegate.onMessage(mMediaRouteId, buildInternalMessage( + "new_session", buildSessionMessage(), clientId, INVALID_SEQUENCE_NUMBER)); return true; } @@ -435,19 +499,24 @@ JSONObject jsonCastMessage = jsonMessage.getJSONObject("message"); String messageType = jsonCastMessage.getString("type"); - - if (sMediaOverloadedMessageTypes.containsKey(messageType)) { - messageType = sMediaOverloadedMessageTypes.get(messageType); - } + int sequenceNumber = jsonMessage.has("sequenceNumber") + ? jsonMessage.getInt("sequenceNumber") : OPTIONAL_SEQUENCE_NUMBER; if ("STOP".equals(messageType)) { - close(); + stopApplication(sequenceNumber); return true; - } else if (Arrays.asList(MEDIA_MESSAGE_TYPES).contains(messageType)) { - if ("SET_VOLUME".equals(messageType)) { - return handleVolumeMessage(jsonCastMessage.getJSONObject("volume")); + } + + if ("SET_VOLUME".equals(messageType)) { + return handleVolumeMessage(jsonCastMessage.getJSONObject("volume")); + } + + if (Arrays.asList(MEDIA_MESSAGE_TYPES).contains(messageType)) { + if (sMediaOverloadedMessageTypes.containsKey(messageType)) { + messageType = sMediaOverloadedMessageTypes.get(messageType); + jsonCastMessage.put("type", messageType); } - return sendCastMessage(jsonMessage.getJSONObject("message"), MEDIA_NAMESPACE); + return sendCastMessage(jsonCastMessage, MEDIA_NAMESPACE, sequenceNumber); } return true; @@ -507,20 +576,25 @@ if (namespaceName == null || namespaceName.isEmpty()) return false; if (!mNamespaces.contains(namespaceName)) addNamespace(namespaceName); - sendCastMessage(jsonAppMessageWrapper, namespaceName); + sendCastMessage(jsonAppMessageWrapper, namespaceName, INVALID_SEQUENCE_NUMBER); return true; } - private boolean sendCastMessage(JSONObject message, String namespace) throws JSONException { + private boolean sendCastMessage(JSONObject message, String namespace, int sequenceNumber) + throws JSONException { if (isApiClientInvalid()) return false; removeNullFields(message); - // We must have a requestId so 0 is used unless there is one already. - // TODO(mlamouri): pass a random requestId if none is present, - // See: https://crbug.com/548822 - if (!message.has("requestId")) message.put("requestId", 0); + // If for some reason, there is already a requestId different than 0, it + // is kept. Otherwise, one is generated and associated with the sequenceNumber + // passed by the client. + if (!message.has("requestId") || (message.getInt("requestId") == 0)) { + int requestId = CastRequestIdGenerator.getNextRequestId(); + mRequests.append(requestId, sequenceNumber); + message.put("requestId", requestId); + } Log.d(TAG, "Sending message to Cast device: " + message); @@ -604,7 +678,8 @@ for (String clientId : mClients) { mRouteDelegate.onMessage(mMediaRouteId, buildInternalMessage( - "update_session", buildSessionMessage(), clientId, -1)); + "update_session", buildSessionMessage(), clientId, + INVALID_SEQUENCE_NUMBER)); } } catch (IllegalStateException e) { Log.e(TAG, "Can't get application status", e);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/media/ui/MediaNotificationManager.java b/chrome/android/java/src/org/chromium/chrome/browser/media/ui/MediaNotificationManager.java index 0cd447e..2c71d30 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/media/ui/MediaNotificationManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/media/ui/MediaNotificationManager.java
@@ -254,8 +254,8 @@ private ListenerService mService; private final String mPlayDescription; - private final String mPauseDescription; + private final String mStopDescription; private NotificationCompat.Builder mNotificationBuilder; @@ -292,6 +292,7 @@ mContext = context; mPlayDescription = context.getResources().getString(R.string.accessibility_play); mPauseDescription = context.getResources().getString(R.string.accessibility_pause); + mStopDescription = context.getResources().getString(R.string.accessibility_stop); // The MediaSession icon is a plain color. int size = context.getResources().getDimensionPixelSize(R.dimen.media_session_icon_size); @@ -388,14 +389,19 @@ RemoteViews contentView = new RemoteViews(mContext.getPackageName(), R.layout.playback_notification_bar); + // By default, play/pause button is the only one. + int playPauseButtonId = R.id.button1; // On Android pre-L, dismissing the notification when the service is no longer in foreground // doesn't work. Instead, a STOP button is shown. if (mMediaNotificationInfo.supportsSwipeAway() && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP || mMediaNotificationInfo.supportsStop()) { - contentView.setViewVisibility(R.id.stop, View.VISIBLE); - contentView.setOnClickPendingIntent(R.id.stop, + contentView.setOnClickPendingIntent(R.id.button1, mService.getPendingIntent(ListenerService.ACTION_STOP)); + contentView.setContentDescription(R.id.button1, mStopDescription); + + // If the play/pause needs to be shown, it moves over to the second button from the end. + playPauseButtonId = R.id.button2; } contentView.setTextViewText(R.id.title, mMediaNotificationInfo.title); @@ -408,23 +414,21 @@ if (mMediaNotificationInfo.supportsPlayPause()) { if (mMediaNotificationInfo.isPaused) { - contentView.setImageViewResource(R.id.playpause, R.drawable.ic_vidcontrol_play); - contentView.setContentDescription(R.id.playpause, mPlayDescription); - contentView.setOnClickPendingIntent(R.id.playpause, + contentView.setImageViewResource(playPauseButtonId, R.drawable.ic_vidcontrol_play); + contentView.setContentDescription(playPauseButtonId, mPlayDescription); + contentView.setOnClickPendingIntent(playPauseButtonId, mService.getPendingIntent(ListenerService.ACTION_PLAY)); } else { // If we're here, the notification supports play/pause button and is playing. - contentView.setImageViewResource(R.id.playpause, R.drawable.ic_vidcontrol_pause); - contentView.setContentDescription(R.id.playpause, mPauseDescription); - contentView.setOnClickPendingIntent(R.id.playpause, + contentView.setImageViewResource(playPauseButtonId, R.drawable.ic_vidcontrol_pause); + contentView.setContentDescription(playPauseButtonId, mPauseDescription); + contentView.setOnClickPendingIntent(playPauseButtonId, mService.getPendingIntent(ListenerService.ACTION_PAUSE)); } - // Even though we create the new view everytime, Android seems to remember the last - // visibility state rather than use the default one. So set it explicitly. - contentView.setViewVisibility(R.id.playpause, View.VISIBLE); + contentView.setViewVisibility(playPauseButtonId, View.VISIBLE); } else { - contentView.setViewVisibility(R.id.playpause, View.GONE); + contentView.setViewVisibility(playPauseButtonId, View.GONE); } return contentView;
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 828718ef..d0d5406f 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
@@ -18,13 +18,10 @@ import android.view.View; import org.chromium.base.ApiCompatibilityUtils; -import org.chromium.base.CommandLine; -import org.chromium.base.FieldTrialList; import org.chromium.base.VisibleForTesting; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.RecordUserAction; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.NativePage; import org.chromium.chrome.browser.UrlConstants; import org.chromium.chrome.browser.compositor.layouts.content.InvalidationAwareThumbnailProvider; @@ -69,9 +66,6 @@ public class NewTabPage implements NativePage, InvalidationAwareThumbnailProvider, TemplateUrlServiceObserver { - private static final String ICON_NTP_FIELD_TRIAL_NAME = "IconNTP"; - private static final String ICON_NTP_ENABLED_PREFIX = "Enabled"; - // The number of times that the document-mode opt-out promo will be shown. private static final int MAX_OPT_OUT_PROMO_COUNT = 10; @@ -446,7 +440,8 @@ LayoutInflater inflater = LayoutInflater.from(activity); mNewTabPageView = (NewTabPageView) inflater.inflate(R.layout.new_tab_page, null); - mIsIconMode = isIconNtpEnabled(); + // TODO(newt): delete thumbnail mode once we're sure that icon mode has stuck for good. + mIsIconMode = true; mNewTabPageView.initialize(mNewTabPageManager, isInSingleUrlBarMode(activity), mSearchProviderHasLogo, mIsIconMode); @@ -462,15 +457,6 @@ } } - private boolean isIconNtpEnabled() { - // Query the field trial state first, to ensure that UMA reports the correct group. - String fieldTrialGroup = FieldTrialList.findFullName(ICON_NTP_FIELD_TRIAL_NAME); - CommandLine commandLine = CommandLine.getInstance(); - if (commandLine.hasSwitch(ChromeSwitches.DISABLE_ICON_NTP)) return false; - if (commandLine.hasSwitch(ChromeSwitches.ENABLE_ICON_NTP)) return true; - return fieldTrialGroup.startsWith(ICON_NTP_ENABLED_PREFIX); - } - /** @return The view container for the new tab page. */ @VisibleForTesting NewTabPageView getNewTabPageView() {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/Tab.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/Tab.java index 2edc697..fed11c88 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/Tab.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/Tab.java
@@ -15,6 +15,7 @@ import android.provider.Browser; import android.text.TextUtils; import android.util.Log; +import android.view.ContextThemeWrapper; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; @@ -135,7 +136,7 @@ /** * The {@link Activity} used to create {@link View}s and other Android components. Unlike - * {@link #mApplicationContext}, this is not publicly exposed to help prevent leaking the + * {@link #mThemedApplicationContext}, this is not publicly exposed to help prevent leaking the * {@link Activity}. */ protected final ChromeActivity mActivity; @@ -152,7 +153,7 @@ * An Application {@link Context}. Unlike {@link #mActivity}, this is the only one that is * publicly exposed to help prevent leaking the {@link Activity}. */ - private final Context mApplicationContext; + private final Context mThemedApplicationContext; /** Gives {@link Tab} a way to interact with the Android window. */ private final WindowAndroid mWindowAndroid; @@ -543,11 +544,12 @@ mParentId = parentId; mIncognito = incognito; mActivity = activity; - mApplicationContext = activity != null ? activity.getApplicationContext() : null; + mThemedApplicationContext = activity != null ? new ContextThemeWrapper( + activity.getApplicationContext(), ChromeActivity.getThemeId()) : null; mWindowAndroid = window; mLaunchType = type; - if (mActivity != null) { - Resources resources = mActivity.getResources(); + if (mThemedApplicationContext != null) { + Resources resources = mThemedApplicationContext.getResources(); mIdealFaviconSize = resources.getDimensionPixelSize(R.dimen.default_favicon_size); mDefaultThemeColor = mIncognito ? ApiCompatibilityUtils.getColor(resources, R.color.incognito_primary_color) @@ -805,7 +807,7 @@ * @return The application {@link Context} associated with this tab. */ protected Context getApplicationContext() { - return mApplicationContext; + return mThemedApplicationContext.getApplicationContext(); } /** @@ -1480,9 +1482,9 @@ * {@link ContentViewCore}. */ protected void initContentViewCore(WebContents webContents) { - ContentViewCore cvc = new ContentViewCore(mActivity); - ContentView cv = ContentView.createContentView(mActivity, cvc); - cv.setContentDescription(mActivity.getResources().getString( + ContentViewCore cvc = new ContentViewCore(mThemedApplicationContext); + ContentView cv = ContentView.createContentView(mThemedApplicationContext, cvc); + cv.setContentDescription(mThemedApplicationContext.getResources().getString( R.string.accessibility_content_view)); cvc.initialize(cv, cv, webContents, getWindowAndroid()); setContentViewCore(cvc); @@ -1518,7 +1520,7 @@ assert false; mContentViewParent.removeAllViews(); } - mContentViewParent = new FrameLayout(mActivity); + mContentViewParent = new FrameLayout(mThemedApplicationContext); mContentViewParent.addView(cvc.getContainerView(), new FrameLayout.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); @@ -1542,14 +1544,14 @@ if (mInfoBarContainer == null) { // The InfoBarContainer needs to be created after the ContentView has been natively // initialized. - mInfoBarContainer = - new InfoBarContainer(mActivity, getId(), mContentViewParent, this); + mInfoBarContainer = new InfoBarContainer( + mThemedApplicationContext, getId(), mContentViewParent, this); } else { mInfoBarContainer.onParentViewChanged(getId(), mContentViewParent); } mInfoBarContainer.setContentViewCore(mContentViewCore); - mSwipeRefreshHandler = new SwipeRefreshHandler(mActivity); + mSwipeRefreshHandler = new SwipeRefreshHandler(mThemedApplicationContext); mSwipeRefreshHandler.setContentViewCore(mContentViewCore); for (TabObserver observer : mObservers) observer.onContentChanged(this); @@ -1559,7 +1561,7 @@ // web views. mContentViewCore.setShouldSetAccessibilityFocusOnPageLoad(true); - mDownloadDelegate = new ChromeDownloadDelegate(mActivity, + mDownloadDelegate = new ChromeDownloadDelegate(mThemedApplicationContext, mActivity.getTabModelSelector(), this); cvc.setDownloadDelegate(mDownloadDelegate); @@ -1641,7 +1643,7 @@ // Make sure we are not adding the "Aw, snap" view over an existing one. assert mSadTabView == null; mSadTabView = SadTabViewFactory.createSadTabView( - mActivity, suggestionAction, reloadButtonAction); + mThemedApplicationContext, suggestionAction, reloadButtonAction); // Show the sad tab inside ContentView. getContentViewCore().getContainerView().addView( @@ -2138,9 +2140,9 @@ @CalledByNative public void swapWebContents( WebContents webContents, boolean didStartLoad, boolean didFinishLoad) { - ContentViewCore cvc = new ContentViewCore(mActivity); - ContentView cv = ContentView.createContentView(mActivity, cvc); - cv.setContentDescription(mActivity.getResources().getString( + ContentViewCore cvc = new ContentViewCore(mThemedApplicationContext); + ContentView cv = ContentView.createContentView(mThemedApplicationContext, cvc); + cv.setContentDescription(mThemedApplicationContext.getResources().getString( R.string.accessibility_content_view)); cvc.initialize(cv, cv, webContents, getWindowAndroid()); swapContentViewCore(cvc, false, didStartLoad, didFinishLoad);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabWebContentsObserver.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabWebContentsObserver.java index 46fbb7d6..800506d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabWebContentsObserver.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabWebContentsObserver.java
@@ -4,6 +4,7 @@ package org.chromium.chrome.browser.tab; +import android.content.Context; import android.graphics.Color; import android.view.View; @@ -27,6 +28,7 @@ import org.chromium.chrome.browser.util.FeatureUtilities; import org.chromium.content_public.browser.WebContents; import org.chromium.content_public.browser.WebContentsObserver; +import org.chromium.ui.base.DeviceFormFactor; import java.util.concurrent.TimeUnit; @@ -227,7 +229,7 @@ } if (mTab.isShowingInterstitialPage()) color = mTab.getDefaultThemeColor(); if (!FeatureUtilities.isDocumentMode(mTab.getApplicationContext()) - && !isThemeColorEnabledInTabbedMode()) { + && !isThemeColorEnabledInTabbedMode(mTab.getApplicationContext())) { color = mTab.getDefaultThemeColor(); } if (color == Color.TRANSPARENT) color = mTab.getDefaultThemeColor(); @@ -300,9 +302,12 @@ return mThemeColor; } - private static boolean isThemeColorEnabledInTabbedMode() { + private static boolean isThemeColorEnabledInTabbedMode(Context context) { + if (DeviceFormFactor.isTablet(context)) return false; CommandLine commandLine = CommandLine.getInstance(); return ChromeVersionInfo.isLocalBuild() + || ChromeVersionInfo.isCanaryBuild() + || ChromeVersionInfo.isDevBuild() || commandLine.hasSwitch(ChromeSwitches.ENABLE_THEME_COLOR_IN_TABBED_MODE); } } \ No newline at end of file
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchFakeServer.java b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchFakeServer.java index de6f1c71..2cbed01 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchFakeServer.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchFakeServer.java
@@ -10,9 +10,14 @@ import org.chromium.chrome.browser.compositor.bottombar.OverlayContentProgressObserver; import org.chromium.chrome.browser.compositor.bottombar.OverlayPanelContent; import org.chromium.chrome.browser.compositor.bottombar.OverlayPanelContentFactory; +import org.chromium.content.browser.ContentViewCore; import java.net.MalformedURLException; import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeoutException; import javax.annotation.Nullable; @@ -26,28 +31,316 @@ class ContextualSearchFakeServer implements ContextualSearchNetworkCommunicator, OverlayPanelContentFactory { + private final ContextualSearchPolicy mPolicy; + + private final ContextualSearchManagerTest mManagerTest; private final ContextualSearchNetworkCommunicator mBaseManager; private final OverlayContentDelegate mContentDelegate; private final OverlayContentProgressObserver mProgressObserver; private final ChromeActivity mActivity; - private OverlayPanelContent mContent; + private final ArrayList<String> mRemovedUrls = new ArrayList<String>(); + + private final Map<String, FakeTapSearch> mFakeTapSearches = new HashMap<>(); + private final Map<String, FakeLongPressSearch> mFakeLongPressSearches = new HashMap<>(); + + private FakeTapSearch mActiveFakeTapSearch; private String mLoadedUrl; private int mLoadedUrlCount; + private String mSearchTermRequested; private boolean mShouldUseHttps; + private boolean mDidEverCallContentViewCoreOnShow; + + //============================================================================================ + // FakeSearch + //============================================================================================ + + /** + * Abstract class that represents a fake contextual search. + */ + public abstract class FakeSearch { + private final String mNodeId; + + /** + * @param nodeId The id of the node where the touch event will be simulated. + */ + FakeSearch(String nodeId) { + mNodeId = nodeId; + } + + /** + * Simulates a fake search. + * + * @throws InterruptedException + * @throws TimeoutException + */ + public abstract void simulate() throws InterruptedException, TimeoutException; + + /** + * @return The search term that will be used in the contextual search. + */ + public abstract String getSearchTerm(); + + /** + * @return The id of the node where the touch event will be simulated. + */ + public String getNodeId() { + return mNodeId; + } + } + + //============================================================================================ + // FakeLongPressSearch + //============================================================================================ + + /** + * Class that represents a fake long-press triggered contextual search. + */ + public class FakeLongPressSearch extends FakeSearch { + private final String mSearchTerm; + + /** + * @param nodeId The id of the node where the touch event will be simulated. + * @param searchTerm The expected text that the node should contain. + */ + FakeLongPressSearch(String nodeId, String searchTerm) { + super(nodeId); + + mSearchTerm = searchTerm; + } + + @Override + public void simulate() throws InterruptedException, TimeoutException { + mManagerTest.longPressNode(getNodeId()); + mManagerTest.waitForSelectionToBe(mSearchTerm); + } + + @Override + public String getSearchTerm() { + return mSearchTerm; + } + } + + //============================================================================================ + // FakeTapSearch + //============================================================================================ + + /** + * Class that represents a fake tap triggered contextual search. + */ + public class FakeTapSearch extends FakeSearch { + private final boolean mIsNetworkUnavailable; + private final int mResponseCode; + private final String mSearchTerm; + private final String mDisplayText; + private final String mAlternateTerm; + private final boolean mDoPreventPreload; + private final int mStartAdjust; + private final int mEndAdjust; + + boolean mDidStartResolution; + boolean mDidFinishResolution; + + /** + * @param nodeId The id of the node where the touch event will be simulated. + * @param isNetworkUnavailable Whether the network is unavailable. + * @param responseCode The HTTP response code of the resolution. + * @param searchTerm The resolved search term. + * @param displayText The display text. + * @param alternateTerm The alternate text. + * @param doPreventPreload Whether search preload should be prevented. + * @param startAdjust The start adjustment of the selection. + * @param endAdjudst The end adjustment of the selection. + */ + FakeTapSearch(String nodeId, boolean isNetworkUnavailable, int responseCode, + String searchTerm, String displayText, String alternateTerm, + boolean doPreventPreload, int startAdjust, int endAdjudst) { + super(nodeId); + + mIsNetworkUnavailable = isNetworkUnavailable; + mResponseCode = responseCode; + mSearchTerm = searchTerm; + mDisplayText = displayText; + mAlternateTerm = alternateTerm; + mDoPreventPreload = doPreventPreload; + mStartAdjust = startAdjust; + mEndAdjust = endAdjudst; + } + + @Override + public void simulate() throws InterruptedException, TimeoutException { + mActiveFakeTapSearch = this; + + // When a resolution is needed, the simulation does not start until the system + // requests one, and it does not finish until the simulated resolution happens. + mDidStartResolution = false; + mDidFinishResolution = false; + + mManagerTest.clickNode(getNodeId()); + mManagerTest.waitForSelectionToBe(mSearchTerm); + + if (mPolicy.shouldPreviousTapResolve(getBasePageUrl())) { + // Now wait for the Search Term Resolution to start. + mManagerTest.waitForSearchTermResolutionToStart(this); + + // Simulate a Search Term Resolution. + simulateSearchTermResolution(); + + // Now wait for the simulated Search Term Resolution to finish. + mManagerTest.waitForSearchTermResolutionToFinish(this); + } else { + mDidFinishResolution = true; + } + } + + @Override + public String getSearchTerm() { + return mSearchTerm; + } + + /** + * Notifies that a Search Term Resolution has started. + */ + public void notifySearchTermResolutionStarted() { + mDidStartResolution = true; + } + + /** + * @return Whether the Search Term Resolution has started. + */ + public boolean didStartSearchTermResolution() { + return mDidStartResolution; + } + + /** + * @return Whether the Search Term Resolution has finished. + */ + public boolean didFinishSearchTermResolution() { + return mDidFinishResolution; + } + + /** + * Simulates a Search Term Resolution. + */ + private void simulateSearchTermResolution() throws InterruptedException, TimeoutException { + mManagerTest.runOnMainSync(getRunnable()); + } + + /** + * @return A Runnable to handle the fake Search Term Resolution. + */ + private Runnable getRunnable() { + return new Runnable() { + @Override + public void run() { + if (!mDidFinishResolution) { + handleSearchTermResolutionResponse( + mIsNetworkUnavailable, mResponseCode, mSearchTerm, mDisplayText, + mAlternateTerm, mDoPreventPreload, mStartAdjust, mEndAdjust); + + mActiveFakeTapSearch = null; + mDidFinishResolution = true; + } + } + }; + } + } + + //============================================================================================ + // OverlayPanelContentWrapper + //============================================================================================ + + /** + * A wrapper around OverlayPanelContent to be used during tests. + */ + public class OverlayPanelContentWrapper extends OverlayPanelContent { + OverlayPanelContentWrapper(OverlayContentDelegate contentDelegate, + OverlayContentProgressObserver progressObserver, ChromeActivity activity) { + super(contentDelegate, progressObserver, activity); + } + + @Override + public void loadUrl(String url) { + mLoadedUrl = url; + mLoadedUrlCount++; + super.loadUrl(url); + } + + @Override + public void removeLastHistoryEntry(String url, long timeInMs) { + // Override to prevent call to native code. + mRemovedUrls.add(url); + } + + @Override + protected ContentViewCore createContentViewCore(ChromeActivity activity) { + return new ContentViewCoreWrapper(activity); + } + } + + //============================================================================================ + // ContentViewCoreWrapper + //============================================================================================ + + /** + * A wrapper around ContentViewCore to be used during tests. + */ + public class ContentViewCoreWrapper extends ContentViewCore { + private boolean mIsVisible; + + ContentViewCoreWrapper(ChromeActivity activity) { + super(activity); + } + + @Override + public void destroy() { + super.destroy(); + mIsVisible = false; + } + + @Override + public void onShow() { + super.onShow(); + mIsVisible = true; + mDidEverCallContentViewCoreOnShow = true; + } + + @Override + public void onHide() { + super.onHide(); + mIsVisible = false; + } + + /** + * @return Whether the ContentViewCore is visible. + */ + public boolean isVisible() { + return mIsVisible; + } + } + + //============================================================================================ + // ContextualSearchFakeServer + //============================================================================================ + /** * Constructs a fake Contextual Search server that will callback to the given baseManager. * @param baseManager The manager to call back to for server responses. */ @VisibleForTesting - ContextualSearchFakeServer(ContextualSearchNetworkCommunicator baseManager, + ContextualSearchFakeServer(ContextualSearchPolicy policy, + ContextualSearchManagerTest managerTest, + ContextualSearchNetworkCommunicator baseManager, OverlayContentDelegate contentDelegate, OverlayContentProgressObserver progressObserver, ChromeActivity activity) { + mPolicy = policy; + + mManagerTest = managerTest; mBaseManager = baseManager; mContentDelegate = contentDelegate; @@ -57,32 +350,84 @@ @Override public OverlayPanelContent createNewOverlayPanelContent() { - mContent = new OverlayPanelContent(mContentDelegate, mProgressObserver, mActivity) { - @Override - public void loadUrl(String url) { - mLoadedUrl = url; - mLoadedUrlCount++; - super.loadUrl(url); - } - - @Override - public void removeLastHistoryEntry(String url, long timeInMs) { - // Override to prevent call to native code. - } - }; - - return mContent; + return new OverlayPanelContentWrapper(mContentDelegate, mProgressObserver, mActivity); } + /** + * @return The search term requested, or {@code null} if no search term was requested. + */ @VisibleForTesting - public boolean didCreateContentView() { - return mContent != null ? mContent.didCreateContentView() : false; + String getSearchTermRequested() { + return mSearchTermRequested; } + /** + * @return the loaded search result page URL if any was requested. + */ + @VisibleForTesting + String getLoadedUrl() { + return mLoadedUrl; + } + + /** + * @return The number of times we loaded a URL in the Content View. + */ + @VisibleForTesting + int getLoadedUrlCount() { + return mLoadedUrlCount; + } + + /** + * Sets whether to return an HTTPS URL instead of HTTP, from {@link #getBasePageUrl}. + */ + @VisibleForTesting + void setShouldUseHttps(boolean setting) { + mShouldUseHttps = setting; + } + + /** + * @return + */ + @VisibleForTesting + boolean didEverCallContentViewCoreOnShow() { + return mDidEverCallContentViewCoreOnShow; + } + + /** + * Resets the fake server's member data. + */ + @VisibleForTesting + void reset() { + mLoadedUrl = null; + mSearchTermRequested = null; + mShouldUseHttps = false; + mLoadedUrlCount = 0; + } + + //============================================================================================ + // History Removal Helpers + //============================================================================================ + + /** + * @param url The URL to be checked. + * @return Whether the given URL was removed from history. + */ + public boolean hasRemovedUrl(String url) { + return mRemovedUrls.contains(url); + } + + //============================================================================================ + // ContextualSearchNetworkCommunicator + //============================================================================================ + @Override public void startSearchTermResolutionRequest(String selection) { mLoadedUrl = null; mSearchTermRequested = selection; + + if (mActiveFakeTapSearch != null) { + mActiveFakeTapSearch.notifySearchTermResolutionStarted(); + } } @Override @@ -108,47 +453,58 @@ return baseUrl; } + //============================================================================================ + // Fake Searches Helpers + //============================================================================================ + /** - * @return The search term requested, or {@code null} if no search term was requested. + * Register fake searches that can be used in tests. Each fake search takes a node ID, which + * represents the DOM node that will be touched. The node ID is also used as an ID for the + * fake search of a given type (LongPress or Tap). This means that if you need different + * behaviors you need to add new DOM nodes with different IDs in the test's HTML file. */ - @VisibleForTesting - String getSearchTermRequested() { - return mSearchTermRequested; + public void registerFakeSearches() { + registerFakeLongPressSearch(new FakeLongPressSearch("search", "Search")); + registerFakeLongPressSearch(new FakeLongPressSearch("term", "Term")); + registerFakeLongPressSearch(new FakeLongPressSearch("resolution", "Resolution")); + + registerFakeTapSearch(new FakeTapSearch("search", false, 200, + "Search", "Search", "alternate-term", false, 0, 0)); + registerFakeTapSearch(new FakeTapSearch("term", false, 200, + "Term", "Term", "alternate-term", false, 0, 0)); + registerFakeTapSearch(new FakeTapSearch("resolution", false, 200, + "Resolution", "Resolution", "alternate-term", false, 0, 0)); } /** - * @return the loaded search result page URL if any was requested. + * @param id The ID of the FakeLongPressSearch. + * @return The FakeLongPressSearch with the given ID. */ - @VisibleForTesting - String getLoadedUrl() { - return mLoadedUrl; + public FakeLongPressSearch getFakeLongPressSearch(String id) { + return mFakeLongPressSearches.get(id); } /** - * @return The number of times we loaded a URL in the Content View. + * @param id The ID of the FakeTapSearch. + * @return The FakeTapSearch with the given ID. */ - @VisibleForTesting - int loadedUrlCount() { - return mLoadedUrlCount; + public FakeTapSearch getFakeTapSearch(String id) { + return mFakeTapSearches.get(id); } /** - * Sets whether to return an HTTPS URL instead of HTTP, from {@link #getBasePageUrl}. + * Register the FakeLongPressSearch. + * @param fakeSearch The FakeLongPressSearch to be registered. */ - @VisibleForTesting - void setShouldUseHttps(boolean setting) { - mShouldUseHttps = setting; + private void registerFakeLongPressSearch(FakeLongPressSearch fakeSearch) { + mFakeLongPressSearches.put(fakeSearch.getNodeId(), fakeSearch); } /** - * Resets the fake server's member data. + * Register the FakeTapSearch. + * @param fakeSearch The FakeTapSearch to be registered. */ - @VisibleForTesting - void reset() { - mContent = null; - mLoadedUrl = null; - mSearchTermRequested = null; - mShouldUseHttps = false; - mLoadedUrlCount = 0; + private void registerFakeTapSearch(FakeTapSearch fakeSearch) { + mFakeTapSearches.put(fakeSearch.getNodeId(), fakeSearch); } }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java index 0dc28a8..8b8290a 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java
@@ -61,7 +61,12 @@ import java.util.concurrent.TimeoutException; -// TODO(pedrosimonetti): add tests for recent regressions crbug.com/543319. +// TODO(pedrosimonetti): Create class with limited API to encapsulate the internals of simulations. +// TODO(pedrosimonetti): Separate tests into different classes grouped by type of tests. Examples: +// Gestures (Tap, LongPress), Search Term Resolution (resolves, expand selection, prevent preload, +// translation), Panel interaction (tap, fling up/down, close), Content (creation, loading, +// visibility, history, delayed load), Tab Promotion, Policy (add tests to check if policies +// affect the behavior correctly), General (remaining tests), etc. /** * Tests the Contextual Search Manager using instrumentation tests. @@ -98,18 +103,24 @@ if (mManager != null) { mPanel = mManager.getContextualSearchPanel(); - mFakeServer = new ContextualSearchFakeServer(mManager, + + mSelectionController = mManager.getSelectionController(); + mPolicy = ContextualSearchPolicy.getInstance(getActivity()); + mPolicy.overrideDecidedStateForTesting(true); + resetCounters(); + + mFakeServer = new ContextualSearchFakeServer( + mPolicy, + this, + mManager, mManager.getOverlayContentDelegate(), new OverlayContentProgressObserver(), getActivity()); mPanel.setOverlayPanelContentFactory(mFakeServer); mManager.setNetworkCommunicator(mFakeServer); - mSelectionController = mManager.getSelectionController(); - mPolicy = ContextualSearchPolicy.getInstance(getActivity()); - mPolicy.overrideDecidedStateForTesting(true); - resetCounters(); + registerFakeSearches(); } IntentFilter filter = new IntentFilter(Intent.ACTION_VIEW); @@ -119,64 +130,132 @@ filter, new Instrumentation.ActivityResult(Activity.RESULT_OK, null), true); } - @Override - public void startMainActivity() throws InterruptedException { - startMainActivityWithURL(TEST_PAGE); + //============================================================================================ + // Public API + //============================================================================================ + + /** + * Simulates a long-press on the given node. + * @param nodeId A string containing the node ID. + */ + public void longPressNode(String nodeId) throws InterruptedException, TimeoutException { + Tab tab = getActivity().getActivityTab(); + DOMUtils.longPressNode(this, tab.getContentViewCore(), nodeId); + waitForPanelToPeekAndAssert(); } /** * Simulates a click on the given node. * @param nodeId A string containing the node ID. */ - private void clickNode(String nodeId) throws InterruptedException, TimeoutException { + public void clickNode(String nodeId) throws InterruptedException, TimeoutException { Tab tab = getActivity().getActivityTab(); DOMUtils.clickNode(this, tab.getContentViewCore(), nodeId); } /** - * Simulates a click on the given word node. - * Waits for the bar to peek. - * @param nodeId A string containing the node ID. + * Waits for the selected text string to be the given string, and asserts. + * @param text The string to wait for the selection to become. */ - private void clickWordNode(String nodeId) throws InterruptedException, TimeoutException { - clickNode(nodeId); + public void waitForSelectionToBe(final String text) throws InterruptedException { + assertTrue("Bar never showed desired text.", + CriteriaHelper.pollForCriteria(new Criteria() { + @Override + public boolean isSatisfied() { + return TextUtils.equals(text, getSelectedText()); + } + }, TEST_TIMEOUT, DEFAULT_POLLING_INTERVAL)); + } + + /** + * Waits for the FakeTapSearch to become ready. + * @param search A given FakeTapSearch. + */ + public void waitForSearchTermResolutionToStart( + final ContextualSearchFakeServer.FakeTapSearch search) throws InterruptedException { + assertTrue("Fake Search Term Resolution never started.", + CriteriaHelper.pollForCriteria(new Criteria() { + @Override + public boolean isSatisfied() { + return search.didStartSearchTermResolution(); + } + }, TEST_TIMEOUT, DEFAULT_POLLING_INTERVAL)); + } + + /** + * Waits for the FakeTapSearch to become ready. + * @param search A given FakeTapSearch. + */ + public void waitForSearchTermResolutionToFinish( + final ContextualSearchFakeServer.FakeTapSearch search) throws InterruptedException { + assertTrue("Fake Search was never ready.", + CriteriaHelper.pollForCriteria(new Criteria() { + @Override + public boolean isSatisfied() { + return search.didFinishSearchTermResolution(); + } + }, TEST_TIMEOUT, DEFAULT_POLLING_INTERVAL)); + } + + /** + * Runs the given Runnable in the main thread. + * @param runnable The Runnable. + */ + public void runOnMainSync(Runnable runnable) { + getInstrumentation().runOnMainSync(runnable); + } + + @Override + public void startMainActivity() throws InterruptedException { + startMainActivityWithURL(TEST_PAGE); + } + + //============================================================================================ + // Fake Searches Helpers + //============================================================================================ + + /** + * Simulates a long-press triggered search. + * + * @param nodeId The id of the node to be long-pressed. + * @throws InterruptedException + * @throws TimeoutException + */ + private void simulateLongPressSearch(String nodeId) + throws InterruptedException, TimeoutException { + ContextualSearchFakeServer.FakeLongPressSearch search = + mFakeServer.getFakeLongPressSearch(nodeId); + search.simulate(); waitForPanelToPeekAndAssert(); } /** - * Simulates a key press. - * @param keycode The key's code. + * Simulates a tap triggered search. + * + * @param nodeId The id of the node to be tapped. + * @throws InterruptedException + * @throws TimeoutException */ - private void pressKey(int keycode) { - getInstrumentation().sendKeyDownUpSync(keycode); - getInstrumentation().waitForIdleSync(); - } - - /** - * Simulates pressing back button. - */ - private void pressBackButton() { - pressKey(KeyEvent.KEYCODE_BACK); - } - - /** - * @return The selected text. - */ - private String getSelectedText() { - return mSelectionController.getSelectedText(); - } - - /** - * Simulates a long-press on the given node. - * @param nodeId A string containing the node ID. - */ - private void longPressNode(String nodeId) throws InterruptedException, TimeoutException { - Tab tab = getActivity().getActivityTab(); - DOMUtils.longPressNode(this, tab.getContentViewCore(), nodeId); + private void simulateTapSearch(String nodeId) throws InterruptedException, TimeoutException { + ContextualSearchFakeServer.FakeTapSearch search = mFakeServer.getFakeTapSearch(nodeId); + search.simulate(); + assertLoadedSearchTermMatches(search.getSearchTerm()); waitForPanelToPeekAndAssert(); } /** + * Registers all fake searches to be used in tests. + */ + private void registerFakeSearches() { + mFakeServer.registerFakeSearches(); + } + + //============================================================================================ + // Fake Response + // TODO(pedrosimonetti): remove these methods and use the new infrastructure instead. + //============================================================================================ + + /** * Posts a fake response on the Main thread. */ private final class FakeResponseOnMainThread implements Runnable { @@ -191,8 +270,8 @@ private final int mEndAdjust; public FakeResponseOnMainThread(boolean isNetworkUnavailable, int responseCode, - String searchTerm, String displayText, String alternateTerm, - boolean doPreventPreload, int startAdjust, int endAdjudst) { + String searchTerm, String displayText, String alternateTerm, + boolean doPreventPreload, int startAdjust, int endAdjudst) { mIsNetworkUnavailable = isNetworkUnavailable; mResponseCode = responseCode; mSearchTerm = searchTerm; @@ -235,6 +314,147 @@ } } + //============================================================================================ + // Content Helpers + //============================================================================================ + + /** + * @return The Panel's ContentViewCore. + */ + private ContentViewCore getPanelContentViewCore() { + return mPanel.getContentViewCore(); + } + + /** + * @return Whether the Panel's ContentViewCore is visible. + */ + private boolean isContentViewCoreVisible() { + ContextualSearchFakeServer.ContentViewCoreWrapper contentViewCore = + (ContextualSearchFakeServer.ContentViewCoreWrapper) getPanelContentViewCore(); + return contentViewCore != null ? contentViewCore.isVisible() : false; + } + + /** + * Asserts that the Panel's ContentViewCore is created. + */ + private void assertContentViewCoreCreated() { + assertNotNull(getPanelContentViewCore()); + } + + /** + * Asserts that the Panel's ContentViewCore is not created. + */ + private void assertNoContentViewCore() { + assertNull(getPanelContentViewCore()); + } + + /** + * Asserts that the Panel's ContentViewCore is visible. + */ + private void assertContentViewCoreVisible() { + assertTrue(isContentViewCoreVisible()); + } + + /** + * Asserts that the Panel's ContentViewCore onShow() method was never called. + */ + private void assertNeverCalledContentViewCoreOnShow() { + assertFalse(mFakeServer.didEverCallContentViewCoreOnShow()); + } + + /** + * Asserts that the Panel's ContentViewCore is created + */ + private void assertContentViewCoreCreatedButNeverMadeVisible() { + assertContentViewCoreCreated(); + assertFalse(isContentViewCoreVisible()); + assertNeverCalledContentViewCoreOnShow(); + } + + /** + * Fakes navigation of the Content View to the URL was previously requested. + * @param isFailure whether the request resulted in a failure. + */ + private void fakeContentViewDidNavigate(boolean isFailure) { + String url = mFakeServer.getLoadedUrl(); + mManager.getOverlayContentDelegate().onMainFrameNavigation(url, isFailure); + } + + /** + * A ContentViewCore that has some methods stubbed out for testing. + * TODO(pedrosimonetti): consider using the real ContentViewCore instead. + */ + private static final class StubbedContentViewCore extends ContentViewCore { + private boolean mIsFocusedNodeEditable; + + public StubbedContentViewCore(Context context) { + super(context); + } + + /** + * Mocks the result of isFocusedNodeEditable() for testing. + * @param isFocusedNodeEditable Whether the focused node is editable. + */ + public void setIsFocusedNodeEditableForTest(boolean isFocusedNodeEditable) { + mIsFocusedNodeEditable = isFocusedNodeEditable; + } + + @Override + public boolean isFocusedNodeEditable() { + return mIsFocusedNodeEditable; + } + } + + //============================================================================================ + // Other Helpers + // TODO(pedrosimonetti): organize into sections. + //============================================================================================ + + /** + * Simulates a click on the given word node. + * Waits for the bar to peek. + * @param nodeId A string containing the node ID. + */ + private void clickWordNode(String nodeId) throws InterruptedException, TimeoutException { + clickNode(nodeId); + waitForPanelToPeekAndAssert(); + } + + /** + * Simulates a key press. + * @param keycode The key's code. + */ + private void pressKey(int keycode) { + getInstrumentation().sendKeyDownUpSync(keycode); + getInstrumentation().waitForIdleSync(); + } + + /** + * Simulates pressing back button. + */ + private void pressBackButton() { + pressKey(KeyEvent.KEYCODE_BACK); + } + + /** + * @return The selected text. + */ + private String getSelectedText() { + return mSelectionController.getSelectedText(); + } + + /** + * Asserts that the loaded search term matches the provided value. + * @param searchTerm The provided search term. + */ + private void assertLoadedSearchTermMatches(String searchTerm) { + boolean doesMatch = false; + if (mFakeServer != null) { + doesMatch = mFakeServer.getLoadedUrl().contains("q=" + searchTerm); + } + assertTrue(doesMatch); + } + private void assertContainsParameters(String searchTerm, String alternateTerm) { assertTrue(mFakeServer == null || mFakeServer.getSearchTermRequested() == null || mFakeServer.getLoadedUrl().contains(searchTerm) @@ -277,7 +497,7 @@ && mFakeServer.getLoadedUrl().contains(LOW_PRIORITY_SEARCH_ENDPOINT)); assertTrue("Low priority request does not have the required prefetch parameter!", mFakeServer.getLoadedUrl() != null - && mFakeServer.getLoadedUrl().contains(CONTEXTUAL_SEARCH_PREFETCH_PARAM)); + && mFakeServer.getLoadedUrl().contains(CONTEXTUAL_SEARCH_PREFETCH_PARAM)); } private void assertLoadedNormalPriorityUrl() { @@ -288,22 +508,14 @@ && mFakeServer.getLoadedUrl().contains(NORMAL_PRIORITY_SEARCH_ENDPOINT)); assertTrue("Normal priority request should not have the prefetch parameter, but did!", mFakeServer.getLoadedUrl() != null - && !mFakeServer.getLoadedUrl().contains(CONTEXTUAL_SEARCH_PREFETCH_PARAM)); + && !mFakeServer.getLoadedUrl().contains(CONTEXTUAL_SEARCH_PREFETCH_PARAM)); } private void assertNoSearchesLoaded() { - assertEquals(0, mFakeServer.loadedUrlCount()); + assertEquals(0, mFakeServer.getLoadedUrlCount()); assertLoadedNoUrl(); } - private void assertContentViewCoreCreated() { - assertTrue(mFakeServer.didCreateContentView()); - } - - private void assertNoContentViewCore() { - assertFalse(mFakeServer.didCreateContentView()); - } - /** * Asserts that the tap triggered promo counter is enabled and at the specified count. */ @@ -321,16 +533,6 @@ } /** - * Fakes navigation of the Content View with the given httpResult code. - * The URL of the navigation is the one requested previously. - * @param isFailure If the request resulted in a failure. - */ - private void fakeContentViewDidNavigate(boolean isFailure) { - String url = mFakeServer.getLoadedUrl(); - mManager.getOverlayContentDelegate().onMainFrameNavigation(url, isFailure); - } - - /** * Waits for the Search Panel (the Search Bar) to peek up from the bottom, and asserts that it * did peek. * @throws InterruptedException @@ -417,20 +619,6 @@ } /** - * Waits for the selected text string to be the given string, and asserts. - * @param text The string to wait for the selection to become. - */ - private void waitForSelectionToBe(final String text) throws InterruptedException { - assertTrue("Bar never showed desired text.", - CriteriaHelper.pollForCriteria(new Criteria() { - @Override - public boolean isSatisfied() { - return TextUtils.equals(text, getSelectedText()); - } - }, TEST_TIMEOUT, DEFAULT_POLLING_INTERVAL)); - } - - /** * Waits for the selection to be dissolved. * Use this method any time a test repeatedly establishes and dissolves a selection to ensure * that the selection has been completely dissolved before simulating the next selection event. @@ -454,24 +642,13 @@ waitForSelectionDissolved(); } - /** - * A ContentViewCore that has some methods stubbed out for testing. - */ - private static final class StubbedContentViewCore extends ContentViewCore { - private boolean mIsFocusedNodeEditable; - - public StubbedContentViewCore(Context context) { - super(context); - } - - public void setIsFocusedNodeEditableForTest(boolean isFocusedNodeEditable) { - mIsFocusedNodeEditable = isFocusedNodeEditable; - } - - @Override - public boolean isFocusedNodeEditable() { - return mIsFocusedNodeEditable; - } + private void waitToPreventDoubleTapRecognition() throws InterruptedException { + // Avoid issues with double-tap detection by ensuring sequential taps + // aren't treated as such. Double-tapping can also select words much as + // longpress, in turn showing the pins and preventing contextual tap + // refinement from nearby taps. The double-tap timeout is sufficiently + // short that this shouldn't conflict with tap refinement by the user. + Thread.sleep(ViewConfiguration.getDoubleTapTimeout()); } /** @@ -492,14 +669,21 @@ } /** - * Swipes the panel up to it's expanded size. + * Swipes the panel up to its expanded state. */ private void swipePanelUp() { swipe(0.5f, 0.95f, 0.5f, 0.55f, 1000); } /** - * Swipes the panel up to it's maximized size. + * Swipes the panel down to its peeked state. + */ + private void swipePanelDown() { + swipe(0.5f, 0.55f, 0.5f, 0.95f, 1000); + } + + /** + * Swipes the panel up to its maximized state. */ private void swipePanelUpToTop() { swipe(0.5f, 0.95f, 0.5f, 0.05f, 1000); @@ -516,7 +700,15 @@ * Taps the base page near the top. */ private void tapBasePageToClosePanel() throws InterruptedException { - tapBasePage(0.1f, 0.1f); + // TODO(pedrosimonetti): This is not reliable. Find a better approach. + // We use the far right side (x == 0.9f) to prevent simulating a tap on top of an + // existing long-press selection (the pins are a tap target). This might not work on RTL. + // We are using y == 0.2f because otherwise it will fail for long press cases. + // It might be better to get the position of the Panel and tap just about outside + // the Panel. I suspect some Flaky tests are caused by this problem (ones involving + // long press and trying to close with the bar peeking, with a long press selection + // established). + tapBasePage(0.9f, 0.2f); waitForPanelToCloseAndAssert(); } @@ -639,6 +831,10 @@ }, TEST_TIMEOUT, DEFAULT_POLLING_INTERVAL); } + //============================================================================================ + // Test Cases + //============================================================================================ + /** * Tests whether the contextual search panel hides when omnibox is clicked. */ @@ -747,13 +943,13 @@ fakeResponse(false, 200, "Intelligence", "United States Intelligence", "alternate-term", false); assertContainsParameters("Intelligence", "alternate-term"); - assertEquals(1, mFakeServer.loadedUrlCount()); + assertEquals(1, mFakeServer.getLoadedUrlCount()); assertLoadedLowPriorityUrl(); waitForPanelToPeekAndAssert(); swipePanelUp(); waitForPanelToExpandAndAssert(); - assertEquals(1, mFakeServer.loadedUrlCount()); + assertEquals(1, mFakeServer.getLoadedUrlCount()); assertLoadedLowPriorityUrl(); } @@ -768,6 +964,10 @@ longPressNode("intelligence"); assertNoContentViewCore(); + // TODO(pedrosimonetti): Long press does not resolve so we shouldn't be faking one. + // Consider changing the fake server to create a fake response automatically, + // when one is requested by the Manager. + // Fake a search term resolution response. fakeResponse(false, 200, "Intelligence", "United States Intelligence", "alternate-term", false); @@ -780,11 +980,11 @@ waitForPanelToExpandAndAssert(); assertContentViewCoreCreated(); assertLoadedNormalPriorityUrl(); - assertEquals(1, mFakeServer.loadedUrlCount()); + assertEquals(1, mFakeServer.getLoadedUrlCount()); // tap the base page to close. tapBasePageToClosePanel(); - assertEquals(1, mFakeServer.loadedUrlCount()); + assertEquals(1, mFakeServer.getLoadedUrlCount()); assertNoContentViewCore(); } @@ -819,16 +1019,16 @@ // Fake a search term resolution response. fakeResponse(false, 200, "states", "United States Intelligence", "alternate-term", false); assertContainsParameters("states", "alternate-term"); - assertEquals(1, mFakeServer.loadedUrlCount()); + assertEquals(1, mFakeServer.getLoadedUrlCount()); assertLoadedLowPriorityUrl(); assertContentViewCoreCreated(); tapPeekingBarToExpandAndAssert(); assertLoadedLowPriorityUrl(); - assertEquals(1, mFakeServer.loadedUrlCount()); + assertEquals(1, mFakeServer.getLoadedUrlCount()); // tap the base page to close. tapBasePageToClosePanel(); - assertEquals(1, mFakeServer.loadedUrlCount()); + assertEquals(1, mFakeServer.getLoadedUrlCount()); assertNoContentViewCore(); } @@ -844,20 +1044,20 @@ // We should not make a second-request until we get a good response from the first-request. assertLoadedNoUrl(); - assertEquals(0, mFakeServer.loadedUrlCount()); + assertEquals(0, mFakeServer.getLoadedUrlCount()); fakeResponse(false, 200, "states", "United States Intelligence", "alternate-term", false); assertLoadedLowPriorityUrl(); - assertEquals(1, mFakeServer.loadedUrlCount()); + assertEquals(1, mFakeServer.getLoadedUrlCount()); // When the second request succeeds, we should not issue a new request. fakeContentViewDidNavigate(false); assertLoadedLowPriorityUrl(); - assertEquals(1, mFakeServer.loadedUrlCount()); + assertEquals(1, mFakeServer.getLoadedUrlCount()); // When the bar opens, we should not make any additional request. tapPeekingBarToExpandAndAssert(); assertLoadedLowPriorityUrl(); - assertEquals(1, mFakeServer.loadedUrlCount()); + assertEquals(1, mFakeServer.getLoadedUrlCount()); assertLoadedLowPriorityUrl(); } @@ -874,20 +1074,20 @@ // We should not make a SERP request until we get a good response from the resolve request. assertLoadedNoUrl(); - assertEquals(0, mFakeServer.loadedUrlCount()); + assertEquals(0, mFakeServer.getLoadedUrlCount()); fakeResponse(false, 200, "states", "United States Intelligence", "alternate-term", false); assertLoadedLowPriorityUrl(); - assertEquals(1, mFakeServer.loadedUrlCount()); + assertEquals(1, mFakeServer.getLoadedUrlCount()); // When the second request fails, we should not issue a new request. fakeContentViewDidNavigate(true); assertLoadedLowPriorityUrl(); - assertEquals(1, mFakeServer.loadedUrlCount()); + assertEquals(1, mFakeServer.getLoadedUrlCount()); // Once the bar opens, we make a new request at normal priority. tapPeekingBarToExpandAndAssert(); assertLoadedNormalPriorityUrl(); - assertEquals(2, mFakeServer.loadedUrlCount()); + assertEquals(2, mFakeServer.getLoadedUrlCount()); } /** @@ -1454,6 +1654,7 @@ assertContainsParameters("states", "alternate-term"); assertLoadedNormalPriorityUrl(); assertContentViewCoreCreated(); + assertContentViewCoreVisible(); } /** @@ -1995,4 +2196,327 @@ waitForPanelToPeekAndAssert(); assertFalse(mPanel.isPeekPromoVisible()); } + + //============================================================================================ + // Content Tests + //============================================================================================ + + /** + * Tests that tap followed by expand makes Content visible. + */ + @SmallTest + @Feature({"ContextualSearch"}) + @Restriction(RESTRICTION_TYPE_NON_LOW_END_DEVICE) + public void testTapContentVisibility() throws InterruptedException, TimeoutException { + // Simulate a tap and make sure Content is not visible. + simulateTapSearch("search"); + assertContentViewCoreCreatedButNeverMadeVisible(); + + // Expanding the Panel should make the Content visible. + tapPeekingBarToExpandAndAssert(); + assertContentViewCoreVisible(); + + // Closing the Panel should destroy the Content. + tapBasePageToClosePanel(); + assertNoContentViewCore(); + } + + /** + * Tests that long press followed by expand creates Content and makes it visible. + * + */ + @SmallTest + @Feature({"ContextualSearch"}) + @Restriction(RESTRICTION_TYPE_NON_LOW_END_DEVICE) + public void testLongPressContentVisibility() throws InterruptedException, TimeoutException { + // Simulate a long press and make sure no Content is created. + simulateLongPressSearch("search"); + assertNoContentViewCore(); + assertNoSearchesLoaded(); + + // Expanding the Panel should make the Content visible. + tapPeekingBarToExpandAndAssert(); + assertContentViewCoreCreated(); + assertContentViewCoreVisible(); + + // Closing the Panel should destroy the Content. + tapBasePageToClosePanel(); + assertNoContentViewCore(); + } + + /** + * Tests swiping panel up and down after a tap search will only load the Content once. + */ + @SmallTest + @Feature({"ContextualSearch"}) + @Restriction(RESTRICTION_TYPE_NON_LOW_END_DEVICE) + public void testTapMultipleSwipeOnlyLoadsContentOnce() + throws InterruptedException, TimeoutException { + // Simulate a tap and make sure Content is not visible. + simulateTapSearch("search"); + assertContentViewCoreCreatedButNeverMadeVisible(); + assertEquals(1, mFakeServer.getLoadedUrlCount()); + + // Swiping the Panel should make the Content visible. + swipePanelUp(); + waitForPanelToExpandAndAssert(); + assertContentViewCoreVisible(); + assertEquals(1, mFakeServer.getLoadedUrlCount()); + + // Swiping the Panel down should not change the visibility or load content again. + swipePanelDown(); + waitForPanelToPeekAndAssert(); + assertContentViewCoreVisible(); + assertEquals(1, mFakeServer.getLoadedUrlCount()); + + // Swiping the Panel up should not change the visibility or load content again. + swipePanelUp(); + waitForPanelToExpandAndAssert(); + assertContentViewCoreVisible(); + assertEquals(1, mFakeServer.getLoadedUrlCount()); + + // Closing the Panel should destroy the Content. + tapBasePageToClosePanel(); + assertNoContentViewCore(); + assertEquals(1, mFakeServer.getLoadedUrlCount()); + } + + /** + * Tests swiping panel up and down after a long press search will only load the Content once. + */ + @SmallTest + @Feature({"ContextualSearch"}) + @Restriction(RESTRICTION_TYPE_NON_LOW_END_DEVICE) + public void testLongPressMultipleSwipeOnlyLoadsContentOnce() + throws InterruptedException, TimeoutException { + // Simulate a long press and make sure no Content is created. + simulateLongPressSearch("search"); + assertNoContentViewCore(); + assertNoSearchesLoaded(); + + // Swiping the Panel should load the URL and make the Content visible. + swipePanelUp(); + waitForPanelToExpandAndAssert(); + assertContentViewCoreCreated(); + assertContentViewCoreVisible(); + assertEquals(1, mFakeServer.getLoadedUrlCount()); + + // Swiping the Panel down should not change the visibility or load content again. + swipePanelDown(); + waitForPanelToPeekAndAssert(); + assertContentViewCoreVisible(); + assertEquals(1, mFakeServer.getLoadedUrlCount()); + + // Swiping the Panel up should not change the visibility or load content again. + swipePanelUp(); + waitForPanelToExpandAndAssert(); + assertContentViewCoreVisible(); + assertEquals(1, mFakeServer.getLoadedUrlCount()); + + // Closing the Panel should destroy the Content. + tapBasePageToClosePanel(); + assertNoContentViewCore(); + assertEquals(1, mFakeServer.getLoadedUrlCount()); + } + + /** + * Tests that chained tap searches create new Content. + */ + @SmallTest + @Feature({"ContextualSearch"}) + @Restriction(RESTRICTION_TYPE_NON_LOW_END_DEVICE) + public void testChainedSearchCreatesNewContent() + throws InterruptedException, TimeoutException { + // Simulate a tap and make sure Content is not visible. + simulateTapSearch("search"); + assertContentViewCoreCreatedButNeverMadeVisible(); + assertEquals(1, mFakeServer.getLoadedUrlCount()); + ContentViewCore cvc1 = getPanelContentViewCore(); + + waitToPreventDoubleTapRecognition(); + + // Simulate a new tap and make sure a new Content is created. + simulateTapSearch("term"); + assertContentViewCoreCreatedButNeverMadeVisible(); + assertEquals(2, mFakeServer.getLoadedUrlCount()); + ContentViewCore cvc2 = getPanelContentViewCore(); + assertNotSame(cvc1, cvc2); + + waitToPreventDoubleTapRecognition(); + + // Simulate a new tap and make sure a new Content is created. + simulateTapSearch("resolution"); + assertContentViewCoreCreatedButNeverMadeVisible(); + assertEquals(3, mFakeServer.getLoadedUrlCount()); + ContentViewCore cvc3 = getPanelContentViewCore(); + assertNotSame(cvc2, cvc3); + + // Closing the Panel should destroy the Content. + tapBasePageToClosePanel(); + assertNoContentViewCore(); + assertEquals(3, mFakeServer.getLoadedUrlCount()); + } + + /** + * Tests that chained searches load correctly. + */ + @SmallTest + @Feature({"ContextualSearch"}) + @Restriction({RESTRICTION_TYPE_NON_LOW_END_DEVICE}) + public void testChainedSearchLoadsCorrectSearchTerm() + throws InterruptedException, TimeoutException { + // Simulate a tap and make sure Content is not visible. + simulateTapSearch("search"); + assertContentViewCoreCreatedButNeverMadeVisible(); + assertEquals(1, mFakeServer.getLoadedUrlCount()); + ContentViewCore cvc1 = getPanelContentViewCore(); + + // Swiping the Panel should make the Content visible. + swipePanelUp(); + waitForPanelToExpandAndAssert(); + assertContentViewCoreVisible(); + assertEquals(1, mFakeServer.getLoadedUrlCount()); + + // Swiping the Panel down should not change the visibility or load content again. + swipePanelDown(); + waitForPanelToPeekAndAssert(); + assertContentViewCoreVisible(); + assertEquals(1, mFakeServer.getLoadedUrlCount()); + + waitToPreventDoubleTapRecognition(); + + // Now simulate a long press, leaving the Panel peeking. + simulateLongPressSearch("resolution"); + + // Swiping the Panel up should load and display the new search. + swipePanelUp(); + waitForPanelToExpandAndAssert(); + assertContentViewCoreCreated(); + assertContentViewCoreVisible(); + assertEquals(2, mFakeServer.getLoadedUrlCount()); + assertLoadedSearchTermMatches("Resolution"); + ContentViewCore cvc2 = getPanelContentViewCore(); + assertNotSame(cvc1, cvc2); + + // Closing the Panel should destroy the Content. + tapBasePageToClosePanel(); + assertNoContentViewCore(); + assertEquals(2, mFakeServer.getLoadedUrlCount()); + } + + /** + * Tests that chained searches make Content visible when opening the Panel. + */ + @SmallTest + @Feature({"ContextualSearch"}) + @Restriction(RESTRICTION_TYPE_NON_LOW_END_DEVICE) + public void testChainedSearchContentVisibility() + throws InterruptedException, TimeoutException { + // Simulate a tap and make sure Content is not visible. + simulateTapSearch("search"); + assertContentViewCoreCreatedButNeverMadeVisible(); + assertEquals(1, mFakeServer.getLoadedUrlCount()); + ContentViewCore cvc1 = getPanelContentViewCore(); + + waitToPreventDoubleTapRecognition(); + + // Now simulate a long press, leaving the Panel peeking. + simulateLongPressSearch("resolution"); + assertNeverCalledContentViewCoreOnShow(); + assertEquals(1, mFakeServer.getLoadedUrlCount()); + + // Swiping the Panel up should load and display the new search. + swipePanelUp(); + waitForPanelToExpandAndAssert(); + assertContentViewCoreCreated(); + assertContentViewCoreVisible(); + assertEquals(2, mFakeServer.getLoadedUrlCount()); + assertLoadedSearchTermMatches("Resolution"); + ContentViewCore cvc2 = getPanelContentViewCore(); + assertNotSame(cvc1, cvc2); + } + + //============================================================================================ + // History Removal Tests + //============================================================================================ + + /** + * Tests that a tap followed by closing the Panel removes the loaded URL from history. + */ + @SmallTest + @Feature({"ContextualSearch"}) + @Restriction(RESTRICTION_TYPE_NON_LOW_END_DEVICE) + public void testTapCloseRemovedFromHistory() + throws InterruptedException, TimeoutException { + // Simulate a tap and make sure a URL was loaded. + simulateTapSearch("search"); + assertEquals(1, mFakeServer.getLoadedUrlCount()); + String url = mFakeServer.getLoadedUrl(); + + // Close the Panel without seeing the Content. + tapBasePageToClosePanel(); + + // Now check that the URL has been removed from history. + assertTrue(mFakeServer.hasRemovedUrl(url)); + } + + /** + * Tests that a tap followed by opening the Panel does not remove the loaded URL from history. + */ + @SmallTest + @Feature({"ContextualSearch"}) + @Restriction(RESTRICTION_TYPE_NON_LOW_END_DEVICE) + public void testTapExpandNotRemovedFromHistory() + throws InterruptedException, TimeoutException { + // Simulate a tap and make sure a URL was loaded. + simulateTapSearch("search"); + assertEquals(1, mFakeServer.getLoadedUrlCount()); + String url = mFakeServer.getLoadedUrl(); + + // Expand Panel so that the Content becomes visible. + tapPeekingBarToExpandAndAssert(); + + // Close the Panel. + tapBasePageToClosePanel(); + + // Now check that the URL has not been removed from history, since the Content was seen. + assertFalse(mFakeServer.hasRemovedUrl(url)); + } + + /** + * Tests that chained searches without opening the Panel removes all loaded URLs from history. + */ + @SmallTest + @Feature({"ContextualSearch"}) + @Restriction(RESTRICTION_TYPE_NON_LOW_END_DEVICE) + public void testChainedTapsRemovedFromHistory() + throws InterruptedException, TimeoutException { + // Simulate a tap and make sure a URL was loaded. + simulateTapSearch("search"); + String url1 = mFakeServer.getLoadedUrl(); + assertNotNull(url1); + + waitToPreventDoubleTapRecognition(); + + // Simulate another tap and make sure another URL was loaded. + simulateTapSearch("term"); + String url2 = mFakeServer.getLoadedUrl(); + assertNotSame(url1, url2); + + waitToPreventDoubleTapRecognition(); + + // Simulate another tap and make sure another URL was loaded. + simulateTapSearch("resolution"); + String url3 = mFakeServer.getLoadedUrl(); + assertNotSame(url2, url3); + + // Close the Panel without seeing any Content. + tapBasePageToClosePanel(); + + // Now check that all three URLs have been removed from history. + assertEquals(3, mFakeServer.getLoadedUrlCount()); + assertTrue(mFakeServer.hasRemovedUrl(url1)); + assertTrue(mFakeServer.hasRemovedUrl(url2)); + assertTrue(mFakeServer.hasRemovedUrl(url3)); + } }
diff --git a/chrome/app/theme/default_100_percent/common/notification_usb_icon.png b/chrome/app/theme/default_100_percent/common/notification_usb_icon.png new file mode 100644 index 0000000..8b1d24c --- /dev/null +++ b/chrome/app/theme/default_100_percent/common/notification_usb_icon.png Binary files differ
diff --git a/chrome/app/theme/default_200_percent/common/notification_usb_icon.png b/chrome/app/theme/default_200_percent/common/notification_usb_icon.png new file mode 100644 index 0000000..4c372b1f --- /dev/null +++ b/chrome/app/theme/default_200_percent/common/notification_usb_icon.png Binary files differ
diff --git a/chrome/app/theme/theme_resources.grd b/chrome/app/theme/theme_resources.grd index 3e15437..91913337 100644 --- a/chrome/app/theme/theme_resources.grd +++ b/chrome/app/theme/theme_resources.grd
@@ -984,6 +984,7 @@ <structure type="chrome_scaled_image" name="IDR_UPDATE_MENU_SEVERITY_LOW" file="common/update_menu_severity_low.png" /> <structure type="chrome_scaled_image" name="IDR_UPDATE_MENU_SEVERITY_MEDIUM" file="common/update_menu_severity_medium.png" /> <structure type="chrome_scaled_image" name="IDR_UPDATE_MENU_SEVERITY_HIGH" file="common/update_menu_severity_high.png" /> + <structure type="chrome_scaled_image" name="IDR_USB_NOTIFICATION_ICON" file="common/notification_usb_icon.png" /> <if expr="chromeos"> <structure type="chrome_scaled_image" name="IDR_USER_IMAGE_CAPTURE" file="common/snapshot_wide.png" /> <structure type="chrome_scaled_image" name="IDR_USER_IMAGE_RECYCLE" file="common/discard_wide.png" />
diff --git a/chrome/browser/browsing_data/browsing_data_remover_unittest.cc b/chrome/browser/browsing_data/browsing_data_remover_unittest.cc index cbaaa50..a7a47d1 100644 --- a/chrome/browser/browsing_data/browsing_data_remover_unittest.cc +++ b/chrome/browser/browsing_data/browsing_data_remover_unittest.cc
@@ -72,7 +72,6 @@ #include "chrome/browser/chromeos/settings/device_settings_service.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/mock_cryptohome_client.h" -#include "components/signin/core/account_id/account_id.h" #endif #if defined(ENABLE_EXTENSIONS) @@ -2019,8 +2018,7 @@ chromeos::ScopedTestCrosSettings test_cros_settings; chromeos::MockUserManager* mock_user_manager = new testing::NiceMock<chromeos::MockUserManager>(); - mock_user_manager->SetActiveUser( - AccountId::FromUserEmail("test@example.com")); + mock_user_manager->SetActiveUser("test@example.com"); chromeos::ScopedUserManagerEnabler user_manager_enabler(mock_user_manager); scoped_ptr<chromeos::DBusThreadManagerSetter> dbus_setter =
diff --git a/chrome/browser/chrome_browser_main_extra_parts_x11.cc b/chrome/browser/chrome_browser_main_extra_parts_x11.cc index 3a068fb..993f4f97 100644 --- a/chrome/browser/chrome_browser_main_extra_parts_x11.cc +++ b/chrome/browser/chrome_browser_main_extra_parts_x11.cc
@@ -7,8 +7,8 @@ #include "base/bind.h" #include "base/debug/debugger.h" #include "base/location.h" -#include "base/single_thread_task_runner.h" -#include "base/thread_task_runner_handle.h" +#include "base/sequenced_task_runner.h" +#include "base/threading/sequenced_task_runner_handle.h" #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/common/chrome_result_codes.h" #include "content/public/browser/browser_thread.h" @@ -28,7 +28,7 @@ int BrowserX11ErrorHandler(Display* d, XErrorEvent* error) { if (!g_in_x11_io_error_handler) { - base::ThreadTaskRunnerHandle::Get()->PostTask( + base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&ui::LogErrorEventDescription, d, *error)); } return 0;
diff --git a/chrome/browser/chrome_webusb_browser_client.cc b/chrome/browser/chrome_webusb_browser_client.cc index ddfcd589..4f55d1d 100644 --- a/chrome/browser/chrome_webusb_browser_client.cc +++ b/chrome/browser/chrome_webusb_browser_client.cc
@@ -11,9 +11,11 @@ #include "chrome/browser/ui/host_desktop.h" #include "chrome/browser/ui/scoped_tabbed_browser_displayer.h" #include "chrome/grit/generated_resources.h" +#include "chrome/grit/theme_resources.h" #include "content/public/common/origin_util.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/page_transition_types.h" +#include "ui/base/resource/resource_bundle.h" #include "ui/base/window_open_disposition.h" #include "ui/gfx/image/image.h" #include "ui/message_center/message_center.h" @@ -74,6 +76,7 @@ return; } + ResourceBundle& rb = ResourceBundle::GetSharedInstance(); message_center::RichNotificationData rich_notification_data; scoped_ptr<message_center::Notification> notification( new message_center::Notification( @@ -83,8 +86,8 @@ l10n_util::GetStringFUTF16( IDS_WEBUSB_DEVICE_DETECTED_NOTIFICATION, base::UTF8ToUTF16(landing_page.GetContent())), - // TODO(juncai): use generic USB device icon here. - gfx::Image(), base::string16(), GURL(), + rb.GetNativeImageNamed(IDR_USB_NOTIFICATION_ICON), + base::string16(), GURL(), message_center::NotifierId( message_center::NotifierId::SYSTEM_COMPONENT, kWebUsbDetectorNotificationID),
diff --git a/chrome/browser/chromeos/accessibility/accessibility_manager_browsertest.cc b/chrome/browser/chromeos/accessibility/accessibility_manager_browsertest.cc index 36e7713..0aeb557ba 100644 --- a/chrome/browser/chromeos/accessibility/accessibility_manager_browsertest.cc +++ b/chrome/browser/chromeos/accessibility/accessibility_manager_browsertest.cc
@@ -261,9 +261,6 @@ content::NotificationRegistrar registrar_; MockBrailleController braille_controller_; - - const AccountId test_account_id_ = AccountId::FromUserEmail(kTestUserName); - DISALLOW_COPY_AND_ASSIGN(AccessibilityManagerTest); }; @@ -277,8 +274,8 @@ EXPECT_EQ(default_autoclick_delay(), GetAutoclickDelay()); // Logs in. - user_manager::UserManager::Get()->UserLoggedIn(test_account_id_, - kTestUserName, true); + user_manager::UserManager::Get()->UserLoggedIn( + kTestUserName, kTestUserName, true); // Confirms that the features still disabled just after login. EXPECT_FALSE(IsLargeCursorEnabled()); @@ -339,8 +336,8 @@ IN_PROC_BROWSER_TEST_F(AccessibilityManagerTest, TypePref) { // Logs in. - user_manager::UserManager::Get()->UserLoggedIn(test_account_id_, - kTestUserName, true); + user_manager::UserManager::Get()->UserLoggedIn( + kTestUserName, kTestUserName, true); user_manager::UserManager::Get()->SessionStarted(); // Confirms that the features are disabled just after login. @@ -399,8 +396,8 @@ IN_PROC_BROWSER_TEST_F(AccessibilityManagerTest, ResumeSavedPref) { // Loads the profile of the user. - user_manager::UserManager::Get()->UserLoggedIn(test_account_id_, - kTestUserName, true); + user_manager::UserManager::Get()->UserLoggedIn( + kTestUserName, kTestUserName, true); // Sets the pref to enable large cursor before login. SetLargeCursorEnabledPref(true); @@ -444,8 +441,8 @@ MockAccessibilityObserver observer; // Logs in. - user_manager::UserManager::Get()->UserLoggedIn(test_account_id_, - kTestUserName, true); + user_manager::UserManager::Get()->UserLoggedIn( + kTestUserName, kTestUserName, true); user_manager::UserManager::Get()->SessionStarted(); EXPECT_FALSE(observer.observed()); @@ -504,8 +501,8 @@ MockAccessibilityObserver observer; // Logs in. - user_manager::UserManager::Get()->UserLoggedIn(test_account_id_, - kTestUserName, true); + user_manager::UserManager::Get()->UserLoggedIn( + kTestUserName, kTestUserName, true); user_manager::UserManager::Get()->SessionStarted(); EXPECT_FALSE(observer.observed()); @@ -596,9 +593,8 @@ EXPECT_EQ(kTestAutoclickDelayMs, GetAutoclickDelay()); // Logs in. - const AccountId account_id = AccountId::FromUserEmail(GetParam()); - user_manager::UserManager::Get()->UserLoggedIn( - account_id, account_id.GetUserEmail(), true); + const char* user_name = GetParam(); + user_manager::UserManager::Get()->UserLoggedIn(user_name, user_name, true); // Confirms that the features are still enabled just after login. EXPECT_TRUE(IsLargeCursorEnabled()); @@ -626,9 +622,8 @@ IN_PROC_BROWSER_TEST_P(AccessibilityManagerUserTypeTest, BrailleWhenLoggedIn) { // Logs in. - const AccountId account_id = AccountId::FromUserEmail(GetParam()); - user_manager::UserManager::Get()->UserLoggedIn( - account_id, account_id.GetUserEmail(), true); + const char* user_name = GetParam(); + user_manager::UserManager::Get()->UserLoggedIn(user_name, user_name, true); user_manager::UserManager::Get()->SessionStarted(); // This object watches for IME preference changes and reflects those in // the IME framework state. @@ -673,8 +668,8 @@ IN_PROC_BROWSER_TEST_F(AccessibilityManagerTest, AccessibilityMenuVisibility) { // Log in. - user_manager::UserManager::Get()->UserLoggedIn(test_account_id_, - kTestUserName, true); + user_manager::UserManager::Get()->UserLoggedIn( + kTestUserName, kTestUserName, true); user_manager::UserManager::Get()->SessionStarted(); // Confirms that the features are disabled.
diff --git a/chrome/browser/chromeos/accessibility/magnification_manager_browsertest.cc b/chrome/browser/chromeos/accessibility/magnification_manager_browsertest.cc index 2cec6c3..970973c 100644 --- a/chrome/browser/chromeos/accessibility/magnification_manager_browsertest.cc +++ b/chrome/browser/chromeos/accessibility/magnification_manager_browsertest.cc
@@ -91,12 +91,11 @@ return prefs()->GetBoolean(prefs::kAccessibilityScreenMagnifierEnabled); } -// Creates and logs into a profile with account |account_id|, and makes sure -// that the profile is regarded as "non new" in the next login. This is used in +// Creates and logs into a profile with account |name|, and makes sure that +// the profile is regarded as "non new" in the next login. This is used in // PRE_XXX cases so that in the main XXX case we can test non new profiles. -void PrepareNonNewProfile(const AccountId& account_id) { - user_manager::UserManager::Get()->UserLoggedIn( - account_id, account_id.GetUserEmail(), true); +void PrepareNonNewProfile(const std::string& name) { + user_manager::UserManager::Get()->UserLoggedIn(name, name, true); // To prepare a non-new profile for tests, we must ensure the profile // directory and the preference files are created, because that's what // Profile::IsNewProfile() checks. UserLoggedIn(), however, does not yet @@ -164,14 +163,12 @@ ProfileManager::GetActiveUserProfile()); } - const AccountId test_account_id_ = AccountId::FromUserEmail(kTestUserName); - DISALLOW_COPY_AND_ASSIGN(MagnificationManagerTest); }; IN_PROC_BROWSER_TEST_F(MagnificationManagerTest, PRE_LoginOffToOff) { // Create a new profile once, to run the test with non-new profile. - PrepareNonNewProfile(test_account_id_); + PrepareNonNewProfile(kTestUserName); // Sets pref to explicitly disable the magnifier. SetScreenMagnifierEnabledPref(false); @@ -186,8 +183,8 @@ EXPECT_FALSE(IsMagnifierEnabled()); // Logs in with existing profile. - user_manager::UserManager::Get()->UserLoggedIn(test_account_id_, - kTestUserName, true); + user_manager::UserManager::Get()->UserLoggedIn( + kTestUserName, kTestUserName, true); // Confirms that magnifier is still disabled just after login. EXPECT_FALSE(IsMagnifierEnabled()); @@ -207,7 +204,7 @@ IN_PROC_BROWSER_TEST_F(MagnificationManagerTest, PRE_LoginFullToOff) { // Create a new profile once, to run the test with non-new profile. - PrepareNonNewProfile(test_account_id_); + PrepareNonNewProfile(kTestUserName); // Sets pref to explicitly disable the magnifier. SetScreenMagnifierEnabledPref(false); @@ -226,8 +223,8 @@ EXPECT_EQ(2.5, GetFullScreenMagnifierScale()); // Logs in (but the session is not started yet). - user_manager::UserManager::Get()->UserLoggedIn(test_account_id_, - kTestUserName, true); + user_manager::UserManager::Get()->UserLoggedIn( + kTestUserName, kTestUserName, true); // Confirms that magnifier is keeping enabled. EXPECT_TRUE(IsMagnifierEnabled()); @@ -242,7 +239,7 @@ IN_PROC_BROWSER_TEST_F(MagnificationManagerTest, PRE_LoginOffToFull) { // Create a new profile once, to run the test with non-new profile. - PrepareNonNewProfile(test_account_id_); + PrepareNonNewProfile(kTestUserName); // Sets prefs to explicitly enable the magnifier. SetScreenMagnifierEnabledPref(true); @@ -256,8 +253,8 @@ EXPECT_FALSE(IsMagnifierEnabled()); // Logs in (but the session is not started yet). - user_manager::UserManager::Get()->UserLoggedIn(test_account_id_, - kTestUserName, true); + user_manager::UserManager::Get()->UserLoggedIn( + kTestUserName, kTestUserName, true); // Confirms that magnifier is keeping disabled. EXPECT_FALSE(IsMagnifierEnabled()); @@ -274,7 +271,7 @@ IN_PROC_BROWSER_TEST_F(MagnificationManagerTest, PRE_LoginFullToFull) { // Create a new profile once, to run the test with non-new profile. - PrepareNonNewProfile(test_account_id_); + PrepareNonNewProfile(kTestUserName); // Sets prefs to explicitly enable the magnifier. SetScreenMagnifierEnabledPref(true); @@ -292,8 +289,8 @@ EXPECT_EQ(3.0, GetFullScreenMagnifierScale()); // Logs in (but the session is not started yet). - user_manager::UserManager::Get()->UserLoggedIn(test_account_id_, - kTestUserName, true); + user_manager::UserManager::Get()->UserLoggedIn( + kTestUserName, kTestUserName, true); // Confirms that magnifier is keeping enabled. EXPECT_TRUE(IsMagnifierEnabled()); @@ -311,7 +308,7 @@ IN_PROC_BROWSER_TEST_F(MagnificationManagerTest, PRE_LoginFullToUnset) { // Creates a new profile once, to run the test with non-new profile. - PrepareNonNewProfile(test_account_id_); + PrepareNonNewProfile(kTestUserName); } IN_PROC_BROWSER_TEST_F(MagnificationManagerTest, LoginFullToUnset) { @@ -322,8 +319,8 @@ EXPECT_EQ(ui::MAGNIFIER_FULL, GetMagnifierType()); // Logs in (but the session is not started yet). - user_manager::UserManager::Get()->UserLoggedIn(test_account_id_, - kTestUserName, true); + user_manager::UserManager::Get()->UserLoggedIn( + kTestUserName, kTestUserName, true); // Confirms that magnifier is keeping enabled. EXPECT_TRUE(IsMagnifierEnabled()); @@ -344,8 +341,8 @@ SetMagnifierEnabled(false); // Logs in (but the session is not started yet). - user_manager::UserManager::Get()->UserLoggedIn(test_account_id_, - kTestUserName, true); + user_manager::UserManager::Get()->UserLoggedIn( + kTestUserName, kTestUserName, true); // Confirms that magnifier is keeping disabled. EXPECT_FALSE(IsMagnifierEnabled()); @@ -367,8 +364,8 @@ EXPECT_EQ(2.5, GetFullScreenMagnifierScale()); // Logs in (but the session is not started yet). - user_manager::UserManager::Get()->UserLoggedIn(test_account_id_, - kTestUserName, true); + user_manager::UserManager::Get()->UserLoggedIn( + kTestUserName, kTestUserName, true); // Confirms that magnifier is keeping enabled. EXPECT_TRUE(IsMagnifierEnabled()); @@ -388,8 +385,8 @@ EXPECT_FALSE(IsMagnifierEnabled()); // Logs in (but the session is not started yet). - user_manager::UserManager::Get()->UserLoggedIn(test_account_id_, - kTestUserName, true); + user_manager::UserManager::Get()->UserLoggedIn( + kTestUserName, kTestUserName, true); // Confirms that magnifier is keeping disabled. EXPECT_FALSE(IsMagnifierEnabled()); @@ -460,8 +457,8 @@ IN_PROC_BROWSER_TEST_F(MagnificationManagerTest, TypePref) { // Logs in - user_manager::UserManager::Get()->UserLoggedIn(test_account_id_, - kTestUserName, true); + user_manager::UserManager::Get()->UserLoggedIn( + kTestUserName, kTestUserName, true); user_manager::UserManager::Get()->SessionStarted(); // Confirms that magnifier is disabled just after login.
diff --git a/chrome/browser/chromeos/app_mode/kiosk_app_manager.cc b/chrome/browser/chromeos/app_mode/kiosk_app_manager.cc index 0dd9f22d..bb339fe 100644 --- a/chrome/browser/chromeos/app_mode/kiosk_app_manager.cc +++ b/chrome/browser/chromeos/app_mode/kiosk_app_manager.cc
@@ -38,7 +38,6 @@ #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/settings/cros_settings_names.h" #include "components/ownership/owner_key_util.h" -#include "components/signin/core/account_id/account_id.h" #include "components/user_manager/user_manager.h" #include "content/public/browser/browser_thread.h" #include "extensions/common/extension_urls.h" @@ -641,9 +640,9 @@ const user_manager::User* active_user = user_manager::UserManager::Get()->GetActiveUser(); if (active_user) { - const AccountId active_account_id = active_user->GetAccountId(); + std::string active_user_id = active_user->GetUserID(); for (const auto& it : old_apps) { - if (it.second->user_id() == active_account_id.GetUserEmail()) { + if (it.second->user_id() == active_user_id) { VLOG(1) << "Currently running kiosk app removed from policy, exiting"; cryptohomes_barrier_closure = BarrierClosure( old_apps.size(), base::Bind(&chrome::AttemptUserExit));
diff --git a/chrome/browser/chromeos/app_mode/kiosk_profile_loader.cc b/chrome/browser/chromeos/app_mode/kiosk_profile_loader.cc index 5612da0..638fdb0 100644 --- a/chrome/browser/chromeos/app_mode/kiosk_profile_loader.cc +++ b/chrome/browser/chromeos/app_mode/kiosk_profile_loader.cc
@@ -158,7 +158,7 @@ // we switch this back to the demo user name to correctly identify this // user as a demo user. UserContext context = user_context; - if (context.GetAccountId() == login::GuestAccountId()) + if (context.GetUserID() == chromeos::login::kGuestUserName) context.SetUserID(login::DemoAccountId().GetUserEmail()); UserSessionManager::GetInstance()->StartSession( context, UserSessionManager::PRIMARY_USER_SESSION,
diff --git a/chrome/browser/chromeos/attestation/platform_verification_flow_unittest.cc b/chrome/browser/chromeos/attestation/platform_verification_flow_unittest.cc index 839e172..21dd3c5 100644 --- a/chrome/browser/chromeos/attestation/platform_verification_flow_unittest.cc +++ b/chrome/browser/chromeos/attestation/platform_verification_flow_unittest.cc
@@ -50,7 +50,7 @@ is_permitted_by_user_(true), is_in_supported_mode_(true) { // Configure a user for the mock user manager. - mock_user_manager_.SetActiveUser(AccountId::FromUserEmail(kTestEmail)); + mock_user_manager_.SetActiveUser(kTestEmail); } ~FakeDelegate() override {}
diff --git a/chrome/browser/chromeos/chrome_browser_main_chromeos.cc b/chrome/browser/chromeos/chrome_browser_main_chromeos.cc index f88e8b82..66e0040 100644 --- a/chrome/browser/chromeos/chrome_browser_main_chromeos.cc +++ b/chrome/browser/chromeos/chrome_browser_main_chromeos.cc
@@ -469,13 +469,12 @@ ChromeBrowserMainPartsLinux::PreProfileInit(); if (immediate_login) { - const std::string user_email = login::CanonicalizeUserID( + const std::string user_id = login::CanonicalizeUserID( parsed_command_line().GetSwitchValueASCII(switches::kLoginUser)); user_manager::UserManager* user_manager = user_manager::UserManager::Get(); - const AccountId account_id(AccountId::FromUserEmail(user_email)); - if (policy::IsDeviceLocalAccountUser(account_id.GetUserEmail(), NULL) && - !user_manager->IsKnownUser(account_id)) { + if (policy::IsDeviceLocalAccountUser(user_id, NULL) && + !user_manager->IsKnownUser(user_id)) { // When a device-local account is removed, its policy is deleted from disk // immediately. If a session using this account happens to be in progress, // the session is allowed to continue with policy served from an in-memory @@ -489,8 +488,8 @@ // In case of multi-profiles --login-profile will contain user_id_hash. std::string user_id_hash = parsed_command_line().GetSwitchValueASCII(switches::kLoginProfile); - user_manager->UserLoggedIn(account_id, user_id_hash, true); - VLOG(1) << "Relaunching browser for user: " << user_email + user_manager->UserLoggedIn(user_id, user_id_hash, true); + VLOG(1) << "Relaunching browser for user: " << user_id << " with hash: " << user_id_hash; } }
diff --git a/chrome/browser/chromeos/extensions/device_local_account_management_policy_provider.cc b/chrome/browser/chromeos/extensions/device_local_account_management_policy_provider.cc index 378b3d4..512d2d4 100644 --- a/chrome/browser/chromeos/extensions/device_local_account_management_policy_provider.cc +++ b/chrome/browser/chromeos/extensions/device_local_account_management_policy_provider.cc
@@ -4,19 +4,24 @@ #include "chrome/browser/chromeos/extensions/device_local_account_management_policy_provider.h" +#include <cstddef> #include <string> #include "base/logging.h" #include "base/strings/utf_string_conversions.h" +#include "base/values.h" #include "chrome/grit/generated_resources.h" #include "extensions/common/extension.h" #include "extensions/common/manifest.h" +#include "extensions/common/manifest_constants.h" #include "ui/base/l10n/l10n_util.h" namespace chromeos { namespace { +namespace emk = extensions::manifest_keys; + // Apps/extensions explicitly whitelisted for use in public sessions. const char* const kPublicSessionWhitelist[] = { // Public sessions in general: @@ -106,6 +111,376 @@ "ljacajndfccfgnfohlgkdphmbnpkjflk", // Chrome Remote Desktop (Dev Build) }; +// List of manifest entries from https://developer.chrome.com/apps/manifest. +// Unsafe entries are commented out and special cases too. +const char* const kSafeManifestEntries[] = { + // Special-cased in IsPlatformAppSafeForPublicSession(). + // emk::kApp, + + // Special-cased in IsPlatformAppSafeForPublicSession(). + // emk::kManifestVersion, + + // Just a display string. + emk::kName, + + // Just a display string. + emk::kShortName, + + // Version string (for app updates). + emk::kVersion, + + // Name of directory containg default strings. + emk::kDefaultLocale, + + // An implementation detail (actually written by Chrome, not the app + // author). + emk::kCurrentLocale, + + // Just a display string. + emk::kDescription, + + // Just UX. + emk::kIcons, + + // No constant in manifest_constants.cc. + // "author", + + // TBD + // emk::kBluetooth, + + // TBD + // emk::kCommands, + + // TBD, doc missing + // emk::kCopresence, + + // TBD, looks unsafe + // emk::kEventRules, + + // TBD + // emk::kExternallyConnectable, + + // TBD + // emk::kFileHandlers, + + // TBD + // emk::kFileSystemProviderCapabilities, + + // Shared Modules configuration: Import resources from another extension. + emk::kImport, + + // Shared Modules configuration: Allow other extensions to access resources. + emk::kExport, + + // Shared Modules configuration: Specify extension id for development. + emk::kKey, + + // Descriptive statement about the app. + emk::kKioskEnabled, + + // Contradicts the purpose of running inside a Public Session. + // emk::kKioskOnly, + + // Descriptive statement about the app. + emk::kMinimumChromeVersion, + + // NaCl modules are bound to app permissions just like the rest of the app + // and thus should not pose a risk. + emk::kNaClModules, + + // TBD, doc missing + // emk::kOAuth2, + + // Descriptive statement about the app. + emk::kOfflineEnabled, + + // Special-cased in IsPlatformAppSafeForPublicSession(). + // emk::kOptionalPermissions, + + // Special-cased in IsPlatformAppSafeForPublicSession(). + // emk::kPermissions, + + // No constant in manifest_constants.cc. + // "platforms", + + // Descriptive statement about the app. + emk::kRequirements, + + // Execute some pages in a separate sandbox. (manifest_constants.cc only has + // constants for sub-keys.) + "sandbox", + + // TBD, doc missing + // emk::kSignature, + + // Network access. + emk::kSockets, + + // TBD + // emk::kIsolatedStorage, + + // TBD, doc missing + // emk::kSystemIndicator, + + // TODO(tnagel): Ensure that extension updates query UserMayLoad(). + // https://crbug.com/549720 + emk::kUpdateURL, + + // Apps may intercept navigations to URL patterns for domains for which the + // app author has proven ownership of to the Web Store. (Chrome starts the + // app instead of fulfilling the navigation.) This is only safe for apps + // that have been loaded from the Web Store and thus is special-cased in + // IsPlatformAppSafeForPublicSession(). + // emk::kUrlHandlers, + + // TBD + // emk::kUsbPrinters, + + // Just a display string. + emk::kVersionName, + + // Webview has no special privileges or capabilities. + emk::kWebview, +}; + +// List of permissions based on +// https://developer.chrome.com/apps/declare_permissions. +// TODO(tnagel): Explain generic rationale for decisions. +const char* const kSafePermissions[] = { + // Risky: Reading accessibility settings could allow to infer health + // information. + // "accessibilityFeatures.read", + + // Modifying accessibility settings seems safe (at most a user could be + // confused by it). + "accessibilityFeatures.modify", + + // Schedule code to run at future times. + "alarms", + + // Risk of listening attack. + // "audio", + + // Risk of listening attack. + // "audioCapture", + + // Just resource management, probably doesn't even apply to Chrome OS. + "background", + + // Open a new tab with a given URL. + "browser", + + // Risky: Reading from clipboard could expose private information. + // "clipboardRead", + + // Writing to clipboard is safe. + "clipboardWrite", + + // TBD + // "contextMenus", + + // Dev channel only. Not evaluated. + // "copresence", + + // Placing a document on the scanner implies user consent. + "documentScan", + + // Possibly risky due to its experimental nature: not vetted for security, + // potentially buggy, subject to change without notice. + // "experimental," + + // TBD + // "fileSystem", + + // TBD + // "fileSystemProvider", + + // Just another type of connectivity. + "gcm", + + // Risky: Accessing location without explicit user consent. + // "geolocation", + + // Risky: Potentially allows keylogging. + // "hid", + + // Detection of idle state. + "idle", + + // Dev channel only. Not evaluated. + // "location", + + // Just another type of connectivity. + "mdns", + + // Risky: The "allAutoDectected" option could allow access to user data + // without their consent. + // "mediaGalleries", + + // Just UX. + "notifications", + + // TBD. Could allow UX spoofing. + // "pointerLock", + + // Power settings. + "power", + + // Risky: Could be used to siphon printed documents. + // "printerProvider", + + // Access serial port. + "serial", + + // Just another type of connectivity. + "socket", + + // Just another type of connectivity. + "sockets", + + // Per-app sandbox. + "storage", + + // Access system parameters. + "system.cpu", + + // Access system parameters. + "system.display", + + // Access system parameters. + "system.memory", + + // Access system parameters. + "system.network", + + // Risky: Could leak the name of a user-supplied storage medium. + // "system.storage", + + // Just UX. + "tts", + + // Excessive resource usage is not a risk. + "unlimitedStorage", + + // Raw peripheral access is out of scope. + // TODO(tnagel): Explain in greater detail. + "usb", + + // TBD: What if one user connects and the next one is unaware of that? + // "vpnProvider", + + // Just UX. + "wallpaper", + + // Web capabilities are safe. + "webview", +}; + +// Return true iff |entry| is contained in |char_array|. +bool ArrayContainsImpl(const char* const char_array[], + size_t entry_count, + const std::string& entry) { + for (size_t i = 0; i < entry_count; ++i) { + if (entry == char_array[i]) { + return true; + } + } + return false; +} + +// See http://blogs.msdn.com/b/the1/archive/2004/05/07/128242.aspx for an +// explanation of array size determination. +template <size_t N> +bool ArrayContains(const char* const (&char_array)[N], + const std::string& entry) { + return ArrayContainsImpl(char_array, N, entry); +} + +// Returns true for platform apps that are considered safe for Public Sessions, +// which among other things requires the manifest top-level entries to be +// contained in the |kSafeManifestEntries| whitelist and all permissions to be +// contained in |kSafePermissions|. +bool IsPlatformAppSafeForPublicSession(const extensions::Extension* extension) { + if (extension->GetType() != extensions::Manifest::TYPE_PLATFORM_APP) { + LOG(ERROR) << extension->id() << " is not a platform app."; + return false; + } + + for (base::DictionaryValue::Iterator it(*extension->manifest()->value()); + !it.IsAtEnd(); it.Advance()) { + if (ArrayContains(kSafeManifestEntries, it.key())) { + continue; + } + + // Permissions must be whitelisted in |kSafePermissions|. + if (it.key() == emk::kPermissions || + it.key() == emk::kOptionalPermissions) { + const base::ListValue* list_value; + if (!it.value().GetAsList(&list_value)) { + LOG(ERROR) << it.key() << " is not a list."; + return false; + } + for (auto it2 = list_value->begin(); it2 != list_value->end(); ++it2) { + std::string permission_string; + if (!(*it2)->GetAsString(&permission_string)) { + LOG(ERROR) << it.key() << " contains a non-string."; + return false; + } + if (!ArrayContains(kSafePermissions, permission_string)) { + LOG(ERROR) << extension->id() + << " requested non-whitelisted permission: " + << permission_string; + return false; + } + } + // "app" may only contain "background". + } else if (it.key() == emk::kApp) { + const base::DictionaryValue *dict_value; + if (!it.value().GetAsDictionary(&dict_value)) { + LOG(ERROR) << extension->id() << " app is not a dictionary."; + return false; + } + for (base::DictionaryValue::Iterator it2(*dict_value); + !it2.IsAtEnd(); it2.Advance()) { + if (it2.key() != "background") { + LOG(ERROR) << extension->id() + << " has non-whitelisted manifest entry: " + << it.key() << "." << it2.key(); + return false; + } + } + // Require v2 because that's the only version + // IsPlatformAppSafeForPublicSession() understands. + } else if (it.key() == emk::kManifestVersion) { + int version; + if (!it.value().GetAsInteger(&version)) { + LOG(ERROR) << extension->id() << " " << emk::kManifestVersion + << " is not an integer."; + return false; + } + if (version != 2) { + LOG(ERROR) << extension->id() + << " has non-whitelisted manifest version."; + return false; + } + // URL handlers depend on the web store to confirm ownership of the domain. + } else if (it.key() == emk::kUrlHandlers) { + if (!extension->from_webstore()) { + LOG(ERROR) << extension->id() << " uses emk::kUrlHandlers but was not " + "installed through the web store."; + return false; + } + // Everything else is an error. + } else { + LOG(ERROR) << extension->id() + << " has non-whitelisted manifest entry: " << it.key(); + return false; + } + } + + return true; +} + } // namespace DeviceLocalAccountManagementPolicyProvider:: @@ -133,20 +508,27 @@ base::string16* error) const { if (account_type_ == policy::DeviceLocalAccount::TYPE_PUBLIC_SESSION) { // Allow extension if it is an externally hosted component of Chrome. - if (extension->location() == - extensions::Manifest::EXTERNAL_COMPONENT) { + if (extension->location() == extensions::Manifest::EXTERNAL_COMPONENT) { return true; } // Allow extension if its type is whitelisted for use in public sessions. - if (extension->GetType() == extensions::Manifest::TYPE_HOSTED_APP) + if (extension->GetType() == extensions::Manifest::TYPE_HOSTED_APP) { return true; + } // Allow extension if its specific ID is whitelisted for use in public // sessions. - for (size_t i = 0; i < arraysize(kPublicSessionWhitelist); ++i) { - if (extension->id() == kPublicSessionWhitelist[i]) - return true; + if (ArrayContains(kPublicSessionWhitelist, extension->id())) { + return true; + } + + // Allow force-installed platform app if all manifest contents are + // whitelisted. + if ((extension->location() == extensions::Manifest::EXTERNAL_POLICY_DOWNLOAD + || extension->location() == extensions::Manifest::EXTERNAL_POLICY) + && IsPlatformAppSafeForPublicSession(extension)) { + return true; } } else if (account_type_ == policy::DeviceLocalAccount::TYPE_KIOSK_APP) { // For single-app kiosk sessions, allow platform apps, extesions and
diff --git a/chrome/browser/chromeos/extensions/device_local_account_management_policy_provider_unittest.cc b/chrome/browser/chromeos/extensions/device_local_account_management_policy_provider_unittest.cc index 41c708e..180be997 100644 --- a/chrome/browser/chromeos/extensions/device_local_account_management_policy_provider_unittest.cc +++ b/chrome/browser/chromeos/extensions/device_local_account_management_policy_provider_unittest.cc
@@ -8,6 +8,7 @@ #include "base/files/file_path.h" #include "base/memory/ref_counted.h" +#include "base/strings/string16.h" #include "base/values.h" #include "extensions/common/extension.h" #include "extensions/common/manifest.h" @@ -23,14 +24,15 @@ scoped_refptr<const extensions::Extension> CreateExtensionFromValues( const std::string& id, extensions::Manifest::Location location, - base::DictionaryValue* values) { + base::DictionaryValue* values, + int flags) { values->SetString(extensions::manifest_keys::kName, "test"); values->SetString(extensions::manifest_keys::kVersion, "0.1"); std::string error; return extensions::Extension::Create(base::FilePath(), location, *values, - extensions::Extension::NO_FLAGS, + flags, id, &error); } @@ -38,14 +40,18 @@ scoped_refptr<const extensions::Extension> CreateRegularExtension( const std::string& id) { base::DictionaryValue values; - return CreateExtensionFromValues(id, extensions::Manifest::INTERNAL, &values); + return CreateExtensionFromValues(id, + extensions::Manifest::INTERNAL, + &values, + extensions::Extension::NO_FLAGS); } scoped_refptr<const extensions::Extension> CreateExternalComponentExtension() { base::DictionaryValue values; return CreateExtensionFromValues(std::string(), extensions::Manifest::EXTERNAL_COMPONENT, - &values); + &values, + extensions::Extension::NO_FLAGS); } scoped_refptr<const extensions::Extension> CreateHostedApp() { @@ -54,19 +60,25 @@ values.Set(extensions::manifest_keys::kWebURLs, new base::ListValue); return CreateExtensionFromValues(std::string(), extensions::Manifest::INTERNAL, - &values); + &values, + extensions::Extension::NO_FLAGS); +} + +scoped_refptr<const extensions::Extension> CreatePlatformAppWithExtraValues( + const base::DictionaryValue* extra_values, + extensions::Manifest::Location location, + int flags) { + base::DictionaryValue values; + values.SetString("app.background.page", "background.html"); + values.MergeDictionary(extra_values); + return CreateExtensionFromValues(std::string(), location, &values, flags); } scoped_refptr<const extensions::Extension> CreatePlatformApp() { base::DictionaryValue values; - values.Set(extensions::manifest_keys::kApp, new base::DictionaryValue); - values.Set(extensions::manifest_keys::kPlatformAppBackground, - new base::DictionaryValue); - values.Set(extensions::manifest_keys::kPlatformAppBackgroundPage, - new base::StringValue("background.html")); - return CreateExtensionFromValues(std::string(), - extensions::Manifest::INTERNAL, - &values); + return CreatePlatformAppWithExtraValues(&values, + extensions::Manifest::INTERNAL, + extensions::Extension::NO_FLAGS); } } // namespace @@ -102,13 +114,193 @@ error.clear(); // Verify that if neither the location, type nor the ID of an extension have - // been whitelisted for use in public sessions, the extension cannot be + // been whitelisted for use in public sessions, the extension cannot be // installed. extension = CreateRegularExtension(std::string()); ASSERT_TRUE(extension.get()); EXPECT_FALSE(provider.UserMayLoad(extension.get(), &error)); EXPECT_NE(base::string16(), error); error.clear(); + + // Verify that a minimal platform app can be installed from location + // EXTERNAL_POLICY. + { + base::DictionaryValue values; + extension = CreatePlatformAppWithExtraValues( + &values, + extensions::Manifest::EXTERNAL_POLICY, + extensions::Extension::NO_FLAGS); + ASSERT_TRUE(extension); + + EXPECT_TRUE(provider.UserMayLoad(extension.get(), &error)); + EXPECT_EQ(base::string16(), error); + error.clear(); + } + + // Verify that a minimal platform app can be installed from location + // EXTERNAL_POLICY_DOWNLOAD. + { + base::DictionaryValue values; + extension = CreatePlatformAppWithExtraValues( + &values, + extensions::Manifest::EXTERNAL_POLICY_DOWNLOAD, + extensions::Extension::NO_FLAGS); + ASSERT_TRUE(extension); + + EXPECT_TRUE(provider.UserMayLoad(extension.get(), &error)); + EXPECT_EQ(base::string16(), error); + error.clear(); + } + + // Verify that a minimal platform app cannot be installed from location + // UNPACKED. + { + base::DictionaryValue values; + extension = CreatePlatformAppWithExtraValues( + &values, + extensions::Manifest::UNPACKED, + extensions::Extension::NO_FLAGS); + ASSERT_TRUE(extension); + + EXPECT_FALSE(provider.UserMayLoad(extension.get(), &error)); + EXPECT_NE(base::string16(), error); + error.clear(); + } + + // Verify that a platform app with all safe manifest entries can be installed. + { + base::DictionaryValue values; + values.SetString(extensions::manifest_keys::kDescription, "something"); + values.SetString(extensions::manifest_keys::kShortName, "something else"); + base::ListValue* permissions = new base::ListValue(); + permissions->AppendString("alarms"); + permissions->AppendString("background"); + values.Set(extensions::manifest_keys::kPermissions, permissions); + base::ListValue* optional_permissions = new base::ListValue(); + optional_permissions->AppendString("alarms"); + optional_permissions->AppendString("background"); + values.Set(extensions::manifest_keys::kOptionalPermissions, + optional_permissions); + extension = CreatePlatformAppWithExtraValues( + &values, + extensions::Manifest::EXTERNAL_POLICY, + extensions::Extension::NO_FLAGS); + ASSERT_TRUE(extension); + + EXPECT_TRUE(provider.UserMayLoad(extension.get(), &error)); + EXPECT_EQ(base::string16(), error); + error.clear(); + } + + // Verify that a platform app with an unknown manifest entry cannot be + // installed. + { + base::DictionaryValue values; + values.SetString("not_whitelisted", "something"); + extension = CreatePlatformAppWithExtraValues( + &values, + extensions::Manifest::EXTERNAL_POLICY, + extensions::Extension::NO_FLAGS); + ASSERT_TRUE(extension); + + EXPECT_FALSE(provider.UserMayLoad(extension.get(), &error)); + EXPECT_NE(base::string16(), error); + error.clear(); + } + + // Verify that a platform app with an unknown manifest entry under "app" + // cannot be installed. + { + base::DictionaryValue values; + values.SetString("app.not_whitelisted2", "something2"); + extension = CreatePlatformAppWithExtraValues( + &values, + extensions::Manifest::EXTERNAL_POLICY, + extensions::Extension::NO_FLAGS); + ASSERT_TRUE(extension); + + EXPECT_FALSE(provider.UserMayLoad(extension.get(), &error)); + EXPECT_NE(base::string16(), error); + error.clear(); + } + + // Verify that a platform app with an unsafe permission entry cannot be + // installed. + { + base::ListValue* const permissions = new base::ListValue(); + permissions->AppendString("audioCapture"); + base::DictionaryValue values; + values.Set(extensions::manifest_keys::kPermissions, permissions); + + extension = CreatePlatformAppWithExtraValues( + &values, + extensions::Manifest::EXTERNAL_POLICY, + extensions::Extension::NO_FLAGS); + ASSERT_TRUE(extension); + + EXPECT_FALSE(provider.UserMayLoad(extension.get(), &error)); + EXPECT_NE(base::string16(), error); + error.clear(); + } + + // Verify that a platform app with an unsafe optional permission entry cannot + // be installed. + { + base::ListValue* const permissions = new base::ListValue(); + permissions->AppendString("audioCapture"); + base::DictionaryValue values; + values.Set(extensions::manifest_keys::kOptionalPermissions, permissions); + + extension = CreatePlatformAppWithExtraValues( + &values, + extensions::Manifest::EXTERNAL_POLICY, + extensions::Extension::NO_FLAGS); + ASSERT_TRUE(extension); + + EXPECT_FALSE(provider.UserMayLoad(extension.get(), &error)); + EXPECT_NE(base::string16(), error); + error.clear(); + } + + // Verify that a platform app with an url_handlers manifest entry and which is + // not installed through the web store cannot be installed. + { + base::ListValue* const matches = new base::ListValue(); + matches->AppendString("https://example.com/*"); + base::DictionaryValue values; + values.Set("url_handlers.example_com.matches", matches); + values.SetString("url_handlers.example_com.title", "example title"); + + extension = CreatePlatformAppWithExtraValues( + &values, + extensions::Manifest::EXTERNAL_POLICY, + extensions::Extension::NO_FLAGS); + ASSERT_TRUE(extension); + + EXPECT_FALSE(provider.UserMayLoad(extension.get(), &error)); + EXPECT_NE(base::string16(), error); + error.clear(); + } + + // Verify that a platform app with a url_handlers manifest entry and which is + // installed through the web store can be installed. + { + base::ListValue* const matches = new base::ListValue(); + matches->AppendString("https://example.com/*"); + base::DictionaryValue values; + values.Set("url_handlers.example_com.matches", matches); + values.SetString("url_handlers.example_com.title", "example title"); + + extension = CreatePlatformAppWithExtraValues( + &values, + extensions::Manifest::EXTERNAL_POLICY, + extensions::Extension::FROM_WEBSTORE); + ASSERT_TRUE(extension); + + EXPECT_TRUE(provider.UserMayLoad(extension.get(), &error)); + EXPECT_EQ(base::string16(), error); + error.clear(); + } } TEST(DeviceLocalAccountManagementPolicyProviderTest, KioskAppSession) {
diff --git a/chrome/browser/chromeos/extensions/file_manager/private_api_misc.cc b/chrome/browser/chromeos/extensions/file_manager/private_api_misc.cc index 143abd9..2790dbf 100644 --- a/chrome/browser/chromeos/extensions/file_manager/private_api_misc.cc +++ b/chrome/browser/chromeos/extensions/file_manager/private_api_misc.cc
@@ -153,7 +153,7 @@ chromeos::ProfileHelper::Get()->GetUserByProfile(GetProfile()); if (user) { user_manager::UserManager::Get()->SaveUserOAuthStatus( - user->GetAccountId(), user_manager::User::OAUTH2_TOKEN_STATUS_INVALID); + user->email(), user_manager::User::OAUTH2_TOKEN_STATUS_INVALID); } chrome::AttemptUserExit();
diff --git a/chrome/browser/chromeos/extensions/users_private/users_private_api.cc b/chrome/browser/chromeos/extensions/users_private/users_private_api.cc index 7fd1286..b33dff6 100644 --- a/chrome/browser/chromeos/extensions/users_private/users_private_api.cc +++ b/chrome/browser/chromeos/extensions/users_private/users_private_api.cc
@@ -170,8 +170,7 @@ PrefsUtil* prefs_util = delegate->GetPrefsUtil(); bool removed = prefs_util->RemoveFromListCrosSetting( chromeos::kAccountsPrefUsers, canonical_email); - user_manager::UserManager::Get()->RemoveUser( - AccountId::FromUserEmail(parameters->email), NULL); + user_manager::UserManager::Get()->RemoveUser(parameters->email, NULL); return RespondNow(OneArgument(new base::FundamentalValue(removed))); }
diff --git a/chrome/browser/chromeos/extensions/wallpaper_private_api_unittest.cc b/chrome/browser/chromeos/extensions/wallpaper_private_api_unittest.cc index ff3e942..16843b7c 100644 --- a/chrome/browser/chromeos/extensions/wallpaper_private_api_unittest.cc +++ b/chrome/browser/chromeos/extensions/wallpaper_private_api_unittest.cc
@@ -15,7 +15,6 @@ #include "chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager.h" #include "chrome/browser/ui/ash/multi_user/multi_user_window_manager.h" #include "chrome/browser/ui/ash/multi_user/multi_user_window_manager_chromeos.h" -#include "components/signin/core/account_id/account_id.h" #include "ui/aura/test/test_windows.h" #include "ui/aura/window.h" #include "ui/aura/window_event_dispatcher.h" @@ -35,9 +34,6 @@ protected: FakeChromeUserManager* fake_user_manager() { return fake_user_manager_; } - const AccountId test_account_id1_ = AccountId::FromUserEmail(kTestAccount1); - const AccountId test_account_id2_ = AccountId::FromUserEmail(kTestAccount2); - private: FakeChromeUserManager* fake_user_manager_; ScopedUserManagerEnabler scoped_user_manager_; @@ -73,7 +69,7 @@ } // namespace TEST_F(WallpaperPrivateApiUnittest, HideAndRestoreWindows) { - fake_user_manager()->AddUser(test_account_id1_); + fake_user_manager()->AddUser(kTestAccount1); scoped_ptr<aura::Window> window4(CreateTestWindowInShellWithId(4)); scoped_ptr<aura::Window> window3(CreateTestWindowInShellWithId(3)); scoped_ptr<aura::Window> window2(CreateTestWindowInShellWithId(2)); @@ -136,7 +132,7 @@ // 2. If some windows are manually unminimized, the following call will minimize // all the unminimized windows. TEST_F(WallpaperPrivateApiUnittest, HideAndManualUnminimizeWindows) { - fake_user_manager()->AddUser(test_account_id1_); + fake_user_manager()->AddUser(kTestAccount1); scoped_ptr<aura::Window> window1(CreateTestWindowInShellWithId(1)); scoped_ptr<aura::Window> window0(CreateTestWindowInShellWithId(0)); @@ -200,10 +196,10 @@ protected: void SetUpMultiUserWindowManager( - const AccountId& active_account_id, + const std::string& active_user_id, chrome::MultiUserWindowManager::MultiProfileMode mode); - void SwitchActiveUser(const AccountId& active_account_id); + void SwitchActiveUser(const std::string& active_user_id); chrome::MultiUserWindowManagerChromeOS* multi_user_window_manager() { return multi_user_window_manager_; @@ -222,8 +218,8 @@ session_state_delegate_ = static_cast<ash::test::TestSessionStateDelegate*> ( ash::Shell::GetInstance()->session_state_delegate()); - fake_user_manager()->AddUser(test_account_id1_); - fake_user_manager()->AddUser(test_account_id2_); + fake_user_manager()->AddUser(kTestAccount1); + fake_user_manager()->AddUser(kTestAccount2); } void WallpaperPrivateApiMultiUserUnittest::TearDown() { @@ -233,10 +229,10 @@ } void WallpaperPrivateApiMultiUserUnittest::SetUpMultiUserWindowManager( - const AccountId& active_account_id, + const std::string& active_user_id, chrome::MultiUserWindowManager::MultiProfileMode mode) { - multi_user_window_manager_ = new chrome::MultiUserWindowManagerChromeOS( - active_account_id.GetUserEmail()); + multi_user_window_manager_ = + new chrome::MultiUserWindowManagerChromeOS(active_user_id); multi_user_window_manager_->Init(); chrome::MultiUserWindowManager::SetInstanceForTest( multi_user_window_manager_, mode); @@ -247,18 +243,16 @@ } void WallpaperPrivateApiMultiUserUnittest::SwitchActiveUser( - const AccountId& active_account_id) { - fake_user_manager()->SwitchActiveUser(active_account_id); - multi_user_window_manager_->ActiveUserChanged( - active_account_id.GetUserEmail()); + const std::string& active_user_id) { + fake_user_manager()->SwitchActiveUser(active_user_id); + multi_user_window_manager_->ActiveUserChanged(active_user_id); } // In multi profile mode, user may open wallpaper picker in one profile and // then switch to a different profile and open another wallpaper picker // without closing the first one. TEST_F(WallpaperPrivateApiMultiUserUnittest, HideAndRestoreWindowsTwoUsers) { - SetUpMultiUserWindowManager( - test_account_id1_, + SetUpMultiUserWindowManager(kTestAccount1, chrome::MultiUserWindowManager::MULTI_PROFILE_MODE_SEPARATED); scoped_ptr<aura::Window> window4(CreateTestWindowInShellWithId(4)); @@ -273,18 +267,13 @@ ash::wm::WindowState* window3_state = ash::wm::GetWindowState(window3.get()); ash::wm::WindowState* window4_state = ash::wm::GetWindowState(window4.get()); - multi_user_window_manager()->SetWindowOwner(window0.get(), - test_account_id1_.GetUserEmail()); - multi_user_window_manager()->SetWindowOwner(window1.get(), - test_account_id1_.GetUserEmail()); + multi_user_window_manager()->SetWindowOwner(window0.get(), kTestAccount1); + multi_user_window_manager()->SetWindowOwner(window1.get(), kTestAccount1); // Set some windows to an inactive owner. - multi_user_window_manager()->SetWindowOwner(window2.get(), - test_account_id2_.GetUserEmail()); - multi_user_window_manager()->SetWindowOwner(window3.get(), - test_account_id2_.GetUserEmail()); - multi_user_window_manager()->SetWindowOwner(window4.get(), - test_account_id2_.GetUserEmail()); + multi_user_window_manager()->SetWindowOwner(window2.get(), kTestAccount2); + multi_user_window_manager()->SetWindowOwner(window3.get(), kTestAccount2); + multi_user_window_manager()->SetWindowOwner(window4.get(), kTestAccount2); EXPECT_FALSE(window0_state->IsMinimized()); EXPECT_FALSE(window1_state->IsMinimized()); @@ -310,7 +299,7 @@ EXPECT_FALSE(window4_state->IsMinimized()); // Activate kTestAccount2. kTestAccount1 becomes inactive user. - SwitchActiveUser(test_account_id2_); + SwitchActiveUser(kTestAccount2); window2_state->Activate(); EXPECT_TRUE(window2_state->IsActive()); @@ -348,7 +337,7 @@ EXPECT_FALSE(window0_state->IsMinimized()); EXPECT_TRUE(window1_state->IsMinimized()); - SwitchActiveUser(test_account_id1_); + SwitchActiveUser(kTestAccount1); // Then we destroy window 0 and call the restore function. window0.reset(); @@ -363,8 +352,7 @@ // In multi profile mode, user may teleport windows. Teleported window should // also be minimized when open wallpaper picker. TEST_F(WallpaperPrivateApiMultiUserUnittest, HideTeleportedWindow) { - SetUpMultiUserWindowManager( - AccountId::FromUserEmail(kTestAccount1), + SetUpMultiUserWindowManager(kTestAccount1, chrome::MultiUserWindowManager::MULTI_PROFILE_MODE_MIXED); scoped_ptr<aura::Window> window3(CreateTestWindowInShellWithId(3)); @@ -377,20 +365,15 @@ ash::wm::WindowState* window2_state = ash::wm::GetWindowState(window2.get()); ash::wm::WindowState* window3_state = ash::wm::GetWindowState(window3.get()); - multi_user_window_manager()->SetWindowOwner(window0.get(), - test_account_id1_.GetUserEmail()); - multi_user_window_manager()->SetWindowOwner(window1.get(), - test_account_id1_.GetUserEmail()); + multi_user_window_manager()->SetWindowOwner(window0.get(), kTestAccount1); + multi_user_window_manager()->SetWindowOwner(window1.get(), kTestAccount1); // Set some windows to an inactive owner. - multi_user_window_manager()->SetWindowOwner(window2.get(), - test_account_id2_.GetUserEmail()); - multi_user_window_manager()->SetWindowOwner(window3.get(), - test_account_id2_.GetUserEmail()); + multi_user_window_manager()->SetWindowOwner(window2.get(), kTestAccount2); + multi_user_window_manager()->SetWindowOwner(window3.get(), kTestAccount2); // Teleport window2 to kTestAccount1. - multi_user_window_manager()->ShowWindowForUser( - window2.get(), test_account_id1_.GetUserEmail()); + multi_user_window_manager()->ShowWindowForUser(window2.get(), kTestAccount1); // Initial window state. All windows shouldn't be minimized. EXPECT_FALSE(window0_state->IsMinimized());
diff --git a/chrome/browser/chromeos/file_manager/external_filesystem_apitest.cc b/chrome/browser/chromeos/file_manager/external_filesystem_apitest.cc index ad0e0691..fd2d19e 100644 --- a/chrome/browser/chromeos/file_manager/external_filesystem_apitest.cc +++ b/chrome/browser/chromeos/file_manager/external_filesystem_apitest.cc
@@ -567,8 +567,7 @@ base::FilePath user_data_directory; PathService::Get(chrome::DIR_USER_DATA, &user_data_directory); user_manager::UserManager::Get()->UserLoggedIn( - AccountId::FromUserEmail(kSecondProfileAccount), kSecondProfileHash, - false); + kSecondProfileAccount, kSecondProfileHash, false); // Set up the secondary profile. base::FilePath profile_dir = user_data_directory.Append(
diff --git a/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc b/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc index d66547df..faae428 100644 --- a/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc +++ b/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc
@@ -609,10 +609,9 @@ void AddUser(const TestAccountInfo& info, bool log_in) { user_manager::UserManager* const user_manager = user_manager::UserManager::Get(); - const AccountId account_id(AccountId::FromUserEmail(info.email)); if (log_in) - user_manager->UserLoggedIn(account_id, info.hash, false); - user_manager->SaveUserDisplayName(account_id, + user_manager->UserLoggedIn(info.email, info.hash, false); + user_manager->SaveUserDisplayName(info.email, base::UTF8ToUTF16(info.display_name)); SigninManagerFactory::GetForProfile( chromeos::ProfileHelper::GetProfileByUserIdHash(info.hash))
diff --git a/chrome/browser/chromeos/file_system_provider/mount_path_util_unittest.cc b/chrome/browser/chromeos/file_system_provider/mount_path_util_unittest.cc index 9bca244f..1d1f838 100644 --- a/chrome/browser/chromeos/file_system_provider/mount_path_util_unittest.cc +++ b/chrome/browser/chromeos/file_system_provider/mount_path_util_unittest.cc
@@ -70,8 +70,7 @@ profile_ = profile_manager_->CreateTestingProfile("testing-profile"); user_manager_ = new FakeChromeUserManager(); user_manager_enabler_.reset(new ScopedUserManagerEnabler(user_manager_)); - user_manager_->AddUser( - AccountId::FromUserEmail(profile_->GetProfileUserName())); + user_manager_->AddUser(profile_->GetProfileUserName()); file_system_provider_service_ = Service::Get(profile_); file_system_provider_service_->SetFileSystemFactoryForTesting( base::Bind(&FakeProvidedFileSystem::Create));
diff --git a/chrome/browser/chromeos/file_system_provider/service_unittest.cc b/chrome/browser/chromeos/file_system_provider/service_unittest.cc index 8e108ce..6a8fe39b 100644 --- a/chrome/browser/chromeos/file_system_provider/service_unittest.cc +++ b/chrome/browser/chromeos/file_system_provider/service_unittest.cc
@@ -191,8 +191,7 @@ ASSERT_TRUE(profile_manager_->SetUp()); profile_ = profile_manager_->CreateTestingProfile("test-user@example.com"); user_manager_ = new FakeChromeUserManager(); - user_manager_->AddUser( - AccountId::FromUserEmail(profile_->GetProfileUserName())); + user_manager_->AddUser(profile_->GetProfileUserName()); user_manager_enabler_.reset(new ScopedUserManagerEnabler(user_manager_)); extension_registry_.reset(new extensions::ExtensionRegistry(profile_));
diff --git a/chrome/browser/chromeos/input_method/input_method_persistence_unittest.cc b/chrome/browser/chromeos/input_method/input_method_persistence_unittest.cc index ad88581f..4811cac 100644 --- a/chrome/browser/chromeos/input_method/input_method_persistence_unittest.cc +++ b/chrome/browser/chromeos/input_method/input_method_persistence_unittest.cc
@@ -43,14 +43,13 @@ ASSERT_TRUE(mock_profile_manager_.SetUp()); // Add a user. - const AccountId test_account_id( - AccountId::FromUserEmail("test-user@example.com")); - fake_user_manager_->AddUser(test_account_id); - fake_user_manager_->LoginUser(test_account_id); + const char kTestUserName[] = "test-user@example.com"; + fake_user_manager_->AddUser(kTestUserName); + fake_user_manager_->LoginUser(kTestUserName); // Create a valid profile for the user. - TestingProfile* mock_profile = mock_profile_manager_.CreateTestingProfile( - test_account_id.GetUserEmail()); + TestingProfile* mock_profile = + mock_profile_manager_.CreateTestingProfile(kTestUserName); mock_profile_manager_.SetLoggedIn(true); EXPECT_TRUE(ProfileManager::GetActiveUserProfile() == mock_profile);
diff --git a/chrome/browser/chromeos/login/app_launch_controller.cc b/chrome/browser/chromeos/login/app_launch_controller.cc index 6bbea04..eb33f14 100644 --- a/chrome/browser/chromeos/login/app_launch_controller.cc +++ b/chrome/browser/chromeos/login/app_launch_controller.cc
@@ -322,7 +322,7 @@ return true; } - return user_manager::UserManager::Get()->GetOwnerAccountId().is_valid(); + return !user_manager::UserManager::Get()->GetOwnerEmail().empty(); } bool AppLaunchController::NeedOwnerAuthToConfigureNetwork() {
diff --git a/chrome/browser/chromeos/login/app_launch_signin_screen.cc b/chrome/browser/chromeos/login/app_launch_signin_screen.cc index b841c3d..8affe30 100644 --- a/chrome/browser/chromeos/login/app_launch_signin_screen.cc +++ b/chrome/browser/chromeos/login/app_launch_signin_screen.cc
@@ -42,8 +42,7 @@ void AppLaunchSigninScreen::InitOwnerUserList() { user_manager::UserManager* user_manager = GetUserManager(); - const std::string& owner_email = - user_manager->GetOwnerAccountId().GetUserEmail(); + const std::string& owner_email = user_manager->GetOwnerEmail(); const user_manager::UserList& all_users = user_manager->GetUsers(); owner_user_list_.clear();
diff --git a/chrome/browser/chromeos/login/auth/chrome_cryptohome_authenticator.cc b/chrome/browser/chromeos/login/auth/chrome_cryptohome_authenticator.cc index 869f4240..97b24d2 100644 --- a/chrome/browser/chromeos/login/auth/chrome_cryptohome_authenticator.cc +++ b/chrome/browser/chromeos/login/auth/chrome_cryptohome_authenticator.cc
@@ -26,7 +26,7 @@ } bool ChromeCryptohomeAuthenticator::IsKnownUser(const UserContext& context) { - return user_manager::UserManager::Get()->IsKnownUser(context.GetAccountId()); + return user_manager::UserManager::Get()->IsKnownUser(context.GetUserID()); } bool ChromeCryptohomeAuthenticator::IsSafeMode() {
diff --git a/chrome/browser/chromeos/login/auth/chrome_login_performer.cc b/chrome/browser/chromeos/login/auth/chrome_login_performer.cc index e912445..e913bc1 100644 --- a/chrome/browser/chromeos/login/auth/chrome_login_performer.cc +++ b/chrome/browser/chromeos/login/auth/chrome_login_performer.cc
@@ -19,7 +19,6 @@ #include "chrome/browser/chromeos/policy/device_local_account_policy_service.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/chromeos/settings/cros_settings.h" -#include "components/signin/core/account_id/account_id.h" namespace chromeos { @@ -131,8 +130,7 @@ const UserContext& user_context) { SupervisedUserAuthentication* authentication = ChromeUserManager::Get()->GetSupervisedUserManager()->GetAuthentication(); - return authentication->GetPasswordSchema( - user_context.GetAccountId().GetUserEmail()) == + return authentication->GetPasswordSchema(user_context.GetUserID()) == SupervisedUserAuthentication::SCHEMA_SALT_HASHED; } @@ -145,15 +143,12 @@ void ChromeLoginPerformer::SetupSupervisedUserFlow(const std::string& user_id) { SupervisedUserLoginFlow* new_flow = new SupervisedUserLoginFlow(user_id); - new_flow->SetHost(ChromeUserManager::Get() - ->GetUserFlow(AccountId::FromUserEmail(user_id)) - ->host()); - ChromeUserManager::Get()->SetUserFlow(AccountId::FromUserEmail(user_id), - new_flow); + new_flow->SetHost(ChromeUserManager::Get()->GetUserFlow(user_id)->host()); + ChromeUserManager::Get()->SetUserFlow(user_id, new_flow); } void ChromeLoginPerformer::SetupEasyUnlockUserFlow(const std::string& user_id) { - ChromeUserManager::Get()->SetUserFlow(AccountId::FromUserEmail(user_id), + ChromeUserManager::Get()->SetUserFlow(user_id, new EasyUnlockUserLoginFlow(user_id)); }
diff --git a/chrome/browser/chromeos/login/auth/cryptohome_authenticator_unittest.cc b/chrome/browser/chromeos/login/auth/cryptohome_authenticator_unittest.cc index 9a5385f4..c96e922a 100644 --- a/chrome/browser/chromeos/login/auth/cryptohome_authenticator_unittest.cc +++ b/chrome/browser/chromeos/login/auth/cryptohome_authenticator_unittest.cc
@@ -131,7 +131,7 @@ class CryptohomeAuthenticatorTest : public testing::Test { public: CryptohomeAuthenticatorTest() - : user_context_(AccountId::FromUserEmail("me@nowhere.org")), + : user_context_("me@nowhere.org"), user_manager_(new user_manager::FakeUserManager()), user_manager_enabler_(user_manager_), mock_caller_(NULL), @@ -142,8 +142,8 @@ user_context_.SetKey(Key("fakepass")); user_context_.SetUserIDHash("me_nowhere_com_hash"); const user_manager::User* user = - user_manager_->AddUser(user_context_.GetAccountId()); - profile_.set_profile_name(user_context_.GetAccountId().GetUserEmail()); + user_manager_->AddUser(user_context_.GetUserID()); + profile_.set_profile_name(user_context_.GetUserID()); ProfileHelper::Get()->SetUserToProfileMappingForTesting(user, &profile_); @@ -264,12 +264,13 @@ cryptohome::KeyDefinition::ProviderData("salt")); key_definition.provider_data.back().bytes = salt.Pass(); } - EXPECT_CALL(*mock_homedir_methods_, - GetKeyDataEx(cryptohome::Identification( - user_context_.GetAccountId().GetUserEmail()), - kCryptohomeGAIAKeyLabel, _)) + EXPECT_CALL(*mock_homedir_methods_, GetKeyDataEx( + cryptohome::Identification(user_context_.GetUserID()), + kCryptohomeGAIAKeyLabel, + _)) .WillOnce(WithArg<2>(Invoke( - this, &CryptohomeAuthenticatorTest::InvokeGetDataExCallback))); + this, + &CryptohomeAuthenticatorTest::InvokeGetDataExCallback))); } void ExpectMountExCall(bool expect_create_attempt) { @@ -284,9 +285,10 @@ cryptohome::PRIV_DEFAULT)); } EXPECT_CALL(*mock_homedir_methods_, - MountEx(cryptohome::Identification( - user_context_.GetAccountId().GetUserEmail()), - cryptohome::Authorization(auth_key), mount, _)) + MountEx(cryptohome::Identification(user_context_.GetUserID()), + cryptohome::Authorization(auth_key), + mount, + _)) .Times(1) .RetiresOnSaturation(); } @@ -560,8 +562,7 @@ // Set up mock async method caller to respond successfully to a cryptohome // remove attempt. mock_caller_->SetUp(true, cryptohome::MOUNT_ERROR_NONE); - EXPECT_CALL(*mock_caller_, - AsyncRemove(user_context_.GetAccountId().GetUserEmail(), _)) + EXPECT_CALL(*mock_caller_, AsyncRemove(user_context_.GetUserID(), _)) .Times(1) .RetiresOnSaturation(); @@ -583,8 +584,7 @@ // Set up mock async method caller to fail a cryptohome remove attempt. mock_caller_->SetUp(false, cryptohome::MOUNT_ERROR_NONE); - EXPECT_CALL(*mock_caller_, - AsyncRemove(user_context_.GetAccountId().GetUserEmail(), _)) + EXPECT_CALL(*mock_caller_, AsyncRemove(user_context_.GetUserID(), _)) .Times(1) .RetiresOnSaturation(); @@ -614,9 +614,10 @@ // Set up mock async method caller to respond successfully to a key migration. mock_caller_->SetUp(true, cryptohome::MOUNT_ERROR_NONE); - EXPECT_CALL(*mock_caller_, - AsyncMigrateKey(user_context_.GetAccountId().GetUserEmail(), _, - transformed_key_.GetSecret(), _)) + EXPECT_CALL( + *mock_caller_, + AsyncMigrateKey( + user_context_.GetUserID(), _, transformed_key_.GetSecret(), _)) .Times(1) .RetiresOnSaturation(); @@ -639,9 +640,10 @@ // Set up mock async method caller to fail a key migration attempt, // asserting that the wrong password was used. mock_caller_->SetUp(false, cryptohome::MOUNT_ERROR_KEY_FAILURE); - EXPECT_CALL(*mock_caller_, - AsyncMigrateKey(user_context_.GetAccountId().GetUserEmail(), _, - transformed_key_.GetSecret(), _)) + EXPECT_CALL( + *mock_caller_, + AsyncMigrateKey( + user_context_.GetUserID(), _, transformed_key_.GetSecret(), _)) .Times(1) .RetiresOnSaturation(); @@ -730,8 +732,7 @@ // Set up mock async method caller to respond successfully to a cryptohome // key-check attempt. mock_caller_->SetUp(true, cryptohome::MOUNT_ERROR_NONE); - EXPECT_CALL(*mock_caller_, - AsyncCheckKey(user_context_.GetAccountId().GetUserEmail(), _, _)) + EXPECT_CALL(*mock_caller_, AsyncCheckKey(user_context_.GetUserID(), _, _)) .Times(1) .RetiresOnSaturation();
diff --git a/chrome/browser/chromeos/login/chrome_restart_request.cc b/chrome/browser/chromeos/login/chrome_restart_request.cc index fd00ab22..07402e4 100644 --- a/chrome/browser/chromeos/login/chrome_restart_request.cc +++ b/chrome/browser/chromeos/login/chrome_restart_request.cc
@@ -114,6 +114,7 @@ ::switches::kEnableRGBA4444Textures, ::switches::kEnableSlimmingPaintV2, ::switches::kEnableTouchDragDrop, + ::switches::kEnableUseZoomForDSF, ::switches::kEnableViewport, ::switches::kEnableZeroCopy, #if defined(USE_OZONE)
diff --git a/chrome/browser/chromeos/login/easy_unlock/bootstrap_browsertest.cc b/chrome/browser/chromeos/login/easy_unlock/bootstrap_browsertest.cc index 70d612e..1b20386 100644 --- a/chrome/browser/chromeos/login/easy_unlock/bootstrap_browsertest.cc +++ b/chrome/browser/chromeos/login/easy_unlock/bootstrap_browsertest.cc
@@ -156,8 +156,7 @@ } IN_PROC_BROWSER_TEST_F(BootstrapTest, CleanUpFailedUser) { - EXPECT_FALSE(user_manager::UserManager::Get()->IsKnownUser( - AccountId::FromUserEmail(kFakeUser))); + EXPECT_FALSE(user_manager::UserManager::Get()->IsKnownUser(kFakeUser)); } } // namespace chromeos
diff --git a/chrome/browser/chromeos/login/easy_unlock/bootstrap_user_context_initializer.cc b/chrome/browser/chromeos/login/easy_unlock/bootstrap_user_context_initializer.cc index d42c5df..9d66402 100644 --- a/chrome/browser/chromeos/login/easy_unlock/bootstrap_user_context_initializer.cc +++ b/chrome/browser/chromeos/login/easy_unlock/bootstrap_user_context_initializer.cc
@@ -68,9 +68,10 @@ } void BootstrapUserContextInitializer::StartCheckExistingKeys() { + const std::string& user_id = user_context_.GetUserID(); + // Use random key for the first time user. - if (!user_manager::UserManager::Get()->IsKnownUser( - user_context_.GetAccountId())) { + if (!user_manager::UserManager::Get()->IsKnownUser(user_id)) { CreateRandomKey(); return; } @@ -78,7 +79,7 @@ EasyUnlockKeyManager* key_manager = UserSessionManager::GetInstance()->GetEasyUnlockKeyManager(); key_manager->GetDeviceDataList( - UserContext(user_context_.GetAccountId()), + UserContext(user_id), base::Bind(&BootstrapUserContextInitializer::OnGetEasyUnlockData, weak_ptr_factory_.GetWeakPtr())); } @@ -98,7 +99,7 @@ service->AddObserver(this); static_cast<EasyUnlockServiceSignin*>(service) - ->SetCurrentUser(user_context_.GetAccountId().GetUserEmail()); + ->SetCurrentUser(user_context_.GetUserID()); OnScreenlockStateChanged(service->GetScreenlockState()); } @@ -202,7 +203,7 @@ service->RemoveObserver(this); service->AttemptAuth( - user_context_.GetAccountId().GetUserEmail(), + user_context_.GetUserID(), base::Bind(&BootstrapUserContextInitializer::OnEasyUnlockAuthenticated, weak_ptr_factory_.GetWeakPtr())); }
diff --git a/chrome/browser/chromeos/login/easy_unlock/bootstrap_user_flow.cc b/chrome/browser/chromeos/login/easy_unlock/bootstrap_user_flow.cc index acf5cf5..64a6b33a 100644 --- a/chrome/browser/chromeos/login/easy_unlock/bootstrap_user_flow.cc +++ b/chrome/browser/chromeos/login/easy_unlock/bootstrap_user_flow.cc
@@ -14,20 +14,19 @@ #include "chrome/browser/signin/easy_unlock_service.h" #include "chrome/browser/signin/easy_unlock_service_regular.h" #include "components/proximity_auth/screenlock_bridge.h" -#include "components/signin/core/account_id/account_id.h" namespace chromeos { BootstrapUserFlow::BootstrapUserFlow(const UserContext& user_context, bool is_new_account) - : ExtendedUserFlow(user_context.GetAccountId().GetUserEmail()), + : ExtendedUserFlow(user_context.GetUserID()), user_context_(user_context), is_new_account_(is_new_account), finished_(false), user_profile_(nullptr), weak_ptr_factory_(this) { ChromeUserManager::Get()->GetBootstrapManager()->AddPendingBootstrap( - user_context_.GetAccountId().GetUserEmail()); + user_context_.GetUserID()); } BootstrapUserFlow::~BootstrapUserFlow() { @@ -111,7 +110,7 @@ finished_ = true; ChromeUserManager::Get()->GetBootstrapManager()->FinishPendingBootstrap( - user_context_.GetAccountId().GetUserEmail()); + user_context_.GetUserID()); UserSessionManager::GetInstance()->DoBrowserLaunch(user_profile_, host()); user_profile_ = nullptr;
diff --git a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_create_keys_operation.cc b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_create_keys_operation.cc index 878eab7a..4d5f15c 100644 --- a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_create_keys_operation.cc +++ b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_create_keys_operation.cc
@@ -346,8 +346,8 @@ kEasyUnlockKeyMetaNameWrappedSecret, device->wrapped_secret)); // Add cryptohome key. - const std::string canonicalized = - gaia::CanonicalizeEmail(user_context_.GetAccountId().GetUserEmail()); + std::string canonicalized = + gaia::CanonicalizeEmail(user_context_.GetUserID()); cryptohome::Identification id(canonicalized); scoped_ptr<Key> auth_key(new Key(*user_context_.GetKey()));
diff --git a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_get_keys_operation.cc b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_get_keys_operation.cc index 7e625679..e0789c8 100644 --- a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_get_keys_operation.cc +++ b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_get_keys_operation.cc
@@ -9,7 +9,6 @@ #include "base/bind.h" #include "base/logging.h" #include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_key_manager.h" -#include "components/signin/core/account_id/account_id.h" #include "google_apis/gaia/gaia_auth_util.h" namespace chromeos { @@ -33,8 +32,8 @@ } void EasyUnlockGetKeysOperation::GetKeyData() { - const std::string canonicalized = - gaia::CanonicalizeEmail(user_context_.GetAccountId().GetUserEmail()); + std::string canonicalized = + gaia::CanonicalizeEmail(user_context_.GetUserID()); cryptohome::Identification id(canonicalized); cryptohome::HomedirMethods::GetInstance()->GetKeyDataEx( id,
diff --git a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_key_manager.cc b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_key_manager.cc index 3cfa4bc..c1ba482f 100644 --- a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_key_manager.cc +++ b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_key_manager.cc
@@ -11,7 +11,6 @@ #include "base/values.h" #include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_tpm_key_manager.h" #include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_tpm_key_manager_factory.h" -#include "components/signin/core/account_id/account_id.h" namespace chromeos { @@ -53,7 +52,7 @@ EasyUnlockTpmKeyManager* tpm_key_manager = EasyUnlockTpmKeyManagerFactory::GetInstance()->GetForUser( - user_context.GetAccountId().GetUserEmail()); + user_context.GetUserID()); if (!tpm_key_manager) { LOG(ERROR) << "No TPM key manager."; callback.Run(false); @@ -82,9 +81,9 @@ const RefreshKeysCallback& callback) { EasyUnlockTpmKeyManager* tpm_key_manager = EasyUnlockTpmKeyManagerFactory::GetInstance()->GetForUser( - user_context.GetAccountId().GetUserEmail()); - const std::string tpm_public_key = tpm_key_manager->GetPublicTpmKey( - user_context.GetAccountId().GetUserEmail()); + user_context.GetUserID()); + std::string tpm_public_key = + tpm_key_manager->GetPublicTpmKey(user_context.GetUserID()); EasyUnlockDeviceKeyDataList devices; if (!RemoteDeviceListToDeviceDataList(*remote_devices, &devices))
diff --git a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_remove_keys_operation.cc b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_remove_keys_operation.cc index 9ead3ef..795db23d 100644 --- a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_remove_keys_operation.cc +++ b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_remove_keys_operation.cc
@@ -47,8 +47,8 @@ } void EasyUnlockRemoveKeysOperation::RemoveKey() { - const std::string canonicalized = - gaia::CanonicalizeEmail(user_context_.GetAccountId().GetUserEmail()); + std::string canonicalized = + gaia::CanonicalizeEmail(user_context_.GetUserID()); cryptohome::Identification id(canonicalized); const Key* const auth_key = user_context_.GetKey(); cryptohome::Authorization auth(auth_key->GetSecret(), auth_key->GetLabel());
diff --git a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_tpm_key_manager_factory.cc b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_tpm_key_manager_factory.cc index ebce3abcc..00d1d0e 100644 --- a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_tpm_key_manager_factory.cc +++ b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_tpm_key_manager_factory.cc
@@ -11,7 +11,6 @@ #include "chrome/browser/profiles/incognito_helpers.h" #include "chrome/browser/profiles/profile.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" -#include "components/signin/core/account_id/account_id.h" #include "components/user_manager/user.h" namespace { @@ -37,8 +36,8 @@ EasyUnlockTpmKeyManager* EasyUnlockTpmKeyManagerFactory::GetForUser( const std::string& user_id) { - const user_manager::User* user = user_manager::UserManager::Get()->FindUser( - AccountId::FromUserEmail(user_id)); + const user_manager::User* user = + user_manager::UserManager::Get()->FindUser(user_id); if (!user) return NULL; Profile* profile = chromeos::ProfileHelper::Get()->GetProfileByUser(user);
diff --git a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_tpm_key_manager_unittest.cc b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_tpm_key_manager_unittest.cc index ef61f00..40462b3f 100644 --- a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_tpm_key_manager_unittest.cc +++ b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_tpm_key_manager_unittest.cc
@@ -202,8 +202,7 @@ void SetUp() override { ASSERT_TRUE(profile_manager_.SetUp()); - const user_manager::User* user = - user_manager_->AddUser(AccountId::FromUserEmail(kTestUserId)); + const user_manager::User* user = user_manager_->AddUser(kTestUserId); username_hash_ = user->username_hash(); signin_profile_ = profile_manager_.CreateTestingProfile(
diff --git a/chrome/browser/chromeos/login/existing_user_controller.cc b/chrome/browser/chromeos/login/existing_user_controller.cc index 94c54bab..2ba77ed 100644 --- a/chrome/browser/chromeos/login/existing_user_controller.cc +++ b/chrome/browser/chromeos/login/existing_user_controller.cc
@@ -125,8 +125,7 @@ if (user_context.GetUserType() == user_manager::USER_TYPE_REGULAR && user_context.GetAuthFlow() == UserContext::AUTH_FLOW_OFFLINE && easy_unlock_service) { - easy_unlock_service->RecordPasswordLoginEvent( - user_context.GetAccountId().GetUserEmail()); + easy_unlock_service->RecordPasswordLoginEvent(user_context.GetUserID()); } } @@ -356,7 +355,7 @@ LoginPerformer::AuthorizationMode auth_mode) { VLOG(1) << "Setting flow from PerformLogin"; ChromeUserManager::Get() - ->GetUserFlow(user_context.GetAccountId()) + ->GetUserFlow(user_context.GetUserID()) ->SetHost(host_); BootTimesRecorder::Get()->RecordLoginAttempted(); @@ -369,7 +368,7 @@ login_performer_.reset(new ChromeLoginPerformer(this)); } - if (gaia::ExtractDomainName(user_context.GetAccountId().GetUserEmail()) == + if (gaia::ExtractDomainName(user_context.GetUserID()) == chromeos::login::kSupervisedUserDomain) { login_performer_->LoginAsSupervisedUser(user_context); } else { @@ -510,7 +509,7 @@ PerformLoginFinishedActions(false /* don't start public session timer */); if (ChromeUserManager::Get() - ->GetUserFlow(last_login_attempt_account_id_) + ->GetUserFlow(last_login_attempt_username_) ->HandleLoginFailure(failure)) { return; } @@ -525,15 +524,15 @@ base::TimeDelta::FromMilliseconds(kSafeModeRestartUiDelayMs)); } else if (failure.reason() == AuthFailure::TPM_ERROR) { ShowTPMError(); - } else if (last_login_attempt_account_id_ == login::GuestAccountId()) { + } else if (last_login_attempt_username_ == chromeos::login::kGuestUserName) { // Show no errors, just re-enable input. login_display_->ClearAndEnablePassword(); StartPublicSessionAutoLoginTimer(); } else { // Check networking after trying to login in case user is // cached locally or the local admin account. - const bool is_known_user = user_manager::UserManager::Get()->IsKnownUser( - last_login_attempt_account_id_); + bool is_known_user = user_manager::UserManager::Get()->IsKnownUser( + last_login_attempt_username_); if (!network_state_helper_->IsConnected()) { if (is_known_user) ShowError(IDS_LOGIN_ERROR_AUTHENTICATING, error); @@ -558,7 +557,7 @@ // Reset user flow to default, so that special flow will not affect next // attempt. - ChromeUserManager::Get()->ResetUserFlow(last_login_attempt_account_id_); + ChromeUserManager::Get()->ResetUserFlow(last_login_attempt_username_); if (auth_status_consumer_) auth_status_consumer_->OnAuthFailure(failure); @@ -569,7 +568,7 @@ // TODO(ginkage): Fix this case once crbug.com/469990 is ready. /* if (failure.reason() == AuthFailure::COULD_NOT_MOUNT_CRYPTOHOME) { - RecordReauthReason(last_login_attempt_account_id_, + RecordReauthReason(last_login_attempt_username_, ReauthReason::MISSING_CRYPTOHOME); } */ @@ -585,7 +584,7 @@ auth_mode_ = login_performer_->auth_mode(); ChromeUserManager::Get() - ->GetUserFlow(user_context.GetAccountId()) + ->GetUserFlow(user_context.GetUserID()) ->HandleLoginSuccess(user_context); StopPublicSessionAutoLoginTimer(); @@ -617,7 +616,7 @@ // Update user's displayed email. if (!display_email_.empty()) { user_manager::UserManager::Get()->SaveUserDisplayEmail( - user_context.GetAccountId(), display_email_); + user_context.GetUserID(), display_email_); display_email_.clear(); } } @@ -633,8 +632,8 @@ // Inform |auth_status_consumer_| about successful login. // TODO(nkostylev): Pass UserContext back crbug.com/424550 if (auth_status_consumer_) { - auth_status_consumer_->OnAuthSuccess( - UserContext(last_login_attempt_account_id_)); + auth_status_consumer_-> + OnAuthSuccess(UserContext(last_login_attempt_username_)); } } @@ -664,7 +663,7 @@ } if (ChromeUserManager::Get() - ->GetUserFlow(last_login_attempt_account_id_) + ->GetUserFlow(last_login_attempt_username_) ->HandlePasswordChangeDetected()) { return; } @@ -761,7 +760,7 @@ // If there is no public account with the given user ID, logging in is not // possible. const user_manager::User* user = - user_manager::UserManager::Get()->FindUser(user_context.GetAccountId()); + user_manager::UserManager::Get()->FindUser(user_context.GetUserID()); if (!user || user->GetType() != user_manager::USER_TYPE_PUBLIC_ACCOUNT) { PerformLoginFinishedActions(true /* start public session timer */); return; @@ -774,15 +773,11 @@ // whether a list of recommended locales was set by policy. If so, use its // first entry. Otherwise, |locale| will remain blank, indicating that the // public session should use the current UI locale. - const policy::PolicyMap::Entry* entry = - g_browser_process->platform_part() - ->browser_policy_connector_chromeos() - ->GetDeviceLocalAccountPolicyService() - ->GetBrokerForUser(user_context.GetAccountId().GetUserEmail()) - ->core() - ->store() - ->policy_map() - .Get(policy::key::kSessionLocales); + const policy::PolicyMap::Entry* entry = g_browser_process->platform_part()-> + browser_policy_connector_chromeos()-> + GetDeviceLocalAccountPolicyService()-> + GetBrokerForUser(user_context.GetUserID())->core()->store()-> + policy_map().Get(policy::key::kSessionLocales); base::ListValue const* list = NULL; if (entry && entry->level == policy::POLICY_LEVEL_RECOMMENDED && @@ -848,7 +843,7 @@ } const user_manager::User* user = user_manager::UserManager::Get()->FindUser( - AccountId::FromUserEmail(public_session_auto_login_username_)); + public_session_auto_login_username_); if (!user || user->GetType() != user_manager::USER_TYPE_PUBLIC_ACCOUNT) public_session_auto_login_username_.clear(); @@ -934,7 +929,7 @@ if (num_login_attempts_ > 1) { const user_manager::User* user = user_manager::UserManager::Get()->FindUser( - last_login_attempt_account_id_); + last_login_attempt_username_); if (user && (user->GetType() == user_manager::USER_TYPE_SUPERVISED)) error_id = IDS_LOGIN_ERROR_AUTHENTICATING_2ND_TIME_SUPERVISED; } @@ -985,8 +980,8 @@ // Disable clicking on other windows and status tray. login_display_->SetUIEnabled(false); - if (last_login_attempt_account_id_ != user_context.GetAccountId()) { - last_login_attempt_account_id_ = user_context.GetAccountId(); + if (last_login_attempt_username_ != user_context.GetUserID()) { + last_login_attempt_username_ = user_context.GetUserID(); num_login_attempts_ = 0; } @@ -1066,11 +1061,11 @@ UserContext user_context = user_context_wo_device_id; std::string device_id = user_manager::UserManager::Get()->GetKnownUserDeviceId( - user_context.GetAccountId()); + user_context.GetUserID()); if (device_id.empty()) { - bool is_ephemeral = ChromeUserManager::Get()->AreEphemeralUsersEnabled() && - user_context.GetAccountId() != - ChromeUserManager::Get()->GetOwnerAccountId(); + bool is_ephemeral = + ChromeUserManager::Get()->AreEphemeralUsersEnabled() && + user_context.GetUserID() != ChromeUserManager::Get()->GetOwnerEmail(); device_id = SigninClient::GenerateSigninScopedDeviceID(is_ephemeral); } user_context.SetDeviceId(device_id); @@ -1078,7 +1073,7 @@ const std::string& gaps_cookie = user_context.GetGAPSCookie(); if (!gaps_cookie.empty()) { user_manager::UserManager::Get()->SetKnownUserGAPSCookie( - user_context.GetAccountId(), gaps_cookie); + user_context.GetUserID(), gaps_cookie); } PerformPreLoginActions(user_context); @@ -1150,8 +1145,7 @@ } if (user_context.GetUserType() == user_manager::USER_TYPE_KIOSK_APP) { - LoginAsKioskApp(user_context.GetAccountId().GetUserEmail(), - specifics.kiosk_diagnostic_mode); + LoginAsKioskApp(user_context.GetUserID(), specifics.kiosk_diagnostic_mode); return; } @@ -1182,7 +1176,7 @@ // Setting a customized login user flow to perform additional initializations // for bootstrap after the user session is started. ChromeUserManager::Get()->SetUserFlow( - user_context.GetAccountId(), + user_context.GetUserID(), new BootstrapUserFlow( user_context, bootstrap_user_context_initializer_->random_key_used()));
diff --git a/chrome/browser/chromeos/login/existing_user_controller.h b/chrome/browser/chromeos/login/existing_user_controller.h index d9c7a503..ea8d1966 100644 --- a/chrome/browser/chromeos/login/existing_user_controller.h +++ b/chrome/browser/chromeos/login/existing_user_controller.h
@@ -254,8 +254,8 @@ // Tests can use this to receive authentication status events. AuthStatusConsumer* auth_status_consumer_; - // AccountId of the last login attempt. - AccountId last_login_attempt_account_id_ = EmptyAccountId(); + // Username of the last login attempt. + std::string last_login_attempt_username_; // OOBE/login display host. LoginDisplayHost* host_;
diff --git a/chrome/browser/chromeos/login/existing_user_controller_auto_login_unittest.cc b/chrome/browser/chromeos/login/existing_user_controller_auto_login_unittest.cc index 3d6ff7f..0725453 100644 --- a/chrome/browser/chromeos/login/existing_user_controller_auto_login_unittest.cc +++ b/chrome/browser/chromeos/login/existing_user_controller_auto_login_unittest.cc
@@ -30,6 +30,7 @@ namespace { +const char kAutoLoginAccountId[] = "public_session_user@localhost"; // These values are only used to test the configuration. They don't // delay the test. const int kAutoLoginDelay1 = 60000; @@ -40,10 +41,14 @@ class ExistingUserControllerAutoLoginTest : public ::testing::Test { protected: ExistingUserControllerAutoLoginTest() - : ui_thread_(content::BrowserThread::UI, &message_loop_), + : auto_login_user_id_(policy::GenerateDeviceLocalAccountUserId( + kAutoLoginAccountId, + policy::DeviceLocalAccount::TYPE_PUBLIC_SESSION)), + ui_thread_(content::BrowserThread::UI, &message_loop_), local_state_(TestingBrowserProcess::GetGlobal()), mock_user_manager_(new MockUserManager()), - scoped_user_manager_(mock_user_manager_) {} + scoped_user_manager_(mock_user_manager_) { + } void SetUp() override { mock_login_display_host_.reset(new MockLoginDisplayHost); @@ -56,16 +61,17 @@ EXPECT_CALL(*mock_user_manager_, Shutdown()).Times(AnyNumber()); EXPECT_CALL(*mock_user_manager_, FindUser(_)) .WillRepeatedly(ReturnNull()); - EXPECT_CALL(*mock_user_manager_, FindUser(auto_login_account_id_)) - .WillRepeatedly(Return(mock_user_manager_->CreatePublicAccountUser( - auto_login_account_id_))); + EXPECT_CALL(*mock_user_manager_, FindUser(auto_login_user_id_)) + .WillRepeatedly(Return( + mock_user_manager_->CreatePublicAccountUser(auto_login_user_id_))); existing_user_controller_.reset( new ExistingUserController(mock_login_display_host_.get())); scoped_ptr<base::DictionaryValue> account(new base::DictionaryValue); account->SetStringWithoutPathExpansion( - kAccountsPrefDeviceLocalAccountsKeyId, auto_login_user_id_); + kAccountsPrefDeviceLocalAccountsKeyId, + kAutoLoginAccountId); account->SetIntegerWithoutPathExpansion( kAccountsPrefDeviceLocalAccountsKeyType, policy::DeviceLocalAccount::TYPE_PUBLIC_SESSION); @@ -88,9 +94,10 @@ return ExistingUserController::current_controller(); } - void SetAutoLoginSettings(const std::string& user_id, int delay) { - CrosSettings::Get()->SetString(kAccountsPrefDeviceLocalAccountAutoLoginId, - user_id); + void SetAutoLoginSettings(const std::string& account_id, int delay) { + CrosSettings::Get()->SetString( + kAccountsPrefDeviceLocalAccountAutoLoginId, + account_id); CrosSettings::Get()->SetInteger( kAccountsPrefDeviceLocalAccountAutoLoginDelay, delay); @@ -126,13 +133,7 @@ existing_user_controller()->ConfigurePublicSessionAutoLogin(); } - const std::string auto_login_user_id_ = - std::string("public_session_user@localhost"); - - const AccountId auto_login_account_id_ = - AccountId::FromUserEmail(policy::GenerateDeviceLocalAccountUserId( - auto_login_user_id_, - policy::DeviceLocalAccount::TYPE_PUBLIC_SESSION)); + const std::string auto_login_user_id_; private: // |mock_login_display_| is owned by the ExistingUserController, which calls @@ -157,7 +158,7 @@ TEST_F(ExistingUserControllerAutoLoginTest, StartAutoLoginTimer) { // Timer shouldn't start until signin screen is ready. - set_auto_login_username(auto_login_account_id_.GetUserEmail()); + set_auto_login_username(auto_login_user_id_); set_auto_login_delay(kAutoLoginDelay2); existing_user_controller()->StartPublicSessionAutoLoginTimer(); EXPECT_FALSE(auto_login_timer()); @@ -169,7 +170,7 @@ EXPECT_FALSE(auto_login_timer()); // Timer shouldn't fire in the middle of a login attempt. - set_auto_login_username(auto_login_account_id_.GetUserEmail()); + set_auto_login_username(auto_login_user_id_); set_is_login_in_progress(true); existing_user_controller()->StartPublicSessionAutoLoginTimer(); EXPECT_FALSE(auto_login_timer()); @@ -185,7 +186,7 @@ TEST_F(ExistingUserControllerAutoLoginTest, StopAutoLoginTimer) { existing_user_controller()->OnSigninScreenReady(); - set_auto_login_username(auto_login_account_id_.GetUserEmail()); + set_auto_login_username(auto_login_user_id_); set_auto_login_delay(kAutoLoginDelay2); existing_user_controller()->StartPublicSessionAutoLoginTimer(); @@ -199,7 +200,7 @@ TEST_F(ExistingUserControllerAutoLoginTest, ResetAutoLoginTimer) { existing_user_controller()->OnSigninScreenReady(); - set_auto_login_username(auto_login_account_id_.GetUserEmail()); + set_auto_login_username(auto_login_user_id_); // Timer starts off not running. EXPECT_FALSE(auto_login_timer()); @@ -243,24 +244,24 @@ EXPECT_EQ(auto_login_username(), ""); // Timer should start when the account ID is set. - SetAutoLoginSettings(auto_login_user_id_, kAutoLoginDelay1); + SetAutoLoginSettings(kAutoLoginAccountId, kAutoLoginDelay1); ConfigureAutoLogin(); ASSERT_TRUE(auto_login_timer()); EXPECT_TRUE(auto_login_timer()->IsRunning()); EXPECT_EQ(auto_login_timer()->GetCurrentDelay().InMilliseconds(), kAutoLoginDelay1); EXPECT_EQ(auto_login_delay(), kAutoLoginDelay1); - EXPECT_EQ(auto_login_username(), auto_login_account_id_.GetUserEmail()); + EXPECT_EQ(auto_login_username(), auto_login_user_id_); // Timer should restart when the delay is changed. - SetAutoLoginSettings(auto_login_user_id_, kAutoLoginDelay2); + SetAutoLoginSettings(kAutoLoginAccountId, kAutoLoginDelay2); ConfigureAutoLogin(); ASSERT_TRUE(auto_login_timer()); EXPECT_TRUE(auto_login_timer()->IsRunning()); EXPECT_EQ(auto_login_timer()->GetCurrentDelay().InMilliseconds(), kAutoLoginDelay2); EXPECT_EQ(auto_login_delay(), kAutoLoginDelay2); - EXPECT_EQ(auto_login_username(), auto_login_account_id_.GetUserEmail()); + EXPECT_EQ(auto_login_username(), auto_login_user_id_); // Timer should stop when the account ID is unset. SetAutoLoginSettings("", kAutoLoginDelay2);
diff --git a/chrome/browser/chromeos/login/existing_user_controller_browsertest.cc b/chrome/browser/chromeos/login/existing_user_controller_browsertest.cc index fec9718c..babb4225 100644 --- a/chrome/browser/chromeos/login/existing_user_controller_browsertest.cc +++ b/chrome/browser/chromeos/login/existing_user_controller_browsertest.cc
@@ -76,7 +76,7 @@ const char kSupervisedUserID[] = "supervised_user@locally-managed.localhost"; const char kPassword[] = "test_password"; -const char kPublicSessionUserEmail[] = "public_session_user@localhost"; +const char kPublicSessionAccountId[] = "public_session_user@localhost"; const int kAutoLoginNoDelay = 0; const int kAutoLoginShortDelay = 1; const int kAutoLoginLongDelay = 10000; @@ -105,7 +105,7 @@ class ExistingUserControllerTest : public policy::DevicePolicyCrosBrowserTest { protected: - ExistingUserControllerTest() {} + ExistingUserControllerTest() : mock_login_display_(NULL) {} ExistingUserController* existing_user_controller() { return ExistingUserController::current_controller(); @@ -196,9 +196,8 @@ return existing_user_controller()->auto_login_timer_.get(); } - AccountId auto_login_account_id() const { - return AccountId::FromUserEmail( - existing_user_controller()->public_session_auto_login_username_); + const std::string& auto_login_username() const { + return existing_user_controller()->public_session_auto_login_username_; } int auto_login_delay() const { @@ -213,29 +212,27 @@ // |mock_login_display_| is owned by the ExistingUserController, which calls // CreateLoginDisplay() on the |mock_login_display_host_| to get it. - MockLoginDisplay* mock_login_display_ = nullptr; + MockLoginDisplay* mock_login_display_; scoped_ptr<MockLoginDisplayHost> mock_login_display_host_; // Mock URLFetcher. MockURLFetcherFactory<SuccessFetcher> factory_; - const AccountId account_id_ = AccountId::FromUserEmail(kUsername); - private: DISALLOW_COPY_AND_ASSIGN(ExistingUserControllerTest); }; IN_PROC_BROWSER_TEST_F(ExistingUserControllerTest, PRE_ExistingUserLogin) { - RegisterUser(account_id_.GetUserEmail()); + RegisterUser(kUsername); } IN_PROC_BROWSER_TEST_F(ExistingUserControllerTest, ExistingUserLogin) { EXPECT_CALL(*mock_login_display_, SetUIEnabled(false)) .Times(2); - UserContext user_context(account_id_); + UserContext user_context(kUsername); user_context.SetGaiaID(kGaiaID); user_context.SetKey(Key(kPassword)); - user_context.SetUserIDHash(account_id_.GetUserEmail()); + user_context.SetUserIDHash(kUsername); test::UserSessionManagerTestApi session_manager_test_api( UserSessionManager::GetInstance()); session_manager_test_api.InjectStubUserContext(user_context); @@ -283,19 +280,19 @@ IN_PROC_BROWSER_TEST_F(ExistingUserControllerUntrustedTest, ExistingUserLoginForbidden) { - UserContext user_context(account_id_); + UserContext user_context(kUsername); user_context.SetGaiaID(kGaiaID); user_context.SetKey(Key(kPassword)); - user_context.SetUserIDHash(account_id_.GetUserEmail()); + user_context.SetUserIDHash(kUsername); existing_user_controller()->Login(user_context, SigninSpecifics()); } IN_PROC_BROWSER_TEST_F(ExistingUserControllerUntrustedTest, NewUserLoginForbidden) { - UserContext user_context(account_id_); + UserContext user_context(kUsername); user_context.SetGaiaID(kGaiaID); user_context.SetKey(Key(kPassword)); - user_context.SetUserIDHash(account_id_.GetUserEmail()); + user_context.SetUserIDHash(kUsername); existing_user_controller()->CompleteLogin(user_context); } @@ -308,9 +305,9 @@ IN_PROC_BROWSER_TEST_F(ExistingUserControllerUntrustedTest, SupervisedUserLoginForbidden) { - UserContext user_context(AccountId::FromUserEmail(kSupervisedUserID)); + UserContext user_context(kSupervisedUserID); user_context.SetKey(Key(kPassword)); - user_context.SetUserIDHash(account_id_.GetUserEmail()); + user_context.SetUserIDHash(kUsername); existing_user_controller()->Login(user_context, SigninSpecifics()); } @@ -321,8 +318,7 @@ SupervisedUserCreationScreen supervised_user_creation_screen( &mock_base_screen_delegate, &supervised_user_creation_screen_handler); - supervised_user_creation_screen.AuthenticateManager( - account_id_.GetUserEmail(), kPassword); + supervised_user_creation_screen.AuthenticateManager(kUsername, kPassword); } MATCHER_P(HasDetails, expected, "") { @@ -332,20 +328,23 @@ class ExistingUserControllerPublicSessionTest : public ExistingUserControllerTest { protected: - ExistingUserControllerPublicSessionTest() {} + ExistingUserControllerPublicSessionTest() + : public_session_user_id_(policy::GenerateDeviceLocalAccountUserId( + kPublicSessionAccountId, + policy::DeviceLocalAccount::TYPE_PUBLIC_SESSION)) { + } void SetUpOnMainThread() override { ExistingUserControllerTest::SetUpOnMainThread(); // Wait for the public session user to be created. if (!user_manager::UserManager::Get()->IsKnownUser( - public_session_account_id_)) { + public_session_user_id_)) { content::WindowedNotificationObserver( chrome::NOTIFICATION_USER_LIST_CHANGED, base::Bind(&user_manager::UserManager::IsKnownUser, base::Unretained(user_manager::UserManager::Get()), - public_session_account_id_)) - .Wait(); + public_session_user_id_)).Wait(); } // Wait for the device local account policy to be installed. @@ -354,7 +353,7 @@ ->platform_part() ->browser_policy_connector_chromeos() ->GetDeviceLocalAccountPolicyService() - ->GetBrokerForUser(public_session_account_id_.GetUserEmail()) + ->GetBrokerForUser(public_session_user_id_) ->core() ->store(); if (!store->has_policy()) { @@ -377,7 +376,7 @@ em::ChromeDeviceSettingsProto& proto(device_policy()->payload()); em::DeviceLocalAccountInfoProto* account = proto.mutable_device_local_accounts()->add_account(); - account->set_account_id(kPublicSessionUserEmail); + account->set_account_id(kPublicSessionAccountId); account->set_type( em::DeviceLocalAccountInfoProto::ACCOUNT_TYPE_PUBLIC_SESSION); RefreshDevicePolicy(); @@ -385,14 +384,15 @@ // Setup the device local account policy. policy::UserPolicyBuilder device_local_account_policy; device_local_account_policy.policy_data().set_username( - kPublicSessionUserEmail); + kPublicSessionAccountId); device_local_account_policy.policy_data().set_policy_type( policy::dm_protocol::kChromePublicAccountPolicyType); device_local_account_policy.policy_data().set_settings_entity_id( - kPublicSessionUserEmail); + kPublicSessionAccountId); device_local_account_policy.Build(); session_manager_client()->set_device_local_account_policy( - kPublicSessionUserEmail, device_local_account_policy.GetBlob()); + kPublicSessionAccountId, + device_local_account_policy.GetBlob()); } void SetUpLoginDisplay() override { @@ -431,7 +431,7 @@ EXPECT_CALL(*mock_login_display_, SetUIEnabled(true)).Times(AnyNumber()); } - void SetAutoLoginPolicy(const std::string& user_email, int delay) { + void SetAutoLoginPolicy(const std::string& username, int delay) { // Wait until ExistingUserController has finished auto-login // configuration by observing the same settings that trigger // ConfigurePublicSessionAutoLogin. @@ -444,7 +444,7 @@ scoped_ptr<CrosSettings::ObserverSubscription> subscription1; if (!proto.has_device_local_accounts() || !proto.device_local_accounts().has_auto_login_id() || - proto.device_local_accounts().auto_login_id() != user_email) { + proto.device_local_accounts().auto_login_id() != username) { runner1 = new content::MessageLoopRunner; subscription1 = chromeos::CrosSettings::Get()->AddSettingsObserver( chromeos::kAccountsPrefDeviceLocalAccountAutoLoginId, @@ -462,7 +462,7 @@ } // Update the policy. - proto.mutable_device_local_accounts()->set_auto_login_id(user_email); + proto.mutable_device_local_accounts()->set_auto_login_id(username); proto.mutable_device_local_accounts()->set_auto_login_delay(delay); RefreshDevicePolicy(); @@ -491,10 +491,7 @@ run_loop.Run(); } - const AccountId public_session_account_id_ = - AccountId::FromUserEmail(policy::GenerateDeviceLocalAccountUserId( - kPublicSessionUserEmail, - policy::DeviceLocalAccount::TYPE_PUBLIC_SESSION)); + const std::string public_session_user_id_; private: DISALLOW_COPY_AND_ASSIGN(ExistingUserControllerPublicSessionTest); @@ -503,20 +500,20 @@ IN_PROC_BROWSER_TEST_F(ExistingUserControllerPublicSessionTest, ConfigureAutoLoginUsingPolicy) { existing_user_controller()->OnSigninScreenReady(); - EXPECT_TRUE(!auto_login_account_id().is_valid()); + EXPECT_EQ("", auto_login_username()); EXPECT_EQ(0, auto_login_delay()); EXPECT_FALSE(auto_login_timer()); // Set the policy. - SetAutoLoginPolicy(kPublicSessionUserEmail, kAutoLoginLongDelay); - EXPECT_EQ(public_session_account_id_, auto_login_account_id()); + SetAutoLoginPolicy(kPublicSessionAccountId, kAutoLoginLongDelay); + EXPECT_EQ(public_session_user_id_, auto_login_username()); EXPECT_EQ(kAutoLoginLongDelay, auto_login_delay()); ASSERT_TRUE(auto_login_timer()); EXPECT_TRUE(auto_login_timer()->IsRunning()); // Unset the policy. SetAutoLoginPolicy("", 0); - EXPECT_TRUE(!auto_login_account_id().is_valid()); + EXPECT_EQ("", auto_login_username()); EXPECT_EQ(0, auto_login_delay()); ASSERT_TRUE(auto_login_timer()); EXPECT_FALSE(auto_login_timer()->IsRunning()); @@ -526,13 +523,13 @@ AutoLoginNoDelay) { // Set up mocks to check login success. UserContext user_context(user_manager::USER_TYPE_PUBLIC_ACCOUNT, - public_session_account_id_.GetUserEmail()); - user_context.SetUserIDHash(user_context.GetAccountId().GetUserEmail()); + public_session_user_id_); + user_context.SetUserIDHash(user_context.GetUserID()); ExpectSuccessfulLogin(user_context); existing_user_controller()->OnSigninScreenReady(); // Start auto-login and wait for login tasks to complete. - SetAutoLoginPolicy(kPublicSessionUserEmail, kAutoLoginNoDelay); + SetAutoLoginPolicy(kPublicSessionAccountId, kAutoLoginNoDelay); content::RunAllPendingInMessageLoop(); } @@ -540,8 +537,8 @@ AutoLoginShortDelay) { // Set up mocks to check login success. UserContext user_context(user_manager::USER_TYPE_PUBLIC_ACCOUNT, - public_session_account_id_.GetUserEmail()); - user_context.SetUserIDHash(user_context.GetAccountId().GetUserEmail()); + public_session_user_id_); + user_context.SetUserIDHash(user_context.GetUserID()); ExpectSuccessfulLogin(user_context); existing_user_controller()->OnSigninScreenReady(); @@ -549,7 +546,7 @@ chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED, content::NotificationService::AllSources()); - SetAutoLoginPolicy(kPublicSessionUserEmail, kAutoLoginShortDelay); + SetAutoLoginPolicy(kPublicSessionAccountId, kAutoLoginShortDelay); ASSERT_TRUE(auto_login_timer()); // Don't assert that timer is running: with the short delay sometimes // the trigger happens before the assert. We've already tested that @@ -572,14 +569,14 @@ IN_PROC_BROWSER_TEST_F(ExistingUserControllerPublicSessionTest, LoginStopsAutoLogin) { // Set up mocks to check login success. - UserContext user_context(account_id_); + UserContext user_context(kUsername); user_context.SetGaiaID(kGaiaID); user_context.SetKey(Key(kPassword)); - user_context.SetUserIDHash(user_context.GetAccountId().GetUserEmail()); + user_context.SetUserIDHash(user_context.GetUserID()); ExpectSuccessfulLogin(user_context); existing_user_controller()->OnSigninScreenReady(); - SetAutoLoginPolicy(kPublicSessionUserEmail, kAutoLoginLongDelay); + SetAutoLoginPolicy(kPublicSessionAccountId, kAutoLoginLongDelay); EXPECT_TRUE(auto_login_timer()); content::WindowedNotificationObserver profile_prepared_observer( @@ -606,7 +603,7 @@ GuestModeLoginStopsAutoLogin) { EXPECT_CALL(*mock_login_display_, SetUIEnabled(false)) .Times(2); - UserContext user_context(account_id_); + UserContext user_context(kUsername); user_context.SetGaiaID(kGaiaID); user_context.SetKey(Key(kPassword)); test::UserSessionManagerTestApi session_manager_test_api( @@ -614,7 +611,7 @@ session_manager_test_api.InjectStubUserContext(user_context); existing_user_controller()->OnSigninScreenReady(); - SetAutoLoginPolicy(kPublicSessionUserEmail, kAutoLoginLongDelay); + SetAutoLoginPolicy(kPublicSessionAccountId, kAutoLoginLongDelay); EXPECT_TRUE(auto_login_timer()); // Login and check that it stopped the timer. @@ -636,16 +633,16 @@ IN_PROC_BROWSER_TEST_F(ExistingUserControllerPublicSessionTest, CompleteLoginStopsAutoLogin) { // Set up mocks to check login success. - UserContext user_context(account_id_); + UserContext user_context(kUsername); user_context.SetGaiaID(kGaiaID); user_context.SetKey(Key(kPassword)); - user_context.SetUserIDHash(user_context.GetAccountId().GetUserEmail()); + user_context.SetUserIDHash(user_context.GetUserID()); ExpectSuccessfulLogin(user_context); EXPECT_CALL(*mock_login_display_host_, OnCompleteLogin()) .Times(1); existing_user_controller()->OnSigninScreenReady(); - SetAutoLoginPolicy(kPublicSessionUserEmail, kAutoLoginLongDelay); + SetAutoLoginPolicy(kPublicSessionAccountId, kAutoLoginLongDelay); EXPECT_TRUE(auto_login_timer()); content::WindowedNotificationObserver profile_prepared_observer( @@ -671,11 +668,11 @@ PublicSessionLoginStopsAutoLogin) { // Set up mocks to check login success. UserContext user_context(user_manager::USER_TYPE_PUBLIC_ACCOUNT, - public_session_account_id_.GetUserEmail()); - user_context.SetUserIDHash(user_context.GetAccountId().GetUserEmail()); + public_session_user_id_); + user_context.SetUserIDHash(user_context.GetUserID()); ExpectSuccessfulLogin(user_context); existing_user_controller()->OnSigninScreenReady(); - SetAutoLoginPolicy(kPublicSessionUserEmail, kAutoLoginLongDelay); + SetAutoLoginPolicy(kPublicSessionAccountId, kAutoLoginLongDelay); EXPECT_TRUE(auto_login_timer()); content::WindowedNotificationObserver profile_prepared_observer( @@ -685,7 +682,7 @@ // Login and check that it stopped the timer. existing_user_controller()->Login( UserContext(user_manager::USER_TYPE_PUBLIC_ACCOUNT, - public_session_account_id_.GetUserEmail()), + public_session_user_id_), SigninSpecifics()); EXPECT_TRUE(is_login_in_progress()); @@ -709,17 +706,17 @@ // Check that the attempt to start a public session fails with an error. ExpectLoginFailure(); - UserContext user_context(account_id_); + UserContext user_context(kUsername); user_context.SetGaiaID(kGaiaID); user_context.SetKey(Key(kPassword)); - user_context.SetUserIDHash(user_context.GetAccountId().GetUserEmail()); + user_context.SetUserIDHash(user_context.GetUserID()); existing_user_controller()->Login(user_context, SigninSpecifics()); } IN_PROC_BROWSER_TEST_F(ExistingUserControllerPublicSessionTest, NoAutoLoginWhenUntrusted) { // Start the public session timer. - SetAutoLoginPolicy(kPublicSessionUserEmail, kAutoLoginLongDelay); + SetAutoLoginPolicy(kPublicSessionAccountId, kAutoLoginLongDelay); existing_user_controller()->OnSigninScreenReady(); EXPECT_TRUE(auto_login_timer());
diff --git a/chrome/browser/chromeos/login/kiosk_browsertest.cc b/chrome/browser/chromeos/login/kiosk_browsertest.cc index f045f45..7b80284 100644 --- a/chrome/browser/chromeos/login/kiosk_browsertest.cc +++ b/chrome/browser/chromeos/login/kiosk_browsertest.cc
@@ -451,6 +451,7 @@ public: KioskTest() : settings_helper_(false), + use_consumer_kiosk_mode_(true), fake_cws_(new FakeCWS) { set_exit_when_last_browser_closes(false); } @@ -703,7 +704,7 @@ } void RunAppLaunchNetworkDownTest() { - mock_user_manager()->SetActiveUser(test_owner_account_id_); + mock_user_manager()->SetActiveUser(kTestOwnerEmail); AppLaunchSigninScreen::SetUserManagerForTesting(mock_user_manager()); // Mock network could be configured with owner's password. @@ -787,11 +788,8 @@ ScopedCrosSettingsTestHelper settings_helper_; scoped_ptr<FakeOwnerSettingsService> owner_settings_service_; - const AccountId test_owner_account_id_ = - AccountId::FromUserEmail(kTestOwnerEmail); - private: - bool use_consumer_kiosk_mode_ = true; + bool use_consumer_kiosk_mode_; std::string test_app_id_; std::string test_app_version_; std::string test_crx_file_; @@ -2019,7 +2017,7 @@ void SetUpInProcessBrowserTestFixture() override { policy::DevicePolicyCrosTestHelper::MarkAsEnterpriseOwnedBy( - test_owner_account_id_.GetUserEmail()); + kTestOwnerEmail); settings_helper_.SetCurrentUserIsOwner(false); KioskTest::SetUpInProcessBrowserTestFixture(); @@ -2230,7 +2228,7 @@ IN_PROC_BROWSER_TEST_F(KioskHiddenWebUITest, AutolaunchWarning) { // Add a device owner. FakeChromeUserManager* user_manager = new FakeChromeUserManager(); - user_manager->AddUser(test_owner_account_id_); + user_manager->AddUser(kTestOwnerEmail); ScopedUserManagerEnabler enabler(user_manager); // Set kiosk app to autolaunch.
diff --git a/chrome/browser/chromeos/login/lock/screen_locker.cc b/chrome/browser/chromeos/login/lock/screen_locker.cc index 38514038a..eea1b56b 100644 --- a/chrome/browser/chromeos/login/lock/screen_locker.cc +++ b/chrome/browser/chromeos/login/lock/screen_locker.cc
@@ -197,7 +197,7 @@ void ScreenLocker::OnAuthSuccess(const UserContext& user_context) { incorrect_passwords_count_ = 0; if (authentication_start_time_.is_null()) { - if (user_context.GetAccountId().is_valid()) + if (!user_context.GetUserID().empty()) LOG(ERROR) << "Start time is not set at authentication success"; } else { base::TimeDelta delta = base::Time::Now() - authentication_start_time_; @@ -206,12 +206,12 @@ } const user_manager::User* user = - user_manager::UserManager::Get()->FindUser(user_context.GetAccountId()); + user_manager::UserManager::Get()->FindUser(user_context.GetUserID()); if (user) { if (!user->is_active()) { saved_ime_state_ = NULL; user_manager::UserManager::Get()->SwitchActiveUser( - user_context.GetAccountId()); + user_context.GetUserID()); } UserSessionManager::GetInstance()->UpdateEasyUnlockKeys(user_context); } else { @@ -250,7 +250,7 @@ } void ScreenLocker::Authenticate(const UserContext& user_context) { - LOG_ASSERT(IsUserLoggedIn(user_context.GetAccountId().GetUserEmail())) + LOG_ASSERT(IsUserLoggedIn(user_context.GetUserID())) << "Invalid user trying to unlock."; authentication_start_time_ = base::Time::Now(); @@ -259,7 +259,7 @@ // Special case: supervised users. Use special authenticator. if (const user_manager::User* user = - FindUnlockUser(user_context.GetAccountId().GetUserEmail())) { + FindUnlockUser(user_context.GetUserID())) { if (user->GetType() == user_manager::USER_TYPE_SUPERVISED) { UserContext updated_context = ChromeUserManager::Get() ->GetSupervisedUserManager()
diff --git a/chrome/browser/chromeos/login/lock/screen_locker_browsertest.cc b/chrome/browser/chromeos/login/lock/screen_locker_browsertest.cc index 6632afe2..c3bbabe 100644 --- a/chrome/browser/chromeos/login/lock/screen_locker_browsertest.cc +++ b/chrome/browser/chromeos/login/lock/screen_locker_browsertest.cc
@@ -155,7 +155,7 @@ EXPECT_GT(lock_bounds.width(), 10); EXPECT_GT(lock_bounds.height(), 10); - UserContext user_context(login::StubAccountId()); + UserContext user_context(chromeos::login::kStubUser); user_context.SetKey(Key("pass")); tester->InjectStubUserContext(user_context); EXPECT_TRUE(tester->IsLocked()); @@ -212,7 +212,7 @@ EXPECT_FALSE(window_state->hide_shelf_when_fullscreen()); EXPECT_TRUE(tester->IsLocked()); } - UserContext user_context(login::StubAccountId()); + UserContext user_context(chromeos::login::kStubUser); user_context.SetKey(Key("pass")); tester->InjectStubUserContext(user_context); tester->EnterPassword("pass");
diff --git a/chrome/browser/chromeos/login/login_browsertest.cc b/chrome/browser/chromeos/login/login_browsertest.cc index 3e8ef591..a43297d0 100644 --- a/chrome/browser/chromeos/login/login_browsertest.cc +++ b/chrome/browser/chromeos/login/login_browsertest.cc
@@ -161,7 +161,7 @@ StartGaiaAuthOffline(); - UserContext user_context(AccountId::FromUserEmail(kTestUser)); + UserContext user_context(kTestUser); user_context.SetGaiaID(kGaiaId); user_context.SetKey(Key(kPassword)); SetExpectedCredentials(user_context);
diff --git a/chrome/browser/chromeos/login/login_manager_test.cc b/chrome/browser/chromeos/login/login_manager_test.cc index 5266a31..d2430746a 100644 --- a/chrome/browser/chromeos/login/login_manager_test.cc +++ b/chrome/browser/chromeos/login/login_manager_test.cc
@@ -48,8 +48,7 @@ const char kTestRefreshToken2[] = "fake-refresh-token-2"; UserContext CreateUserContext(const std::string& user_id) { - UserContext user_context(AccountId::FromUserEmailGaiaId( - user_id, LoginManagerTest::GetGaiaIDForUserID(user_id))); + UserContext user_context(user_id); user_context.SetGaiaID(LoginManagerTest::GetGaiaIDForUserID(user_id)); user_context.SetKey(Key("password")); if (user_id == LoginManagerTest::kEnterpriseUser1) { @@ -169,7 +168,7 @@ return false; if (const user_manager::User* active_user = user_manager::UserManager::Get()->GetActiveUser()) - return active_user->GetAccountId() == user_context.GetAccountId(); + return active_user->email() == user_context.GetUserID(); return false; } @@ -190,7 +189,7 @@ for (user_manager::UserList::const_iterator it = logged_users.begin(); it != logged_users.end(); ++it) { - if ((*it)->GetAccountId() == user_context.GetAccountId()) + if ((*it)->email() == user_context.GetUserID()) return true; } return false;
diff --git a/chrome/browser/chromeos/login/reauth_stats.cc b/chrome/browser/chromeos/login/reauth_stats.cc index f3924659..f442c974 100644 --- a/chrome/browser/chromeos/login/reauth_stats.cc +++ b/chrome/browser/chromeos/login/reauth_stats.cc
@@ -9,26 +9,26 @@ namespace chromeos { -void RecordReauthReason(const AccountId& account_id, ReauthReason reason) { +void RecordReauthReason(const std::string& user_id, ReauthReason reason) { user_manager::UserManager* user_manager = user_manager::UserManager::Get(); int old_reason; // We record only the first value, skipping everything else, except "none" // value, which is used to reset the current state. - if (!user_manager->FindReauthReason(account_id, &old_reason) || + if (!user_manager->FindReauthReason(user_id, &old_reason) || (static_cast<ReauthReason>(old_reason) == ReauthReason::NONE && reason != ReauthReason::NONE)) { - user_manager->UpdateReauthReason(account_id, static_cast<int>(reason)); + user_manager->UpdateReauthReason(user_id, static_cast<int>(reason)); } } -void SendReauthReason(const AccountId& account_id) { +void SendReauthReason(const std::string& user_id) { user_manager::UserManager* user_manager = user_manager::UserManager::Get(); int reauth_reason; - if (user_manager->FindReauthReason(account_id, &reauth_reason) && + if (user_manager->FindReauthReason(user_id, &reauth_reason) && static_cast<ReauthReason>(reauth_reason) != ReauthReason::NONE) { UMA_HISTOGRAM_ENUMERATION("Login.ReauthReason", reauth_reason, NUM_REAUTH_FLOW_REASONS); - user_manager->UpdateReauthReason(account_id, + user_manager->UpdateReauthReason(user_id, static_cast<int>(ReauthReason::NONE)); } }
diff --git a/chrome/browser/chromeos/login/reauth_stats.h b/chrome/browser/chromeos/login/reauth_stats.h index d62489f..99bd159 100644 --- a/chrome/browser/chromeos/login/reauth_stats.h +++ b/chrome/browser/chromeos/login/reauth_stats.h
@@ -7,8 +7,6 @@ #include <string> -class AccountId; - namespace chromeos { // Track all the ways a user may be sent through the re-auth flow. @@ -53,8 +51,8 @@ NUM_REAUTH_FLOW_REASONS, }; -void RecordReauthReason(const AccountId& account_id, ReauthReason reason); -void SendReauthReason(const AccountId& account_id); +void RecordReauthReason(const std::string& user_id, ReauthReason reason); +void SendReauthReason(const std::string& user_id); } // namespace chromeos
diff --git a/chrome/browser/chromeos/login/saml/saml_browsertest.cc b/chrome/browser/chromeos/login/saml/saml_browsertest.cc index 6c88365..f1349d56 100644 --- a/chrome/browser/chromeos/login/saml/saml_browsertest.cc +++ b/chrome/browser/chromeos/login/saml/saml_browsertest.cc
@@ -968,13 +968,11 @@ // Pretend that the test users' OAuth tokens are valid. user_manager::UserManager::Get()->SaveUserOAuthStatus( - AccountId::FromUserEmail(kFirstSAMLUserEmail), - user_manager::User::OAUTH2_TOKEN_STATUS_VALID); + kFirstSAMLUserEmail, user_manager::User::OAUTH2_TOKEN_STATUS_VALID); user_manager::UserManager::Get()->SaveUserOAuthStatus( - AccountId::FromUserEmail(kNonSAMLUserEmail), - user_manager::User::OAUTH2_TOKEN_STATUS_VALID); + kNonSAMLUserEmail, user_manager::User::OAUTH2_TOKEN_STATUS_VALID); user_manager::UserManager::Get()->SaveUserOAuthStatus( - AccountId::FromUserEmail(kDifferentDomainSAMLUserEmail), + kDifferentDomainSAMLUserEmail, user_manager::User::OAUTH2_TOKEN_STATUS_VALID); // Set up fake networks.
diff --git a/chrome/browser/chromeos/login/saml/saml_offline_signin_limiter.cc b/chrome/browser/chromeos/login/saml/saml_offline_signin_limiter.cc index ede2bee..826aa1c 100644 --- a/chrome/browser/chromeos/login/saml/saml_offline_signin_limiter.cc +++ b/chrome/browser/chromeos/login/saml/saml_offline_signin_limiter.cc
@@ -45,14 +45,14 @@ NOTREACHED(); return; } - const AccountId account_id = user->GetAccountId(); + const std::string& user_id = user->email(); if (auth_flow == UserContext::AUTH_FLOW_GAIA_WITHOUT_SAML) { // The user went through online authentication and GAIA did not redirect to // a SAML IdP. No limit applies in this case. Clear the time of last login // with SAML and the flag enforcing online login, then return. prefs->ClearPref(prefs::kSAMLLastGAIASignInTime); - user_manager::UserManager::Get()->SaveForceOnlineSignin(account_id, false); + user_manager::UserManager::Get()->SaveForceOnlineSignin(user_id, false); return; } @@ -62,7 +62,7 @@ // enforcing online login. The flag will be set again when the limit // expires. If the limit already expired (e.g. because it was set to zero), // the flag will be set again immediately. - user_manager::UserManager::Get()->SaveForceOnlineSignin(account_id, false); + user_manager::UserManager::Get()->SaveForceOnlineSignin(user_id, false); prefs->SetInt64(prefs::kSAMLLastGAIASignInTime, clock_->Now().ToInternalValue()); } @@ -143,9 +143,8 @@ return; } - user_manager::UserManager::Get()->SaveForceOnlineSignin(user->GetAccountId(), - true); - RecordReauthReason(user->GetAccountId(), ReauthReason::SAML_REAUTH_POLICY); + user_manager::UserManager::Get()->SaveForceOnlineSignin(user->email(), true); + RecordReauthReason(user->email(), ReauthReason::SAML_REAUTH_POLICY); offline_signin_limit_timer_.reset(); }
diff --git a/chrome/browser/chromeos/login/saml/saml_offline_signin_limiter_unittest.cc b/chrome/browser/chromeos/login/saml/saml_offline_signin_limiter_unittest.cc index bf8fbfe..c82a3985 100644 --- a/chrome/browser/chromeos/login/saml/saml_offline_signin_limiter_unittest.cc +++ b/chrome/browser/chromeos/login/saml/saml_offline_signin_limiter_unittest.cc
@@ -46,9 +46,6 @@ void CreateLimiter(); void SetUpUserManager(); - - const AccountId test_account_id_ = AccountId::FromUserEmail(kTestUser); - TestingPrefServiceSimple* GetTestingLocalState(); scoped_refptr<base::TestSimpleTaskRunner> runner_; @@ -72,7 +69,8 @@ runner_handle_(runner_), user_manager_(new MockUserManager), user_manager_enabler_(user_manager_), - limiter_(NULL) {} + limiter_(NULL) { +} SAMLOfflineSigninLimiterTest::~SAMLOfflineSigninLimiterTest() { DestroyLimiter(); @@ -105,7 +103,7 @@ profile_.reset(new TestingProfile); SAMLOfflineSigninLimiterFactory::SetClockForTesting(&clock_); - user_manager_->AddUser(test_account_id_); + user_manager_->AddUser(kTestUser); profile_->set_profile_name(kTestUser); clock_.Advance(base::TimeDelta::FromHours(1)); @@ -131,10 +129,8 @@ // Authenticate against GAIA without SAML. Verify that the flag enforcing // online login and the time of last login with SAML are cleared. CreateLimiter(); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, false)) - .Times(1); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, true)) - .Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, false)).Times(1); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, true)).Times(0); limiter_->SignedIn(UserContext::AUTH_FLOW_GAIA_WITHOUT_SAML); const PrefService::Preference* pref = @@ -153,10 +149,8 @@ CreateLimiter(); Mock::VerifyAndClearExpectations(user_manager_); SetUpUserManager(); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, false)) - .Times(0); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, true)) - .Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, false)).Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, true)).Times(0); limiter_->SignedIn(UserContext::AUTH_FLOW_OFFLINE); pref = prefs->FindPreference(prefs::kSAMLLastGAIASignInTime); @@ -180,10 +174,8 @@ // Authenticate against GAIA without SAML. Verify that the flag enforcing // online login and the time of last login with SAML are cleared. CreateLimiter(); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, false)) - .Times(1); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, true)) - .Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, false)).Times(1); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, true)).Times(0); limiter_->SignedIn(UserContext::AUTH_FLOW_GAIA_WITHOUT_SAML); const PrefService::Preference* pref = @@ -202,10 +194,8 @@ CreateLimiter(); Mock::VerifyAndClearExpectations(user_manager_); SetUpUserManager(); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, false)) - .Times(0); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, true)) - .Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, false)).Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, true)).Times(0); limiter_->SignedIn(UserContext::AUTH_FLOW_OFFLINE); pref = prefs->FindPreference(prefs::kSAMLLastGAIASignInTime); @@ -229,10 +219,8 @@ // Authenticate against GAIA without SAML. Verify that the flag enforcing // online login and the time of last login with SAML are cleared. CreateLimiter(); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, false)) - .Times(1); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, true)) - .Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, false)).Times(1); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, true)).Times(0); limiter_->SignedIn(UserContext::AUTH_FLOW_GAIA_WITHOUT_SAML); const PrefService::Preference* pref = @@ -251,10 +239,8 @@ CreateLimiter(); Mock::VerifyAndClearExpectations(user_manager_); SetUpUserManager(); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, false)) - .Times(0); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, true)) - .Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, false)).Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, true)).Times(0); limiter_->SignedIn(UserContext::AUTH_FLOW_OFFLINE); pref = prefs->FindPreference(prefs::kSAMLLastGAIASignInTime); @@ -278,10 +264,8 @@ // Authenticate against GAIA without SAML. Verify that the flag enforcing // online login and the time of last login with SAML are cleared. CreateLimiter(); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, false)) - .Times(1); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, true)) - .Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, false)).Times(1); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, true)).Times(0); limiter_->SignedIn(UserContext::AUTH_FLOW_GAIA_WITHOUT_SAML); const PrefService::Preference* pref = @@ -309,10 +293,8 @@ // Authenticate against GAIA without SAML. Verify that the flag enforcing // online login and the time of last login with SAML are cleared. CreateLimiter(); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, false)) - .Times(1); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, true)) - .Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, false)).Times(1); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, true)).Times(0); limiter_->SignedIn(UserContext::AUTH_FLOW_GAIA_WITHOUT_SAML); const PrefService::Preference* pref = @@ -343,10 +325,8 @@ // Authenticate against GAIA without SAML. Verify that the flag enforcing // online login and the time of last login with SAML are cleared. CreateLimiter(); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, false)) - .Times(1); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, true)) - .Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, false)).Times(1); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, true)).Times(0); limiter_->SignedIn(UserContext::AUTH_FLOW_GAIA_WITHOUT_SAML); const PrefService::Preference* pref = @@ -364,10 +344,8 @@ // Authenticate against GAIA with SAML. Verify that the flag enforcing online // login is cleared and the time of last login with SAML is set. CreateLimiter(); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, false)) - .Times(1); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, true)) - .Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, false)).Times(1); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, true)).Times(0); limiter_->SignedIn(UserContext::AUTH_FLOW_GAIA_WITH_SAML); base::Time last_gaia_signin_time = base::Time::FromInternalValue( @@ -388,10 +366,8 @@ CreateLimiter(); Mock::VerifyAndClearExpectations(user_manager_); SetUpUserManager(); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, false)) - .Times(1); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, true)) - .Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, false)).Times(1); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, true)).Times(0); limiter_->SignedIn(UserContext::AUTH_FLOW_GAIA_WITH_SAML); last_gaia_signin_time = base::Time::FromInternalValue( @@ -413,10 +389,8 @@ CreateLimiter(); Mock::VerifyAndClearExpectations(user_manager_); SetUpUserManager(); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, false)) - .Times(0); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, true)) - .Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, false)).Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, true)).Times(0); limiter_->SignedIn(UserContext::AUTH_FLOW_OFFLINE); last_gaia_signin_time = base::Time::FromInternalValue( @@ -433,10 +407,8 @@ // set. Mock::VerifyAndClearExpectations(user_manager_); SetUpUserManager(); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, false)) - .Times(0); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, true)) - .Times(1); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, false)).Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, true)).Times(1); runner_->RunPendingTasks(); } @@ -449,10 +421,8 @@ // Authenticate against GAIA with SAML. Verify that the flag enforcing online // login is cleared and the time of last login with SAML is set. CreateLimiter(); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, false)) - .Times(1); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, true)) - .Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, false)).Times(1); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, true)).Times(0); limiter_->SignedIn(UserContext::AUTH_FLOW_GAIA_WITH_SAML); base::Time last_gaia_signin_time = base::Time::FromInternalValue( @@ -473,10 +443,8 @@ CreateLimiter(); Mock::VerifyAndClearExpectations(user_manager_); SetUpUserManager(); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, false)) - .Times(1); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, true)) - .Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, false)).Times(1); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, true)).Times(0); limiter_->SignedIn(UserContext::AUTH_FLOW_GAIA_WITH_SAML); last_gaia_signin_time = base::Time::FromInternalValue( @@ -498,10 +466,8 @@ CreateLimiter(); Mock::VerifyAndClearExpectations(user_manager_); SetUpUserManager(); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, false)) - .Times(0); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, true)) - .Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, false)).Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, true)).Times(0); limiter_->SignedIn(UserContext::AUTH_FLOW_OFFLINE); last_gaia_signin_time = base::Time::FromInternalValue( @@ -523,10 +489,10 @@ // last login with SAML is set. CreateLimiter(); Sequence sequence; - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, false)) + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, false)) .Times(1) .InSequence(sequence); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, true)) + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, true)) .Times(1) .InSequence(sequence); limiter_->SignedIn(UserContext::AUTH_FLOW_GAIA_WITH_SAML); @@ -545,10 +511,8 @@ // Authenticate against GAIA with SAML. Verify that the flag enforcing online // login is cleared and the time of last login with SAML is set. CreateLimiter(); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, false)) - .Times(1); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, true)) - .Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, false)).Times(1); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, true)).Times(0); limiter_->SignedIn(UserContext::AUTH_FLOW_GAIA_WITH_SAML); const base::Time last_gaia_signin_time = base::Time::FromInternalValue( @@ -561,10 +525,8 @@ // Set a zero time limit. Verify that the flag enforcing online login is set. Mock::VerifyAndClearExpectations(user_manager_); SetUpUserManager(); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, false)) - .Times(0); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, true)) - .Times(1); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, false)).Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, true)).Times(1); prefs->SetInteger(prefs::kSAMLOfflineSigninTimeLimit, 0); } @@ -574,10 +536,8 @@ // Authenticate against GAIA with SAML. Verify that the flag enforcing online // login is cleared and the time of last login with SAML is set. CreateLimiter(); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, false)) - .Times(1); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, true)) - .Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, false)).Times(1); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, true)).Times(0); limiter_->SignedIn(UserContext::AUTH_FLOW_GAIA_WITH_SAML); const base::Time last_gaia_signin_time = base::Time::FromInternalValue( @@ -594,10 +554,8 @@ // changed. Mock::VerifyAndClearExpectations(user_manager_); SetUpUserManager(); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, false)) - .Times(0); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, true)) - .Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, false)).Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, true)).Times(0); runner_->RunUntilIdle(); } @@ -614,10 +572,8 @@ // Authenticate against GAIA with SAML. Verify that the flag enforcing online // login is cleared and the time of last login with SAML is updated. CreateLimiter(); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, false)) - .Times(1); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, true)) - .Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, false)).Times(1); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, true)).Times(0); limiter_->SignedIn(UserContext::AUTH_FLOW_GAIA_WITH_SAML); const base::Time last_gaia_signin_time = base::Time::FromInternalValue( @@ -642,10 +598,8 @@ // Authenticate offline. Verify that the flag enforcing online login is // set and the time of last login with SAML is not changed. CreateLimiter(); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, false)) - .Times(0); - EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(test_account_id_, true)) - .Times(1); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, false)).Times(0); + EXPECT_CALL(*user_manager_, SaveForceOnlineSignin(kTestUser, true)).Times(1); limiter_->SignedIn(UserContext::AUTH_FLOW_OFFLINE); const base::Time last_gaia_signin_time = base::Time::FromInternalValue(
diff --git a/chrome/browser/chromeos/login/screens/chrome_user_selection_screen.cc b/chrome/browser/chromeos/login/screens/chrome_user_selection_screen.cc index e309e136..37737c7c 100644 --- a/chrome/browser/chromeos/login/screens/chrome_user_selection_screen.cc +++ b/chrome/browser/chromeos/login/screens/chrome_user_selection_screen.cc
@@ -21,7 +21,6 @@ #include "components/policy/core/common/cloud/cloud_policy_store.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_types.h" -#include "components/signin/core/account_id/account_id.h" #include "components/user_manager/user.h" #include "components/user_manager/user_manager.h" #include "components/user_manager/user_type.h" @@ -51,7 +50,7 @@ for (user_manager::UserList::const_iterator it = users.begin(); it != users.end(); ++it) { if ((*it)->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT) - OnPolicyUpdated((*it)->GetAccountId().GetUserEmail()); + OnPolicyUpdated((*it)->GetUserID()); } } @@ -144,8 +143,8 @@ void ChromeUserSelectionScreen::SetPublicSessionDisplayName( const std::string& user_id) { - const user_manager::User* user = user_manager::UserManager::Get()->FindUser( - AccountId::FromUserEmail(user_id)); + const user_manager::User* user = + user_manager::UserManager::Get()->FindUser(user_id); if (!user || user->GetType() != user_manager::USER_TYPE_PUBLIC_ACCOUNT) return;
diff --git a/chrome/browser/chromeos/login/screens/user_image_screen.cc b/chrome/browser/chromeos/login/screens/user_image_screen.cc index 091e8e73..7805543 100644 --- a/chrome/browser/chromeos/login/screens/user_image_screen.cc +++ b/chrome/browser/chromeos/login/screens/user_image_screen.cc
@@ -111,7 +111,7 @@ void UserImageScreen::HideCurtain() { // Skip user image selection for ephemeral users. if (user_manager::UserManager::Get()->IsUserNonCryptohomeDataEphemeral( - GetUser()->GetAccountId())) { + GetUser()->GetUserID())) { ExitScreen(); } if (view_) @@ -227,8 +227,7 @@ } UserImageManager* UserImageScreen::GetUserImageManager() { - return ChromeUserManager::Get()->GetUserImageManager( - GetUser()->GetAccountId()); + return ChromeUserManager::Get()->GetUserImageManager(GetUser()->email()); } UserImageSyncObserver* UserImageScreen::GetSyncObserver() {
diff --git a/chrome/browser/chromeos/login/screens/user_selection_screen.cc b/chrome/browser/chromeos/login/screens/user_selection_screen.cc index 37bb77b..df270c44 100644 --- a/chrome/browser/chromeos/login/screens/user_selection_screen.cc +++ b/chrome/browser/chromeos/login/screens/user_selection_screen.cc
@@ -22,7 +22,7 @@ #include "chrome/browser/ui/webui/chromeos/login/l10n_util.h" #include "chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h" #include "components/proximity_auth/screenlock_bridge.h" -#include "components/signin/core/account_id/account_id.h" +#include "components/user_manager/user_id.h" #include "components/user_manager/user_manager.h" #include "components/user_manager/user_type.h" #include "ui/base/user_activity/user_activity_detector.h" @@ -142,13 +142,14 @@ AuthType auth_type, const std::vector<std::string>* public_session_recommended_locales, base::DictionaryValue* user_dict) { + const user_manager::UserID user_id = user->email(); const bool is_public_session = user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT; const bool is_legacy_supervised_user = user->GetType() == user_manager::USER_TYPE_SUPERVISED; const bool is_child_user = user->GetType() == user_manager::USER_TYPE_CHILD; - user_dict->SetString(kKeyUsername, user->GetAccountId().GetUserEmail()); + user_dict->SetString(kKeyUsername, user_id); user_dict->SetString(kKeyEmailAddress, user->display_email()); user_dict->SetString(kKeyDisplayName, user->GetDisplayName()); user_dict->SetBoolean(kKeyPublicAccount, is_public_session); @@ -172,8 +173,7 @@ void UserSelectionScreen::FillKnownUserPrefs(user_manager::User* user, base::DictionaryValue* user_dict) { std::string gaia_id; - if (user_manager::UserManager::Get()->FindGaiaID(user->GetAccountId(), - &gaia_id)) { + if (user_manager::UserManager::Get()->FindGaiaID(user->email(), &gaia_id)) { user_dict->SetString(kKeyGaiaID, gaia_id); } } @@ -239,7 +239,7 @@ // At this point the reason for invalid token should be already set. If not, // this might be a leftover from an old version. if (token_status == user_manager::User::OAUTH2_TOKEN_STATUS_INVALID) - RecordReauthReason(user->GetAccountId(), ReauthReason::OTHER); + RecordReauthReason(user->email(), ReauthReason::OTHER); return user->force_online_signin() || (token_status == user_manager::User::OAUTH2_TOKEN_STATUS_INVALID) || @@ -404,7 +404,7 @@ SendUserList(); } -void UserSelectionScreen::CheckUserStatus(const std::string& user_email) { +void UserSelectionScreen::CheckUserStatus(const std::string& user_id) { // No checks on lock screen. if (ScreenLocker::default_screen_locker()) return; @@ -414,21 +414,20 @@ new TokenHandleUtil(user_manager::UserManager::Get())); } - const AccountId account_id = AccountId::FromUserEmail(user_email); - if (token_handle_util_->HasToken(account_id)) { + if (token_handle_util_->HasToken(user_id)) { token_handle_util_->CheckToken( - account_id, base::Bind(&UserSelectionScreen::OnUserStatusChecked, - weak_factory_.GetWeakPtr())); + user_id, base::Bind(&UserSelectionScreen::OnUserStatusChecked, + weak_factory_.GetWeakPtr())); } } void UserSelectionScreen::OnUserStatusChecked( - const AccountId& account_id, + const user_manager::UserID& user_id, TokenHandleUtil::TokenHandleStatus status) { if (status == TokenHandleUtil::INVALID) { - RecordReauthReason(account_id, ReauthReason::INVALID_TOKEN_HANDLE); - token_handle_util_->MarkHandleInvalid(account_id); - SetAuthType(account_id.GetUserEmail(), ONLINE_SIGN_IN, base::string16()); + RecordReauthReason(user_id, ReauthReason::INVALID_TOKEN_HANDLE); + token_handle_util_->MarkHandleInvalid(user_id); + SetAuthType(user_id, ONLINE_SIGN_IN, base::string16()); } } @@ -499,7 +498,7 @@ const std::string& key_label) { DCHECK_EQ(GetScreenType(), SIGNIN_SCREEN); - UserContext user_context(AccountId::FromUserEmail(user_id)); + UserContext user_context(user_id); user_context.SetAuthFlow(UserContext::AUTH_FLOW_EASY_UNLOCK); user_context.SetKey(Key(secret)); user_context.GetKey()->SetLabel(key_label);
diff --git a/chrome/browser/chromeos/login/screens/user_selection_screen.h b/chrome/browser/chromeos/login/screens/user_selection_screen.h index 0c2879b5..f52657a 100644 --- a/chrome/browser/chromeos/login/screens/user_selection_screen.h +++ b/chrome/browser/chromeos/login/screens/user_selection_screen.h
@@ -17,9 +17,9 @@ #include "chrome/browser/chromeos/login/ui/models/user_board_model.h" #include "components/proximity_auth/screenlock_bridge.h" #include "components/user_manager/user.h" +#include "components/user_manager/user_id.h" #include "ui/base/user_activity/user_activity_observer.h" -class AccountId; class EasyUnlockService; namespace chromeos { @@ -122,7 +122,7 @@ EasyUnlockService* GetEasyUnlockServiceForUser( const std::string& user_id) const; - void OnUserStatusChecked(const AccountId& account_id, + void OnUserStatusChecked(const user_manager::UserID& user_id, TokenHandleUtil::TokenHandleStatus status); // Whether to show guest login.
diff --git a/chrome/browser/chromeos/login/session/user_session_manager.cc b/chrome/browser/chromeos/login/session/user_session_manager.cc index 7c2aa36..1efaa70 100644 --- a/chrome/browser/chromeos/login/session/user_session_manager.cc +++ b/chrome/browser/chromeos/login/session/user_session_manager.cc
@@ -452,8 +452,7 @@ delegate_ = delegate; start_session_type_ = start_session_type; - VLOG(1) << "Starting session for " - << user_context.GetAccountId().GetUserEmail(); + VLOG(1) << "Starting session for " << user_context.GetUserID(); PreStartSession(); CreateUserSession(user_context, has_auth_cookies); @@ -467,7 +466,7 @@ if (!user_context.GetDeviceId().empty()) { user_manager::UserManager::Get()->SetKnownUserDeviceId( - user_context.GetAccountId(), user_context.GetDeviceId()); + user_context.GetUserID(), user_context.GetDeviceId()); } PrepareProfile(); @@ -703,7 +702,7 @@ } bool UserSessionManager::NeedsToUpdateEasyUnlockKeys() const { - return user_context_.GetAccountId().is_valid() && + return !user_context_.GetUserID().empty() && user_manager::User::TypeHasGaiaAccount(user_context_.GetUserType()) && user_context_.GetKey() && !user_context_.GetKey()->GetSecret().empty(); } @@ -761,7 +760,7 @@ if (!connection_error) { // We are in one of "done" states here. user_manager::UserManager::Get()->SaveUserOAuthStatus( - user_manager::UserManager::Get()->GetLoggedInUser()->GetAccountId(), + user_manager::UserManager::Get()->GetLoggedInUser()->email(), user_status); } @@ -864,7 +863,7 @@ void UserSessionManager::StoreUserContextDataBeforeProfileIsCreated() { // Store obfuscated GAIA ID. if (!user_context_.GetGaiaID().empty()) { - user_manager::UserManager::Get()->UpdateGaiaID(user_context_.GetAccountId(), + user_manager::UserManager::Get()->UpdateGaiaID(user_context_.GetUserID(), user_context_.GetGaiaID()); } } @@ -872,8 +871,8 @@ void UserSessionManager::StartCrosSession() { BootTimesRecorder* btl = BootTimesRecorder::Get(); btl->AddLoginTimeMarker("StartSession-Start", false); - DBusThreadManager::Get()->GetSessionManagerClient()->StartSession( - user_context_.GetAccountId().GetUserEmail()); + DBusThreadManager::Get()->GetSessionManagerClient()-> + StartSession(user_context_.GetUserID()); btl->AddLoginTimeMarker("StartSession-End", false); } @@ -881,14 +880,15 @@ BootTimesRecorder* btl = BootTimesRecorder::Get(); btl->AddLoginTimeMarker("UserLoggedIn-Start", false); user_manager::UserManager* user_manager = user_manager::UserManager::Get(); - user_manager->UserLoggedIn(user_context_.GetAccountId(), - user_context_.GetUserIDHash(), false); + user_manager->UserLoggedIn(user_context_.GetUserID(), + user_context_.GetUserIDHash(), + false); btl->AddLoginTimeMarker("UserLoggedIn-End", false); } void UserSessionManager::PrepareProfile() { - const bool is_demo_session = DemoAppLauncher::IsDemoAppSession( - user_context_.GetAccountId().GetUserEmail()); + bool is_demo_session = + DemoAppLauncher::IsDemoAppSession(user_context_.GetUserID()); // TODO(nkostylev): Figure out whether demo session is using the right profile // path or not. See https://codereview.chromium.org/171423009 @@ -914,8 +914,9 @@ // Profile is created, extensions and promo resources are initialized. // At this point all other Chrome OS services will be notified that it is // safe to use this profile. - UserProfileInitialized(profile, is_incognito_profile, - user_context.GetAccountId()); + UserProfileInitialized(profile, + is_incognito_profile, + user_context.GetUserID()); break; case Profile::CREATE_STATUS_LOCAL_FAIL: case Profile::CREATE_STATUS_REMOTE_FAIL: @@ -965,8 +966,8 @@ if (gaia_id.empty()) { AccountTrackerService* account_tracker = AccountTrackerServiceFactory::GetForProfile(profile); - const AccountInfo info = account_tracker->FindAccountInfoByEmail( - user_context.GetAccountId().GetUserEmail()); + AccountInfo info = + account_tracker->FindAccountInfoByEmail(user_context.GetUserID()); gaia_id = info.gaia; DCHECK(!gaia_id.empty()); } @@ -976,22 +977,22 @@ // profiles that might not have it set yet). SigninManagerBase* signin_manager = SigninManagerFactory::GetForProfile(profile); - signin_manager->SetAuthenticatedAccountInfo( - gaia_id, user_context.GetAccountId().GetUserEmail()); + signin_manager->SetAuthenticatedAccountInfo(gaia_id, + user_context.GetUserID()); // Backfill GAIA ID in user prefs stored in Local State. std::string tmp_gaia_id; user_manager::UserManager* user_manager = user_manager::UserManager::Get(); - if (!user_manager->FindGaiaID(user_context.GetAccountId(), &tmp_gaia_id) && + if (!user_manager->FindGaiaID(user_context.GetUserID(), &tmp_gaia_id) && !gaia_id.empty()) { - user_manager->UpdateGaiaID(user_context.GetAccountId(), gaia_id); + user_manager->UpdateGaiaID(user_context.GetUserID(), gaia_id); } } } void UserSessionManager::UserProfileInitialized(Profile* profile, bool is_incognito_profile, - const AccountId& account_id) { + const std::string& user_id) { // Demo user signed in. if (is_incognito_profile) { profile->OnLogin(); @@ -1018,10 +1019,9 @@ // first. bool transfer_saml_auth_cookies_on_subsequent_login = false; if (has_auth_cookies_ && - g_browser_process->platform_part() - ->browser_policy_connector_chromeos() - ->GetUserAffiliation(account_id.GetUserEmail()) == - policy::USER_AFFILIATION_MANAGED) { + g_browser_process->platform_part()-> + browser_policy_connector_chromeos()->GetUserAffiliation(user_id) == + policy::USER_AFFILIATION_MANAGED) { CrosSettings::Get()->GetBoolean( kAccountsPrefTransferSAMLCookies, &transfer_saml_auth_cookies_on_subsequent_login); @@ -1090,7 +1090,7 @@ user_manager::UserManager* user_manager = user_manager::UserManager::Get(); if (user_manager->IsLoggedInAsUserWithGaiaAccount()) { if (user_context_.GetAuthFlow() == UserContext::AUTH_FLOW_GAIA_WITH_SAML) - user_manager->UpdateUsingSAML(user_context_.GetAccountId(), true); + user_manager->UpdateUsingSAML(user_context_.GetUserID(), true); SAMLOfflineSigninLimiter* saml_offline_signin_limiter = SAMLOfflineSigninLimiterFactory::GetForProfile(profile); if (saml_offline_signin_limiter) @@ -1123,10 +1123,10 @@ user_context_.ClearSecrets(); if (TokenHandlesEnabled()) { CreateTokenUtilIfMissing(); - if (token_handle_util_->ShouldObtainHandle(user->GetAccountId())) { + if (token_handle_util_->ShouldObtainHandle(user->GetUserID())) { if (!token_handle_fetcher_.get()) { token_handle_fetcher_.reset(new TokenHandleFetcher( - token_handle_util_.get(), user->GetAccountId())); + token_handle_util_.get(), user->GetUserID())); token_handle_fetcher_->BackfillToken( profile, base::Bind(&UserSessionManager::OnTokenHandleObtained, weak_factory_.GetWeakPtr())); @@ -1438,7 +1438,7 @@ DCHECK(!user_already_logged_in); if (!user_already_logged_in) { - UserContext user_context(AccountId::FromUserEmail(user_id)); + UserContext user_context(user_id); user_context.SetUserIDHash(user_id_hash); user_context.SetIsUsingOAuth(false); @@ -1476,7 +1476,7 @@ // TODO(xiyuan): Fix inconsistency user type of |user_context| introduced in // authenticator. const user_manager::User* user = - user_manager::UserManager::Get()->FindUser(user_context.GetAccountId()); + user_manager::UserManager::Get()->FindUser(user_context.GetUserID()); if (!user || !user->HasGaiaAccount()) return; @@ -1501,7 +1501,7 @@ key_manager->RefreshKeys( user_context, *device_list, base::Bind(&UserSessionManager::OnEasyUnlockKeyOpsFinished, AsWeakPtr(), - user_context.GetAccountId().GetUserEmail())); + user_context.GetUserID())); } net::URLRequestContextGetter* @@ -1562,8 +1562,8 @@ if (!easy_unlock_key_ops_finished_callback_.is_null()) easy_unlock_key_ops_finished_callback_.Run(); - const user_manager::User* user = user_manager::UserManager::Get()->FindUser( - AccountId::FromUserEmail(user_id)); + const user_manager::User* user = + user_manager::UserManager::Get()->FindUser(user_id); EasyUnlockService* easy_unlock_service = EasyUnlockService::GetForUser(*user); easy_unlock_service->CheckCryptohomeKeysAndMaybeHardlock(); @@ -1724,9 +1724,9 @@ void UserSessionManager::OnOAuth2TokensFetched(UserContext context) { if (StartupUtils::IsWebviewSigninEnabled() && TokenHandlesEnabled()) { CreateTokenUtilIfMissing(); - if (token_handle_util_->ShouldObtainHandle(context.GetAccountId())) { + if (token_handle_util_->ShouldObtainHandle(context.GetUserID())) { token_handle_fetcher_.reset(new TokenHandleFetcher( - token_handle_util_.get(), context.GetAccountId())); + token_handle_util_.get(), context.GetUserID())); token_handle_fetcher_->FillForNewUser( context.GetAccessToken(), base::Bind(&UserSessionManager::OnTokenHandleObtained, @@ -1735,7 +1735,7 @@ } } -void UserSessionManager::OnTokenHandleObtained(const AccountId& account_id, +void UserSessionManager::OnTokenHandleObtained(const user_manager::UserID& id, bool success) { if (!success) LOG(ERROR) << "OAuth2 token handle fetch failed.";
diff --git a/chrome/browser/chromeos/login/session/user_session_manager.h b/chrome/browser/chromeos/login/session/user_session_manager.h index 755132cd..dee2273 100644 --- a/chrome/browser/chromeos/login/session/user_session_manager.h +++ b/chrome/browser/chromeos/login/session/user_session_manager.h
@@ -24,7 +24,6 @@ #include "net/base/network_change_notifier.h" #include "ui/base/ime/chromeos/input_method_manager.h" -class AccountId; class GURL; class PrefRegistrySimple; class PrefService; @@ -301,7 +300,7 @@ // Profile is created, extensions and promo resources are initialized. void UserProfileInitialized(Profile* profile, bool is_incognito_profile, - const AccountId& account_id); + const std::string& user_id); // Callback to resume profile creation after transferring auth data from // the authentication profile. @@ -369,7 +368,7 @@ const locale_util::LanguageSwitchResult& result); // Callback invoked when |token_handle_util_| has finished. - void OnTokenHandleObtained(const AccountId& account_id, bool success); + void OnTokenHandleObtained(const user_manager::UserID& id, bool success); // Returns |true| if token handles should be used on this device. bool TokenHandlesEnabled();
diff --git a/chrome/browser/chromeos/login/signin/auth_sync_observer.cc b/chrome/browser/chromeos/login/signin/auth_sync_observer.cc index 99b50e53..8fa57495 100644 --- a/chrome/browser/chromeos/login/signin/auth_sync_observer.cc +++ b/chrome/browser/chromeos/login/signin/auth_sync_observer.cc
@@ -62,14 +62,14 @@ // TODO(nkostylev): Remove after crosbug.com/25978 is implemented. LOG(WARNING) << "Invalidate OAuth token because of a sync error: " << sync_service->GetAuthError().ToString(); - const AccountId& account_id = user->GetAccountId(); - DCHECK(account_id.is_valid()); + std::string email = user->email(); + DCHECK(!email.empty()); // TODO(nkostyelv): Change observer after active user has changed. user_manager::User::OAuthTokenStatus old_status = user->oauth_token_status(); user_manager::UserManager::Get()->SaveUserOAuthStatus( - account_id, user_manager::User::OAUTH2_TOKEN_STATUS_INVALID); - RecordReauthReason(account_id, ReauthReason::SYNC_FAILED); + email, user_manager::User::OAUTH2_TOKEN_STATUS_INVALID); + RecordReauthReason(email, ReauthReason::SYNC_FAILED); if (user->GetType() == user_manager::USER_TYPE_SUPERVISED && old_status != user_manager::User::OAUTH2_TOKEN_STATUS_INVALID) { // Attempt to restore token from file. @@ -89,7 +89,7 @@ LOG(ERROR) << "Got an incorrectly invalidated token case, restoring token status."; user_manager::UserManager::Get()->SaveUserOAuthStatus( - user->GetAccountId(), user_manager::User::OAUTH2_TOKEN_STATUS_VALID); + user->email(), user_manager::User::OAUTH2_TOKEN_STATUS_VALID); content::RecordAction( base::UserMetricsAction("ManagedUsers_Chromeos_Sync_Recovered")); }
diff --git a/chrome/browser/chromeos/login/signin/device_id_browsertest.cc b/chrome/browser/chromeos/login/signin/device_id_browsertest.cc index ad33d48..e210e9a 100644 --- a/chrome/browser/chromeos/login/signin/device_id_browsertest.cc +++ b/chrome/browser/chromeos/login/signin/device_id_browsertest.cc
@@ -57,14 +57,14 @@ OobeBaseTest::TearDownOnMainThread(); } - std::string GetDeviceId(const AccountId& account_id) { - return user_manager::UserManager::Get()->GetKnownUserDeviceId(account_id); + std::string GetDeviceId(const std::string& user_id) { + return user_manager::UserManager::Get()->GetKnownUserDeviceId(user_id); } - std::string GetDeviceIdFromSigninClient(const AccountId& account_id) { + std::string GetDeviceIdFromSigninClient(const std::string& user_id) { return ChromeSigninClientFactory::GetForProfile( ProfileHelper::Get()->GetProfileByUser( - user_manager::UserManager::Get()->FindUser(account_id))) + user_manager::UserManager::Get()->FindUser(user_id))) ->GetSigninScopedDeviceId(); } @@ -76,11 +76,11 @@ // are the same. // If |refresh_token| is not empty, checks that device ID associated with the // |refresh_token| in GAIA is the same as ID saved on device. - void CheckDeviceIDIsConsistent(const AccountId& account_id, + void CheckDeviceIDIsConsistent(const std::string& user_id, const std::string& refresh_token) { const std::string device_id_in_signin_client = - GetDeviceIdFromSigninClient(account_id); - const std::string device_id_in_local_state = GetDeviceId(account_id); + GetDeviceIdFromSigninClient(user_id); + const std::string device_id_in_local_state = GetDeviceId(user_id); EXPECT_FALSE(device_id_in_signin_client.empty()); EXPECT_EQ(device_id_in_signin_client, device_id_in_local_state); @@ -122,8 +122,8 @@ WaitForSessionStart(); } - void RemoveUser(const AccountId& account_id) { - user_manager::UserManager::Get()->RemoveUser(account_id, this); + void RemoveUser(const std::string& user_id) { + user_manager::UserManager::Get()->RemoveUser(user_id, this); user_removal_loop_.Run(); } @@ -176,39 +176,34 @@ IN_PROC_BROWSER_TEST_F(DeviceIDTest, PRE_PRE_PRE_PRE_PRE_NewUsers) { SignInOnline(kFakeUserEmail, kFakeUserPassword, kRefreshToken1, kFakeUserGaiaId); - CheckDeviceIDIsConsistent(AccountId::FromUserEmail(kFakeUserEmail), - kRefreshToken1); + CheckDeviceIDIsConsistent(kFakeUserEmail, kRefreshToken1); } // Authenticate the first user through GAIA and verify that device ID remains // the same. IN_PROC_BROWSER_TEST_F(DeviceIDTest, PRE_PRE_PRE_PRE_NewUsers) { - const std::string device_id = - GetDeviceId(AccountId::FromUserEmail(kFakeUserEmail)); + const std::string device_id = GetDeviceId(kFakeUserEmail); EXPECT_FALSE(device_id.empty()); EXPECT_EQ(device_id, GetDeviceIdFromGAIA(kRefreshToken1)); SignInOnline(kFakeUserEmail, kFakeUserPassword, kRefreshToken2, kFakeUserGaiaId); - CheckDeviceIDIsConsistent(AccountId::FromUserEmail(kFakeUserEmail), - kRefreshToken2); + CheckDeviceIDIsConsistent(kFakeUserEmail, kRefreshToken2); - CHECK_EQ(device_id, GetDeviceId(AccountId::FromUserEmail(kFakeUserEmail))); + CHECK_EQ(device_id, GetDeviceId(kFakeUserEmail)); } // Authenticate the first user offline and verify that device ID remains // the same. IN_PROC_BROWSER_TEST_F(DeviceIDTest, PRE_PRE_PRE_NewUsers) { - const std::string device_id = - GetDeviceId(AccountId::FromUserEmail(kFakeUserEmail)); + const std::string device_id = GetDeviceId(kFakeUserEmail); EXPECT_FALSE(device_id.empty()); SignInOffline(kFakeUserEmail, kFakeUserPassword); - CheckDeviceIDIsConsistent(AccountId::FromUserEmail(kFakeUserEmail), - kRefreshToken2); + CheckDeviceIDIsConsistent(kFakeUserEmail, kRefreshToken2); // Verify that device ID remained the same after offline auth. - CHECK_EQ(device_id, GetDeviceId(AccountId::FromUserEmail(kFakeUserEmail))); + CHECK_EQ(device_id, GetDeviceId(kFakeUserEmail)); } // Add the second user. @@ -217,25 +212,23 @@ JS().ExecuteAsync("chrome.send('showAddUser')"); SignInOnline(kSecondUserEmail, kSecondUserPassword, kSecondUserRefreshToken1, kSecondUserGaiaId); - CheckDeviceIDIsConsistent(AccountId::FromUserEmail(kSecondUserEmail), - kSecondUserRefreshToken1); + CheckDeviceIDIsConsistent(kSecondUserEmail, kSecondUserRefreshToken1); } // Remove the second user. IN_PROC_BROWSER_TEST_F(DeviceIDTest, PRE_NewUsers) { WaitForSigninScreen(); - RemoveUser(AccountId::FromUserEmail(kSecondUserEmail)); + RemoveUser(kSecondUserEmail); } // Add the second user back. Verify that device ID has been changed. IN_PROC_BROWSER_TEST_F(DeviceIDTest, NewUsers) { - EXPECT_TRUE(GetDeviceId(AccountId::FromUserEmail(kSecondUserEmail)).empty()); + EXPECT_TRUE(GetDeviceId(kSecondUserEmail).empty()); SignInOnline(kSecondUserEmail, kSecondUserPassword, kSecondUserRefreshToken2, kSecondUserGaiaId); - CheckDeviceIDIsConsistent(AccountId::FromUserEmail(kSecondUserEmail), - kSecondUserRefreshToken2); + CheckDeviceIDIsConsistent(kSecondUserEmail, kSecondUserRefreshToken2); EXPECT_NE(GetDeviceIdFromGAIA(kSecondUserRefreshToken1), - GetDeviceId(AccountId::FromUserEmail(kSecondUserEmail))); + GetDeviceId(kSecondUserEmail)); } // Set up a user that has a device ID stored in preference only. @@ -249,21 +242,20 @@ ->GetProfileByUser(user_manager::UserManager::Get()->GetActiveUser()) ->GetPrefs(); prefs->SetString(prefs::kGoogleServicesSigninScopedDeviceId, - GetDeviceId(AccountId::FromUserEmail(kFakeUserEmail))); + GetDeviceId(kFakeUserEmail)); // Can't use SetKnownUserDeviceId here, because it forbids changing a device // ID. user_manager::UserManager::Get()->SetKnownUserStringPref( - AccountId::FromUserEmail(kFakeUserEmail), "device_id", std::string()); + kFakeUserEmail, "device_id", std::string()); } // Tests that after the first sign in the device ID has been moved to the Local // state. IN_PROC_BROWSER_TEST_F(DeviceIDTest, Migration) { - EXPECT_TRUE(GetDeviceId(AccountId::FromUserEmail(kFakeUserEmail)).empty()); + EXPECT_TRUE(GetDeviceId(kFakeUserEmail).empty()); SignInOffline(kFakeUserEmail, kFakeUserPassword); - CheckDeviceIDIsConsistent(AccountId::FromUserEmail(kFakeUserEmail), - kRefreshToken1); + CheckDeviceIDIsConsistent(kFakeUserEmail, kRefreshToken1); } // Set up a user that doesn't have a device ID. @@ -281,17 +273,16 @@ // Can't use SetKnownUserDeviceId here, because it forbids changing a device // ID. user_manager::UserManager::Get()->SetKnownUserStringPref( - AccountId::FromUserEmail(kFakeUserEmail), "device_id", std::string()); + kFakeUserEmail, "device_id", std::string()); } // Tests that device ID has been generated after the first sign in. IN_PROC_BROWSER_TEST_F(DeviceIDTest, LegacyUsers) { - EXPECT_TRUE(GetDeviceId(AccountId::FromUserEmail(kFakeUserEmail)).empty()); + EXPECT_TRUE(GetDeviceId(kFakeUserEmail).empty()); SignInOffline(kFakeUserEmail, kFakeUserPassword); // Last param |auth_code| is empty, because we don't pass a device ID to GAIA // in this case. - CheckDeviceIDIsConsistent(AccountId::FromUserEmail(kFakeUserEmail), - std::string()); + CheckDeviceIDIsConsistent(kFakeUserEmail, std::string()); } } // namespace chromeos
diff --git a/chrome/browser/chromeos/login/signin/oauth2_browsertest.cc b/chrome/browser/chromeos/login/signin/oauth2_browsertest.cc index 3c224239..b83bb0c 100644 --- a/chrome/browser/chromeos/login/signin/oauth2_browsertest.cc +++ b/chrome/browser/chromeos/login/signin/oauth2_browsertest.cc
@@ -29,7 +29,6 @@ #include "chromeos/login/auth/user_context.h" #include "components/app_modal/javascript_app_modal_dialog.h" #include "components/app_modal/native_app_modal_dialog.h" -#include "components/signin/core/account_id/account_id.h" #include "components/signin/core/browser/account_tracker_service.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" #include "components/user_manager/user.h" @@ -198,9 +197,7 @@ user_manager::User::OAUTH2_TOKEN_STATUS_VALID); // Try login. Primary profile has changed. - EXPECT_TRUE( - TryToLogin(AccountId::FromUserEmailGaiaId(kTestEmail, kTestGaiaId), - kTestAccountPassword)); + EXPECT_TRUE(TryToLogin(kTestGaiaId, kTestEmail, kTestAccountPassword)); Profile* profile = ProfileManager::GetPrimaryUserProfile(); // Wait for the session merge to finish. @@ -215,13 +212,15 @@ user_manager::User::OAUTH2_TOKEN_STATUS_VALID); } - bool TryToLogin(const AccountId& account_id, const std::string& password) { - if (!AddUserToSession(account_id, password)) + bool TryToLogin(const std::string& gaia_id, + const std::string& username, + const std::string& password) { + if (!AddUserToSession(gaia_id, username, password)) return false; if (const user_manager::User* active_user = user_manager::UserManager::Get()->GetActiveUser()) { - return active_user->GetAccountId() == account_id; + return active_user->email() == username; } return false; @@ -252,7 +251,8 @@ return OobeBaseTest::profile(); } - bool AddUserToSession(const AccountId& account_id, + bool AddUserToSession(const std::string& gaia_id, + const std::string& username, const std::string& password) { ExistingUserController* controller = ExistingUserController::current_controller(); @@ -261,8 +261,8 @@ return false; } - UserContext user_context(account_id); - user_context.SetGaiaID(account_id.GetGaiaId()); + UserContext user_context(username); + user_context.SetGaiaID(gaia_id); user_context.SetKey(Key(password)); controller->Login(user_context, SigninSpecifics()); content::WindowedNotificationObserver( @@ -273,7 +273,7 @@ for (user_manager::UserList::const_iterator it = logged_users.begin(); it != logged_users.end(); ++it) { - if ((*it)->GetAccountId() == account_id) + if ((*it)->email() == username) return true; } return false; @@ -494,9 +494,7 @@ EXPECT_EQ(GetOAuthStatusFromLocalState(account_id), user_manager::User::OAUTH2_TOKEN_STATUS_VALID); - EXPECT_TRUE( - TryToLogin(AccountId::FromUserEmailGaiaId(kTestEmail, kTestGaiaId), - kTestAccountPassword)); + EXPECT_TRUE(TryToLogin(kTestGaiaId, kTestEmail, kTestAccountPassword)); // Wait for the session merge to finish. WaitForMergeSessionCompletion(OAuth2LoginManager::SESSION_RESTORE_FAILED);
diff --git a/chrome/browser/chromeos/login/signin/oauth2_login_manager.cc b/chrome/browser/chromeos/login/signin/oauth2_login_manager.cc index 8b79b2f5..5e046a4 100644 --- a/chrome/browser/chromeos/login/signin/oauth2_login_manager.cc +++ b/chrome/browser/chromeos/login/signin/oauth2_login_manager.cc
@@ -16,7 +16,6 @@ #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chromeos/chromeos_switches.h" -#include "components/signin/core/account_id/account_id.h" #include "components/signin/core/browser/account_tracker_service.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" #include "components/signin/core/browser/signin_client.h" @@ -109,8 +108,7 @@ // cause user to go through Gaia in next login to obtain a new refresh // token. user_manager::UserManager::Get()->SaveUserOAuthStatus( - AccountId::FromUserEmail(primary_account_id), - user_manager::User::OAUTH_TOKEN_STATUS_UNKNOWN); + primary_account_id, user_manager::User::OAUTH_TOKEN_STATUS_UNKNOWN); token_service->LoadCredentials(primary_account_id); } @@ -131,14 +129,14 @@ } void OAuth2LoginManager::OnRefreshTokenAvailable( - const std::string& user_email) { + const std::string& account_id) { VLOG(1) << "OnRefreshTokenAvailable"; if (state_ == SESSION_RESTORE_NOT_STARTED) return; // TODO(fgorski): Once ProfileOAuth2TokenService supports multi-login, make - // sure to restore session cookies in the context of the correct user_email. + // sure to restore session cookies in the context of the correct account_id. // Do not validate tokens for supervised users, as they don't actually have // oauth2 token. @@ -147,11 +145,10 @@ return; } // Only restore session cookies for the primary account in the profile. - if (GetPrimaryAccountId() == user_email) { + if (GetPrimaryAccountId() == account_id) { // Token is loaded. Undo the flagging before token loading. user_manager::UserManager::Get()->SaveUserOAuthStatus( - AccountId::FromUserEmail(user_email), - user_manager::User::OAUTH2_TOKEN_STATUS_VALID); + account_id, user_manager::User::OAUTH2_TOKEN_STATUS_VALID); VerifySessionCookies(); } }
diff --git a/chrome/browser/chromeos/login/signin/oauth2_login_manager.h b/chrome/browser/chromeos/login/signin/oauth2_login_manager.h index 184a2e54..580f3cb 100644 --- a/chrome/browser/chromeos/login/signin/oauth2_login_manager.h +++ b/chrome/browser/chromeos/login/signin/oauth2_login_manager.h
@@ -166,7 +166,7 @@ void OnOAuth2TokensFetchFailed() override; // OAuth2TokenService::Observer implementation: - void OnRefreshTokenAvailable(const std::string& user_email) override; + void OnRefreshTokenAvailable(const std::string& account_id) override; // Signals delegate that authentication is completed, kicks off token fetching // process.
diff --git a/chrome/browser/chromeos/login/signin/token_handle_fetcher.cc b/chrome/browser/chromeos/login/signin/token_handle_fetcher.cc index 83a287a..3f79988b7 100644 --- a/chrome/browser/chromeos/login/signin/token_handle_fetcher.cc +++ b/chrome/browser/chromeos/login/signin/token_handle_fetcher.cc
@@ -42,10 +42,15 @@ } // namespace TokenHandleFetcher::TokenHandleFetcher(TokenHandleUtil* util, - const AccountId& account_id) + const user_manager::UserID& user_id) : OAuth2TokenService::Consumer("user_session_manager"), token_handle_util_(util), - account_id_(account_id) {} + user_id_(user_id), + token_service_(nullptr), + waiting_for_refresh_token_(false), + profile_(nullptr), + tokeninfo_response_start_time_(base::TimeTicks()) { +} TokenHandleFetcher::~TokenHandleFetcher() { if (waiting_for_refresh_token_) @@ -60,9 +65,9 @@ token_service_ = ProfileOAuth2TokenServiceFactory::GetForProfile(profile); SigninManagerBase* signin_manager = SigninManagerFactory::GetForProfile(profile); - const std::string user_email = signin_manager->GetAuthenticatedAccountId(); - if (!token_service_->RefreshTokenIsAvailable(user_email)) { - account_without_token_ = user_email; + std::string account_id = signin_manager->GetAuthenticatedAccountId(); + if (!token_service_->RefreshTokenIsAvailable(account_id)) { + account_without_token_ = account_id; profile_shutdown_notification_ = ShutdownNotifierFactory::GetInstance()->Get(profile)->Subscribe( base::Bind(&TokenHandleFetcher::OnProfileDestroyed, @@ -72,23 +77,23 @@ waiting_for_refresh_token_ = true; return; } - RequestAccessToken(user_email); + RequestAccessToken(account_id); } void TokenHandleFetcher::OnRefreshTokenAvailable( - const std::string& user_email) { - if (account_without_token_ != user_email) + const std::string& account_id) { + if (account_without_token_ != account_id) return; waiting_for_refresh_token_ = false; token_service_->RemoveObserver(this); - RequestAccessToken(user_email); + RequestAccessToken(account_id); } -void TokenHandleFetcher::RequestAccessToken(const std::string& user_email) { +void TokenHandleFetcher::RequestAccessToken(const std::string& account_id) { OAuth2TokenService::ScopeSet scopes; scopes.insert(GaiaConstants::kOAuth1LoginScope); oauth2_access_token_request_ = - token_service_->StartRequest(user_email, scopes, this); + token_service_->StartRequest(account_id, scopes, this); } void TokenHandleFetcher::OnGetTokenSuccess( @@ -105,7 +110,7 @@ oauth2_access_token_request_.reset(); LOG(ERROR) << "Could not get access token to backfill token handler" << error.ToString(); - callback_.Run(account_id_, false); + callback_.Run(user_id_, false); } void TokenHandleFetcher::FillForNewUser(const std::string& access_token, @@ -124,11 +129,11 @@ } void TokenHandleFetcher::OnOAuthError() { - callback_.Run(account_id_, false); + callback_.Run(user_id_, false); } void TokenHandleFetcher::OnNetworkError(int response_code) { - callback_.Run(account_id_, false); + callback_.Run(user_id_, false); } void TokenHandleFetcher::OnGetTokenInfoResponse( @@ -138,15 +143,15 @@ std::string handle; if (token_info->GetString("token_handle", &handle)) { success = true; - token_handle_util_->StoreTokenHandle(account_id_, handle); + token_handle_util_->StoreTokenHandle(user_id_, handle); } } const base::TimeDelta duration = base::TimeTicks::Now() - tokeninfo_response_start_time_; UMA_HISTOGRAM_TIMES("Login.TokenObtainResponseTime", duration); - callback_.Run(account_id_, success); + callback_.Run(user_id_, success); } void TokenHandleFetcher::OnProfileDestroyed() { - callback_.Run(account_id_, false); + callback_.Run(user_id_, false); }
diff --git a/chrome/browser/chromeos/login/signin/token_handle_fetcher.h b/chrome/browser/chromeos/login/signin/token_handle_fetcher.h index 77ebb8a..5c471a438 100644 --- a/chrome/browser/chromeos/login/signin/token_handle_fetcher.h +++ b/chrome/browser/chromeos/login/signin/token_handle_fetcher.h
@@ -13,7 +13,7 @@ #include "base/memory/weak_ptr.h" #include "base/time/time.h" #include "components/keyed_service/core/keyed_service_shutdown_notifier.h" -#include "components/signin/core/account_id/account_id.h" +#include "components/user_manager/user_id.h" #include "google_apis/gaia/gaia_oauth_client.h" #include "google_apis/gaia/oauth2_token_service.h" @@ -29,11 +29,12 @@ public OAuth2TokenService::Consumer, public OAuth2TokenService::Observer { public: - TokenHandleFetcher(TokenHandleUtil* util, const AccountId& account_id); + TokenHandleFetcher(TokenHandleUtil* util, + const user_manager::UserID& user_id); ~TokenHandleFetcher() override; - using TokenFetchingCallback = - base::Callback<void(const AccountId&, bool success)>; + typedef base::Callback<void(const user_manager::UserID&, bool success)> + TokenFetchingCallback; // Get token handle for user who have just signed in via GAIA. This // request will be performed using signin profile. @@ -45,7 +46,7 @@ private: // OAuth2TokenService::Observer override: - void OnRefreshTokenAvailable(const std::string& user_email) override; + void OnRefreshTokenAvailable(const std::string& account_id) override; // OAuth2TokenService::Consumer overrides: void OnGetTokenSuccess(const OAuth2TokenService::Request* request, @@ -60,20 +61,20 @@ void OnGetTokenInfoResponse( scoped_ptr<base::DictionaryValue> token_info) override; - void RequestAccessToken(const std::string& user_email); + void RequestAccessToken(const std::string& account_id); void FillForAccessToken(const std::string& access_token); // This is called before profile is detroyed. void OnProfileDestroyed(); - TokenHandleUtil* token_handle_util_ = nullptr; - AccountId account_id_; - OAuth2TokenService* token_service_ = nullptr; + TokenHandleUtil* token_handle_util_; + user_manager::UserID user_id_; + OAuth2TokenService* token_service_; - bool waiting_for_refresh_token_ = false; + bool waiting_for_refresh_token_; std::string account_without_token_; - Profile* profile_ = nullptr; - base::TimeTicks tokeninfo_response_start_time_ = base::TimeTicks(); + Profile* profile_; + base::TimeTicks tokeninfo_response_start_time_; TokenFetchingCallback callback_; scoped_ptr<gaia::GaiaOAuthClient> gaia_client_; scoped_ptr<OAuth2TokenService::Request> oauth2_access_token_request_;
diff --git a/chrome/browser/chromeos/login/signin/token_handle_util.cc b/chrome/browser/chromeos/login/signin/token_handle_util.cc index 5304a94..4e688a7 100644 --- a/chrome/browser/chromeos/login/signin/token_handle_util.cc +++ b/chrome/browser/chromeos/login/signin/token_handle_util.cc
@@ -9,6 +9,7 @@ #include "base/values.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/profiles/profile.h" +#include "components/user_manager/user_id.h" #include "components/user_manager/user_manager.h" #include "google_apis/gaia/gaia_oauth_client.h" @@ -34,20 +35,20 @@ gaia_client_.reset(); } -bool TokenHandleUtil::HasToken(const AccountId& account_id) { +bool TokenHandleUtil::HasToken(const user_manager::UserID& user_id) { const base::DictionaryValue* dict = nullptr; std::string token; - if (!user_manager_->FindKnownUserPrefs(account_id, &dict)) + if (!user_manager_->FindKnownUserPrefs(user_id, &dict)) return false; if (!dict->GetString(kTokenHandlePref, &token)) return false; return !token.empty(); } -bool TokenHandleUtil::ShouldObtainHandle(const AccountId& account_id) { +bool TokenHandleUtil::ShouldObtainHandle(const user_manager::UserID& user_id) { const base::DictionaryValue* dict = nullptr; std::string token; - if (!user_manager_->FindKnownUserPrefs(account_id, &dict)) + if (!user_manager_->FindKnownUserPrefs(user_id, &dict)) return true; if (!dict->GetString(kTokenHandlePref, &token)) return true; @@ -58,32 +59,32 @@ return kHandleStatusInvalid == status; } -void TokenHandleUtil::DeleteHandle(const AccountId& account_id) { +void TokenHandleUtil::DeleteHandle(const user_manager::UserID& user_id) { const base::DictionaryValue* dict = nullptr; - if (!user_manager_->FindKnownUserPrefs(account_id, &dict)) + if (!user_manager_->FindKnownUserPrefs(user_id, &dict)) return; scoped_ptr<base::DictionaryValue> dict_copy(dict->DeepCopy()); dict_copy->Remove(kTokenHandlePref, nullptr); dict_copy->Remove(kTokenHandleStatusPref, nullptr); - user_manager_->UpdateKnownUserPrefs(account_id, *dict_copy.get(), + user_manager_->UpdateKnownUserPrefs(user_id, *dict_copy.get(), /* replace values */ true); } -void TokenHandleUtil::MarkHandleInvalid(const AccountId& account_id) { - user_manager_->SetKnownUserStringPref(account_id, kTokenHandleStatusPref, +void TokenHandleUtil::MarkHandleInvalid(const user_manager::UserID& user_id) { + user_manager_->SetKnownUserStringPref(user_id, kTokenHandleStatusPref, kHandleStatusInvalid); } -void TokenHandleUtil::CheckToken(const AccountId& account_id, +void TokenHandleUtil::CheckToken(const user_manager::UserID& user_id, const TokenValidationCallback& callback) { const base::DictionaryValue* dict = nullptr; std::string token; - if (!user_manager_->FindKnownUserPrefs(account_id, &dict)) { - callback.Run(account_id, UNKNOWN); + if (!user_manager_->FindKnownUserPrefs(user_id, &dict)) { + callback.Run(user_id, UNKNOWN); return; } if (!dict->GetString(kTokenHandlePref, &token)) { - callback.Run(account_id, UNKNOWN); + callback.Run(user_id, UNKNOWN); return; } @@ -95,15 +96,15 @@ validation_delegates_.set( token, scoped_ptr<TokenDelegate>(new TokenDelegate( - weak_factory_.GetWeakPtr(), account_id, token, callback))); + weak_factory_.GetWeakPtr(), user_id, token, callback))); gaia_client_->GetTokenHandleInfo(token, kMaxRetries, validation_delegates_.get(token)); } -void TokenHandleUtil::StoreTokenHandle(const AccountId& account_id, +void TokenHandleUtil::StoreTokenHandle(const user_manager::UserID& user_id, const std::string& handle) { - user_manager_->SetKnownUserStringPref(account_id, kTokenHandlePref, handle); - user_manager_->SetKnownUserStringPref(account_id, kTokenHandleStatusPref, + user_manager_->SetKnownUserStringPref(user_id, kTokenHandlePref, handle); + user_manager_->SetKnownUserStringPref(user_id, kTokenHandleStatusPref, kHandleStatusValid); } @@ -111,26 +112,28 @@ validation_delegates_.erase(token); } -void TokenHandleUtil::OnObtainTokenComplete(const AccountId& account_id) { - obtain_delegates_.erase(account_id); +void TokenHandleUtil::OnObtainTokenComplete( + const user_manager::UserID& user_id) { + obtain_delegates_.erase(user_id); } TokenHandleUtil::TokenDelegate::TokenDelegate( const base::WeakPtr<TokenHandleUtil>& owner, - const AccountId& account_id, + const user_manager::UserID& user_id, const std::string& token, const TokenValidationCallback& callback) : owner_(owner), - account_id_(account_id), + user_id_(user_id), token_(token), tokeninfo_response_start_time_(base::TimeTicks::Now()), - callback_(callback) {} + callback_(callback) { +} TokenHandleUtil::TokenDelegate::~TokenDelegate() { } void TokenHandleUtil::TokenDelegate::OnOAuthError() { - callback_.Run(account_id_, INVALID); + callback_.Run(user_id_, INVALID); NotifyDone(); } @@ -141,7 +144,7 @@ } void TokenHandleUtil::TokenDelegate::OnNetworkError(int response_code) { - callback_.Run(account_id_, UNKNOWN); + callback_.Run(user_id_, UNKNOWN); NotifyDone(); } @@ -157,6 +160,6 @@ const base::TimeDelta duration = base::TimeTicks::Now() - tokeninfo_response_start_time_; UMA_HISTOGRAM_TIMES("Login.TokenCheckResponseTime", duration); - callback_.Run(account_id_, outcome); + callback_.Run(user_id_, outcome); NotifyDone(); }
diff --git a/chrome/browser/chromeos/login/signin/token_handle_util.h b/chrome/browser/chromeos/login/signin/token_handle_util.h index 20ef090..572d3345 100644 --- a/chrome/browser/chromeos/login/signin/token_handle_util.h +++ b/chrome/browser/chromeos/login/signin/token_handle_util.h
@@ -12,11 +12,9 @@ #include "base/containers/scoped_ptr_hash_map.h" #include "base/memory/weak_ptr.h" #include "base/time/time.h" -#include "components/signin/core/account_id/account_id.h" +#include "components/user_manager/user_id.h" #include "google_apis/gaia/gaia_oauth_client.h" -class AccountId; - namespace base { class DictionaryValue; } @@ -36,36 +34,37 @@ enum TokenHandleStatus { VALID, INVALID, UNKNOWN }; - using TokenValidationCallback = - base::Callback<void(const AccountId&, TokenHandleStatus)>; + typedef base::Callback<void(const user_manager::UserID&, TokenHandleStatus)> + TokenValidationCallback; - // Returns true if UserManager has token handle associated with |account_id|. - bool HasToken(const AccountId& account_id); + // Returns true if UserManager has token handle associated with |user_id|. + bool HasToken(const user_manager::UserID& user_id); - // Removes token handle for |account_id| from UserManager storage. - void DeleteHandle(const AccountId& account_id); + // Removes token handle for |user_id| from UserManager storage. + void DeleteHandle(const user_manager::UserID& user_id); // Marks current handle as invalid, new one should be obtained at next sign // in. - void MarkHandleInvalid(const AccountId& account_id); + void MarkHandleInvalid(const user_manager::UserID& user_id); - // Indicates if token handle for |account_id| is missing or marked as invalid. - bool ShouldObtainHandle(const AccountId& account_id); + // Indicates if token handle for |user_id| is missing or marked as invalid. + bool ShouldObtainHandle(const user_manager::UserID& user_id); - // Performs token handle check for |account_id|. Will call |callback| with + // Performs token handle check for |user_id|. Will call |callback| with // corresponding result. - void CheckToken(const AccountId& account_id, + void CheckToken(const user_manager::UserID& user_id, const TokenValidationCallback& callback); - // Given the token |handle| store it for |account_id|. - void StoreTokenHandle(const AccountId& account_id, const std::string& handle); + // Given the token |handle| store it for |user_id|. + void StoreTokenHandle(const user_manager::UserID& user_id, + const std::string& handle); private: // Associates GaiaOAuthClient::Delegate with User ID and Token. class TokenDelegate : public gaia::GaiaOAuthClient::Delegate { public: TokenDelegate(const base::WeakPtr<TokenHandleUtil>& owner, - const AccountId& account_id, + const user_manager::UserID& user_id, const std::string& token, const TokenValidationCallback& callback); ~TokenDelegate() override; @@ -77,7 +76,7 @@ private: base::WeakPtr<TokenHandleUtil> owner_; - AccountId account_id_; + user_manager::UserID user_id_; std::string token_; base::TimeTicks tokeninfo_response_start_time_; TokenValidationCallback callback_; @@ -86,7 +85,7 @@ }; void OnValidationComplete(const std::string& token); - void OnObtainTokenComplete(const AccountId& account_id); + void OnObtainTokenComplete(const user_manager::UserID& id); // UserManager that stores corresponding user data. user_manager::UserManager* user_manager_; @@ -96,7 +95,7 @@ validation_delegates_; // Map of pending obtain operations. - base::ScopedPtrHashMap<AccountId, scoped_ptr<TokenDelegate>> + base::ScopedPtrHashMap<user_manager::UserID, scoped_ptr<TokenDelegate>> obtain_delegates_; // Instance of GAIA Client.
diff --git a/chrome/browser/chromeos/login/signin_screen_controller.cc b/chrome/browser/chromeos/login/signin_screen_controller.cc index fdcfd5a..06e683d 100644 --- a/chrome/browser/chromeos/login/signin_screen_controller.cc +++ b/chrome/browser/chromeos/login/signin_screen_controller.cc
@@ -59,8 +59,7 @@ } void SignInScreenController::RemoveUser(const std::string& user_id) { - user_manager::UserManager::Get()->RemoveUser( - AccountId::FromUserEmail(user_id), this); + user_manager::UserManager::Get()->RemoveUser(user_id, this); } void SignInScreenController::OnBeforeUserRemoved(const std::string& username) {
diff --git a/chrome/browser/chromeos/login/supervised/supervised_user_authentication.cc b/chrome/browser/chromeos/login/supervised/supervised_user_authentication.cc index 7fcd6e8..7485604 100644 --- a/chrome/browser/chromeos/login/supervised/supervised_user_authentication.cc +++ b/chrome/browser/chromeos/login/supervised/supervised_user_authentication.cc
@@ -104,15 +104,14 @@ UserContext SupervisedUserAuthentication::TransformKey( const UserContext& context) { UserContext result = context; - int user_schema = GetPasswordSchema(context.GetAccountId().GetUserEmail()); + int user_schema = GetPasswordSchema(context.GetUserID()); if (user_schema == SCHEMA_PLAIN) return result; if (user_schema == SCHEMA_SALT_HASHED) { base::DictionaryValue holder; std::string salt; - owner_->GetPasswordInformation(context.GetAccountId().GetUserEmail(), - &holder); + owner_->GetPasswordInformation(context.GetUserID(), &holder); holder.GetStringWithoutPathExpansion(kSalt, &salt); DCHECK(!salt.empty()); Key* const key = result.GetKey(); @@ -121,8 +120,7 @@ result.SetIsUsingOAuth(false); return result; } - NOTREACHED() << "Unknown password schema for " - << context.GetAccountId().GetUserEmail(); + NOTREACHED() << "Unknown password schema for " << context.GetUserID(); return context; } @@ -225,8 +223,8 @@ void SupervisedUserAuthentication::ScheduleSupervisedPasswordChange( const std::string& supervised_user_id, const base::DictionaryValue* password_data) { - const user_manager::User* user = user_manager::UserManager::Get()->FindUser( - AccountId::FromUserEmail(supervised_user_id)); + const user_manager::User* user = + user_manager::UserManager::Get()->FindUser(supervised_user_id); base::FilePath profile_path = ProfileHelper::GetProfilePathByUserIdHash( user->username_hash()); JSONFileValueSerializer serializer(profile_path.Append(kPasswordUpdateFile)); @@ -283,8 +281,8 @@ const std::string& user_id, const PasswordDataCallback& success_callback, const base::Closure& failure_callback) { - const user_manager::User* user = user_manager::UserManager::Get()->FindUser( - AccountId::FromUserEmail(user_id)); + const user_manager::User* user = + user_manager::UserManager::Get()->FindUser(user_id); base::FilePath profile_path = ProfileHelper::GetProfilePathByUserIdHash(user->username_hash()); PostTaskAndReplyWithResult(
diff --git a/chrome/browser/chromeos/login/supervised/supervised_user_creation_controller_new.cc b/chrome/browser/chromeos/login/supervised/supervised_user_creation_controller_new.cc index 1ad658c..0e512ff 100644 --- a/chrome/browser/chromeos/login/supervised/supervised_user_creation_controller_new.cc +++ b/chrome/browser/chromeos/login/supervised/supervised_user_creation_controller_new.cc
@@ -27,7 +27,6 @@ #include "chromeos/dbus/session_manager_client.h" #include "chromeos/login/auth/key.h" #include "chromeos/login/auth/user_context.h" -#include "components/signin/core/account_id/account_id.h" #include "components/user_manager/user.h" #include "components/user_manager/user_manager.h" #include "content/public/browser/browser_thread.h" @@ -288,8 +287,7 @@ std::string(), // The salt is stored elsewhere. creation_context_->salted_master_key); key.SetLabel(kCryptohomeMasterKeyLabel); - UserContext context( - AccountId::FromUserEmail(creation_context_->local_user_id)); + UserContext context(creation_context_->local_user_id); context.SetKey(key); context.SetIsUsingOAuth(false); @@ -383,7 +381,7 @@ // Assume that new token is valid. It will be automatically invalidated if // sync service fails to use it. user_manager::UserManager::Get()->SaveUserOAuthStatus( - AccountId::FromUserEmail(creation_context_->local_user_id), + creation_context_->local_user_id, user_manager::User::OAUTH2_TOKEN_STATUS_VALID); stage_ = TOKEN_WRITTEN;
diff --git a/chrome/browser/chromeos/login/supervised/supervised_user_creation_screen.cc b/chrome/browser/chromeos/login/supervised/supervised_user_creation_screen.cc index 99ef7a4f..2648f7f 100644 --- a/chrome/browser/chromeos/login/supervised/supervised_user_creation_screen.cc +++ b/chrome/browser/chromeos/login/supervised/supervised_user_creation_screen.cc
@@ -223,15 +223,14 @@ manager_signin_in_progress_ = true; UserFlow* flow = new SupervisedUserCreationFlow(manager_id); - ChromeUserManager::Get()->SetUserFlow(AccountId::FromUserEmail(manager_id), - flow); + ChromeUserManager::Get()->SetUserFlow(manager_id, flow); // Make sure no two controllers exist at the same time. controller_.reset(); controller_.reset(new SupervisedUserCreationControllerNew(this, manager_id)); - UserContext user_context(AccountId::FromUserEmail(manager_id)); + UserContext user_context(manager_id); user_context.SetKey(Key(manager_password)); ExistingUserController::current_controller()->Login(user_context, SigninSpecifics()); @@ -485,8 +484,7 @@ void SupervisedUserCreationScreen::ApplyPicture() { std::string user_id = controller_->GetSupervisedUserId(); UserImageManager* image_manager = - ChromeUserManager::Get()->GetUserImageManager( - AccountId::FromUserEmail(user_id)); + ChromeUserManager::Get()->GetUserImageManager(user_id); switch (selected_image_) { case user_manager::User::USER_IMAGE_EXTERNAL: // Photo decoding may not have been finished yet.
diff --git a/chrome/browser/chromeos/login/supervised/supervised_user_test_base.cc b/chrome/browser/chromeos/login/supervised/supervised_user_test_base.cc index ab41788..39fca9f 100644 --- a/chrome/browser/chromeos/login/supervised/supervised_user_test_base.cc +++ b/chrome/browser/chromeos/login/supervised/supervised_user_test_base.cc
@@ -294,7 +294,7 @@ // Next button is now enabled. JSExpect("!$('supervised-user-creation-next-button').disabled"); - UserContext user_context(AccountId::FromUserEmail(kTestManager)); + UserContext user_context(kTestManager); user_context.SetGaiaID(GetGaiaIDForUserID(kTestManager)); user_context.SetKey(Key(kTestManagerPassword)); SetExpectedCredentials(user_context); @@ -308,8 +308,7 @@ // OAuth token is valid. user_manager::UserManager::Get()->SaveUserOAuthStatus( - AccountId::FromUserEmail(kTestManager), - user_manager::User::OAUTH2_TOKEN_STATUS_VALID); + kTestManager, user_manager::User::OAUTH2_TOKEN_STATUS_VALID); base::RunLoop().RunUntilIdle(); // Check the page have changed.
diff --git a/chrome/browser/chromeos/login/user_flow.cc b/chrome/browser/chromeos/login/user_flow.cc index 74e37c3..7f48e1b 100644 --- a/chrome/browser/chromeos/login/user_flow.cc +++ b/chrome/browser/chromeos/login/user_flow.cc
@@ -6,14 +6,13 @@ #include "base/message_loop/message_loop.h" #include "chrome/browser/chromeos/login/user_flow.h" #include "chrome/browser/chromeos/login/users/chrome_user_manager.h" -#include "components/signin/core/account_id/account_id.h" namespace chromeos { namespace { void UnregisterFlow(const std::string& user_id) { - ChromeUserManager::Get()->ResetUserFlow(AccountId::FromUserEmail(user_id)); + ChromeUserManager::Get()->ResetUserFlow(user_id); } } // namespace
diff --git a/chrome/browser/chromeos/login/users/avatar/user_image_manager_browsertest.cc b/chrome/browser/chromeos/login/users/avatar/user_image_manager_browsertest.cc index df168436..b3ceb6882 100644 --- a/chrome/browser/chromeos/login/users/avatar/user_image_manager_browsertest.cc +++ b/chrome/browser/chromeos/login/users/avatar/user_image_manager_browsertest.cc
@@ -103,9 +103,8 @@ class UserImageManagerTest : public LoginManagerTest, public user_manager::UserManager::Observer { protected: - UserImageManagerTest() - : LoginManagerTest(true), - enterprise_account_id_(AccountId::FromUserEmail(kEnterpriseUser1)) {} + UserImageManagerTest() : LoginManagerTest(true) { + } // LoginManagerTest overrides: void SetUpInProcessBrowserTestFixture() override { @@ -132,35 +131,32 @@ run_loop_->Quit(); } - // Logs in |account_id|. - void LogIn(const AccountId& account_id) { - user_manager::UserManager::Get()->UserLoggedIn( - account_id, account_id.GetUserEmail(), false); + // Logs in |username|. + void LogIn(const std::string& username) { + user_manager::UserManager::Get()->UserLoggedIn(username, username, false); } // Stores old (pre-migration) user image info. - void SetOldUserImageInfo(const AccountId& account_id, + void SetOldUserImageInfo(const std::string& username, int image_index, const base::FilePath& image_path) { - RegisterUser(account_id.GetUserEmail()); + RegisterUser(username); DictionaryPrefUpdate images_pref(local_state_, "UserImages"); base::DictionaryValue* image_properties = new base::DictionaryValue(); image_properties->Set("index", new base::FundamentalValue(image_index)); image_properties->Set( "path" , new base::StringValue(image_path.value())); - images_pref->SetWithoutPathExpansion(account_id.GetUserEmail(), - image_properties); + images_pref->SetWithoutPathExpansion(username, image_properties); } // Verifies user image info in |images_pref| dictionary. void ExpectUserImageInfo(const base::DictionaryValue* images_pref, - const AccountId& account_id, + const std::string& username, int image_index, const base::FilePath& image_path) { ASSERT_TRUE(images_pref); const base::DictionaryValue* image_properties = NULL; - images_pref->GetDictionaryWithoutPathExpansion(account_id.GetUserEmail(), - &image_properties); + images_pref->GetDictionaryWithoutPathExpansion(username, &image_properties); ASSERT_TRUE(image_properties); int actual_image_index; std::string actual_image_path; @@ -170,42 +166,42 @@ EXPECT_EQ(image_path.value(), actual_image_path); } - // Verifies that there is no image info for |account_id| in dictionary + // Verifies that there is no image info for |username| in dictionary // |images_pref|. void ExpectNoUserImageInfo(const base::DictionaryValue* images_pref, - const AccountId& account_id) { + const std::string& username) { ASSERT_TRUE(images_pref); const base::DictionaryValue* image_properties = NULL; - images_pref->GetDictionaryWithoutPathExpansion(account_id.GetUserEmail(), - &image_properties); + images_pref->GetDictionaryWithoutPathExpansion(username, &image_properties); ASSERT_FALSE(image_properties); } // Verifies that old user image info matches |image_index| and |image_path| // and that new user image info does not exist. - void ExpectOldUserImageInfo(const AccountId& account_id, + void ExpectOldUserImageInfo(const std::string& username, int image_index, const base::FilePath& image_path) { - ExpectUserImageInfo(local_state_->GetDictionary("UserImages"), account_id, - image_index, image_path); + ExpectUserImageInfo(local_state_->GetDictionary("UserImages"), + username, image_index, image_path); ExpectNoUserImageInfo(local_state_->GetDictionary("user_image_info"), - account_id); + username); } // Verifies that new user image info matches |image_index| and |image_path| // and that old user image info does not exist. - void ExpectNewUserImageInfo(const AccountId& account_id, + void ExpectNewUserImageInfo(const std::string& username, int image_index, const base::FilePath& image_path) { ExpectUserImageInfo(local_state_->GetDictionary("user_image_info"), - account_id, image_index, image_path); + username, image_index, image_path); ExpectNoUserImageInfo(local_state_->GetDictionary("UserImages"), - account_id); + username); } - // Sets bitmap |resource_id| as image for |account_id| and saves it to disk. - void SaveUserImagePNG(const AccountId& account_id, int resource_id) { - base::FilePath image_path = GetUserImagePath(account_id, "png"); + // Sets bitmap |resource_id| as image for |username| and saves it to disk. + void SaveUserImagePNG(const std::string& username, + int resource_id) { + base::FilePath image_path = GetUserImagePath(username, "png"); scoped_refptr<base::RefCountedStaticMemory> image_data( ResourceBundle::GetSharedInstance().LoadDataResourceBytesForScale( resource_id, ui::SCALE_FACTOR_100P)); @@ -214,29 +210,28 @@ reinterpret_cast<const char*>(image_data->front()), image_data->size()); EXPECT_EQ(static_cast<int>(image_data->size()), written); - SetOldUserImageInfo(account_id, user_manager::User::USER_IMAGE_EXTERNAL, - image_path); + SetOldUserImageInfo( + username, user_manager::User::USER_IMAGE_EXTERNAL, image_path); } - // Returns the image path for user |account_id| with specified |extension|. - base::FilePath GetUserImagePath(const AccountId& account_id, + // Returns the image path for user |username| with specified |extension|. + base::FilePath GetUserImagePath(const std::string& username, const std::string& extension) { - return user_data_dir_.Append(account_id.GetUserEmail()) - .AddExtension(extension); + return user_data_dir_.Append(username).AddExtension(extension); } // Seeds the AccountTrackerService with test data so the ProfileDownloader can // retrieve the picture URL and fetch the image. - void SeedAccountTrackerService(const AccountId& account_id, + void SeedAccountTrackerService(const std::string& username, Profile* profile) { AccountInfo info; info.account_id = std::string(); - info.gaia = account_id.GetUserEmail(); - info.email = account_id.GetUserEmail(); - info.full_name = account_id.GetUserEmail(); - info.given_name = account_id.GetUserEmail(); + info.gaia = username; + info.email = username; + info.full_name = username; + info.given_name = username; info.hosted_domain = std::string(); - info.locale = account_id.GetUserEmail(); + info.locale = username; info.picture_url = "http://localhost/avatar.jpg"; info.is_child_account = false; @@ -244,16 +239,16 @@ } // Completes the download of all non-image profile data for the user - // |account_id|. This method must only be called after a profile data + // |username|. This method must only be called after a profile data // download has been started. |url_fetcher_factory| will capture // the net::TestURLFetcher created by the ProfileDownloader to // download the profile image. void CompleteProfileMetadataDownload( - const AccountId& account_id, + const std::string& username, net::TestURLFetcherFactory* url_fetcher_factory) { ProfileDownloader* profile_downloader = reinterpret_cast<UserImageManagerImpl*>( - ChromeUserManager::Get()->GetUserImageManager(account_id)) + ChromeUserManager::Get()->GetUserImageManager(username)) ->profile_downloader_.get(); ASSERT_TRUE(profile_downloader); @@ -295,7 +290,7 @@ user_manager::UserManager::Get()->GetLoggedInUser(); ASSERT_TRUE(user); UserImageManagerImpl* uim = reinterpret_cast<UserImageManagerImpl*>( - ChromeUserManager::Get()->GetUserImageManager(user->GetAccountId())); + ChromeUserManager::Get()->GetUserImageManager(user->email())); if (uim->job_.get()) { run_loop_.reset(new base::RunLoop); run_loop_->Run(); @@ -311,10 +306,6 @@ scoped_ptr<base::RunLoop> run_loop_; - const AccountId test_account_id1_ = AccountId::FromUserEmail(kTestUser1); - const AccountId test_account_id2_ = AccountId::FromUserEmail(kTestUser2); - const AccountId enterprise_account_id_; - private: DISALLOW_COPY_AND_ASSIGN(UserImageManagerTest); }; @@ -322,56 +313,49 @@ IN_PROC_BROWSER_TEST_F(UserImageManagerTest, PRE_DefaultUserImagePreserved) { // Setup an old default (stock) user image. ScopedUserManagerEnabler(new MockUserManager); - SetOldUserImageInfo(test_account_id1_, user_manager::kFirstDefaultImageIndex, - base::FilePath()); + SetOldUserImageInfo( + kTestUser1, user_manager::kFirstDefaultImageIndex, base::FilePath()); } IN_PROC_BROWSER_TEST_F(UserImageManagerTest, DefaultUserImagePreserved) { user_manager::UserManager::Get()->GetUsers(); // Load users. // Old info preserved. - ExpectOldUserImageInfo(test_account_id1_, - user_manager::kFirstDefaultImageIndex, - base::FilePath()); - LogIn(test_account_id1_); + ExpectOldUserImageInfo( + kTestUser1, user_manager::kFirstDefaultImageIndex, base::FilePath()); + LogIn(kTestUser1); // Image info is migrated now. - ExpectNewUserImageInfo(test_account_id1_, - user_manager::kFirstDefaultImageIndex, - base::FilePath()); + ExpectNewUserImageInfo( + kTestUser1, user_manager::kFirstDefaultImageIndex, base::FilePath()); } IN_PROC_BROWSER_TEST_F(UserImageManagerTest, PRE_OtherUsersUnaffected) { // Setup two users with stock images. ScopedUserManagerEnabler(new MockUserManager); - SetOldUserImageInfo(test_account_id1_, user_manager::kFirstDefaultImageIndex, - base::FilePath()); - SetOldUserImageInfo(test_account_id2_, - user_manager::kFirstDefaultImageIndex + 1, - base::FilePath()); + SetOldUserImageInfo( + kTestUser1, user_manager::kFirstDefaultImageIndex, base::FilePath()); + SetOldUserImageInfo( + kTestUser2, user_manager::kFirstDefaultImageIndex + 1, base::FilePath()); } IN_PROC_BROWSER_TEST_F(UserImageManagerTest, OtherUsersUnaffected) { user_manager::UserManager::Get()->GetUsers(); // Load users. // Old info preserved. - ExpectOldUserImageInfo(test_account_id1_, - user_manager::kFirstDefaultImageIndex, - base::FilePath()); - ExpectOldUserImageInfo(test_account_id2_, - user_manager::kFirstDefaultImageIndex + 1, - base::FilePath()); - LogIn(test_account_id1_); + ExpectOldUserImageInfo( + kTestUser1, user_manager::kFirstDefaultImageIndex, base::FilePath()); + ExpectOldUserImageInfo( + kTestUser2, user_manager::kFirstDefaultImageIndex + 1, base::FilePath()); + LogIn(kTestUser1); // Image info is migrated for the first user and unaffected for the rest. - ExpectNewUserImageInfo(test_account_id1_, - user_manager::kFirstDefaultImageIndex, - base::FilePath()); - ExpectOldUserImageInfo(test_account_id2_, - user_manager::kFirstDefaultImageIndex + 1, - base::FilePath()); + ExpectNewUserImageInfo( + kTestUser1, user_manager::kFirstDefaultImageIndex, base::FilePath()); + ExpectOldUserImageInfo( + kTestUser2, user_manager::kFirstDefaultImageIndex + 1, base::FilePath()); } IN_PROC_BROWSER_TEST_F(UserImageManagerTest, PRE_PRE_NonJPEGImageFromFile) { // Setup a user with non-JPEG image. ScopedUserManagerEnabler(new MockUserManager); - SaveUserImagePNG(test_account_id1_, + SaveUserImagePNG(kTestUser1, user_manager::kDefaultImageResourceIDs [user_manager::kFirstDefaultImageIndex]); } @@ -379,26 +363,26 @@ IN_PROC_BROWSER_TEST_F(UserImageManagerTest, PRE_NonJPEGImageFromFile) { user_manager::UserManager::Get()->GetUsers(); // Load users. // Old info preserved. - ExpectOldUserImageInfo(test_account_id1_, + ExpectOldUserImageInfo(kTestUser1, user_manager::User::USER_IMAGE_EXTERNAL, - GetUserImagePath(test_account_id1_, "png")); + GetUserImagePath(kTestUser1, "png")); const user_manager::User* user = - user_manager::UserManager::Get()->FindUser(test_account_id1_); + user_manager::UserManager::Get()->FindUser(kTestUser1); EXPECT_TRUE(user->image_is_stub()); base::RunLoop run_loop; PrefChangeRegistrar pref_change_registrar_; pref_change_registrar_.Init(local_state_); pref_change_registrar_.Add("UserImages", run_loop.QuitClosure()); - LogIn(test_account_id1_); + LogIn(kTestUser1); // Wait for migration. run_loop.Run(); // Image info is migrated and the image is converted to JPG. - ExpectNewUserImageInfo(test_account_id1_, + ExpectNewUserImageInfo(kTestUser1, user_manager::User::USER_IMAGE_EXTERNAL, - GetUserImagePath(test_account_id1_, "jpg")); + GetUserImagePath(kTestUser1, "jpg")); user = user_manager::UserManager::Get()->GetLoggedInUser(); ASSERT_TRUE(user); EXPECT_FALSE(user->image_is_safe_format()); @@ -412,7 +396,7 @@ IN_PROC_BROWSER_TEST_F(UserImageManagerTest, NonJPEGImageFromFile) { user_manager::UserManager::Get()->GetUsers(); // Load users. const user_manager::User* user = - user_manager::UserManager::Get()->FindUser(test_account_id1_); + user_manager::UserManager::Get()->FindUser(kTestUser1); ASSERT_TRUE(user); // Wait for image load. if (user->image_index() == user_manager::User::USER_IMAGE_INVALID) { @@ -430,41 +414,40 @@ } IN_PROC_BROWSER_TEST_F(UserImageManagerTest, PRE_SaveUserDefaultImageIndex) { - RegisterUser(test_account_id1_.GetUserEmail()); + RegisterUser(kTestUser1); } // Verifies that SaveUserDefaultImageIndex() correctly sets and persists the // chosen user image. IN_PROC_BROWSER_TEST_F(UserImageManagerTest, SaveUserDefaultImageIndex) { const user_manager::User* user = - user_manager::UserManager::Get()->FindUser(test_account_id1_); + user_manager::UserManager::Get()->FindUser(kTestUser1); ASSERT_TRUE(user); const gfx::ImageSkia& default_image = user_manager::GetDefaultImage(user_manager::kFirstDefaultImageIndex); UserImageManager* user_image_manager = - ChromeUserManager::Get()->GetUserImageManager(test_account_id1_); + ChromeUserManager::Get()->GetUserImageManager(kTestUser1); user_image_manager->SaveUserDefaultImageIndex( user_manager::kFirstDefaultImageIndex); EXPECT_TRUE(user->HasDefaultImage()); EXPECT_EQ(user_manager::kFirstDefaultImageIndex, user->image_index()); EXPECT_TRUE(test::AreImagesEqual(default_image, user->GetImage())); - ExpectNewUserImageInfo(test_account_id1_, - user_manager::kFirstDefaultImageIndex, - base::FilePath()); + ExpectNewUserImageInfo( + kTestUser1, user_manager::kFirstDefaultImageIndex, base::FilePath()); } IN_PROC_BROWSER_TEST_F(UserImageManagerTest, PRE_SaveUserImage) { - RegisterUser(test_account_id1_.GetUserEmail()); + RegisterUser(kTestUser1); } // Verifies that SaveUserImage() correctly sets and persists the chosen user // image. IN_PROC_BROWSER_TEST_F(UserImageManagerTest, SaveUserImage) { const user_manager::User* user = - user_manager::UserManager::Get()->FindUser(test_account_id1_); + user_manager::UserManager::Get()->FindUser(kTestUser1); ASSERT_TRUE(user); SkBitmap custom_image_bitmap; @@ -476,7 +459,7 @@ run_loop_.reset(new base::RunLoop); UserImageManager* user_image_manager = - ChromeUserManager::Get()->GetUserImageManager(test_account_id1_); + ChromeUserManager::Get()->GetUserImageManager(kTestUser1); user_image_manager->SaveUserImage( user_manager::UserImage::CreateAndEncode(custom_image)); run_loop_->Run(); @@ -484,12 +467,12 @@ EXPECT_FALSE(user->HasDefaultImage()); EXPECT_EQ(user_manager::User::USER_IMAGE_EXTERNAL, user->image_index()); EXPECT_TRUE(test::AreImagesEqual(custom_image, user->GetImage())); - ExpectNewUserImageInfo(test_account_id1_, + ExpectNewUserImageInfo(kTestUser1, user_manager::User::USER_IMAGE_EXTERNAL, - GetUserImagePath(test_account_id1_, "jpg")); + GetUserImagePath(kTestUser1, "jpg")); const scoped_ptr<gfx::ImageSkia> saved_image = - test::ImageLoader(GetUserImagePath(test_account_id1_, "jpg")).Load(); + test::ImageLoader(GetUserImagePath(kTestUser1, "jpg")).Load(); ASSERT_TRUE(saved_image); // Check image dimensions. Images can't be compared since JPEG is lossy. @@ -498,14 +481,14 @@ } IN_PROC_BROWSER_TEST_F(UserImageManagerTest, PRE_SaveUserImageFromFile) { - RegisterUser(test_account_id1_.GetUserEmail()); + RegisterUser(kTestUser1); } // Verifies that SaveUserImageFromFile() correctly sets and persists the chosen // user image. IN_PROC_BROWSER_TEST_F(UserImageManagerTest, SaveUserImageFromFile) { const user_manager::User* user = - user_manager::UserManager::Get()->FindUser(test_account_id1_); + user_manager::UserManager::Get()->FindUser(kTestUser1); ASSERT_TRUE(user); const base::FilePath custom_image_path = @@ -516,19 +499,19 @@ run_loop_.reset(new base::RunLoop); UserImageManager* user_image_manager = - ChromeUserManager::Get()->GetUserImageManager(test_account_id1_); + ChromeUserManager::Get()->GetUserImageManager(kTestUser1); user_image_manager->SaveUserImageFromFile(custom_image_path); run_loop_->Run(); EXPECT_FALSE(user->HasDefaultImage()); EXPECT_EQ(user_manager::User::USER_IMAGE_EXTERNAL, user->image_index()); EXPECT_TRUE(test::AreImagesEqual(*custom_image, user->GetImage())); - ExpectNewUserImageInfo(test_account_id1_, + ExpectNewUserImageInfo(kTestUser1, user_manager::User::USER_IMAGE_EXTERNAL, - GetUserImagePath(test_account_id1_, "jpg")); + GetUserImagePath(kTestUser1, "jpg")); const scoped_ptr<gfx::ImageSkia> saved_image = - test::ImageLoader(GetUserImagePath(test_account_id1_, "jpg")).Load(); + test::ImageLoader(GetUserImagePath(kTestUser1, "jpg")).Load(); ASSERT_TRUE(saved_image); // Check image dimensions. Images can't be compared since JPEG is lossy. @@ -538,7 +521,7 @@ IN_PROC_BROWSER_TEST_F(UserImageManagerTest, PRE_SaveUserImageFromProfileImage) { - RegisterUser(test_account_id1_.GetUserEmail()); + RegisterUser(kTestUser1); chromeos::StartupUtils::MarkOobeCompleted(); } @@ -546,22 +529,22 @@ // persists the chosen user image. IN_PROC_BROWSER_TEST_F(UserImageManagerTest, SaveUserImageFromProfileImage) { const user_manager::User* user = - user_manager::UserManager::Get()->FindUser(test_account_id1_); + user_manager::UserManager::Get()->FindUser(kTestUser1); ASSERT_TRUE(user); UserImageManagerImpl::IgnoreProfileDataDownloadDelayForTesting(); - LoginUser(test_account_id1_.GetUserEmail()); + LoginUser(kTestUser1); Profile* profile = ProfileHelper::Get()->GetProfileByUserUnsafe(user); - SeedAccountTrackerService(test_account_id1_, profile); + SeedAccountTrackerService(kTestUser1, profile); run_loop_.reset(new base::RunLoop); UserImageManager* user_image_manager = - ChromeUserManager::Get()->GetUserImageManager(test_account_id1_); + ChromeUserManager::Get()->GetUserImageManager(kTestUser1); user_image_manager->SaveUserImageFromProfileImage(); run_loop_->Run(); net::TestURLFetcherFactory url_fetcher_factory; - CompleteProfileMetadataDownload(test_account_id1_, &url_fetcher_factory); + CompleteProfileMetadataDownload(kTestUser1, &url_fetcher_factory); CompleteProfileImageDownload(&url_fetcher_factory); const gfx::ImageSkia& profile_image = @@ -570,12 +553,12 @@ EXPECT_FALSE(user->HasDefaultImage()); EXPECT_EQ(user_manager::User::USER_IMAGE_PROFILE, user->image_index()); EXPECT_TRUE(test::AreImagesEqual(profile_image, user->GetImage())); - ExpectNewUserImageInfo(test_account_id1_, + ExpectNewUserImageInfo(kTestUser1, user_manager::User::USER_IMAGE_PROFILE, - GetUserImagePath(test_account_id1_, "jpg")); + GetUserImagePath(kTestUser1, "jpg")); const scoped_ptr<gfx::ImageSkia> saved_image = - test::ImageLoader(GetUserImagePath(test_account_id1_, "jpg")).Load(); + test::ImageLoader(GetUserImagePath(kTestUser1, "jpg")).Load(); ASSERT_TRUE(saved_image); // Check image dimensions. Images can't be compared since JPEG is lossy. @@ -585,7 +568,7 @@ IN_PROC_BROWSER_TEST_F(UserImageManagerTest, PRE_ProfileImageDownloadDoesNotClobber) { - RegisterUser(test_account_id1_.GetUserEmail()); + RegisterUser(kTestUser1); chromeos::StartupUtils::MarkOobeCompleted(); } @@ -596,25 +579,25 @@ IN_PROC_BROWSER_TEST_F(UserImageManagerTest, ProfileImageDownloadDoesNotClobber) { const user_manager::User* user = - user_manager::UserManager::Get()->FindUser(test_account_id1_); + user_manager::UserManager::Get()->FindUser(kTestUser1); ASSERT_TRUE(user); const gfx::ImageSkia& default_image = user_manager::GetDefaultImage(user_manager::kFirstDefaultImageIndex); UserImageManagerImpl::IgnoreProfileDataDownloadDelayForTesting(); - LoginUser(test_account_id1_.GetUserEmail()); + LoginUser(kTestUser1); Profile* profile = ProfileHelper::Get()->GetProfileByUserUnsafe(user); - SeedAccountTrackerService(test_account_id1_, profile); + SeedAccountTrackerService(kTestUser1, profile); run_loop_.reset(new base::RunLoop); UserImageManager* user_image_manager = - ChromeUserManager::Get()->GetUserImageManager(test_account_id1_); + ChromeUserManager::Get()->GetUserImageManager(kTestUser1); user_image_manager->SaveUserImageFromProfileImage(); run_loop_->Run(); net::TestURLFetcherFactory url_fetcher_factory; - CompleteProfileMetadataDownload(test_account_id1_, &url_fetcher_factory); + CompleteProfileMetadataDownload(kTestUser1, &url_fetcher_factory); user_image_manager->SaveUserDefaultImageIndex( user_manager::kFirstDefaultImageIndex); @@ -624,9 +607,8 @@ EXPECT_TRUE(user->HasDefaultImage()); EXPECT_EQ(user_manager::kFirstDefaultImageIndex, user->image_index()); EXPECT_TRUE(test::AreImagesEqual(default_image, user->GetImage())); - ExpectNewUserImageInfo(test_account_id1_, - user_manager::kFirstDefaultImageIndex, - base::FilePath()); + ExpectNewUserImageInfo( + kTestUser1, user_manager::kFirstDefaultImageIndex, base::FilePath()); } class UserImageManagerPolicyTest : public UserImageManagerTest, @@ -650,8 +632,7 @@ ASSERT_TRUE(PathService::Get(chromeos::DIR_USER_POLICY_KEYS, &user_keys_dir)); const std::string sanitized_username = - chromeos::CryptohomeClient::GetStubSanitizedUsername( - enterprise_account_id_.GetUserEmail()); + chromeos::CryptohomeClient::GetStubSanitizedUsername(kEnterpriseUser1); const base::FilePath user_key_file = user_keys_dir.AppendASCII(sanitized_username) .AppendASCII("policy.pub"); @@ -663,8 +644,7 @@ reinterpret_cast<const char*>(user_key_bits.data()), user_key_bits.size()), static_cast<int>(user_key_bits.size())); - user_policy_.policy_data().set_username( - enterprise_account_id_.GetUserEmail()); + user_policy_.policy_data().set_username(kEnterpriseUser1); policy_image_ = test::ImageLoader(test_data_dir_.Append( test::kUserAvatarImage2RelativePath)).Load(); @@ -708,7 +688,7 @@ }; IN_PROC_BROWSER_TEST_F(UserImageManagerPolicyTest, PRE_SetAndClear) { - RegisterUser(enterprise_account_id_.GetUserEmail()); + RegisterUser(kEnterpriseUser1); chromeos::StartupUtils::MarkOobeCompleted(); } @@ -718,10 +698,10 @@ // http://crbug.com/396352 IN_PROC_BROWSER_TEST_F(UserImageManagerPolicyTest, DISABLED_SetAndClear) { const user_manager::User* user = - user_manager::UserManager::Get()->FindUser(enterprise_account_id_); + user_manager::UserManager::Get()->FindUser(kEnterpriseUser1); ASSERT_TRUE(user); - LoginUser(enterprise_account_id_.GetUserEmail()); + LoginUser(kEnterpriseUser1); base::RunLoop().RunUntilIdle(); policy::CloudPolicyStore* store = GetStoreForUser(user); @@ -732,8 +712,8 @@ user_policy_.payload().mutable_useravatarimage()->set_value( ConstructPolicy(test::kUserAvatarImage2RelativePath)); user_policy_.Build(); - fake_session_manager_client_->set_user_policy( - enterprise_account_id_.GetUserEmail(), user_policy_.GetBlob()); + fake_session_manager_client_->set_user_policy(kEnterpriseUser1, + user_policy_.GetBlob()); run_loop_.reset(new base::RunLoop); store->Load(); run_loop_->Run(); @@ -741,12 +721,12 @@ EXPECT_FALSE(user->HasDefaultImage()); EXPECT_EQ(user_manager::User::USER_IMAGE_EXTERNAL, user->image_index()); EXPECT_TRUE(test::AreImagesEqual(*policy_image_, user->GetImage())); - ExpectNewUserImageInfo(enterprise_account_id_, + ExpectNewUserImageInfo(kEnterpriseUser1, user_manager::User::USER_IMAGE_EXTERNAL, - GetUserImagePath(enterprise_account_id_, "jpg")); + GetUserImagePath(kEnterpriseUser1, "jpg")); scoped_ptr<gfx::ImageSkia> saved_image = - test::ImageLoader(GetUserImagePath(enterprise_account_id_, "jpg")).Load(); + test::ImageLoader(GetUserImagePath(kEnterpriseUser1, "jpg")).Load(); ASSERT_TRUE(saved_image); // Check image dimensions. Images can't be compared since JPEG is lossy. @@ -757,8 +737,8 @@ // image. user_policy_.payload().Clear(); user_policy_.Build(); - fake_session_manager_client_->set_user_policy( - enterprise_account_id_.GetUserEmail(), user_policy_.GetBlob()); + fake_session_manager_client_->set_user_policy(kEnterpriseUser1, + user_policy_.GetBlob()); run_loop_.reset(new base::RunLoop); store->AddObserver(this); store->Load(); @@ -775,7 +755,7 @@ const gfx::ImageSkia& default_image = user_manager::GetDefaultImage(default_image_index); EXPECT_TRUE(test::AreImagesEqual(default_image, user->GetImage())); - ExpectNewUserImageInfo(enterprise_account_id_, default_image_index, + ExpectNewUserImageInfo(kEnterpriseUser1, default_image_index, base::FilePath()); // Choose a different user image. Verify that the chosen user image is set and @@ -788,18 +768,17 @@ user_manager::GetDefaultImage(user_image_index); UserImageManager* user_image_manager = - ChromeUserManager::Get()->GetUserImageManager(enterprise_account_id_); + ChromeUserManager::Get()->GetUserImageManager(kEnterpriseUser1); user_image_manager->SaveUserDefaultImageIndex(user_image_index); EXPECT_TRUE(user->HasDefaultImage()); EXPECT_EQ(user_image_index, user->image_index()); EXPECT_TRUE(test::AreImagesEqual(user_image, user->GetImage())); - ExpectNewUserImageInfo(enterprise_account_id_, user_image_index, - base::FilePath()); + ExpectNewUserImageInfo(kEnterpriseUser1, user_image_index, base::FilePath()); } IN_PROC_BROWSER_TEST_F(UserImageManagerPolicyTest, PRE_PolicyOverridesUser) { - RegisterUser(enterprise_account_id_.GetUserEmail()); + RegisterUser(kEnterpriseUser1); chromeos::StartupUtils::MarkOobeCompleted(); } @@ -808,10 +787,10 @@ // previously chosen image. IN_PROC_BROWSER_TEST_F(UserImageManagerPolicyTest, PolicyOverridesUser) { const user_manager::User* user = - user_manager::UserManager::Get()->FindUser(enterprise_account_id_); + user_manager::UserManager::Get()->FindUser(kEnterpriseUser1); ASSERT_TRUE(user); - LoginUser(enterprise_account_id_.GetUserEmail()); + LoginUser(kEnterpriseUser1); base::RunLoop().RunUntilIdle(); policy::CloudPolicyStore* store = GetStoreForUser(user); @@ -823,14 +802,14 @@ user_manager::GetDefaultImage(user_manager::kFirstDefaultImageIndex); UserImageManager* user_image_manager = - ChromeUserManager::Get()->GetUserImageManager(enterprise_account_id_); + ChromeUserManager::Get()->GetUserImageManager(kEnterpriseUser1); user_image_manager->SaveUserDefaultImageIndex( user_manager::kFirstDefaultImageIndex); EXPECT_TRUE(user->HasDefaultImage()); EXPECT_EQ(user_manager::kFirstDefaultImageIndex, user->image_index()); EXPECT_TRUE(test::AreImagesEqual(default_image, user->GetImage())); - ExpectNewUserImageInfo(enterprise_account_id_, + ExpectNewUserImageInfo(kEnterpriseUser1, user_manager::kFirstDefaultImageIndex, base::FilePath()); @@ -839,8 +818,8 @@ user_policy_.payload().mutable_useravatarimage()->set_value( ConstructPolicy(test::kUserAvatarImage2RelativePath)); user_policy_.Build(); - fake_session_manager_client_->set_user_policy( - enterprise_account_id_.GetUserEmail(), user_policy_.GetBlob()); + fake_session_manager_client_->set_user_policy(kEnterpriseUser1, + user_policy_.GetBlob()); run_loop_.reset(new base::RunLoop); store->Load(); run_loop_->Run(); @@ -848,12 +827,12 @@ EXPECT_FALSE(user->HasDefaultImage()); EXPECT_EQ(user_manager::User::USER_IMAGE_EXTERNAL, user->image_index()); EXPECT_TRUE(test::AreImagesEqual(*policy_image_, user->GetImage())); - ExpectNewUserImageInfo(enterprise_account_id_, + ExpectNewUserImageInfo(kEnterpriseUser1, user_manager::User::USER_IMAGE_EXTERNAL, - GetUserImagePath(enterprise_account_id_, "jpg")); + GetUserImagePath(kEnterpriseUser1, "jpg")); scoped_ptr<gfx::ImageSkia> saved_image = - test::ImageLoader(GetUserImagePath(enterprise_account_id_, "jpg")).Load(); + test::ImageLoader(GetUserImagePath(kEnterpriseUser1, "jpg")).Load(); ASSERT_TRUE(saved_image); // Check image dimensions. Images can't be compared since JPEG is lossy. @@ -863,7 +842,7 @@ IN_PROC_BROWSER_TEST_F(UserImageManagerPolicyTest, PRE_UserDoesNotOverridePolicy) { - RegisterUser(enterprise_account_id_.GetUserEmail()); + RegisterUser(kEnterpriseUser1); chromeos::StartupUtils::MarkOobeCompleted(); } @@ -872,10 +851,10 @@ // from overriding the previously chosen image. IN_PROC_BROWSER_TEST_F(UserImageManagerPolicyTest, UserDoesNotOverridePolicy) { const user_manager::User* user = - user_manager::UserManager::Get()->FindUser(enterprise_account_id_); + user_manager::UserManager::Get()->FindUser(kEnterpriseUser1); ASSERT_TRUE(user); - LoginUser(enterprise_account_id_.GetUserEmail()); + LoginUser(kEnterpriseUser1); base::RunLoop().RunUntilIdle(); policy::CloudPolicyStore* store = GetStoreForUser(user); @@ -886,8 +865,8 @@ user_policy_.payload().mutable_useravatarimage()->set_value( ConstructPolicy(test::kUserAvatarImage2RelativePath)); user_policy_.Build(); - fake_session_manager_client_->set_user_policy( - enterprise_account_id_.GetUserEmail(), user_policy_.GetBlob()); + fake_session_manager_client_->set_user_policy(kEnterpriseUser1, + user_policy_.GetBlob()); run_loop_.reset(new base::RunLoop); store->Load(); run_loop_->Run(); @@ -895,12 +874,12 @@ EXPECT_FALSE(user->HasDefaultImage()); EXPECT_EQ(user_manager::User::USER_IMAGE_EXTERNAL, user->image_index()); EXPECT_TRUE(test::AreImagesEqual(*policy_image_, user->GetImage())); - ExpectNewUserImageInfo(enterprise_account_id_, + ExpectNewUserImageInfo(kEnterpriseUser1, user_manager::User::USER_IMAGE_EXTERNAL, - GetUserImagePath(enterprise_account_id_, "jpg")); + GetUserImagePath(kEnterpriseUser1, "jpg")); scoped_ptr<gfx::ImageSkia> saved_image = - test::ImageLoader(GetUserImagePath(enterprise_account_id_, "jpg")).Load(); + test::ImageLoader(GetUserImagePath(kEnterpriseUser1, "jpg")).Load(); ASSERT_TRUE(saved_image); // Check image dimensions. Images can't be compared since JPEG is lossy. @@ -910,19 +889,19 @@ // Choose a different user image. Verify that the user image does not change // as policy takes precedence. UserImageManager* user_image_manager = - ChromeUserManager::Get()->GetUserImageManager(enterprise_account_id_); + ChromeUserManager::Get()->GetUserImageManager(kEnterpriseUser1); user_image_manager->SaveUserDefaultImageIndex( user_manager::kFirstDefaultImageIndex); EXPECT_FALSE(user->HasDefaultImage()); EXPECT_EQ(user_manager::User::USER_IMAGE_EXTERNAL, user->image_index()); EXPECT_TRUE(test::AreImagesEqual(*policy_image_, user->GetImage())); - ExpectNewUserImageInfo(enterprise_account_id_, + ExpectNewUserImageInfo(kEnterpriseUser1, user_manager::User::USER_IMAGE_EXTERNAL, - GetUserImagePath(enterprise_account_id_, "jpg")); + GetUserImagePath(kEnterpriseUser1, "jpg")); saved_image = - test::ImageLoader(GetUserImagePath(enterprise_account_id_, "jpg")).Load(); + test::ImageLoader(GetUserImagePath(kEnterpriseUser1, "jpg")).Load(); ASSERT_TRUE(saved_image); // Check image dimensions. Images can't be compared since JPEG is lossy.
diff --git a/chrome/browser/chromeos/login/users/avatar/user_image_manager_impl.cc b/chrome/browser/chromeos/login/users/avatar/user_image_manager_impl.cc index df6d304..f9f4a49 100644 --- a/chrome/browser/chromeos/login/users/avatar/user_image_manager_impl.cc +++ b/chrome/browser/chromeos/login/users/avatar/user_image_manager_impl.cc
@@ -410,7 +410,8 @@ } void UserImageManagerImpl::Job::UpdateUser() { - user_manager::User* user = parent_->GetUserAndModify(); + user_manager::User* user = + parent_->user_manager_->FindUserAndModify(user_id()); if (!user) return; @@ -450,8 +451,7 @@ void UserImageManagerImpl::Job::UpdateLocalState() { // Ignore if data stored or cached outside the user's cryptohome is to be // treated as ephemeral. - if (parent_->user_manager_->IsUserNonCryptohomeDataEphemeral( - AccountId::FromUserEmail(user_id()))) + if (parent_->user_manager_->IsUserNonCryptohomeDataEphemeral(user_id())) return; scoped_ptr<base::DictionaryValue> entry(new base::DictionaryValue); @@ -769,9 +769,10 @@ DCHECK_EQ(downloader, profile_downloader.get()); user_manager_->UpdateUserAccountData( - AccountId::FromUserEmail(user_id()), + user_id(), user_manager::UserManager::UserAccountData( - downloader->GetProfileFullName(), downloader->GetProfileGivenName(), + downloader->GetProfileFullName(), + downloader->GetProfileGivenName(), downloader->GetProfileLocale())); if (!downloading_profile_image_) return; @@ -1016,11 +1017,11 @@ } const user_manager::User* UserImageManagerImpl::GetUser() const { - return user_manager_->FindUser(AccountId::FromUserEmail(user_id())); + return user_manager_->FindUser(user_id()); } user_manager::User* UserImageManagerImpl::GetUserAndModify() const { - return user_manager_->FindUserAndModify(AccountId::FromUserEmail(user_id())); + return user_manager_->FindUserAndModify(user_id()); } bool UserImageManagerImpl::IsUserLoggedInAndHasGaiaAccount() const {
diff --git a/chrome/browser/chromeos/login/users/avatar/user_image_sync_observer.cc b/chrome/browser/chromeos/login/users/avatar/user_image_sync_observer.cc index 47a774d..bf501d1 100644 --- a/chrome/browser/chromeos/login/users/avatar/user_image_sync_observer.cc +++ b/chrome/browser/chromeos/login/users/avatar/user_image_sync_observer.cc
@@ -171,7 +171,7 @@ if ((synced_index == local_index) || !IsIndexSupported(synced_index)) return; UserImageManager* image_manager = - ChromeUserManager::Get()->GetUserImageManager(user_->GetAccountId()); + ChromeUserManager::Get()->GetUserImageManager(user_->email()); if (synced_index == user_manager::User::USER_IMAGE_PROFILE) { image_manager->SaveUserImageFromProfileImage(); } else {
diff --git a/chrome/browser/chromeos/login/users/chrome_user_manager_impl.cc b/chrome/browser/chromeos/login/users/chrome_user_manager_impl.cc index 40e4a0ee..a846b7ac 100644 --- a/chrome/browser/chromeos/login/users/chrome_user_manager_impl.cc +++ b/chrome/browser/chromeos/login/users/chrome_user_manager_impl.cc
@@ -206,13 +206,12 @@ } UserImageManager* ChromeUserManagerImpl::GetUserImageManager( - const AccountId& account_id) { - UserImageManagerMap::iterator ui = user_image_managers_.find(account_id); + const std::string& user_id) { + UserImageManagerMap::iterator ui = user_image_managers_.find(user_id); if (ui != user_image_managers_.end()) return ui->second.get(); - linked_ptr<UserImageManagerImpl> mgr( - new UserImageManagerImpl(account_id.GetUserEmail(), this)); - user_image_managers_[account_id] = mgr; + linked_ptr<UserImageManagerImpl> mgr(new UserImageManagerImpl(user_id, this)); + user_image_managers_[user_id] = mgr; return mgr.get(); } @@ -317,13 +316,15 @@ } void ChromeUserManagerImpl::RemoveUserInternal( - const AccountId& account_id, + const std::string& user_email, user_manager::RemoveUserDelegate* delegate) { CrosSettings* cros_settings = CrosSettings::Get(); const base::Closure& callback = base::Bind(&ChromeUserManagerImpl::RemoveUserInternal, - weak_factory_.GetWeakPtr(), account_id, delegate); + weak_factory_.GetWeakPtr(), + user_email, + delegate); // Ensure the value of owner email has been fetched. if (CrosSettingsProvider::TRUSTED != @@ -334,34 +335,32 @@ } std::string owner; cros_settings->GetString(kDeviceOwner, &owner); - if (account_id == AccountId::FromUserEmail(owner)) { + if (user_email == owner) { // Owner is not allowed to be removed from the device. return; } - RemoveNonOwnerUserInternal(account_id, delegate); + RemoveNonOwnerUserInternal(user_email, delegate); } void ChromeUserManagerImpl::SaveUserOAuthStatus( - const AccountId& account_id, + const std::string& user_id, user_manager::User::OAuthTokenStatus oauth_token_status) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - ChromeUserManager::SaveUserOAuthStatus(account_id, oauth_token_status); + ChromeUserManager::SaveUserOAuthStatus(user_id, oauth_token_status); - GetUserFlow(account_id)->HandleOAuthTokenStatusChange(oauth_token_status); + GetUserFlow(user_id)->HandleOAuthTokenStatusChange(oauth_token_status); } void ChromeUserManagerImpl::SaveUserDisplayName( - const AccountId& account_id, + const std::string& user_id, const base::string16& display_name) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - ChromeUserManager::SaveUserDisplayName(account_id, display_name); + ChromeUserManager::SaveUserDisplayName(user_id, display_name); // Do not update local state if data stored or cached outside the user's // cryptohome is to be treated as ephemeral. - if (!IsUserNonCryptohomeDataEphemeral(account_id)) { - supervised_user_manager_->UpdateManagerName(account_id.GetUserEmail(), - display_name); - } + if (!IsUserNonCryptohomeDataEphemeral(user_id)) + supervised_user_manager_->UpdateManagerName(user_id, display_name); } void ChromeUserManagerImpl::StopPolicyObserverForTesting() { @@ -412,12 +411,14 @@ if (user != NULL) { user->set_profile_is_created(); - if (user->HasGaiaAccount()) - GetUserImageManager(user->GetAccountId())->UserProfileCreated(); + if (user->HasGaiaAccount()) { + UserImageManager* image_manager = GetUserImageManager(user->email()); + image_manager->UserProfileCreated(); + } } // If there is pending user switch, do it now. - if (GetPendingUserSwitchID().is_valid()) { + if (!GetPendingUserSwitchID().empty()) { // Call SwitchActiveUser async because otherwise it may cause // ProfileManager::GetProfile before the profile gets registered // in ProfileManager. It happens in case of sync profile load when @@ -427,7 +428,7 @@ base::Bind(&ChromeUserManagerImpl::SwitchActiveUser, weak_factory_.GetWeakPtr(), GetPendingUserSwitchID())); - SetPendingUserSwitchId(EmptyAccountId()); + SetPendingUserSwitchID(std::string()); } break; } @@ -439,8 +440,7 @@ void ChromeUserManagerImpl::OnExternalDataSet(const std::string& policy, const std::string& user_id) { if (policy == policy::key::kUserAvatarImage) - GetUserImageManager(AccountId::FromUserEmail(user_id)) - ->OnExternalDataSet(policy); + GetUserImageManager(user_id)->OnExternalDataSet(policy); else if (policy == policy::key::kWallpaperImage) WallpaperManager::Get()->OnPolicySet(policy, user_id); else @@ -450,8 +450,7 @@ void ChromeUserManagerImpl::OnExternalDataCleared(const std::string& policy, const std::string& user_id) { if (policy == policy::key::kUserAvatarImage) - GetUserImageManager(AccountId::FromUserEmail(user_id)) - ->OnExternalDataCleared(policy); + GetUserImageManager(user_id)->OnExternalDataCleared(policy); else if (policy == policy::key::kWallpaperImage) WallpaperManager::Get()->OnPolicyCleared(policy, user_id); else @@ -463,8 +462,7 @@ const std::string& user_id, scoped_ptr<std::string> data) { if (policy == policy::key::kUserAvatarImage) - GetUserImageManager(AccountId::FromUserEmail(user_id)) - ->OnExternalDataFetched(policy, data.Pass()); + GetUserImageManager(user_id)->OnExternalDataFetched(policy, data.Pass()); else if (policy == policy::key::kWallpaperImage) WallpaperManager::Get()->OnPolicyFetched(policy, user_id, data.Pass()); else @@ -472,7 +470,7 @@ } void ChromeUserManagerImpl::OnPolicyUpdated(const std::string& user_id) { - const user_manager::User* user = FindUser(AccountId::FromUserEmail(user_id)); + const user_manager::User* user = FindUser(user_id); if (!user || user->GetType() != user_manager::USER_TYPE_PUBLIC_ACCOUNT) return; UpdatePublicAccountDisplayName(user_id); @@ -489,24 +487,24 @@ } bool ChromeUserManagerImpl::IsUserNonCryptohomeDataEphemeral( - const AccountId& account_id) const { + const std::string& user_id) const { // Data belonging to the obsolete public accounts whose data has not been // removed yet is not ephemeral. - bool is_obsolete_public_account = IsPublicAccountMarkedForRemoval(account_id); + bool is_obsolete_public_account = IsPublicAccountMarkedForRemoval(user_id); return !is_obsolete_public_account && - ChromeUserManager::IsUserNonCryptohomeDataEphemeral(account_id); + ChromeUserManager::IsUserNonCryptohomeDataEphemeral(user_id); } bool ChromeUserManagerImpl::AreEphemeralUsersEnabled() const { policy::BrowserPolicyConnectorChromeOS* connector = g_browser_process->platform_part()->browser_policy_connector_chromeos(); return GetEphemeralUsersEnabled() && - (connector->IsEnterpriseManaged() || GetOwnerAccountId().is_valid()); + (connector->IsEnterpriseManaged() || !GetOwnerEmail().empty()); } -void ChromeUserManagerImpl::OnUserRemoved(const AccountId& account_id) { - RemoveReportingUser(FullyCanonicalize(account_id.GetUserEmail())); +void ChromeUserManagerImpl::OnUserRemoved(const std::string& user_id) { + RemoveReportingUser(FullyCanonicalize(user_id)); } const std::string& ChromeUserManagerImpl::GetApplicationLocale() const { @@ -518,9 +516,9 @@ } void ChromeUserManagerImpl::HandleUserOAuthTokenStatusChange( - const AccountId& account_id, + const std::string& user_id, user_manager::User::OAuthTokenStatus status) const { - GetUserFlow(account_id)->HandleOAuthTokenStatusChange(status); + GetUserFlow(user_id)->HandleOAuthTokenStatusChange(status); } bool ChromeUserManagerImpl::IsEnterpriseManaged() const { @@ -530,15 +528,19 @@ } void ChromeUserManagerImpl::LoadPublicAccounts( - std::set<AccountId>* public_sessions_set) { + std::set<std::string>* public_sessions_set) { const base::ListValue* prefs_public_sessions = GetLocalState()->GetList(kPublicAccounts); - std::vector<AccountId> public_sessions; - ParseUserList(*prefs_public_sessions, std::set<AccountId>(), &public_sessions, + std::vector<std::string> public_sessions; + ParseUserList(*prefs_public_sessions, + std::set<std::string>(), + &public_sessions, public_sessions_set); - for (const AccountId& account_id : public_sessions) { - users_.push_back(user_manager::User::CreatePublicAccountUser(account_id)); - UpdatePublicAccountDisplayName(account_id.GetUserEmail()); + for (std::vector<std::string>::const_iterator it = public_sessions.begin(); + it != public_sessions.end(); + ++it) { + users_.push_back(user_manager::User::CreatePublicAccountUser(*it)); + UpdatePublicAccountDisplayName(*it); } } @@ -557,7 +559,7 @@ for (user_manager::UserList::iterator ui = users_.begin(), ue = users_.end(); ui != ue; ++ui) { - GetUserImageManager((*ui)->GetAccountId())->LoadUserImage(); + GetUserImageManager((*ui)->email())->LoadUserImage(); } } @@ -569,22 +571,22 @@ new SessionLengthLimiter(NULL, browser_restart)); } -bool ChromeUserManagerImpl::IsDemoApp(const AccountId& account_id) const { - return DemoAppLauncher::IsDemoAppSession(account_id.GetUserEmail()); +bool ChromeUserManagerImpl::IsDemoApp(const std::string& user_id) const { + return DemoAppLauncher::IsDemoAppSession(user_id); } -bool ChromeUserManagerImpl::IsKioskApp(const AccountId& account_id) const { +bool ChromeUserManagerImpl::IsKioskApp(const std::string& user_id) const { policy::DeviceLocalAccount::Type device_local_account_type; - return policy::IsDeviceLocalAccountUser(account_id.GetUserEmail(), + return policy::IsDeviceLocalAccountUser(user_id, &device_local_account_type) && device_local_account_type == policy::DeviceLocalAccount::TYPE_KIOSK_APP; } bool ChromeUserManagerImpl::IsPublicAccountMarkedForRemoval( - const AccountId& account_id) const { - return account_id == AccountId::FromUserEmail(GetLocalState()->GetString( - kPublicAccountPendingDataRemoval)); + const std::string& user_id) const { + return user_id == + GetLocalState()->GetString(kPublicAccountPendingDataRemoval); } void ChromeUserManagerImpl::RetrieveTrustedDevicePolicies() { @@ -593,7 +595,7 @@ return; SetEphemeralUsersEnabled(false); - SetOwnerId(EmptyAccountId()); + SetOwnerEmail(std::string()); // Schedule a callback if device policy has not yet been verified. if (CrosSettingsProvider::TRUSTED != @@ -610,7 +612,7 @@ std::string owner_email; cros_settings_->GetString(kDeviceOwner, &owner_email); - SetOwnerId(AccountId::FromUserEmail(owner_email)); + SetOwnerEmail(owner_email); EnsureUsersLoaded(); @@ -624,16 +626,15 @@ prefs_users_update->Clear(); for (user_manager::UserList::iterator it = users_.begin(); it != users_.end();) { - const AccountId account_id = (*it)->GetAccountId(); - if ((*it)->HasGaiaAccount() && account_id != GetOwnerAccountId()) { - RemoveNonCryptohomeData(account_id); + const std::string user_email = (*it)->email(); + if ((*it)->HasGaiaAccount() && user_email != GetOwnerEmail()) { + RemoveNonCryptohomeData(user_email); DeleteUser(*it); it = users_.erase(it); changed = true; } else { if ((*it)->GetType() != user_manager::USER_TYPE_PUBLIC_ACCOUNT) - prefs_users_update->Append( - new base::StringValue(account_id.GetUserEmail())); + prefs_users_update->Append(new base::StringValue(user_email)); ++it; } } @@ -662,21 +663,20 @@ login::GuestAccountId().GetUserEmail()); } -void ChromeUserManagerImpl::RegularUserLoggedIn(const AccountId& account_id) { - ChromeUserManager::RegularUserLoggedIn(account_id); +void ChromeUserManagerImpl::RegularUserLoggedIn(const std::string& user_id) { + ChromeUserManager::RegularUserLoggedIn(user_id); if (FakeOwnership()) { - const AccountId owner_account_id = GetActiveUser()->GetAccountId(); - VLOG(1) << "Set device owner to: " << owner_account_id.GetUserEmail(); - CrosSettings::Get()->SetString(kDeviceOwner, - owner_account_id.GetUserEmail()); - SetOwnerId(owner_account_id); + std::string owner_email = GetActiveUser()->email(); + VLOG(1) << "Set device owner to: " << owner_email; + CrosSettings::Get()->SetString(kDeviceOwner, owner_email); + SetOwnerEmail(owner_email); } if (IsCurrentUserNew()) - WallpaperManager::Get()->SetUserWallpaperNow(account_id.GetUserEmail()); + WallpaperManager::Get()->SetUserWallpaperNow(user_id); - GetUserImageManager(account_id)->UserLoggedIn(IsCurrentUserNew(), false); + GetUserImageManager(user_id)->UserLoggedIn(IsCurrentUserNew(), false); WallpaperManager::Get()->EnsureLoggedInUserWallpaperLoaded(); @@ -685,31 +685,30 @@ } void ChromeUserManagerImpl::RegularUserLoggedInAsEphemeral( - const AccountId& account_id) { + const std::string& user_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - ChromeUserManager::RegularUserLoggedInAsEphemeral(account_id); + ChromeUserManager::RegularUserLoggedInAsEphemeral(user_id); - GetUserImageManager(account_id)->UserLoggedIn(IsCurrentUserNew(), false); - WallpaperManager::Get()->SetUserWallpaperNow(account_id.GetUserEmail()); + GetUserImageManager(user_id)->UserLoggedIn(IsCurrentUserNew(), false); + WallpaperManager::Get()->SetUserWallpaperNow(user_id); } -void ChromeUserManagerImpl::SupervisedUserLoggedIn( - const AccountId& account_id) { +void ChromeUserManagerImpl::SupervisedUserLoggedIn(const std::string& user_id) { // TODO(nkostylev): Refactor, share code with RegularUserLoggedIn(). // Remove the user from the user list. - active_user_ = RemoveRegularOrSupervisedUserFromList(account_id); + active_user_ = RemoveRegularOrSupervisedUserFromList(user_id); // If the user was not found on the user list, create a new user. if (!GetActiveUser()) { SetIsCurrentUserNew(true); - active_user_ = user_manager::User::CreateSupervisedUser(account_id); + active_user_ = user_manager::User::CreateSupervisedUser(user_id); // Leaving OAuth token status at the default state = unknown. - WallpaperManager::Get()->SetUserWallpaperNow(account_id.GetUserEmail()); + WallpaperManager::Get()->SetUserWallpaperNow(user_id); } else { - if (supervised_user_manager_->CheckForFirstRun(account_id.GetUserEmail())) { + if (supervised_user_manager_->CheckForFirstRun(user_id)) { SetIsCurrentUserNew(true); - WallpaperManager::Get()->SetUserWallpaperNow(account_id.GetUserEmail()); + WallpaperManager::Get()->SetUserWallpaperNow(user_id); } else { SetIsCurrentUserNew(false); } @@ -717,17 +716,16 @@ // Add the user to the front of the user list. ListPrefUpdate prefs_users_update(GetLocalState(), kRegularUsers); - prefs_users_update->Insert(0, - new base::StringValue(account_id.GetUserEmail())); + prefs_users_update->Insert(0, new base::StringValue(user_id)); users_.insert(users_.begin(), active_user_); // Now that user is in the list, save display name. if (IsCurrentUserNew()) { - SaveUserDisplayName(GetActiveUser()->GetAccountId(), + SaveUserDisplayName(GetActiveUser()->email(), GetActiveUser()->GetDisplayName()); } - GetUserImageManager(account_id)->UserLoggedIn(IsCurrentUserNew(), true); + GetUserImageManager(user_id)->UserLoggedIn(IsCurrentUserNew(), true); WallpaperManager::Get()->EnsureLoggedInUserWallpaperLoaded(); // Make sure that new data is persisted to Local State. @@ -735,8 +733,8 @@ } bool ChromeUserManagerImpl::HasPendingBootstrap( - const AccountId& account_id) const { - return bootstrap_manager_->HasPendingBootstrap(account_id.GetUserEmail()); + const std::string& user_id) const { + return bootstrap_manager_->HasPendingBootstrap(user_id); } void ChromeUserManagerImpl::PublicAccountUserLoggedIn( @@ -747,20 +745,18 @@ // The UserImageManager chooses a random avatar picture when a user logs in // for the first time. Tell the UserImageManager that this user is not new to // prevent the avatar from getting changed. - GetUserImageManager(user->GetAccountId())->UserLoggedIn(false, true); + GetUserImageManager(user->email())->UserLoggedIn(false, true); WallpaperManager::Get()->EnsureLoggedInUserWallpaperLoaded(); } -void ChromeUserManagerImpl::KioskAppLoggedIn( - const AccountId& kiosk_app_account_id) { +void ChromeUserManagerImpl::KioskAppLoggedIn(const std::string& app_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); policy::DeviceLocalAccount::Type device_local_account_type; - DCHECK(policy::IsDeviceLocalAccountUser(kiosk_app_account_id.GetUserEmail(), - &device_local_account_type)); + DCHECK(policy::IsDeviceLocalAccountUser(app_id, &device_local_account_type)); DCHECK_EQ(policy::DeviceLocalAccount::TYPE_KIOSK_APP, device_local_account_type); - active_user_ = user_manager::User::CreateKioskAppUser(kiosk_app_account_id); + active_user_ = user_manager::User::CreateKioskAppUser(app_id); active_user_->SetStubImage( user_manager::UserImage( *ResourceBundle::GetSharedInstance().GetImageSkiaNamed( @@ -768,8 +764,7 @@ user_manager::User::USER_IMAGE_INVALID, false); - WallpaperManager::Get()->SetUserWallpaperNow( - kiosk_app_account_id.GetUserEmail()); + WallpaperManager::Get()->SetUserWallpaperNow(app_id); // TODO(bartfab): Add KioskAppUsers to the users_ list and keep metadata like // the kiosk_app_id in these objects, removing the need to re-parse the @@ -781,23 +776,22 @@ device_local_accounts.begin(); it != device_local_accounts.end(); ++it) { - if (it->user_id == kiosk_app_account_id.GetUserEmail()) { + if (it->user_id == app_id) { account = &*it; break; } } - std::string kiosk_app_name; + std::string kiosk_app_id; if (account) { - kiosk_app_name = account->kiosk_app_id; + kiosk_app_id = account->kiosk_app_id; } else { - LOG(ERROR) << "Logged into nonexistent kiosk-app account: " - << kiosk_app_account_id.GetUserEmail(); + LOG(ERROR) << "Logged into nonexistent kiosk-app account: " << app_id; NOTREACHED(); } base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); command_line->AppendSwitch(::switches::kForceAppMode); - command_line->AppendSwitchASCII(::switches::kAppId, kiosk_app_name); + command_line->AppendSwitchASCII(::switches::kAppId, kiosk_app_id); // Disable window animation since kiosk app runs in a single full screen // window and window animation causes start-up janks. @@ -806,7 +800,8 @@ void ChromeUserManagerImpl::DemoAccountLoggedIn() { DCHECK_CURRENTLY_ON(BrowserThread::UI); - active_user_ = user_manager::User::CreateKioskAppUser(login::DemoAccountId()); + active_user_ = user_manager::User::CreateKioskAppUser( + login::DemoAccountId().GetUserEmail()); active_user_->SetStubImage( user_manager::UserImage( *ResourceBundle::GetSharedInstance().GetImageSkiaNamed( @@ -854,17 +849,17 @@ } void ChromeUserManagerImpl::RemoveNonCryptohomeData( - const AccountId& account_id) { - ChromeUserManager::RemoveNonCryptohomeData(account_id); + const std::string& user_id) { + ChromeUserManager::RemoveNonCryptohomeData(user_id); - WallpaperManager::Get()->RemoveUserWallpaperInfo(account_id.GetUserEmail()); - GetUserImageManager(account_id)->DeleteUserImage(); + WallpaperManager::Get()->RemoveUserWallpaperInfo(user_id); + GetUserImageManager(user_id)->DeleteUserImage(); - supervised_user_manager_->RemoveNonCryptohomeData(account_id.GetUserEmail()); + supervised_user_manager_->RemoveNonCryptohomeData(user_id); - multi_profile_user_controller_->RemoveCachedValues(account_id.GetUserEmail()); + multi_profile_user_controller_->RemoveCachedValues(user_id); - EasyUnlockService::ResetLocalStateForUser(account_id.GetUserEmail()); + EasyUnlockService::ResetLocalStateForUser(user_id); } void @@ -878,8 +873,7 @@ return; } - RemoveNonCryptohomeData( - AccountId::FromUserEmail(public_account_pending_data_removal)); + RemoveNonCryptohomeData(public_account_pending_data_removal); local_state->ClearPref(kPublicAccountPendingDataRemoval); } @@ -909,7 +903,7 @@ it != old_public_accounts.end(); ++it) { if (users.find(*it) == users.end()) - RemoveNonCryptohomeData(AccountId::FromUserEmail(*it)); + RemoveNonCryptohomeData(*it); } } @@ -982,8 +976,8 @@ if (IsLoggedInAsPublicAccount() && *it == GetActiveUser()->email()) users_.insert(users_.begin(), GetLoggedInUser()); else - users_.insert(users_.begin(), user_manager::User::CreatePublicAccountUser( - AccountId::FromUserEmail(*it))); + users_.insert(users_.begin(), + user_manager::User::CreatePublicAccountUser(*it)); UpdatePublicAccountDisplayName(*it); } @@ -992,7 +986,7 @@ ue = users_.begin() + new_public_accounts.size(); ui != ue; ++ui) { - GetUserImageManager((*ui)->GetAccountId())->LoadUserImage(); + GetUserImageManager((*ui)->email())->LoadUserImage(); } // Remove data belonging to public accounts that are no longer found on the @@ -1014,36 +1008,34 @@ } // Set or clear the display name. - SaveUserDisplayName(AccountId::FromUserEmail(user_id), - base::UTF8ToUTF16(display_name)); + SaveUserDisplayName(user_id, base::UTF8ToUTF16(display_name)); } UserFlow* ChromeUserManagerImpl::GetCurrentUserFlow() const { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!IsUserLoggedIn()) return GetDefaultUserFlow(); - return GetUserFlow(GetLoggedInUser()->GetAccountId()); + return GetUserFlow(GetLoggedInUser()->email()); } -UserFlow* ChromeUserManagerImpl::GetUserFlow( - const AccountId& account_id) const { +UserFlow* ChromeUserManagerImpl::GetUserFlow(const std::string& user_id) const { DCHECK_CURRENTLY_ON(BrowserThread::UI); - FlowMap::const_iterator it = specific_flows_.find(account_id); + FlowMap::const_iterator it = specific_flows_.find(user_id); if (it != specific_flows_.end()) return it->second; return GetDefaultUserFlow(); } -void ChromeUserManagerImpl::SetUserFlow(const AccountId& account_id, +void ChromeUserManagerImpl::SetUserFlow(const std::string& user_id, UserFlow* flow) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - ResetUserFlow(account_id); - specific_flows_[account_id] = flow; + ResetUserFlow(user_id); + specific_flows_[user_id] = flow; } -void ChromeUserManagerImpl::ResetUserFlow(const AccountId& account_id) { +void ChromeUserManagerImpl::ResetUserFlow(const std::string& user_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - FlowMap::iterator it = specific_flows_.find(account_id); + FlowMap::iterator it = specific_flows_.find(user_id); if (it != specific_flows_.end()) { delete it->second; specific_flows_.erase(it); @@ -1080,7 +1072,7 @@ // before the crash. if (user_switch_pending && !UserSessionManager::GetInstance()->UserSessionsRestoreInProgress()) { - SetPendingUserSwitchId(added_user->GetAccountId()); + SetPendingUserSwitchID(added_user->email()); } UpdateNumberOfUsers(); @@ -1095,9 +1087,8 @@ void ChromeUserManagerImpl::RemovePendingBootstrapUser( const std::string& user_id) { - const AccountId account_id(AccountId::FromUserEmail(user_id)); - DCHECK(HasPendingBootstrap(account_id)); - RemoveNonOwnerUserInternal(account_id, nullptr); + DCHECK(HasPendingBootstrap(user_id)); + RemoveNonOwnerUserInternal(user_id, NULL); } void ChromeUserManagerImpl::UpdateNumberOfUsers() { @@ -1151,8 +1142,7 @@ const std::string& user_email, const AffiliationIDSet& user_affiliation_ids) { std::string canonicalized_email = FullyCanonicalize(user_email); - user_manager::User* user = - FindUserAndModify(AccountId::FromUserEmail(canonicalized_email)); + user_manager::User* user = FindUserAndModify(canonicalized_email); if (user) { policy::BrowserPolicyConnectorChromeOS const* const connector =
diff --git a/chrome/browser/chromeos/login/users/chrome_user_manager_impl.h b/chrome/browser/chromeos/login/users/chrome_user_manager_impl.h index 20cbdba..dbbf3f5 100644 --- a/chrome/browser/chromeos/login/users/chrome_user_manager_impl.h +++ b/chrome/browser/chromeos/login/users/chrome_user_manager_impl.h
@@ -27,7 +27,6 @@ #include "chrome/browser/chromeos/policy/device_local_account_policy_service.h" #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/chromeos/settings/device_settings_service.h" -#include "components/signin/core/account_id/account_id.h" #include "components/user_manager/user.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" @@ -70,12 +69,12 @@ // UserManagerInterface implementation: BootstrapManager* GetBootstrapManager() override; MultiProfileUserController* GetMultiProfileUserController() override; - UserImageManager* GetUserImageManager(const AccountId& account_id) override; + UserImageManager* GetUserImageManager(const std::string& user_id) override; SupervisedUserManager* GetSupervisedUserManager() override; UserFlow* GetCurrentUserFlow() const override; - UserFlow* GetUserFlow(const AccountId& account_id) const override; - void SetUserFlow(const AccountId& account_id, UserFlow* flow) override; - void ResetUserFlow(const AccountId& account_id) override; + UserFlow* GetUserFlow(const std::string& user_id) const override; + void SetUserFlow(const std::string& user_id, UserFlow* flow) override; + void ResetUserFlow(const std::string& user_id) override; // UserManager implementation: void Shutdown() override; @@ -85,13 +84,13 @@ user_manager::UserList GetUnlockUsers() const override; void SessionStarted() override; void SaveUserOAuthStatus( - const AccountId& account_id, + const std::string& user_id, user_manager::User::OAuthTokenStatus oauth_token_status) override; - void SaveUserDisplayName(const AccountId& account_id, + void SaveUserDisplayName(const std::string& user_id, const base::string16& display_name) override; bool CanCurrentUserLock() const override; bool IsUserNonCryptohomeDataEphemeral( - const AccountId& account_id) const override; + const std::string& user_id) const override; bool AreSupervisedUsersAllowed() const override; // content::NotificationObserver implementation. @@ -116,7 +115,7 @@ // UserManagerBase implementation: bool AreEphemeralUsersEnabled() const override; - void OnUserRemoved(const AccountId& account_id) override; + void OnUserRemoved(const std::string& user_id) override; // ChromeUserManager implementation: bool ShouldReportUser(const std::string& user_id) const override; @@ -128,31 +127,31 @@ const std::string& GetApplicationLocale() const override; PrefService* GetLocalState() const override; void HandleUserOAuthTokenStatusChange( - const AccountId& account_id, + const std::string& user_id, user_manager::User::OAuthTokenStatus status) const override; bool IsEnterpriseManaged() const override; - void LoadPublicAccounts(std::set<AccountId>* users_set) override; + void LoadPublicAccounts(std::set<std::string>* users_set) override; void NotifyOnLogin() override; void NotifyUserAddedToSession(const user_manager::User* added_user, bool user_switch_pending) override; void PerformPreUserListLoadingActions() override; void PerformPostUserListLoadingActions() override; void PerformPostUserLoggedInActions(bool browser_restart) override; - void RemoveNonCryptohomeData(const AccountId& account_id) override; - void RemoveUserInternal(const AccountId& account_id, + void RemoveNonCryptohomeData(const std::string& user_id) override; + void RemoveUserInternal(const std::string& user_email, user_manager::RemoveUserDelegate* delegate) override; - bool IsDemoApp(const AccountId& account_id) const override; - bool IsKioskApp(const AccountId& account_id) const override; + bool IsDemoApp(const std::string& user_id) const override; + bool IsKioskApp(const std::string& user_id) const override; bool IsPublicAccountMarkedForRemoval( - const AccountId& account_id) const override; + const std::string& user_id) const override; void DemoAccountLoggedIn() override; void GuestUserLoggedIn() override; - void KioskAppLoggedIn(const AccountId& kiosk_app_account_id) override; + void KioskAppLoggedIn(const std::string& app_id) override; void PublicAccountUserLoggedIn(user_manager::User* user) override; - void RegularUserLoggedIn(const AccountId& account_id) override; - void RegularUserLoggedInAsEphemeral(const AccountId& account_id) override; - void SupervisedUserLoggedIn(const AccountId& account_id) override; - bool HasPendingBootstrap(const AccountId& account_id) const override; + void RegularUserLoggedIn(const std::string& user_id) override; + void RegularUserLoggedInAsEphemeral(const std::string& user_id) override; + void SupervisedUserLoggedIn(const std::string& user_id) override; + bool HasPendingBootstrap(const std::string& user_id) const override; private: friend class SupervisedUserManagerImpl; @@ -160,8 +159,8 @@ friend class WallpaperManager; friend class WallpaperManagerTest; - using UserImageManagerMap = - base::hash_map<AccountId, linked_ptr<UserImageManager> >; + typedef base::hash_map<std::string, linked_ptr<UserImageManager> > + UserImageManagerMap; ChromeUserManagerImpl(); @@ -238,7 +237,7 @@ // Session length limiter. scoped_ptr<SessionLengthLimiter> session_length_limiter_; - using FlowMap = std::map<AccountId, UserFlow*>; + typedef std::map<std::string, UserFlow*> FlowMap; // Lazy-initialized default flow. mutable scoped_ptr<UserFlow> default_flow_;
diff --git a/chrome/browser/chromeos/login/users/fake_chrome_user_manager.cc b/chrome/browser/chromeos/login/users/fake_chrome_user_manager.cc index 88fec2c9..7191f0c 100644 --- a/chrome/browser/chromeos/login/users/fake_chrome_user_manager.cc +++ b/chrome/browser/chromeos/login/users/fake_chrome_user_manager.cc
@@ -20,23 +20,24 @@ FakeChromeUserManager::FakeChromeUserManager() : supervised_user_manager_(new FakeSupervisedUserManager), bootstrap_manager_(NULL), - multi_profile_user_controller_(NULL) {} + multi_profile_user_controller_(NULL) { +} FakeChromeUserManager::~FakeChromeUserManager() { } const user_manager::User* FakeChromeUserManager::AddUser( - const AccountId& account_id) { - return AddUserWithAffiliation(account_id, false); + const std::string& email) { + return AddUserWithAffiliation(email, false); } const user_manager::User* FakeChromeUserManager::AddUserWithAffiliation( - const AccountId& account_id, + const std::string& email, bool is_affiliated) { - user_manager::User* user = user_manager::User::CreateRegularUser(account_id); + user_manager::User* user = user_manager::User::CreateRegularUser(email); user->set_affiliation(is_affiliated); - user->set_username_hash(ProfileHelper::GetUserIdHashByUserIdForTesting( - account_id.GetUserEmail())); + user->set_username_hash( + ProfileHelper::GetUserIdHashByUserIdForTesting(email)); user->SetStubImage(user_manager::UserImage( *ResourceBundle::GetSharedInstance().GetImageSkiaNamed( IDR_PROFILE_PICTURE_LOADING)), @@ -46,11 +47,10 @@ } const user_manager::User* FakeChromeUserManager::AddPublicAccountUser( - const AccountId& account_id) { - user_manager::User* user = - user_manager::User::CreatePublicAccountUser(account_id); - user->set_username_hash(ProfileHelper::GetUserIdHashByUserIdForTesting( - account_id.GetUserEmail())); + const std::string& email) { + user_manager::User* user = user_manager::User::CreatePublicAccountUser(email); + user->set_username_hash( + ProfileHelper::GetUserIdHashByUserIdForTesting(email)); user->SetStubImage(user_manager::UserImage( *ResourceBundle::GetSharedInstance().GetImageSkiaNamed( IDR_PROFILE_PICTURE_LOADING)), @@ -60,17 +60,16 @@ } void FakeChromeUserManager::AddKioskAppUser( - const AccountId& kiosk_app_account_id) { + const std::string& kiosk_app_username) { user_manager::User* user = - user_manager::User::CreateKioskAppUser(kiosk_app_account_id); - user->set_username_hash(ProfileHelper::GetUserIdHashByUserIdForTesting( - kiosk_app_account_id.GetUserEmail())); + user_manager::User::CreateKioskAppUser(kiosk_app_username); + user->set_username_hash( + ProfileHelper::GetUserIdHashByUserIdForTesting(kiosk_app_username)); users_.push_back(user); } -void FakeChromeUserManager::LoginUser(const AccountId& account_id) { - UserLoggedIn(account_id, ProfileHelper::GetUserIdHashByUserIdForTesting( - account_id.GetUserEmail()), +void FakeChromeUserManager::LoginUser(const std::string& email) { + UserLoggedIn(email, ProfileHelper::GetUserIdHashByUserIdForTesting(email), false /* browser_restart */); } @@ -88,59 +87,58 @@ } UserImageManager* FakeChromeUserManager::GetUserImageManager( - const AccountId& /* account_id */) { + const std::string& /* user_id */) { return nullptr; } -void FakeChromeUserManager::SetUserFlow(const AccountId& account_id, +void FakeChromeUserManager::SetUserFlow(const std::string& email, UserFlow* flow) { - ResetUserFlow(account_id); - specific_flows_[account_id] = flow; + ResetUserFlow(email); + specific_flows_[email] = flow; } UserFlow* FakeChromeUserManager::GetCurrentUserFlow() const { if (!IsUserLoggedIn()) return GetDefaultUserFlow(); - return GetUserFlow(GetLoggedInUser()->GetAccountId()); + return GetUserFlow(GetLoggedInUser()->email()); } -UserFlow* FakeChromeUserManager::GetUserFlow( - const AccountId& account_id) const { - FlowMap::const_iterator it = specific_flows_.find(account_id); +UserFlow* FakeChromeUserManager::GetUserFlow(const std::string& email) const { + FlowMap::const_iterator it = specific_flows_.find(email); if (it != specific_flows_.end()) return it->second; return GetDefaultUserFlow(); } -void FakeChromeUserManager::ResetUserFlow(const AccountId& account_id) { - FlowMap::iterator it = specific_flows_.find(account_id); +void FakeChromeUserManager::ResetUserFlow(const std::string& email) { + FlowMap::iterator it = specific_flows_.find(email); if (it != specific_flows_.end()) { delete it->second; specific_flows_.erase(it); } } -void FakeChromeUserManager::SwitchActiveUser(const AccountId& account_id) { - active_account_id_ = account_id; +void FakeChromeUserManager::SwitchActiveUser(const std::string& email) { + active_user_id_ = email; ProfileHelper::Get()->ActiveUserHashChanged( - ProfileHelper::GetUserIdHashByUserIdForTesting( - account_id.GetUserEmail())); - if (!users_.empty() && active_account_id_.is_valid()) { + ProfileHelper::GetUserIdHashByUserIdForTesting(email)); + if (!users_.empty() && !active_user_id_.empty()) { for (user_manager::User* user : users_) - user->set_is_active(user->GetAccountId() == active_account_id_); + user->set_is_active(user->email() == active_user_id_); } } -const AccountId& FakeChromeUserManager::GetOwnerAccountId() const { - return owner_account_id_; +const std::string& FakeChromeUserManager::GetOwnerEmail() const { + return owner_email_; } void FakeChromeUserManager::SessionStarted() { } void FakeChromeUserManager::RemoveUser( - const AccountId& account_id, - user_manager::RemoveUserDelegate* delegate) {} + const std::string& email, + user_manager::RemoveUserDelegate* delegate) { +} user_manager::UserList FakeChromeUserManager::GetUsersAllowedForSupervisedUsersCreation() const { @@ -183,14 +181,15 @@ } bool FakeChromeUserManager::FindKnownUserPrefs( - const AccountId& account_id, + const user_manager::UserID& user_id, const base::DictionaryValue** out_value) { return false; } void FakeChromeUserManager::UpdateKnownUserPrefs( - const AccountId& account_id, + const user_manager::UserID& user_id, const base::DictionaryValue& values, - bool clear) {} + bool clear) { +} } // namespace chromeos
diff --git a/chrome/browser/chromeos/login/users/fake_chrome_user_manager.h b/chrome/browser/chromeos/login/users/fake_chrome_user_manager.h index 6c4d975..d5c90fcc 100644 --- a/chrome/browser/chromeos/login/users/fake_chrome_user_manager.h +++ b/chrome/browser/chromeos/login/users/fake_chrome_user_manager.h
@@ -29,46 +29,46 @@ ~FakeChromeUserManager() override; // Create and add a kiosk app user. - void AddKioskAppUser(const AccountId& kiosk_app_account_id); + void AddKioskAppUser(const std::string& kiosk_app_username); // Create and add a public account user. - const user_manager::User* AddPublicAccountUser(const AccountId& account_id); + const user_manager::User* AddPublicAccountUser(const std::string& email); // Calculates the user name hash and calls UserLoggedIn to login a user. - void LoginUser(const AccountId& account_id); + void LoginUser(const std::string& email); // UserManager overrides. user_manager::UserList GetUsersAllowedForMultiProfile() const override; // user_manager::FakeUserManager override. - const user_manager::User* AddUser(const AccountId& account_id) override; - const user_manager::User* AddUserWithAffiliation(const AccountId& account_id, + const user_manager::User* AddUser(const std::string& email) override; + const user_manager::User* AddUserWithAffiliation(const std::string& email, bool is_affiliated) override; // UserManagerInterface implementation. BootstrapManager* GetBootstrapManager() override; MultiProfileUserController* GetMultiProfileUserController() override; - UserImageManager* GetUserImageManager(const AccountId& account_id) override; + UserImageManager* GetUserImageManager(const std::string& user_id) override; SupervisedUserManager* GetSupervisedUserManager() override; - void SetUserFlow(const AccountId& account_id, UserFlow* flow) override; + void SetUserFlow(const std::string& email, UserFlow* flow) override; UserFlow* GetCurrentUserFlow() const override; - UserFlow* GetUserFlow(const AccountId& account_id) const override; - void ResetUserFlow(const AccountId& account_id) override; + UserFlow* GetUserFlow(const std::string& email) const override; + void ResetUserFlow(const std::string& email) override; user_manager::UserList GetUsersAllowedForSupervisedUsersCreation() const override; - void SwitchActiveUser(const AccountId& account_id) override; - const AccountId& GetOwnerAccountId() const override; + void SwitchActiveUser(const std::string& email) override; + const std::string& GetOwnerEmail() const override; void SessionStarted() override; - void RemoveUser(const AccountId& account_id, + void RemoveUser(const std::string& email, user_manager::RemoveUserDelegate* delegate) override; - bool FindKnownUserPrefs(const AccountId& account_id, + bool FindKnownUserPrefs(const user_manager::UserID& user_id, const base::DictionaryValue** out_value) override; - void UpdateKnownUserPrefs(const AccountId& account_id, + void UpdateKnownUserPrefs(const user_manager::UserID& user_id, const base::DictionaryValue& values, bool clear) override; - void set_owner_id(const AccountId& owner_account_id) { - owner_account_id_ = owner_account_id; + void set_owner_email(const std::string& owner_email) { + owner_email_ = owner_email; } void set_bootstrap_manager(BootstrapManager* bootstrap_manager) { @@ -85,16 +85,16 @@ UserFlow* GetDefaultUserFlow() const; scoped_ptr<FakeSupervisedUserManager> supervised_user_manager_; - AccountId owner_account_id_ = EmptyAccountId(); + std::string owner_email_; BootstrapManager* bootstrap_manager_; MultiProfileUserController* multi_profile_user_controller_; + typedef std::map<std::string, UserFlow*> FlowMap; + // Lazy-initialized default flow. mutable scoped_ptr<UserFlow> default_flow_; - using FlowMap = std::map<AccountId, UserFlow*>; - // Specific flows by user e-mail. // Keys should be canonicalized before access. FlowMap specific_flows_;
diff --git a/chrome/browser/chromeos/login/users/mock_user_manager.cc b/chrome/browser/chromeos/login/users/mock_user_manager.cc index 20be180..0e79f65 100644 --- a/chrome/browser/chromeos/login/users/mock_user_manager.cc +++ b/chrome/browser/chromeos/login/users/mock_user_manager.cc
@@ -56,9 +56,8 @@ return user_list_; } -const AccountId& MockUserManager::GetOwnerAccountId() const { - temporary_owner_account_id_ = GetLoggedInUser()->GetAccountId(); - return temporary_owner_account_id_; +const std::string& MockUserManager::GetOwnerEmail() const { + return GetLoggedInUser()->email(); } const user_manager::User* MockUserManager::GetActiveUser() const { @@ -82,7 +81,7 @@ } UserImageManager* MockUserManager::GetUserImageManager( - const AccountId& account_id) { + const std::string& user_id) { return NULL; } @@ -91,44 +90,43 @@ } // Creates a new User instance. -void MockUserManager::SetActiveUser(const AccountId& account_id) { +void MockUserManager::SetActiveUser(const std::string& email) { ClearUserList(); - AddUser(account_id); + AddUser(email); } UserFlow* MockUserManager::GetCurrentUserFlow() const { return user_flow_.get(); } -UserFlow* MockUserManager::GetUserFlow(const AccountId&) const { +UserFlow* MockUserManager::GetUserFlow(const std::string&) const { return user_flow_.get(); } user_manager::User* MockUserManager::CreatePublicAccountUser( - const AccountId& account_id) { + const std::string& email) { ClearUserList(); - user_manager::User* user = - user_manager::User::CreatePublicAccountUser(account_id); + user_manager::User* user = user_manager::User::CreatePublicAccountUser(email); user_list_.push_back(user); ProfileHelper::Get()->SetProfileToUserMappingForTesting(user); return user_list_.back(); } user_manager::User* MockUserManager::CreateKioskAppUser( - const AccountId& account_id) { + const std::string& email) { ClearUserList(); - user_list_.push_back(user_manager::User::CreateKioskAppUser(account_id)); + user_list_.push_back(user_manager::User::CreateKioskAppUser(email)); ProfileHelper::Get()->SetProfileToUserMappingForTesting(user_list_.back()); return user_list_.back(); } -void MockUserManager::AddUser(const AccountId& account_id) { - AddUserWithAffiliation(account_id, false); +void MockUserManager::AddUser(const std::string& email) { + AddUserWithAffiliation(email, false); } -void MockUserManager::AddUserWithAffiliation(const AccountId& account_id, +void MockUserManager::AddUserWithAffiliation(const std::string& email, bool is_affiliated) { - user_manager::User* user = user_manager::User::CreateRegularUser(account_id); + user_manager::User* user = user_manager::User::CreateRegularUser(email); user->set_affiliation(is_affiliated); user_list_.push_back(user); ProfileHelper::Get()->SetProfileToUserMappingForTesting(user); @@ -136,16 +134,17 @@ void MockUserManager::ClearUserList() { // Can't use STLDeleteElements because of the protected destructor of User. - for (user_manager::UserList::iterator user = user_list_.begin(); - user != user_list_.end(); ++user) + user_manager::UserList::iterator user; + for (user = user_list_.begin(); user != user_list_.end(); ++user) delete *user; user_list_.clear(); } bool MockUserManager::ShouldReportUser(const std::string& user_id) const { for (const auto& user : user_list_) { - if (user->email() == user_id) + if (user->GetUserID() == user_id) { return user->is_affiliated(); + } } NOTREACHED(); return false;
diff --git a/chrome/browser/chromeos/login/users/mock_user_manager.h b/chrome/browser/chromeos/login/users/mock_user_manager.h index 77a25ad..bc05a8f 100644 --- a/chrome/browser/chromeos/login/users/mock_user_manager.h +++ b/chrome/browser/chromeos/login/users/mock_user_manager.h
@@ -13,7 +13,6 @@ #include "chrome/browser/chromeos/login/users/affiliation.h" #include "chrome/browser/chromeos/login/users/avatar/mock_user_image_manager.h" #include "chrome/browser/chromeos/login/users/chrome_user_manager.h" -#include "components/signin/core/account_id/account_id.h" #include "components/user_manager/user.h" #include "components/user_manager/user_image/user_image.h" #include "testing/gmock/include/gmock/gmock.h" @@ -34,26 +33,27 @@ user_manager::UserList(void)); MOCK_CONST_METHOD0(GetLoggedInUsers, const user_manager::UserList&(void)); MOCK_CONST_METHOD0(GetLRULoggedInUsers, const user_manager::UserList&(void)); - MOCK_METHOD3(UserLoggedIn, void(const AccountId&, const std::string&, bool)); - MOCK_METHOD1(SwitchActiveUser, void(const AccountId& account_id)); + MOCK_METHOD3(UserLoggedIn, void( + const std::string&, const std::string&, bool)); + MOCK_METHOD1(SwitchActiveUser, void(const std::string& email)); MOCK_METHOD0(SessionStarted, void(void)); MOCK_METHOD2(RemoveUser, - void(const AccountId&, user_manager::RemoveUserDelegate*)); - MOCK_METHOD1(RemoveUserFromList, void(const AccountId&)); - MOCK_CONST_METHOD1(IsKnownUser, bool(const AccountId&)); - MOCK_CONST_METHOD1(FindUser, const user_manager::User*(const AccountId&)); - MOCK_METHOD1(FindUserAndModify, user_manager::User*(const AccountId&)); + void(const std::string&, user_manager::RemoveUserDelegate*)); + MOCK_METHOD1(RemoveUserFromList, void(const std::string&)); + MOCK_CONST_METHOD1(IsKnownUser, bool(const std::string&)); + MOCK_CONST_METHOD1(FindUser, const user_manager::User*(const std::string&)); + MOCK_METHOD1(FindUserAndModify, user_manager::User*(const std::string&)); MOCK_METHOD2(SaveUserOAuthStatus, - void(const AccountId&, user_manager::User::OAuthTokenStatus)); - MOCK_METHOD2(SaveForceOnlineSignin, void(const AccountId&, bool)); - MOCK_METHOD2(SaveUserDisplayName, - void(const AccountId&, const base::string16&)); + void(const std::string&, user_manager::User::OAuthTokenStatus)); + MOCK_METHOD2(SaveForceOnlineSignin, void(const std::string&, bool)); + MOCK_METHOD2(SaveUserDisplayName, void(const std::string&, + const base::string16&)); MOCK_METHOD2(UpdateUserAccountData, - void(const AccountId&, const UserAccountData&)); - MOCK_CONST_METHOD1(GetUserDisplayName, base::string16(const AccountId&)); - MOCK_METHOD2(SaveUserDisplayEmail, - void(const AccountId&, const std::string&)); - MOCK_CONST_METHOD1(GetUserDisplayEmail, std::string(const AccountId&)); + void(const std::string&, const UserAccountData&)); + MOCK_CONST_METHOD1(GetUserDisplayName, base::string16(const std::string&)); + MOCK_METHOD2(SaveUserDisplayEmail, void(const std::string&, + const std::string&)); + MOCK_CONST_METHOD1(GetUserDisplayEmail, std::string(const std::string&)); MOCK_CONST_METHOD0(IsCurrentUserOwner, bool(void)); MOCK_CONST_METHOD0(IsCurrentUserNew, bool(void)); MOCK_CONST_METHOD0(IsCurrentUserNonCryptohomeDataEphemeral, bool(void)); @@ -66,7 +66,8 @@ MOCK_CONST_METHOD0(IsLoggedInAsKioskApp, bool(void)); MOCK_CONST_METHOD0(IsLoggedInAsStub, bool(void)); MOCK_CONST_METHOD0(IsSessionStarted, bool(void)); - MOCK_CONST_METHOD1(IsUserNonCryptohomeDataEphemeral, bool(const AccountId&)); + MOCK_CONST_METHOD1(IsUserNonCryptohomeDataEphemeral, + bool(const std::string&)); MOCK_METHOD1(AddObserver, void(UserManager::Observer*)); MOCK_METHOD1(RemoveObserver, void(UserManager::Observer*)); MOCK_METHOD1(AddSessionStateObserver, @@ -81,28 +82,31 @@ MOCK_CONST_METHOD0(GetApplicationLocale, const std::string&(void)); MOCK_CONST_METHOD0(GetLocalState, PrefService*(void)); MOCK_CONST_METHOD2(HandleUserOAuthTokenStatusChange, - void(const AccountId&, + void(const std::string&, user_manager::User::OAuthTokenStatus status)); MOCK_CONST_METHOD0(IsEnterpriseManaged, bool(void)); - MOCK_METHOD1(LoadPublicAccounts, void(std::set<AccountId>*)); + MOCK_METHOD1(LoadPublicAccounts, void(std::set<std::string>*)); MOCK_METHOD0(PerformPreUserListLoadingActions, void(void)); MOCK_METHOD0(PerformPostUserListLoadingActions, void(void)); MOCK_METHOD1(PerformPostUserLoggedInActions, void(bool)); - MOCK_CONST_METHOD1(IsDemoApp, bool(const AccountId&)); - MOCK_CONST_METHOD1(IsKioskApp, bool(const AccountId&)); - MOCK_CONST_METHOD1(IsPublicAccountMarkedForRemoval, bool(const AccountId&)); + MOCK_CONST_METHOD1(IsDemoApp, bool(const std::string&)); + MOCK_CONST_METHOD1(IsKioskApp, bool(const std::string&)); + MOCK_CONST_METHOD1(IsPublicAccountMarkedForRemoval, bool(const std::string&)); MOCK_METHOD0(DemoAccountLoggedIn, void(void)); - MOCK_METHOD1(KioskAppLoggedIn, void(const AccountId&)); + MOCK_METHOD1(KioskAppLoggedIn, void(const std::string&)); MOCK_METHOD1(PublicAccountUserLoggedIn, void(user_manager::User*)); - MOCK_METHOD1(SupervisedUserLoggedIn, void(const AccountId&)); - MOCK_METHOD1(OnUserRemoved, void(const AccountId&)); + MOCK_METHOD1(SupervisedUserLoggedIn, void(const std::string&)); + MOCK_METHOD1(OnUserRemoved, void(const std::string&)); + MOCK_METHOD2(SetUserAffiliation, + void(const std::string& user_id, + const chromeos::AffiliationIDSet& user_affiliation_ids)); // You can't mock these functions easily because nobody can create // User objects but the ChromeUserManager and us. const user_manager::UserList& GetUsers() const override; const user_manager::User* GetLoggedInUser() const override; user_manager::UserList GetUnlockUsers() const override; - const AccountId& GetOwnerAccountId() const override; + const std::string& GetOwnerEmail() const override; user_manager::User* GetLoggedInUser() override; const user_manager::User* GetActiveUser() const override; user_manager::User* GetActiveUser() override; @@ -111,38 +115,35 @@ // ChromeUserManager overrides: BootstrapManager* GetBootstrapManager() override; MultiProfileUserController* GetMultiProfileUserController() override; - UserImageManager* GetUserImageManager(const AccountId& account_id) override; + UserImageManager* GetUserImageManager(const std::string& user_id) override; SupervisedUserManager* GetSupervisedUserManager() override; - MOCK_METHOD2(SetUserFlow, void(const AccountId&, UserFlow*)); - MOCK_METHOD1(ResetUserFlow, void(const AccountId&)); + MOCK_METHOD2(SetUserFlow, void(const std::string&, UserFlow*)); + MOCK_METHOD1(ResetUserFlow, void(const std::string&)); UserFlow* GetCurrentUserFlow() const override; - UserFlow* GetUserFlow(const AccountId&) const override; - MOCK_METHOD2(SetUserAffiliation, - void(const std::string& user_id, - const chromeos::AffiliationIDSet& user_affiliation_ids)); + UserFlow* GetUserFlow(const std::string&) const override; bool ShouldReportUser(const std::string& user_id) const override; // Sets a new User instance. Users previously created by this MockUserManager // become invalid. - void SetActiveUser(const AccountId& account_id); + void SetActiveUser(const std::string& email); // Creates a new public session user. Users previously created by this // MockUserManager become invalid. - user_manager::User* CreatePublicAccountUser(const AccountId& account_id); + user_manager::User* CreatePublicAccountUser(const std::string& email); // Creates a new kiosk app user. Users previously created by this // MockUserManager become invalid. - user_manager::User* CreateKioskAppUser(const AccountId& account_id); + user_manager::User* CreateKioskAppUser(const std::string& user_id); // Adds a new User instance to the back of the user list. Users previously // created by this MockUserManager remain valid. The added User is not // affiliated with the domain, that owns the device. - void AddUser(const AccountId& account_id); + void AddUser(const std::string& email); // The same as AddUser, but allows specifying affiliation with the domain, // that owns the device. - void AddUserWithAffiliation(const AccountId& account_id, bool is_affiliated); + void AddUserWithAffiliation(const std::string& email, bool is_affiliated); // Clears the user list and the active user. Users previously created by this // MockUserManager become invalid. @@ -152,10 +153,6 @@ scoped_ptr<MockUserImageManager> user_image_manager_; scoped_ptr<FakeSupervisedUserManager> supervised_user_manager_; user_manager::UserList user_list_; - // TODO (alemate): remove temporary_owner_account_id_ as soon as - // User::GetAccountId will - // return constant reference. crbug.com/546863 - mutable AccountId temporary_owner_account_id_ = EmptyAccountId(); }; } // namespace chromeos
diff --git a/chrome/browser/chromeos/login/users/multi_profile_user_controller_unittest.cc b/chrome/browser/chromeos/login/users/multi_profile_user_controller_unittest.cc index 68cceed..04c945e 100644 --- a/chrome/browser/chromeos/login/users/multi_profile_user_controller_unittest.cc +++ b/chrome/browser/chromeos/login/users/multi_profile_user_controller_unittest.cc
@@ -116,12 +116,7 @@ MultiProfileUserControllerTest() : fake_user_manager_(new FakeChromeUserManager), user_manager_enabler_(fake_user_manager_), - user_not_allowed_count_(0) { - for (size_t i = 0; i < arraysize(kUsers); ++i) { - test_users_.push_back(AccountId::FromUserEmail(kUsers[i])); - } - } - + user_not_allowed_count_(0) {} ~MultiProfileUserControllerTest() override {} void SetUp() override { @@ -131,15 +126,14 @@ controller_.reset(new MultiProfileUserController( this, TestingBrowserProcess::GetGlobal()->local_state())); - for (size_t i = 0; i < test_users_.size(); ++i) { - const AccountId account_id(test_users_[i]); - const user_manager::User* user = - fake_user_manager_->AddUser(test_users_[i]); + for (size_t i = 0; i < arraysize(kUsers); ++i) { + const std::string user_email(kUsers[i]); + const user_manager::User* user = fake_user_manager_->AddUser(user_email); // Note that user profiles are created after user login in reality. TestingProfile* user_profile = - profile_manager_->CreateTestingProfile(account_id.GetUserEmail()); - user_profile->set_profile_name(account_id.GetUserEmail()); + profile_manager_->CreateTestingProfile(user_email); + user_profile->set_profile_name(user_email); user_profiles_.push_back(user_profile); ProfileHelper::Get()->SetUserToProfileMappingForTesting(user, @@ -163,13 +157,13 @@ } void LoginUser(size_t user_index) { - ASSERT_LT(user_index, test_users_.size()); - fake_user_manager_->LoginUser(test_users_[user_index]); + ASSERT_LT(user_index, arraysize(kUsers)); + fake_user_manager_->LoginUser(kUsers[user_index]); controller_->StartObserving(user_profiles_[user_index]); } void SetOwner(size_t user_index) { - fake_user_manager_->set_owner_id(test_users_[user_index]); + fake_user_manager_->set_owner_email(kUsers[user_index]); } PrefService* GetUserPrefs(size_t user_index) { @@ -182,13 +176,12 @@ } std::string GetCachedBehavior(size_t user_index) { - return controller_->GetCachedValue(test_users_[user_index].GetUserEmail()); + return controller_->GetCachedValue(kUsers[user_index]); } void SetCachedBehavior(size_t user_index, const std::string& behavior) { - controller_->SetCachedValue(test_users_[user_index].GetUserEmail(), - behavior); + controller_->SetCachedValue(kUsers[user_index], behavior); } void ResetCounts() { @@ -219,8 +212,6 @@ int user_not_allowed_count_; - std::vector<AccountId> test_users_; - private: DISALLOW_COPY_AND_ASSIGN(MultiProfileUserControllerTest); }; @@ -235,8 +226,7 @@ for (size_t i = 0; i < arraysize(kTestCases); ++i) { SetCachedBehavior(0, kTestCases[i]); MultiProfileUserController::UserAllowedInSessionReason reason; - EXPECT_TRUE(controller()->IsUserAllowedInSession( - test_users_[0].GetUserEmail(), &reason)) + EXPECT_TRUE(controller()->IsUserAllowedInSession(kUsers[0], &reason)) << "Case " << i; EXPECT_EQ(MultiProfileUserController::ALLOWED, reason) << "Case " << i; EXPECT_EQ(MultiProfileUserController::ALLOWED, @@ -302,8 +292,7 @@ MultiProfileUserController::GetPrimaryUserPolicy()) << "Case " << i; MultiProfileUserController::UserAllowedInSessionReason reason; - controller()->IsUserAllowedInSession(test_users_[1].GetUserEmail(), - &reason); + controller()->IsUserAllowedInSession(kUsers[1], &reason); EXPECT_EQ(kBehaviorTestCases[i].expected_secondary_allowed, reason) << "Case " << i; } @@ -337,14 +326,11 @@ UsedPolicyCertificatesAllowedForPrimary) { // Verifies that any user can sign-in as the primary user, regardless of the // tainted state. - policy::PolicyCertServiceFactory::SetUsedPolicyCertificates( - test_users_[0].GetUserEmail()); + policy::PolicyCertServiceFactory::SetUsedPolicyCertificates(kUsers[0]); MultiProfileUserController::UserAllowedInSessionReason reason; - EXPECT_TRUE(controller()->IsUserAllowedInSession( - test_users_[0].GetUserEmail(), &reason)); + EXPECT_TRUE(controller()->IsUserAllowedInSession(kUsers[0], &reason)); EXPECT_EQ(MultiProfileUserController::ALLOWED, reason); - EXPECT_TRUE(controller()->IsUserAllowedInSession( - test_users_[1].GetUserEmail(), &reason)); + EXPECT_TRUE(controller()->IsUserAllowedInSession(kUsers[1], &reason)); EXPECT_EQ(MultiProfileUserController::ALLOWED, reason); EXPECT_EQ(MultiProfileUserController::ALLOWED, MultiProfileUserController::GetPrimaryUserPolicy()); @@ -361,14 +347,11 @@ SetPrefBehavior(1, MultiProfileUserController::kBehaviorUnrestricted); MultiProfileUserController::UserAllowedInSessionReason reason; - EXPECT_TRUE(controller()->IsUserAllowedInSession( - test_users_[0].GetUserEmail(), &reason)); + EXPECT_TRUE(controller()->IsUserAllowedInSession(kUsers[0], &reason)); EXPECT_EQ(MultiProfileUserController::ALLOWED, reason); - policy::PolicyCertServiceFactory::SetUsedPolicyCertificates( - test_users_[0].GetUserEmail()); - EXPECT_FALSE(controller()->IsUserAllowedInSession( - test_users_[0].GetUserEmail(), &reason)); + policy::PolicyCertServiceFactory::SetUsedPolicyCertificates(kUsers[0]); + EXPECT_FALSE(controller()->IsUserAllowedInSession(kUsers[0], &reason)); EXPECT_EQ(MultiProfileUserController::NOT_ALLOWED_POLICY_CERT_TAINTED, reason); } @@ -377,8 +360,7 @@ UsedPolicyCertificatesDisallowsSecondaries) { // Verifies that if a tainted user is signed-in then no other users can // be added. - policy::PolicyCertServiceFactory::SetUsedPolicyCertificates( - test_users_[0].GetUserEmail()); + policy::PolicyCertServiceFactory::SetUsedPolicyCertificates(kUsers[0]); LoginUser(0); cert_verifier_.reset(new policy::PolicyCertVerifier(base::Closure())); @@ -388,16 +370,13 @@ profile(0), TestPolicyCertServiceFactory)); MultiProfileUserController::UserAllowedInSessionReason reason; - EXPECT_FALSE(controller()->IsUserAllowedInSession( - test_users_[1].GetUserEmail(), &reason)); + EXPECT_FALSE(controller()->IsUserAllowedInSession(kUsers[1], &reason)); EXPECT_EQ(MultiProfileUserController::NOT_ALLOWED_PRIMARY_POLICY_CERT_TAINTED, reason); EXPECT_EQ(MultiProfileUserController::NOT_ALLOWED_PRIMARY_POLICY_CERT_TAINTED, MultiProfileUserController::GetPrimaryUserPolicy()); - policy::PolicyCertServiceFactory::SetUsedPolicyCertificates( - test_users_[1].GetUserEmail()); - EXPECT_FALSE(controller()->IsUserAllowedInSession( - test_users_[1].GetUserEmail(), &reason)); + policy::PolicyCertServiceFactory::SetUsedPolicyCertificates(kUsers[1]); + EXPECT_FALSE(controller()->IsUserAllowedInSession(kUsers[1], &reason)); EXPECT_EQ(MultiProfileUserController::NOT_ALLOWED_POLICY_CERT_TAINTED, reason); EXPECT_EQ(MultiProfileUserController::NOT_ALLOWED_PRIMARY_POLICY_CERT_TAINTED, @@ -428,8 +407,7 @@ EXPECT_FALSE(service->has_policy_certificates()); MultiProfileUserController::UserAllowedInSessionReason reason; - EXPECT_TRUE(controller()->IsUserAllowedInSession( - test_users_[1].GetUserEmail(), &reason)); + EXPECT_TRUE(controller()->IsUserAllowedInSession(kUsers[1], &reason)); EXPECT_EQ(MultiProfileUserController::ALLOWED, reason); EXPECT_EQ(MultiProfileUserController::ALLOWED, MultiProfileUserController::GetPrimaryUserPolicy()); @@ -439,8 +417,7 @@ "subject", "issuer", base::Time(), base::Time())); service->OnTrustAnchorsChanged(certificates); EXPECT_TRUE(service->has_policy_certificates()); - EXPECT_FALSE(controller()->IsUserAllowedInSession( - test_users_[1].GetUserEmail(), &reason)); + EXPECT_FALSE(controller()->IsUserAllowedInSession(kUsers[1], &reason)); EXPECT_EQ(MultiProfileUserController::NOT_ALLOWED_PRIMARY_POLICY_CERT_TAINTED, reason); EXPECT_EQ(MultiProfileUserController::NOT_ALLOWED_PRIMARY_POLICY_CERT_TAINTED,
diff --git a/chrome/browser/chromeos/login/users/supervised_user_manager_impl.cc b/chrome/browser/chromeos/login/users/supervised_user_manager_impl.cc index c54efe2c..0668465 100644 --- a/chrome/browser/chromeos/login/users/supervised_user_manager_impl.cc +++ b/chrome/browser/chromeos/login/users/supervised_user_manager_impl.cc
@@ -149,7 +149,7 @@ id = base::StringPrintf( "%d@%s", counter, chromeos::login::kSupervisedUserDomain); counter++; - user_exists = (nullptr != owner_->FindUser(AccountId::FromUserEmail(id))); + user_exists = (NULL != owner_->FindUser(id)); DCHECK(!user_exists); if (user_exists) { LOG(ERROR) << "Supervised user with id " << id << " already exists."; @@ -186,14 +186,13 @@ DCHECK(!user); if (user) return user; - const user_manager::User* manager = - owner_->FindUser(AccountId::FromUserEmail(manager_id)); + const user_manager::User* manager = owner_->FindUser(manager_id); CHECK(manager); PrefService* local_state = g_browser_process->local_state(); - user_manager::User* new_user = user_manager::User::CreateSupervisedUser( - AccountId::FromUserEmail(local_user_id)); + user_manager::User* new_user = + user_manager::User::CreateSupervisedUser(local_user_id); owner_->AddUserRecord(new_user); @@ -218,8 +217,7 @@ manager_email_update->SetWithoutPathExpansion(local_user_id, new base::StringValue(manager->display_email())); - owner_->SaveUserDisplayName(AccountId::FromUserEmail(local_user_id), - display_name); + owner_->SaveUserDisplayName(local_user_id, display_name); g_browser_process->local_state()->CommitPendingWrite(); return new_user; @@ -444,8 +442,7 @@ prefs->CommitPendingWrite(); return; } - owner_->RemoveNonOwnerUserInternal(AccountId::FromUserEmail(user_id), - nullptr); + owner_->RemoveNonOwnerUserInternal(user_id, NULL); prefs->ClearPref(kSupervisedUserCreationTransactionDisplayName); prefs->ClearPref(kSupervisedUserCreationTransactionUserId);
diff --git a/chrome/browser/chromeos/login/users/user_manager_interface.h b/chrome/browser/chromeos/login/users/user_manager_interface.h index c6bf205..4ca26eb 100644 --- a/chrome/browser/chromeos/login/users/user_manager_interface.h +++ b/chrome/browser/chromeos/login/users/user_manager_interface.h
@@ -9,8 +9,6 @@ #include "components/user_manager/user.h" #include "components/user_manager/user_type.h" -class AccountId; - namespace chromeos { class BootstrapManager; @@ -19,7 +17,7 @@ class UserFlow; class UserImageManager; -// ChromeOS specific add-ons interface for the UserManager. +// Chrome specific add-ons interface for the UserManager. class UserManagerInterface { public: UserManagerInterface() {} @@ -27,28 +25,27 @@ virtual BootstrapManager* GetBootstrapManager() = 0; virtual MultiProfileUserController* GetMultiProfileUserController() = 0; - virtual UserImageManager* GetUserImageManager( - const AccountId& account_id) = 0; + virtual UserImageManager* GetUserImageManager(const std::string& user_id) = 0; virtual SupervisedUserManager* GetSupervisedUserManager() = 0; - // Method that allows to set |flow| for user identified by |account_id|. + // Method that allows to set |flow| for user identified by |user_id|. // Flow should be set before login attempt. // Takes ownership of the |flow|, |flow| will be deleted in case of login // failure. - virtual void SetUserFlow(const AccountId& account_id, UserFlow* flow) = 0; + virtual void SetUserFlow(const std::string& user_id, UserFlow* flow) = 0; // Return user flow for current user. Returns instance of DefaultUserFlow if // no flow was defined for current user, or user is not logged in. // Returned value should not be cached. virtual UserFlow* GetCurrentUserFlow() const = 0; - // Return user flow for user identified by |account_id|. Returns instance of + // Return user flow for user identified by |user_id|. Returns instance of // DefaultUserFlow if no flow was defined for user. // Returned value should not be cached. - virtual UserFlow* GetUserFlow(const AccountId& account_id) const = 0; + virtual UserFlow* GetUserFlow(const std::string& user_id) const = 0; - // Resets user flow for user identified by |account_id|. - virtual void ResetUserFlow(const AccountId& account_id) = 0; + // Resets user flow for user identified by |user_id|. + virtual void ResetUserFlow(const std::string& user_id) = 0; // Returns list of users allowed for supervised user creation. // Returns an empty list in cases when supervised user creation or adding new
diff --git a/chrome/browser/chromeos/login/users/user_manager_unittest.cc b/chrome/browser/chromeos/login/users/user_manager_unittest.cc index db5a69a..b2e6368 100644 --- a/chrome/browser/chromeos/login/users/user_manager_unittest.cc +++ b/chrome/browser/chromeos/login/users/user_manager_unittest.cc
@@ -47,9 +47,6 @@ }; class UserManagerTest : public testing::Test { - public: - UserManagerTest() {} - protected: void SetUp() override { base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); @@ -102,12 +99,12 @@ GetChromeUserManager()->SetEphemeralUsersEnabled(ephemeral_users_enabled); } - AccountId GetUserManagerOwnerId() const { - return GetChromeUserManager()->GetOwnerAccountId(); + const std::string& GetUserManagerOwnerEmail() const { + return GetChromeUserManager()->GetOwnerEmail(); } - void SetUserManagerOwnerId(const AccountId& owner_account_id) { - GetChromeUserManager()->SetOwnerId(owner_account_id); + void SetUserManagerOwnerEmail(const std::string& owner_email) { + GetChromeUserManager()->SetOwnerEmail(owner_email); } void ResetUserManager() { @@ -136,13 +133,6 @@ GetChromeUserManager()->RetrieveTrustedDevicePolicies(); } - const AccountId owner_account_id_at_invalid_domain_ = - AccountId::FromUserEmail("owner@invalid.domain"); - const AccountId account_id0_at_invalid_domain_ = - AccountId::FromUserEmail("user0@invalid.domain"); - const AccountId account_id1_at_invalid_domain_ = - AccountId::FromUserEmail("user1@invalid.domain"); - protected: content::TestBrowserThreadBundle thread_bundle_; @@ -155,64 +145,56 @@ TEST_F(UserManagerTest, RetrieveTrustedDevicePolicies) { SetUserManagerEphemeralUsersEnabled(true); - SetUserManagerOwnerId(EmptyAccountId()); + SetUserManagerOwnerEmail(""); - SetDeviceSettings(false, owner_account_id_at_invalid_domain_.GetUserEmail(), - false); + SetDeviceSettings(false, "owner@invalid.domain", false); RetrieveTrustedDevicePolicies(); EXPECT_FALSE(GetUserManagerEphemeralUsersEnabled()); - EXPECT_EQ(GetUserManagerOwnerId(), owner_account_id_at_invalid_domain_); + EXPECT_EQ(GetUserManagerOwnerEmail(), "owner@invalid.domain"); } TEST_F(UserManagerTest, RemoveAllExceptOwnerFromList) { user_manager::UserManager::Get()->UserLoggedIn( - owner_account_id_at_invalid_domain_, - owner_account_id_at_invalid_domain_.GetUserEmail(), false); + "owner@invalid.domain", "owner@invalid.domain", false); ResetUserManager(); user_manager::UserManager::Get()->UserLoggedIn( - account_id0_at_invalid_domain_, - owner_account_id_at_invalid_domain_.GetUserEmail(), false); + "user0@invalid.domain", "owner@invalid.domain", false); ResetUserManager(); user_manager::UserManager::Get()->UserLoggedIn( - account_id1_at_invalid_domain_, - owner_account_id_at_invalid_domain_.GetUserEmail(), false); + "user1@invalid.domain", "owner@invalid.domain", false); ResetUserManager(); const user_manager::UserList* users = &user_manager::UserManager::Get()->GetUsers(); ASSERT_EQ(3U, users->size()); - EXPECT_EQ((*users)[0]->GetAccountId(), account_id1_at_invalid_domain_); - EXPECT_EQ((*users)[1]->GetAccountId(), account_id0_at_invalid_domain_); - EXPECT_EQ((*users)[2]->GetAccountId(), owner_account_id_at_invalid_domain_); + EXPECT_EQ((*users)[0]->email(), "user1@invalid.domain"); + EXPECT_EQ((*users)[1]->email(), "user0@invalid.domain"); + EXPECT_EQ((*users)[2]->email(), "owner@invalid.domain"); - SetDeviceSettings(true, owner_account_id_at_invalid_domain_.GetUserEmail(), - false); + SetDeviceSettings(true, "owner@invalid.domain", false); RetrieveTrustedDevicePolicies(); users = &user_manager::UserManager::Get()->GetUsers(); EXPECT_EQ(1U, users->size()); - EXPECT_EQ((*users)[0]->GetAccountId(), owner_account_id_at_invalid_domain_); + EXPECT_EQ((*users)[0]->email(), "owner@invalid.domain"); } TEST_F(UserManagerTest, RegularUserLoggedInAsEphemeral) { - SetDeviceSettings(true, owner_account_id_at_invalid_domain_.GetUserEmail(), - false); + SetDeviceSettings(true, "owner@invalid.domain", false); RetrieveTrustedDevicePolicies(); user_manager::UserManager::Get()->UserLoggedIn( - owner_account_id_at_invalid_domain_, - account_id0_at_invalid_domain_.GetUserEmail(), false); + "owner@invalid.domain", "user0@invalid.domain", false); ResetUserManager(); user_manager::UserManager::Get()->UserLoggedIn( - account_id0_at_invalid_domain_, - account_id0_at_invalid_domain_.GetUserEmail(), false); + "user0@invalid.domain", "user0@invalid.domain", false); ResetUserManager(); const user_manager::UserList* users = &user_manager::UserManager::Get()->GetUsers(); EXPECT_EQ(1U, users->size()); - EXPECT_EQ((*users)[0]->GetAccountId(), owner_account_id_at_invalid_domain_); + EXPECT_EQ((*users)[0]->email(), "owner@invalid.domain"); } } // namespace chromeos
diff --git a/chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager.cc b/chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager.cc index 4b8f6c8..cf3d3af 100644 --- a/chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager.cc +++ b/chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager.cc
@@ -478,12 +478,12 @@ return; } - const user_manager::User* user = user_manager::UserManager::Get()->FindUser( - AccountId::FromUserEmail(user_id)); + const user_manager::User* user = + user_manager::UserManager::Get()->FindUser(user_id); CHECK(user); - const bool is_persistent = + bool is_persistent = !user_manager::UserManager::Get()->IsUserNonCryptohomeDataEphemeral( - AccountId::FromUserEmail(user_id)) || + user_id) || (type == user_manager::User::POLICY && user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT); @@ -556,8 +556,8 @@ const base::FilePath* file = NULL; - const user_manager::User* user = user_manager::UserManager::Get()->FindUser( - AccountId::FromUserEmail(user_id)); + const user_manager::User* user = + user_manager::UserManager::Get()->FindUser(user_id); if (user_manager::UserManager::Get()->IsLoggedInAsGuest()) { file = @@ -624,9 +624,8 @@ return; } - const AccountId account_id = AccountId::FromUserEmail(user_id); const user_manager::User* user = - user_manager::UserManager::Get()->FindUser(account_id); + user_manager::UserManager::Get()->FindUser(user_id); // User is unknown or there is no visible background in kiosk mode. if (!user || user->GetType() == user_manager::USER_TYPE_KIOSK_APP) @@ -634,7 +633,7 @@ // Guest user or regular user in ephemeral mode. if ((user_manager::UserManager::Get()->IsUserNonCryptohomeDataEphemeral( - account_id) && + user_id) && user->HasGaiaAccount()) || user->GetType() == user_manager::USER_TYPE_GUEST) { InitInitialUserWallpaper(user_id, false); @@ -811,7 +810,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); if (user_manager::UserManager::Get()->IsUserNonCryptohomeDataEphemeral( - AccountId::FromUserEmail(user_id))) { + user_id)) { // Default to the values cached in memory. *info = current_user_wallpaper_info_;
diff --git a/chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager_browsertest.cc b/chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager_browsertest.cc index f3fb513a..b61138f 100644 --- a/chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager_browsertest.cc +++ b/chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager_browsertest.cc
@@ -111,20 +111,20 @@ return wallpaper_path; } - // Logs in |account_id|. - void LogIn(const AccountId& account_id, const std::string& user_id_hash) { - user_manager::UserManager::Get()->UserLoggedIn(account_id, user_id_hash, - false); + // Logs in |username|. + void LogIn(const std::string& username, const std::string& username_hash) { + user_manager::UserManager::Get()->UserLoggedIn( + username, username_hash, false); WaitAsyncWallpaperLoadStarted(); } - // Logs in |account_id| and sets it as child account. - void LogInAsChild(const AccountId& account_id, - const std::string& user_id_hash) { - user_manager::UserManager::Get()->UserLoggedIn(account_id, user_id_hash, - false); + // Logs in |username| and sets it as child account. + void LogInAsChild( + const std::string& username, const std::string& username_hash) { + user_manager::UserManager::Get()->UserLoggedIn( + username, username_hash, false); user_manager::User* user = - user_manager::UserManager::Get()->FindUserAndModify(account_id); + user_manager::UserManager::Get()->FindUserAndModify(username); user_manager::UserManager::Get()->ChangeUserChildStatus( user, true /* is_child */); } @@ -169,7 +169,7 @@ IN_PROC_BROWSER_TEST_F(WallpaperManagerBrowserTest, LoadCustomLargeWallpaperForLargeExternalScreen) { WallpaperManager* wallpaper_manager = WallpaperManager::Get(); - LogIn(AccountId::FromUserEmail(kTestUser1), kTestUser1Hash); + LogIn(kTestUser1, kTestUser1Hash); std::string id = base::Int64ToString(base::Time::Now().ToInternalValue()); base::FilePath small_wallpaper_path = GetCustomWallpaperPath( wallpaper::kSmallWallpaperSubDir, kTestUser1Hash, id); @@ -245,7 +245,7 @@ PreventReloadingSameWallpaper) { WallpaperManager* wallpaper_manager = WallpaperManager::Get(); // New user log in, a default wallpaper is loaded. - LogIn(AccountId::FromUserEmail(kTestUser1), kTestUser1Hash); + LogIn(kTestUser1, kTestUser1Hash); EXPECT_EQ(1, LoadedWallpapers()); // Loads the same wallpaper before the initial one finished. It should be // prevented. @@ -296,7 +296,7 @@ IN_PROC_BROWSER_TEST_F(WallpaperManagerBrowserTest, PRE_UseMigratedWallpaperInfo) { // New user log in, a default wallpaper is loaded. - LogIn(AccountId::FromUserEmail(kTestUser1), kTestUser1Hash); + LogIn(kTestUser1, kTestUser1Hash); // Old wallpaper migration code doesn't exist in codebase anymore. Modify user // wallpaper info directly to simulate the wallpaper migration. See // crosbug.com/38429 for details about why we modify wallpaper info this way. @@ -315,7 +315,7 @@ IN_PROC_BROWSER_TEST_F(WallpaperManagerBrowserTest, UseMigratedWallpaperInfo) { - LogIn(AccountId::FromUserEmail(kTestUser1), kTestUser1Hash); + LogIn(kTestUser1, kTestUser1Hash); wallpaper_manager_test_utils::WaitAsyncWallpaperLoadFinished(); // This test should finish normally. If timeout, it is probably because // migrated wallpaper is somehow not loaded. Bad things can happen if @@ -327,7 +327,7 @@ IN_PROC_BROWSER_TEST_F(WallpaperManagerBrowserTest, PRE_UsePreMigrationWallpaperInfo) { // New user log in, a default wallpaper is loaded. - LogIn(AccountId::FromUserEmail(kTestUser1), kTestUser1Hash); + LogIn(kTestUser1, kTestUser1Hash); // Old wallpaper migration code doesn't exist in codebase anymore. So if // user's profile is not migrated, it is the same as no wallpaper info. To // simulate this, we remove user's wallpaper info here. @@ -336,7 +336,7 @@ IN_PROC_BROWSER_TEST_F(WallpaperManagerBrowserTest, UsePreMigrationWallpaperInfo) { - LogIn(AccountId::FromUserEmail(kTestUser1), kTestUser1Hash); + LogIn(kTestUser1, kTestUser1Hash); wallpaper_manager_test_utils::WaitAsyncWallpaperLoadFinished(); // This test should finish normally. If timeout, it is probably because chrome // can not handle pre migrated user profile (M21 profile or older). @@ -374,7 +374,7 @@ IN_PROC_BROWSER_TEST_F(WallpaperManagerBrowserTestNoAnimation, PRE_UseMigratedWallpaperInfo) { // New user log in, a default wallpaper is loaded. - LogIn(AccountId::FromUserEmail(kTestUser1), kTestUser1Hash); + LogIn(kTestUser1, kTestUser1Hash); // Old wallpaper migration code doesn't exist in codebase anymore. Modify user // wallpaper info directly to simulate the wallpaper migration. See // crosbug.com/38429 for details about why we modify wallpaper info this way. @@ -393,7 +393,7 @@ IN_PROC_BROWSER_TEST_F(WallpaperManagerBrowserTestNoAnimation, UseMigratedWallpaperInfo) { - LogIn(AccountId::FromUserEmail(kTestUser1), kTestUser1Hash); + LogIn(kTestUser1, kTestUser1Hash); wallpaper_manager_test_utils::WaitAsyncWallpaperLoadFinished(); // This test should finish normally. If timeout, it is probably because // migrated wallpaper is somehow not loaded. Bad things can happen if @@ -405,7 +405,7 @@ IN_PROC_BROWSER_TEST_F(WallpaperManagerBrowserTestNoAnimation, PRE_UsePreMigrationWallpaperInfo) { // New user log in, a default wallpaper is loaded. - LogIn(AccountId::FromUserEmail(kTestUser1), kTestUser1Hash); + LogIn(kTestUser1, kTestUser1Hash); wallpaper_manager_test_utils::WaitAsyncWallpaperLoadFinished(); // Old wallpaper migration code doesn't exist in codebase anymore. So if // user's profile is not migrated, it is the same as no wallpaper info. To @@ -415,7 +415,7 @@ IN_PROC_BROWSER_TEST_F(WallpaperManagerBrowserTestNoAnimation, UsePreMigrationWallpaperInfo) { - LogIn(AccountId::FromUserEmail(kTestUser1), kTestUser1Hash); + LogIn(kTestUser1, kTestUser1Hash); wallpaper_manager_test_utils::WaitAsyncWallpaperLoadFinished(); // This test should finish normally. If timeout, it is probably because chrome // can not handle pre migrated user profile (M21 profile or older). @@ -434,7 +434,7 @@ IN_PROC_BROWSER_TEST_F(WallpaperManagerBrowserTestCrashRestore, PRE_RestoreWallpaper) { - LogIn(AccountId::FromUserEmail(kTestUser1), kTestUser1Hash); + LogIn(kTestUser1, kTestUser1Hash); wallpaper_manager_test_utils::WaitAsyncWallpaperLoadFinished(); } @@ -469,7 +469,7 @@ IN_PROC_BROWSER_TEST_F(WallpaperManagerBrowserTestCacheUpdate, PRE_VerifyWallpaperCache) { // Add kTestUser1 to user list. kTestUser1 is the default login profile. - LogIn(AccountId::FromUserEmail(kTestUser1), kTestUser1Hash); + LogIn(kTestUser1, kTestUser1Hash); std::string id = base::Int64ToString(base::Time::Now().ToInternalValue()); WallpaperManager* wallpaper_manager = WallpaperManager::Get(); @@ -535,7 +535,7 @@ EXPECT_TRUE(test_api->GetPathFromCache(kTestUser1, &original_path)); EXPECT_FALSE(original_path.empty()); - LogIn(AccountId::FromUserEmail(kTestUser2), kTestUser2Hash); + LogIn(kTestUser2, kTestUser2Hash); wallpaper_manager_test_utils::WaitAsyncWallpaperLoadFinished(); // Login another user should not delete logged in user's wallpaper cache. // Note active user is still kTestUser1. @@ -756,8 +756,7 @@ return; CreateCmdlineWallpapers(); user_manager::UserManager::Get()->UserLoggedIn( - chromeos::login::GuestAccountId(), chromeos::login::kGuestUserName, - false); + chromeos::login::kGuestUserName, chromeos::login::kGuestUserName, false); UpdateDisplay("800x600"); WallpaperManager::Get()->SetDefaultWallpaperNow(std::string()); wallpaper_manager_test_utils::WaitAsyncWallpaperLoadFinished(); @@ -772,8 +771,7 @@ CreateCmdlineWallpapers(); user_manager::UserManager::Get()->UserLoggedIn( - chromeos::login::GuestAccountId(), chromeos::login::kGuestUserName, - false); + chromeos::login::kGuestUserName, chromeos::login::kGuestUserName, false); UpdateDisplay("1600x1200"); WallpaperManager::Get()->SetDefaultWallpaperNow(std::string()); wallpaper_manager_test_utils::WaitAsyncWallpaperLoadFinished(); @@ -786,7 +784,7 @@ if (!ash::test::AshTestHelper::SupportsMultipleDisplays()) return; CreateCmdlineWallpapers(); - LogInAsChild(AccountId::FromUserEmail(kTestUser1), kTestUser1Hash); + LogInAsChild(kTestUser1, kTestUser1Hash); UpdateDisplay("800x600"); WallpaperManager::Get()->SetDefaultWallpaperNow(std::string()); wallpaper_manager_test_utils::WaitAsyncWallpaperLoadFinished(); @@ -800,7 +798,7 @@ return; CreateCmdlineWallpapers(); - LogInAsChild(AccountId::FromUserEmail(kTestUser1), kTestUser1Hash); + LogInAsChild(kTestUser1, kTestUser1Hash); UpdateDisplay("1600x1200"); WallpaperManager::Get()->SetDefaultWallpaperNow(std::string()); wallpaper_manager_test_utils::WaitAsyncWallpaperLoadFinished(); @@ -815,7 +813,7 @@ UpdateDisplay("640x480"); CreateCmdlineWallpapers(); user_manager::UserManager::Get()->UserLoggedIn( - chromeos::login::StubAccountId(), "test_hash", false); + chromeos::login::kStubUser, "test_hash", false); WallpaperManager::Get()->SetDefaultWallpaperNow(std::string());
diff --git a/chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager_policy_browsertest.cc b/chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager_policy_browsertest.cc index 11876de..ca7ff24 100644 --- a/chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager_policy_browsertest.cc +++ b/chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager_policy_browsertest.cc
@@ -244,8 +244,8 @@ } builder->Build(); fake_session_manager_client_->set_user_policy(user_id, builder->GetBlob()); - const user_manager::User* user = user_manager::UserManager::Get()->FindUser( - AccountId::FromUserEmail(user_id)); + const user_manager::User* user = + user_manager::UserManager::Get()->FindUser(user_id); ASSERT_TRUE(user); policy::CloudPolicyStore* store = GetStoreForUser(user); ASSERT_TRUE(store);
diff --git a/chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager_unittest.cc b/chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager_unittest.cc index ac00c1d..9c9f6154 100644 --- a/chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager_unittest.cc +++ b/chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager_unittest.cc
@@ -72,22 +72,19 @@ TEST_F(WallpaperManagerCacheTest, VerifyWallpaperCache) { // Add three users to known users. - const AccountId test_account_id_1 = - AccountId::FromUserEmail("test1@example.com"); - const AccountId test_account_id_2 = - AccountId::FromUserEmail("test2@example.com"); - const AccountId test_account_id_3 = - AccountId::FromUserEmail("test3@example.com"); + std::string test_user_1 = "test1@example.com"; + std::string test_user_2 = "test2@example.com"; + std::string test_user_3 = "test3@example.com"; base::FilePath path1("path1"); base::FilePath path2("path2"); base::FilePath path3("path3"); - fake_user_manager()->AddUser(test_account_id_1); - fake_user_manager()->AddUser(test_account_id_2); - fake_user_manager()->AddUser(test_account_id_3); + fake_user_manager()->AddUser(test_user_1); + fake_user_manager()->AddUser(test_user_2); + fake_user_manager()->AddUser(test_user_3); // Login two users. - fake_user_manager()->LoginUser(test_account_id_1); - fake_user_manager()->LoginUser(test_account_id_2); + fake_user_manager()->LoginUser(test_user_1); + fake_user_manager()->LoginUser(test_user_2); scoped_ptr<WallpaperManager::TestApi> test_api; test_api.reset(new WallpaperManager::TestApi(WallpaperManager::Get())); @@ -95,36 +92,27 @@ gfx::ImageSkia test_user_1_wallpaper = CreateTestImage(SK_ColorRED); gfx::ImageSkia test_user_2_wallpaper = CreateTestImage(SK_ColorGREEN); gfx::ImageSkia test_user_3_wallpaper = CreateTestImage(SK_ColorWHITE); - test_api->SetWallpaperCache(test_account_id_1.GetUserEmail(), path1, - test_user_1_wallpaper); - test_api->SetWallpaperCache(test_account_id_2.GetUserEmail(), path2, - test_user_2_wallpaper); - test_api->SetWallpaperCache(test_account_id_3.GetUserEmail(), path3, - test_user_3_wallpaper); + test_api->SetWallpaperCache(test_user_1, path1, test_user_1_wallpaper); + test_api->SetWallpaperCache(test_user_2, path2, test_user_2_wallpaper); + test_api->SetWallpaperCache(test_user_3, path3, test_user_3_wallpaper); test_api->ClearDisposableWallpaperCache(); gfx::ImageSkia cached_wallpaper; - EXPECT_TRUE(test_api->GetWallpaperFromCache(test_account_id_1.GetUserEmail(), - &cached_wallpaper)); + EXPECT_TRUE(test_api->GetWallpaperFromCache(test_user_1, &cached_wallpaper)); base::FilePath path; - EXPECT_TRUE( - test_api->GetPathFromCache(test_account_id_1.GetUserEmail(), &path)); + EXPECT_TRUE(test_api->GetPathFromCache(test_user_1, &path)); // Logged in users' wallpaper cache should be kept. EXPECT_TRUE(cached_wallpaper.BackedBySameObjectAs(test_user_1_wallpaper)); EXPECT_EQ(path, path1); - EXPECT_TRUE(test_api->GetWallpaperFromCache(test_account_id_2.GetUserEmail(), - &cached_wallpaper)); - EXPECT_TRUE( - test_api->GetPathFromCache(test_account_id_2.GetUserEmail(), &path)); + EXPECT_TRUE(test_api->GetWallpaperFromCache(test_user_2, &cached_wallpaper)); + EXPECT_TRUE(test_api->GetPathFromCache(test_user_2, &path)); EXPECT_TRUE(cached_wallpaper.BackedBySameObjectAs(test_user_2_wallpaper)); EXPECT_EQ(path, path2); // Not logged in user's wallpaper cache should be cleared. - EXPECT_FALSE(test_api->GetWallpaperFromCache(test_account_id_3.GetUserEmail(), - &cached_wallpaper)); - EXPECT_FALSE( - test_api->GetPathFromCache(test_account_id_3.GetUserEmail(), &path)); + EXPECT_FALSE(test_api->GetWallpaperFromCache(test_user_3, &cached_wallpaper)); + EXPECT_FALSE(test_api->GetPathFromCache(test_user_3, &path)); } } // namespace chromeos
diff --git a/chrome/browser/chromeos/net/network_portal_detector_impl_unittest.cc b/chrome/browser/chromeos/net/network_portal_detector_impl_unittest.cc index e3760aa..75b5b9a 100644 --- a/chrome/browser/chromeos/net/network_portal_detector_impl_unittest.cc +++ b/chrome/browser/chromeos/net/network_portal_detector_impl_unittest.cc
@@ -89,14 +89,12 @@ ASSERT_TRUE(test_profile_manager_.SetUp()); // Add a user. - const AccountId test_account_id( - AccountId::FromUserEmail("test-user@example.com")); - user_manager->AddUser(test_account_id); - user_manager->LoginUser(test_account_id); + const char kTestUserName[] = "test-user@example.com"; + user_manager->AddUser(kTestUserName); + user_manager->LoginUser(kTestUserName); // Create a profile for the user. - profile_ = test_profile_manager_.CreateTestingProfile( - test_account_id.GetUserEmail()); + profile_ = test_profile_manager_.CreateTestingProfile(kTestUserName); test_profile_manager_.SetLoggedIn(true); EXPECT_TRUE(user_manager::UserManager::Get()->GetPrimaryUser());
diff --git a/chrome/browser/chromeos/ownership/owner_settings_service_chromeos.cc b/chrome/browser/chromeos/ownership/owner_settings_service_chromeos.cc index a6c5d91c7..6a4ba6d3 100644 --- a/chrome/browser/chromeos/ownership/owner_settings_service_chromeos.cc +++ b/chrome/browser/chromeos/ownership/owner_settings_service_chromeos.cc
@@ -721,7 +721,7 @@ const user_manager::User* user = ProfileHelper::Get()->GetUserByProfile(profile_); - user_id_ = user ? user->GetAccountId().GetUserEmail() : std::string(); + user_id_ = user ? user->GetUserID() : std::string(); const bool is_owner = IsOwner() || IsOwnerInTests(user_id_); if (is_owner && device_settings_service_)
diff --git a/chrome/browser/chromeos/ownership/owner_settings_service_chromeos_unittest.cc b/chrome/browser/chromeos/ownership/owner_settings_service_chromeos_unittest.cc index 1a36696..aa4d68909 100644 --- a/chrome/browser/chromeos/ownership/owner_settings_service_chromeos_unittest.cc +++ b/chrome/browser/chromeos/ownership/owner_settings_service_chromeos_unittest.cc
@@ -100,8 +100,7 @@ provider_.reset(new DeviceSettingsProvider(base::Bind(&OnPrefChanged), &device_settings_service_)); owner_key_util_->SetPrivateKey(device_policy_.GetSigningKey()); - InitOwner(AccountId::FromUserEmail(device_policy_.policy_data().username()), - true); + InitOwner(device_policy_.policy_data().username(), true); FlushDeviceSettings(); service_ = OwnerSettingsServiceChromeOSFactory::GetForBrowserContext( @@ -343,8 +342,7 @@ EXPECT_FALSE(FindInListValue(device_policy_.policy_data().username(), provider_->Get(kAccountsPrefUsers))); owner_key_util_->SetPrivateKey(device_policy_.GetSigningKey()); - InitOwner(AccountId::FromUserEmail(device_policy_.policy_data().username()), - true); + InitOwner(device_policy_.policy_data().username(), true); ReloadDeviceSettings(); ASSERT_TRUE(service_->IsOwner());
diff --git a/chrome/browser/chromeos/policy/affiliated_invalidation_service_provider_impl_unittest.cc b/chrome/browser/chromeos/policy/affiliated_invalidation_service_provider_impl_unittest.cc index 9009677..143a37e1 100644 --- a/chrome/browser/chromeos/policy/affiliated_invalidation_service_provider_impl_unittest.cc +++ b/chrome/browser/chromeos/policy/affiliated_invalidation_service_provider_impl_unittest.cc
@@ -222,7 +222,7 @@ Profile* AffiliatedInvalidationServiceProviderImplTest::LogInAndReturnProfile( const std::string& user_id) { - fake_user_manager_->AddUser(AccountId::FromUserEmail(user_id)); + fake_user_manager_->AddUser(user_id); Profile* profile = profile_manager_.CreateTestingProfile(user_id); content::NotificationService::current()->Notify( chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED,
diff --git a/chrome/browser/chromeos/policy/blocking_login_browsertest.cc b/chrome/browser/chromeos/policy/blocking_login_browsertest.cc index f3ce1e1..768bb466 100644 --- a/chrome/browser/chromeos/policy/blocking_login_browsertest.cc +++ b/chrome/browser/chromeos/policy/blocking_login_browsertest.cc
@@ -246,8 +246,7 @@ EXPECT_EQ(policy::USER_AFFILIATION_MANAGED, browser_policy_connector()->GetUserAffiliation(kUsername)); RunUntilIdle(); - EXPECT_FALSE( - user_manager->IsKnownUser(AccountId::FromUserEmail(kUsername))); + EXPECT_FALSE(user_manager->IsKnownUser(kUsername)); } // Skip the OOBE, go to the sign-in screen, and wait for the login screen to
diff --git a/chrome/browser/chromeos/policy/cloud_external_data_policy_observer_unittest.cc b/chrome/browser/chromeos/policy/cloud_external_data_policy_observer_unittest.cc index e963d02..95982a3 100644 --- a/chrome/browser/chromeos/policy/cloud_external_data_policy_observer_unittest.cc +++ b/chrome/browser/chromeos/policy/cloud_external_data_policy_observer_unittest.cc
@@ -123,7 +123,7 @@ void RefreshDeviceLocalAccountPolicy(DeviceLocalAccountPolicyBroker* broker); - void LogInAsDeviceLocalAccount(const AccountId& account_id); + void LogInAsDeviceLocalAccount(const std::string& user_id); void SetRegularUserAvatarPolicy(const std::string& value); @@ -320,12 +320,13 @@ } void CloudExternalDataPolicyObserverTest::LogInAsDeviceLocalAccount( - const AccountId& account_id) { - user_manager_->AddUser(account_id); + const std::string& user_id) { + user_manager_->AddUser(user_id); device_local_account_policy_provider_.reset( new DeviceLocalAccountPolicyProvider( - account_id.GetUserEmail(), device_local_account_policy_service_.get(), + user_id, + device_local_account_policy_service_.get(), scoped_ptr<PolicyMap>())); PolicyServiceImpl::Providers providers; @@ -334,11 +335,10 @@ builder.SetPolicyService( scoped_ptr<PolicyService>(new PolicyServiceImpl(providers))); builder.SetPath(chromeos::ProfileHelper::Get()->GetProfilePathByUserIdHash( - chromeos::ProfileHelper::GetUserIdHashByUserIdForTesting( - account_id.GetUserEmail()))); + chromeos::ProfileHelper::GetUserIdHashByUserIdForTesting(user_id))); profile_ = builder.Build(); - profile_->set_profile_name(account_id.GetUserEmail()); + profile_->set_profile_name(user_id); content::NotificationService::current()->Notify( chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED, @@ -363,7 +363,7 @@ } void CloudExternalDataPolicyObserverTest::LogInAsRegularUser() { - user_manager_->AddUser(AccountId::FromUserEmail(kRegularUserID)); + user_manager_->AddUser(kRegularUserID); PolicyServiceImpl::Providers providers; providers.push_back(&user_policy_provider_); @@ -661,7 +661,7 @@ CreateObserver(); - LogInAsDeviceLocalAccount(AccountId::FromUserEmail(kDeviceLocalAccount)); + LogInAsDeviceLocalAccount(kDeviceLocalAccount); EXPECT_TRUE(set_calls_.empty()); EXPECT_TRUE(cleared_calls_.empty());
diff --git a/chrome/browser/chromeos/policy/consumer_enrollment_handler_factory_unittest.cc b/chrome/browser/chromeos/policy/consumer_enrollment_handler_factory_unittest.cc index c0f2c93f..b1c209d 100644 --- a/chrome/browser/chromeos/policy/consumer_enrollment_handler_factory_unittest.cc +++ b/chrome/browser/chromeos/policy/consumer_enrollment_handler_factory_unittest.cc
@@ -44,9 +44,9 @@ make_scoped_ptr(fake_service_)); // Set up FakeChromeUserManager. - fake_user_manager_->AddUser(AccountId::FromUserEmail(kTestOwner)); - fake_user_manager_->AddUser(AccountId::FromUserEmail(kTestUser)); - fake_user_manager_->set_owner_id(AccountId::FromUserEmail(kTestOwner)); + fake_user_manager_->AddUser(kTestOwner); + fake_user_manager_->AddUser(kTestUser); + fake_user_manager_->set_owner_email(kTestOwner); } void SetUp() override {
diff --git a/chrome/browser/chromeos/policy/consumer_enrollment_handler_unittest.cc b/chrome/browser/chromeos/policy/consumer_enrollment_handler_unittest.cc index 74e806f..7116c61 100644 --- a/chrome/browser/chromeos/policy/consumer_enrollment_handler_unittest.cc +++ b/chrome/browser/chromeos/policy/consumer_enrollment_handler_unittest.cc
@@ -62,9 +62,9 @@ make_scoped_ptr(fake_initializer_)); // Set up FakeChromeUserManager. - fake_user_manager_->AddUser(AccountId::FromUserEmail(kTestOwner)); - fake_user_manager_->AddUser(AccountId::FromUserEmail(kTestUser)); - fake_user_manager_->set_owner_id(AccountId::FromUserEmail(kTestOwner)); + fake_user_manager_->AddUser(kTestOwner); + fake_user_manager_->AddUser(kTestUser); + fake_user_manager_->set_owner_email(kTestOwner); } void SetUp() override {
diff --git a/chrome/browser/chromeos/policy/consumer_management_notifier_factory_unittest.cc b/chrome/browser/chromeos/policy/consumer_management_notifier_factory_unittest.cc index 23df640..5963c82 100644 --- a/chrome/browser/chromeos/policy/consumer_management_notifier_factory_unittest.cc +++ b/chrome/browser/chromeos/policy/consumer_management_notifier_factory_unittest.cc
@@ -44,9 +44,9 @@ make_scoped_ptr(fake_service_)); // Set up FakeChromeUserManager. - fake_user_manager_->AddUser(AccountId::FromUserEmail(kTestOwner)); - fake_user_manager_->AddUser(AccountId::FromUserEmail(kTestUser)); - fake_user_manager_->set_owner_id(AccountId::FromUserEmail(kTestOwner)); + fake_user_manager_->AddUser(kTestOwner); + fake_user_manager_->AddUser(kTestUser); + fake_user_manager_->set_owner_email(kTestOwner); } void SetUp() override {
diff --git a/chrome/browser/chromeos/policy/consumer_unenrollment_handler_unittest.cc b/chrome/browser/chromeos/policy/consumer_unenrollment_handler_unittest.cc index c9717879..1a9ba8b 100644 --- a/chrome/browser/chromeos/policy/consumer_unenrollment_handler_unittest.cc +++ b/chrome/browser/chromeos/policy/consumer_unenrollment_handler_unittest.cc
@@ -44,8 +44,7 @@ // Set up the ownership, so that we can modify device settings. owner_key_util_->SetPrivateKey(device_policy_.GetSigningKey()); - InitOwner(AccountId::FromUserEmail(device_policy_.policy_data().username()), - true); + InitOwner(device_policy_.policy_data().username(), true); FlushDeviceSettings();
diff --git a/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos_unittest.cc b/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos_unittest.cc index 3795901..7bc9ec7 100644 --- a/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos_unittest.cc +++ b/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos_unittest.cc
@@ -682,8 +682,7 @@ SuccessfulConsumerManagementEnrollment) { management_mode_ = MANAGEMENT_MODE_CONSUMER_MANAGED; owner_key_util_->SetPrivateKey(device_policy_.GetNewSigningKey()); - InitOwner(AccountId::FromUserEmail(device_policy_.policy_data().username()), - true); + InitOwner(device_policy_.policy_data().username(), true); FlushDeviceSettings(); device_policy_.policy_data().set_management_mode(em::PolicyData::LOCAL_OWNER);
diff --git a/chrome/browser/chromeos/policy/device_local_account_browsertest.cc b/chrome/browser/chromeos/policy/device_local_account_browsertest.cc index f7f4019..53cbbdc9 100644 --- a/chrome/browser/chromeos/policy/device_local_account_browsertest.cc +++ b/chrome/browser/chromeos/policy/device_local_account_browsertest.cc
@@ -419,9 +419,13 @@ public extensions::AppWindowRegistry::Observer { protected: DeviceLocalAccountTest() - : public_session_input_method_id_( - base::StringPrintf(kPublicSessionInputMethodIDTemplate, - chromeos::extension_ime_util::kXkbExtensionId)), + : user_id_1_(GenerateDeviceLocalAccountUserId( + kAccountId1, DeviceLocalAccount::TYPE_PUBLIC_SESSION)), + user_id_2_(GenerateDeviceLocalAccountUserId( + kAccountId2, DeviceLocalAccount::TYPE_PUBLIC_SESSION)), + public_session_input_method_id_(base::StringPrintf( + kPublicSessionInputMethodIDTemplate, + chromeos::extension_ime_util::kXkbExtensionId)), contents_(NULL) { set_exit_when_last_browser_closes(false); } @@ -630,11 +634,11 @@ proto.SerializeAsString())); } - void CheckPublicSessionPresent(const AccountId& account_id) { + void CheckPublicSessionPresent(const std::string& id) { const user_manager::User* user = - user_manager::UserManager::Get()->FindUser(account_id); + user_manager::UserManager::Get()->FindUser(id); ASSERT_TRUE(user); - EXPECT_EQ(account_id, user->GetAccountId()); + EXPECT_EQ(id, user->email()); EXPECT_EQ(user_manager::USER_TYPE_PUBLIC_ACCOUNT, user->GetType()); } @@ -680,7 +684,7 @@ // Wait for the display name becoming available as that indicates // device-local account policy is fully loaded, which is a prerequisite for // successful login. - WaitForDisplayName(account_id_1_.GetUserEmail(), kDisplayName1); + WaitForDisplayName(user_id_1_, kDisplayName1); } void ExpandPublicSessionPod(bool expect_advanced) { @@ -693,7 +697,7 @@ " document.getElementById('pod-row').getPodWithUsername_('%s');" "pod.click();" "domAutomationController.send(pod.classList.contains('advanced'));", - account_id_1_.GetUserEmail().c_str()), + user_id_1_.c_str()), &advanced)); // Verify that the pod expanded to its basic/advanced form, as expected. EXPECT_EQ(expect_advanced, advanced); @@ -737,7 +741,7 @@ ASSERT_TRUE(controller); chromeos::UserContext user_context(user_manager::USER_TYPE_PUBLIC_ACCOUNT, - account_id_1_.GetUserEmail()); + user_id_1_); user_context.SetPublicSessionLocale(locale); user_context.SetPublicSessionInputMethod(input_method); controller->Login(user_context, chromeos::SigninSpecifics()); @@ -783,14 +787,8 @@ VerifyKeyboardLayoutMatchesLocale(); } - const AccountId account_id_1_ = - AccountId::FromUserEmail(GenerateDeviceLocalAccountUserId( - kAccountId1, - DeviceLocalAccount::TYPE_PUBLIC_SESSION)); - const AccountId account_id_2_ = - AccountId::FromUserEmail(GenerateDeviceLocalAccountUserId( - kAccountId2, - DeviceLocalAccount::TYPE_PUBLIC_SESSION)); + const std::string user_id_1_; + const std::string user_id_2_; const std::string public_session_input_method_id_; std::string initial_locale_; @@ -807,7 +805,7 @@ DISALLOW_COPY_AND_ASSIGN(DeviceLocalAccountTest); }; -static bool IsKnownUser(const AccountId& account_id) { +static bool IsKnownUser(const std::string& account_id) { return user_manager::UserManager::Get()->IsKnownUser(account_id); } @@ -816,12 +814,12 @@ AddPublicSessionToDevicePolicy(kAccountId2); content::WindowedNotificationObserver(chrome::NOTIFICATION_USER_LIST_CHANGED, - base::Bind(&IsKnownUser, account_id_1_)) + base::Bind(&IsKnownUser, user_id_1_)) .Wait(); - EXPECT_TRUE(IsKnownUser(account_id_2_)); + EXPECT_TRUE(IsKnownUser(user_id_2_)); - CheckPublicSessionPresent(account_id_1_); - CheckPublicSessionPresent(account_id_2_); + CheckPublicSessionPresent(user_id_1_); + CheckPublicSessionPresent(user_id_2_); } // Flaky: http://crbug.com/512670. @@ -835,7 +833,7 @@ const std::string get_compact_pod_display_name = base::StringPrintf( "domAutomationController.send(document.getElementById('pod-row')" " .getPodWithUsername_('%s').nameElement.textContent);", - account_id_1_.GetUserEmail().c_str()); + user_id_1_.c_str()); std::string display_name; ASSERT_TRUE(content::ExecuteScriptAndExtractString( contents_, @@ -846,7 +844,7 @@ "domAutomationController.send(document.getElementById('pod-row')" " .getPodWithUsername_('%s').querySelector('.expanded-pane-name')" " .textContent);", - account_id_1_.GetUserEmail().c_str()); + user_id_1_.c_str()); display_name.clear(); ASSERT_TRUE(content::ExecuteScriptAndExtractString( contents_, @@ -860,7 +858,7 @@ base::StringPrintf( "document.getElementById('pod-row').getPodWithUsername_('%s')" " .click();", - account_id_1_.GetUserEmail().c_str()))); + user_id_1_.c_str()))); // Change the display name. device_local_account_policy_.payload().mutable_userdisplayname()->set_value( @@ -870,10 +868,10 @@ g_browser_process->platform_part()->browser_policy_connector_chromeos(); DeviceLocalAccountPolicyBroker* broker = connector->GetDeviceLocalAccountPolicyService()->GetBrokerForUser( - account_id_1_.GetUserEmail()); + user_id_1_); ASSERT_TRUE(broker); broker->core()->store()->Load(); - WaitForDisplayName(account_id_1_.GetUserEmail(), kDisplayName2); + WaitForDisplayName(user_id_1_, kDisplayName2); // Verify that the new display name is shown in the UI. display_name.clear(); @@ -897,7 +895,7 @@ base::StringPrintf( "domAutomationController.send(document.getElementById('pod-row')" " .getPodWithUsername_('%s').expanded);", - account_id_1_.GetUserEmail().c_str()), + user_id_1_.c_str()), &expanded)); EXPECT_TRUE(expanded); } @@ -913,7 +911,7 @@ kAccountId1).empty()); } -static bool IsNotKnownUser(const AccountId& account_id) { +static bool IsNotKnownUser(const std::string& account_id) { return !IsKnownUser(account_id); } @@ -922,9 +920,9 @@ AddPublicSessionToDevicePolicy(kAccountId2); content::WindowedNotificationObserver(chrome::NOTIFICATION_USER_LIST_CHANGED, - base::Bind(&IsKnownUser, account_id_1_)) + base::Bind(&IsKnownUser, user_id_1_)) .Wait(); - EXPECT_TRUE(IsKnownUser(account_id_2_)); + EXPECT_TRUE(IsKnownUser(user_id_2_)); // Update policy to remove kAccountId2. em::ChromeDeviceSettingsProto& proto(device_policy()->payload()); @@ -944,9 +942,8 @@ g_browser_process->policy_service()->RefreshPolicies(base::Closure()); // Make sure the second device-local account disappears. - content::WindowedNotificationObserver( - chrome::NOTIFICATION_USER_LIST_CHANGED, - base::Bind(&IsNotKnownUser, account_id_2_)) + content::WindowedNotificationObserver(chrome::NOTIFICATION_USER_LIST_CHANGED, + base::Bind(&IsNotKnownUser, user_id_2_)) .Wait(); } @@ -1081,10 +1078,8 @@ // Verify that the extension was removed from the account's extension cache // after the installation failure. DeviceLocalAccountPolicyBroker* broker = - g_browser_process->platform_part() - ->browser_policy_connector_chromeos() - ->GetDeviceLocalAccountPolicyService() - ->GetBrokerForUser(account_id_1_.GetUserEmail()); + g_browser_process->platform_part()->browser_policy_connector_chromeos()-> + GetDeviceLocalAccountPolicyService()->GetBrokerForUser(user_id_1_); ASSERT_TRUE(broker); chromeos::ExternalCache* cache = broker->extension_loader()->GetExternalCacheForTesting(); @@ -1156,10 +1151,8 @@ // Verify that the extension was removed from the account's extension cache. DeviceLocalAccountPolicyBroker* broker = - g_browser_process->platform_part() - ->browser_policy_connector_chromeos() - ->GetDeviceLocalAccountPolicyService() - ->GetBrokerForUser(account_id_1_.GetUserEmail()); + g_browser_process->platform_part()->browser_policy_connector_chromeos()-> + GetDeviceLocalAccountPolicyService()->GetBrokerForUser(user_id_1_); ASSERT_TRUE(broker); chromeos::ExternalCache* cache = broker->extension_loader()->GetExternalCacheForTesting(); @@ -1318,7 +1311,7 @@ g_browser_process->platform_part()->browser_policy_connector_chromeos(); DeviceLocalAccountPolicyBroker* broker = connector->GetDeviceLocalAccountPolicyService()->GetBrokerForUser( - account_id_1_.GetUserEmail()); + user_id_1_); ASSERT_TRUE(broker); broker->core()->store()->Load(); @@ -1408,7 +1401,7 @@ g_browser_process->platform_part()->browser_policy_connector_chromeos(); DeviceLocalAccountPolicyBroker* broker = connector->GetDeviceLocalAccountPolicyService()->GetBrokerForUser( - account_id_1_.GetUserEmail()); + user_id_1_); ASSERT_TRUE(broker); run_loop_.reset(new base::RunLoop); @@ -1422,13 +1415,13 @@ ASSERT_TRUE(policy_image); const user_manager::User* user = - user_manager::UserManager::Get()->FindUser(account_id_1_); + user_manager::UserManager::Get()->FindUser(user_id_1_); ASSERT_TRUE(user); base::FilePath user_data_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)); const base::FilePath saved_image_path = - user_data_dir.Append(account_id_1_.GetUserEmail()).AddExtension("jpg"); + user_data_dir.Append(user_id_1_).AddExtension("jpg"); EXPECT_FALSE(user->HasDefaultImage()); EXPECT_EQ(user_manager::User::USER_IMAGE_EXTERNAL, user->image_index()); @@ -1438,7 +1431,8 @@ ASSERT_TRUE(images_pref); const base::DictionaryValue* image_properties; ASSERT_TRUE(images_pref->GetDictionaryWithoutPathExpansion( - account_id_1_.GetUserEmail(), &image_properties)); + user_id_1_, + &image_properties)); int image_index; std::string image_path; ASSERT_TRUE(image_properties->GetInteger("index", &image_index)); @@ -1624,7 +1618,7 @@ base::StringPrintf( "document.getElementById('pod-row').getPodWithUsername_('%s')" " .querySelector('.enter-button').click();", - account_id_1_.GetUserEmail().c_str()))); + user_id_1_.c_str()))); WaitForSessionStart(); @@ -1653,7 +1647,7 @@ " document.getElementById('pod-row').getPodWithUsername_('%s');" "pod.querySelector('.language-and-input').click();" "domAutomationController.send(pod.classList.contains('advanced'));", - account_id_1_.GetUserEmail().c_str()), + user_id_1_.c_str()), &advanced)); EXPECT_FALSE(advanced); @@ -1667,7 +1661,8 @@ "var event = document.createEvent('HTMLEvents');" "event.initEvent('change', false, true);" "languageSelect.dispatchEvent(event);", - account_id_1_.GetUserEmail().c_str(), kPublicSessionLocale))); + user_id_1_.c_str(), + kPublicSessionLocale))); // The UI will have requested an updated list of keyboard layouts at this // point. Wait for the constructions of this list to finish. @@ -1682,7 +1677,7 @@ " document.getElementById('pod-row').getPodWithUsername_('%s');" "pod.querySelector('.keyboard-select').value = '%s';" "pod.querySelector('.enter-button').click();", - account_id_1_.GetUserEmail().c_str(), + user_id_1_.c_str(), public_session_input_method_id_.c_str()))); WaitForSessionStart(); @@ -1715,7 +1710,7 @@ base::StringPrintf( "document.getElementById('pod-row').getPodWithUsername_('%s')" " .querySelector('.enter-button').click();", - account_id_1_.GetUserEmail().c_str()))); + user_id_1_.c_str()))); WaitForSessionStart(); @@ -1748,7 +1743,7 @@ "for (var i = 0; i < languageSelect.length; ++i)" " locales.push(languageSelect.options[i].value);" "domAutomationController.send(JSON.stringify(locales));", - account_id_1_.GetUserEmail().c_str()); + user_id_1_.c_str()); std::string json; ASSERT_TRUE(content::ExecuteScriptAndExtractString(contents_, get_locale_list, @@ -1779,11 +1774,12 @@ } // Verify that the first recommended locale is selected. - const std::string get_selected_locale = base::StringPrintf( - "domAutomationController.send(document.getElementById('pod-row')" - " .getPodWithUsername_('%s').querySelector('.language-select')" - " .value);", - account_id_1_.GetUserEmail().c_str()); + const std::string get_selected_locale = + base::StringPrintf( + "domAutomationController.send(document.getElementById('pod-row')" + " .getPodWithUsername_('%s').querySelector('.language-select')" + " .value);", + user_id_1_.c_str()); std::string selected_locale; ASSERT_TRUE(content::ExecuteScriptAndExtractString(contents_, get_selected_locale, @@ -1802,10 +1798,10 @@ g_browser_process->platform_part()->browser_policy_connector_chromeos(); DeviceLocalAccountPolicyBroker* broker = connector->GetDeviceLocalAccountPolicyService()->GetBrokerForUser( - account_id_1_.GetUserEmail()); + user_id_1_); ASSERT_TRUE(broker); broker->core()->store()->Load(); - WaitForDisplayName(account_id_1_.GetUserEmail(), kDisplayName2); + WaitForDisplayName(user_id_1_, kDisplayName2); // Verify that the new list of locales is shown in the UI. ASSERT_TRUE(content::ExecuteScriptAndExtractString(contents_, @@ -1838,7 +1834,8 @@ "var event = document.createEvent('HTMLEvents');" "event.initEvent('change', false, true);" "languageSelect.dispatchEvent(event);", - account_id_1_.GetUserEmail().c_str(), kPublicSessionLocale))); + user_id_1_.c_str(), + kPublicSessionLocale))); // Change the list of recommended locales. SetRecommendedLocales(kRecommendedLocales2, arraysize(kRecommendedLocales2)); @@ -1846,7 +1843,7 @@ kDisplayName1); UploadAndInstallDeviceLocalAccountPolicy(); broker->core()->store()->Load(); - WaitForDisplayName(account_id_1_.GetUserEmail(), kDisplayName1); + WaitForDisplayName(user_id_1_, kDisplayName1); // Verify that the manually selected locale is still selected. ASSERT_TRUE(content::ExecuteScriptAndExtractString(contents_, @@ -1864,7 +1861,7 @@ base::StringPrintf( "document.getElementById('pod-row').getPodWithUsername_('%s')" " .querySelector('.keyboard-select').value = '%s';", - account_id_1_.GetUserEmail().c_str(), + user_id_1_.c_str(), public_session_input_method_id_.c_str()))); // Click on a different pod, causing focus to shift away and the pod to @@ -1874,7 +1871,7 @@ base::StringPrintf( "document.getElementById('pod-row').getPodWithUsername_('%s')" " .click();", - account_id_2_.GetUserEmail().c_str()))); + user_id_2_.c_str()))); // Click on the pod again, causing it to expand again. Verify that the pod has // kept all its state (the advanced form is being shown, the manually selected @@ -1891,7 +1888,7 @@ "state.keyboardLayout = pod.querySelector('.keyboard-select').value;" "console.log(JSON.stringify(state));" "domAutomationController.send(JSON.stringify(state));", - account_id_1_.GetUserEmail().c_str()), + user_id_1_.c_str()), &json)); LOG(ERROR) << json; value_ptr = base::JSONReader::Read(json); @@ -1913,7 +1910,7 @@ base::StringPrintf( "document.getElementById('pod-row').getPodWithUsername_('%s')" " .querySelector('.enter-button').click();", - account_id_1_.GetUserEmail().c_str()))); + user_id_1_.c_str()))); WaitForSessionStart(); @@ -1947,7 +1944,7 @@ " document.getElementById('pod-row').getPodWithUsername_('%s');" "pod.click();" "domAutomationController.send(pod.classList.contains('advanced'));", - account_id_1_.GetUserEmail().c_str()), + user_id_1_.c_str()), &advanced)); EXPECT_FALSE(advanced); EXPECT_EQ(l10n_util::GetLanguage(initial_locale_), @@ -1959,7 +1956,7 @@ base::StringPrintf( "document.getElementById('pod-row').getPodWithUsername_('%s')" " .querySelector('.enter-button').click();", - account_id_1_.GetUserEmail().c_str()))); + user_id_1_.c_str()))); WaitForSessionStart(); @@ -2052,7 +2049,8 @@ "var event = document.createEvent('HTMLEvents');" "event.initEvent('change', false, true);" "languageSelect.dispatchEvent(event);", - account_id_1_.GetUserEmail().c_str(), kPublicSessionLocale))); + user_id_1_.c_str(), + kPublicSessionLocale))); // The UI will have requested an updated list of keyboard layouts at this // point. Wait for the constructions of this list to finish. @@ -2078,7 +2076,7 @@ " document.getElementById('pod-row').getPodWithUsername_('%s');" "pod.querySelector('.keyboard-select').value = '%s';" "pod.querySelector('.enter-button').click();", - account_id_1_.GetUserEmail().c_str(), + user_id_1_.c_str(), public_session_input_method_id_.c_str()))); // Spin the loop until the login observer fires. Then, unregister the
diff --git a/chrome/browser/chromeos/policy/device_status_collector.cc b/chrome/browser/chromeos/policy/device_status_collector.cc index fc12d3d..f857846 100644 --- a/chrome/browser/chromeos/policy/device_status_collector.cc +++ b/chrome/browser/chromeos/policy/device_status_collector.cc
@@ -216,12 +216,12 @@ return scoped_ptr<policy::DeviceLocalAccount>(); const user_manager::User* const user = user_manager::UserManager::Get()->GetActiveUser(); + const std::string user_id = user->GetUserID(); const std::vector<policy::DeviceLocalAccount> accounts = policy::GetDeviceLocalAccounts(settings); for (const auto& device_local_account : accounts) { - if (AccountId::FromUserEmail(device_local_account.user_id) == - user->GetAccountId()) { + if (device_local_account.user_id == user_id) { return make_scoped_ptr( new policy::DeviceLocalAccount(device_local_account)).Pass(); }
diff --git a/chrome/browser/chromeos/policy/device_status_collector_browsertest.cc b/chrome/browser/chromeos/policy/device_status_collector_browsertest.cc index c24d867..ec8f3955 100644 --- a/chrome/browser/chromeos/policy/device_status_collector_browsertest.cc +++ b/chrome/browser/chromeos/policy/device_status_collector_browsertest.cc
@@ -378,8 +378,7 @@ std::vector<DeviceLocalAccount> accounts; accounts.push_back(account); SetDeviceLocalAccounts(owner_settings_service_.get(), accounts); - user_manager_->CreateKioskAppUser( - AccountId::FromUserEmail(account.user_id)); + user_manager_->CreateKioskAppUser(account.user_id); EXPECT_CALL(*user_manager_, IsLoggedInAsKioskApp()).WillRepeatedly( Return(true)); } @@ -773,22 +772,13 @@ } TEST_F(DeviceStatusCollectorTest, ReportUsers) { - const AccountId public_account_id( - AccountId::FromUserEmail("public@localhost")); - const AccountId account_id0(AccountId::FromUserEmail("user0@managed.com")); - const AccountId account_id1(AccountId::FromUserEmail("user1@managed.com")); - const AccountId account_id2(AccountId::FromUserEmail("user2@managed.com")); - const AccountId account_id3(AccountId::FromUserEmail("user3@unmanaged.com")); - const AccountId account_id4(AccountId::FromUserEmail("user4@managed.com")); - const AccountId account_id5(AccountId::FromUserEmail("user5@managed.com")); - - user_manager_->CreatePublicAccountUser(public_account_id); - user_manager_->AddUserWithAffiliation(account_id0, true); - user_manager_->AddUserWithAffiliation(account_id1, true); - user_manager_->AddUserWithAffiliation(account_id2, true); - user_manager_->AddUserWithAffiliation(account_id3, false); - user_manager_->AddUserWithAffiliation(account_id4, true); - user_manager_->AddUserWithAffiliation(account_id5, true); + user_manager_->CreatePublicAccountUser("public@localhost"); + user_manager_->AddUserWithAffiliation("user0@managed.com", true); + user_manager_->AddUserWithAffiliation("user1@managed.com", true); + user_manager_->AddUserWithAffiliation("user2@managed.com", true); + user_manager_->AddUserWithAffiliation("user3@unmanaged.com", false); + user_manager_->AddUserWithAffiliation("user4@managed.com", true); + user_manager_->AddUserWithAffiliation("user5@managed.com", true); // Verify that users are reported by default. GetStatus(); @@ -799,17 +789,17 @@ GetStatus(); EXPECT_EQ(6, status_.user_size()); EXPECT_EQ(em::DeviceUser::USER_TYPE_MANAGED, status_.user(0).type()); - EXPECT_EQ(account_id0.GetUserEmail(), status_.user(0).email()); + EXPECT_EQ("user0@managed.com", status_.user(0).email()); EXPECT_EQ(em::DeviceUser::USER_TYPE_MANAGED, status_.user(1).type()); - EXPECT_EQ(account_id1.GetUserEmail(), status_.user(1).email()); + EXPECT_EQ("user1@managed.com", status_.user(1).email()); EXPECT_EQ(em::DeviceUser::USER_TYPE_MANAGED, status_.user(2).type()); - EXPECT_EQ(account_id2.GetUserEmail(), status_.user(2).email()); + EXPECT_EQ("user2@managed.com", status_.user(2).email()); EXPECT_EQ(em::DeviceUser::USER_TYPE_UNMANAGED, status_.user(3).type()); EXPECT_FALSE(status_.user(3).has_email()); EXPECT_EQ(em::DeviceUser::USER_TYPE_MANAGED, status_.user(4).type()); - EXPECT_EQ(account_id4.GetUserEmail(), status_.user(4).email()); + EXPECT_EQ("user4@managed.com", status_.user(4).email()); EXPECT_EQ(em::DeviceUser::USER_TYPE_MANAGED, status_.user(5).type()); - EXPECT_EQ(account_id5.GetUserEmail(), status_.user(5).email()); + EXPECT_EQ("user5@managed.com", status_.user(5).email()); // Verify that users are no longer reported if setting is disabled. settings_helper_.SetBoolean(chromeos::kReportDeviceUsers, false); @@ -1303,8 +1293,7 @@ TEST_F(DeviceStatusCollectorNetworkInterfacesTest, ReportIfPublicSession) { // Report netowork state for public accounts. - user_manager_->CreatePublicAccountUser( - AccountId::FromUserEmail(kPublicAccountId)); + user_manager_->CreatePublicAccountUser(kPublicAccountId); EXPECT_CALL(*user_manager_, IsLoggedInAsPublicAccount()) .WillRepeatedly(Return(true));
diff --git a/chrome/browser/chromeos/policy/network_configuration_updater_unittest.cc b/chrome/browser/chromeos/policy/network_configuration_updater_unittest.cc index 45367bdf..8f75d38 100644 --- a/chrome/browser/chromeos/policy/network_configuration_updater_unittest.cc +++ b/chrome/browser/chromeos/policy/network_configuration_updater_unittest.cc
@@ -25,7 +25,6 @@ #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_service_impl.h" #include "components/policy/core/common/policy_types.h" -#include "components/signin/core/account_id/account_id.h" #include "components/user_manager/user.h" #include "components/user_manager/user_type.h" #include "content/public/test/test_browser_thread_bundle.h" @@ -54,7 +53,7 @@ class FakeUser : public user_manager::User { public: - FakeUser() : User(AccountId::FromUserEmail(kFakeUserEmail)) { + FakeUser() : User(kFakeUserEmail) { set_display_email(kFakeUserEmail); set_username_hash(kFakeUsernameHash); }
diff --git a/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.cc b/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.cc index 98c3026..466fd01 100644 --- a/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.cc +++ b/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.cc
@@ -69,8 +69,7 @@ // logged-in session is not possible. Fix this either by delaying the // cryptohome deletion operation or by getting rid of the in-session // wildcard check. - user_manager::UserManager::Get()->RemoveUserFromList( - AccountId::FromUserEmail(username)); + user_manager::UserManager::Get()->RemoveUserFromList(username); chrome::AttemptUserExit(); } }
diff --git a/chrome/browser/chromeos/power/extension_event_observer_unittest.cc b/chrome/browser/chromeos/power/extension_event_observer_unittest.cc index 06fff499..455fb6a 100644 --- a/chrome/browser/chromeos/power/extension_event_observer_unittest.cc +++ b/chrome/browser/chromeos/power/extension_event_observer_unittest.cc
@@ -68,11 +68,9 @@ ASSERT_TRUE(profile_manager_->SetUp()); const char kUserProfile[] = "profile1@example.com"; - const AccountId account_id(AccountId::FromUserEmail(kUserProfile)); - fake_user_manager_->AddUser(account_id); - fake_user_manager_->LoginUser(account_id); - profile_ = - profile_manager_->CreateTestingProfile(account_id.GetUserEmail()); + fake_user_manager_->AddUser(kUserProfile); + fake_user_manager_->LoginUser(kUserProfile); + profile_ = profile_manager_->CreateTestingProfile(kUserProfile); profile_manager_->SetLoggedIn(true); }
diff --git a/chrome/browser/chromeos/power/power_prefs_unittest.cc b/chrome/browser/chromeos/power/power_prefs_unittest.cc index 194e4698..00586c3 100644 --- a/chrome/browser/chromeos/power/power_prefs_unittest.cc +++ b/chrome/browser/chromeos/power/power_prefs_unittest.cc
@@ -241,11 +241,10 @@ // Set up user profile. const char test_user1[] = "test-user1@example.com"; - const AccountId test_account_id1(AccountId::FromUserEmail(test_user1)); - user_manager->AddUser(test_account_id1); - user_manager->LoginUser(test_account_id1); + user_manager->AddUser(test_user1); + user_manager->LoginUser(test_user1); TestingProfile* user_profile = - profile_manager_.CreateTestingProfile(test_account_id1.GetUserEmail()); + profile_manager_.CreateTestingProfile(test_user1); profile_manager_.SetLoggedIn(true); @@ -261,11 +260,10 @@ GetCurrentAllowScreenWakeLocks()); const char test_user2[] = "test-user2@example.com"; - const AccountId test_account_id2(AccountId::FromUserEmail(test_user2)); - user_manager->AddUser(test_account_id2); - user_manager->LoginUser(test_account_id2); + user_manager->AddUser(test_user2); + user_manager->LoginUser(test_user2); TestingProfile* other_profile = - profile_manager_.CreateTestingProfile(test_account_id2.GetUserEmail()); + profile_manager_.CreateTestingProfile(test_user2); // Inform power_prefs_ that an unrelated profile has been destroyed. power_prefs_->Observe(chrome::NOTIFICATION_PROFILE_DESTROYED,
diff --git a/chrome/browser/chromeos/preferences.cc b/chrome/browser/chromeos/preferences.cc index c5336f7..d32f60a 100644 --- a/chrome/browser/chromeos/preferences.cc +++ b/chrome/browser/chromeos/preferences.cc
@@ -400,8 +400,7 @@ const std::string& pref_name) { DCHECK(reason != REASON_PREF_CHANGED || !pref_name.empty()); const bool user_is_owner = - user_manager::UserManager::Get()->GetOwnerAccountId() == - user_->GetAccountId(); + user_manager::UserManager::Get()->GetOwnerEmail() == user_->email(); const bool user_is_active = user_->is_active(); system::TouchpadSettings touchpad_settings; @@ -626,7 +625,7 @@ reason != REASON_ACTIVE_USER_CHANGED) { const bool value = prefs_->GetBoolean(prefs::kUse24HourClock); user_manager::UserManager::Get()->SetKnownUserBooleanPref( - user_->GetAccountId(), prefs::kUse24HourClock, value); + user_->GetUserID(), prefs::kUse24HourClock, value); } }
diff --git a/chrome/browser/chromeos/preferences_chromeos_browsertest.cc b/chrome/browser/chromeos/preferences_chromeos_browsertest.cc index afbd9f5e..ef44d88 100644 --- a/chrome/browser/chromeos/preferences_chromeos_browsertest.cc +++ b/chrome/browser/chromeos/preferences_chromeos_browsertest.cc
@@ -41,11 +41,9 @@ class PreferencesTest : public LoginManagerTest { public: PreferencesTest() - : LoginManagerTest(true), input_settings_(NULL), keyboard_(NULL) { - for (size_t i = 0; i < arraysize(kTestUsers); ++i) { - test_users_.push_back(AccountId::FromUserEmail(kTestUsers[i])); - } - } + : LoginManagerTest(true), + input_settings_(NULL), + keyboard_(NULL) {} void SetUpCommandLine(base::CommandLine* command_line) override { LoginManagerTest::SetUpCommandLine(command_line); @@ -60,7 +58,7 @@ static_cast<input_method::InputMethodManagerImpl*>( input_method::InputMethodManager::Get()) ->SetImeKeyboardForTesting(keyboard_); - CrosSettings::Get()->SetString(kDeviceOwner, test_users_[0].GetUserEmail()); + CrosSettings::Get()->SetString(kDeviceOwner, kTestUsers[0]); } // Sets set of preferences in given |prefs|. Value of prefernece depends of @@ -131,8 +129,6 @@ chrome::MultiUserWindowManagerChromeOS::ANIMATION_SPEED_DISABLED); } - std::vector<AccountId> test_users_; - private: system::FakeInputDeviceSettings* input_settings_; input_method::FakeImeKeyboard* keyboard_; @@ -141,8 +137,8 @@ }; IN_PROC_BROWSER_TEST_F(PreferencesTest, PRE_MultiProfiles) { - RegisterUser(test_users_[0].GetUserEmail()); - RegisterUser(test_users_[1].GetUserEmail()); + RegisterUser(kTestUsers[0]); + RegisterUser(kTestUsers[1]); chromeos::StartupUtils::MarkOobeCompleted(); } @@ -151,8 +147,8 @@ // Add first user and init its preferences. Check that corresponding // settings has been changed. - LoginUser(test_users_[0].GetUserEmail()); - const user_manager::User* user1 = user_manager->FindUser(test_users_[0]); + LoginUser(kTestUsers[0]); + const user_manager::User* user1 = user_manager->FindUser(kTestUsers[0]); PrefService* prefs1 = ProfileHelper::Get()->GetProfileByUserUnsafe(user1)->GetPrefs(); SetPrefs(prefs1, false); @@ -163,9 +159,9 @@ UserAddingScreen::Get()->Start(); content::RunAllPendingInMessageLoop(); DisableAnimations(); - AddUser(test_users_[1].GetUserEmail()); + AddUser(kTestUsers[1]); content::RunAllPendingInMessageLoop(); - const user_manager::User* user2 = user_manager->FindUser(test_users_[1]); + const user_manager::User* user2 = user_manager->FindUser(kTestUsers[1]); EXPECT_TRUE(user2->is_active()); PrefService* prefs2 = ProfileHelper::Get()->GetProfileByUserUnsafe(user2)->GetPrefs(); @@ -198,7 +194,7 @@ // Check that changing non-owner prefs doesn't change corresponding local // state prefs and vice versa. - EXPECT_EQ(user_manager->GetOwnerAccountId(), test_users_[0]); + EXPECT_EQ(user_manager->GetOwnerEmail(), kTestUsers[0]); CheckLocalStateCorrespondsToPrefs(prefs1); prefs2->SetBoolean(prefs::kTapToClickEnabled, !prefs1->GetBoolean(prefs::kTapToClickEnabled)); @@ -208,7 +204,7 @@ CheckLocalStateCorrespondsToPrefs(prefs1); // Switch user back. - user_manager->SwitchActiveUser(test_users_[0]); + user_manager->SwitchActiveUser(kTestUsers[0]); CheckSettingsCorrespondToPrefs(prefs1); CheckLocalStateCorrespondsToPrefs(prefs1); }
diff --git a/chrome/browser/chromeos/preferences_unittest.cc b/chrome/browser/chromeos/preferences_unittest.cc index 88936630..3875cb37 100644 --- a/chrome/browser/chromeos/preferences_unittest.cc +++ b/chrome/browser/chromeos/preferences_unittest.cc
@@ -155,10 +155,9 @@ new chromeos::ScopedUserManagerEnabler(user_manager)); const char test_user_email[] = "test_user@example.com"; - const AccountId test_account_id(AccountId::FromUserEmail(test_user_email)); - test_user_ = user_manager->AddUser(test_account_id); - user_manager->LoginUser(test_account_id); - user_manager->SwitchActiveUser(test_account_id); + test_user_ = user_manager->AddUser(test_user_email); + user_manager->LoginUser(test_user_email); + user_manager->SwitchActiveUser(test_user_email); test_profile_ = profile_manager_->CreateTestingProfile( chrome::kInitialProfile);
diff --git a/chrome/browser/chromeos/printer_detector/printer_detector_unittest.cc b/chrome/browser/chromeos/printer_detector/printer_detector_unittest.cc index e547d4a..181cc2e 100644 --- a/chrome/browser/chromeos/printer_detector/printer_detector_unittest.cc +++ b/chrome/browser/chromeos/printer_detector/printer_detector_unittest.cc
@@ -103,8 +103,7 @@ } void AddTestUser() { - const user_manager::User* user = - user_manager_->AddUser(AccountId::FromUserEmail(kTestUserId)); + const user_manager::User* user = user_manager_->AddUser(kTestUserId); profile_->set_profile_name(kTestUserId); chromeos::ProfileHelper::Get()->SetUserToProfileMappingForTesting( user, profile_.get());
diff --git a/chrome/browser/chromeos/profiles/profile_helper.cc b/chrome/browser/chromeos/profiles/profile_helper.cc index ddcd388..24411c3 100644 --- a/chrome/browser/chromeos/profiles/profile_helper.cc +++ b/chrome/browser/chromeos/profiles/profile_helper.cc
@@ -170,8 +170,7 @@ ProfileHelper::Get()->GetUserByProfile(profile); if (!user) return false; - return user->GetAccountId() == - user_manager::UserManager::Get()->GetOwnerAccountId(); + return user->email() == user_manager::UserManager::Get()->GetOwnerEmail(); } // static
diff --git a/chrome/browser/chromeos/profiles/profile_list_chromeos_unittest.cc b/chrome/browser/chromeos/profiles/profile_list_chromeos_unittest.cc index c5c751ae..200eb1e5 100644 --- a/chrome/browser/chromeos/profiles/profile_list_chromeos_unittest.cc +++ b/chrome/browser/chromeos/profiles/profile_list_chromeos_unittest.cc
@@ -72,15 +72,14 @@ void AddProfile(base::string16 name, bool log_in) { std::string email_string = base::UTF16ToASCII(name) + "@example.com"; - const AccountId account_id(AccountId::FromUserEmail(email_string)); // Add a user to the fake user manager. - GetFakeChromeUserManager()->AddUser(account_id); + GetFakeChromeUserManager()->AddUser(email_string); if (log_in) - GetFakeChromeUserManager()->LoginUser(account_id); + GetFakeChromeUserManager()->LoginUser(email_string); // Create a profile for the user. - manager()->CreateTestingProfile(account_id.GetUserEmail()); + manager()->CreateTestingProfile(email_string); } AvatarMenu* GetAvatarMenu() { @@ -100,8 +99,7 @@ void ActiveUserChanged(const base::string16& name) { std::string email_string = base::UTF16ToASCII(name) + "@example.com"; - const AccountId account_id(AccountId::FromUserEmail(email_string)); - GetFakeChromeUserManager()->SwitchActiveUser(account_id); + GetFakeChromeUserManager()->SwitchActiveUser(email_string); } TestingProfileManager* manager() { return &manager_; } @@ -169,8 +167,7 @@ cache->GetUserDataDir().AppendASCII("p2"), supervised_name, std::string(), base::string16(), 0, "TEST_ID"); - GetFakeChromeUserManager()->AddUser( - AccountId::FromUserEmail(base::UTF16ToASCII(supervised_name))); + GetFakeChromeUserManager()->AddUser(base::UTF16ToASCII(supervised_name)); AvatarMenu* menu = GetAvatarMenu(); ASSERT_EQ(1U, menu->GetNumberOfItems()); @@ -246,8 +243,7 @@ // Change name of the first profile, to trigger resorting of the profiles: // now the first menu item should be named "beta", and the second be "gamma". GetFakeChromeUserManager()->SaveUserDisplayName( - AccountId::FromUserEmail(base::UTF16ToASCII(name1) + "@example.com"), - newname1); + base::UTF16ToASCII(name1) + "@example.com", newname1); manager()->profile_info_cache()->SetNameOfProfileAtIndex(0, newname1); EXPECT_EQ(1, change_count());
diff --git a/chrome/browser/chromeos/settings/device_settings_provider_unittest.cc b/chrome/browser/chromeos/settings/device_settings_provider_unittest.cc index 754e8ff4..e02000c 100644 --- a/chrome/browser/chromeos/settings/device_settings_provider_unittest.cc +++ b/chrome/browser/chromeos/settings/device_settings_provider_unittest.cc
@@ -262,8 +262,7 @@ TEST_F(DeviceSettingsProviderTest, SetPrefSucceed) { owner_key_util_->SetPrivateKey(device_policy_.GetSigningKey()); - InitOwner(AccountId::FromUserEmail(device_policy_.policy_data().username()), - true); + InitOwner(device_policy_.policy_data().username(), true); FlushDeviceSettings(); base::FundamentalValue value(true); @@ -291,8 +290,7 @@ TEST_F(DeviceSettingsProviderTest, SetPrefTwice) { owner_key_util_->SetPrivateKey(device_policy_.GetSigningKey()); - InitOwner(AccountId::FromUserEmail(device_policy_.policy_data().username()), - true); + InitOwner(device_policy_.policy_data().username(), true); FlushDeviceSettings(); EXPECT_CALL(*this, SettingChanged(_)).Times(AnyNumber()); @@ -412,8 +410,7 @@ TEST_F(DeviceSettingsProviderTest, OwnerIsStillSetWhenDeviceIsConsumerManaged) { owner_key_util_->SetPrivateKey(device_policy_.GetSigningKey()); - InitOwner(AccountId::FromUserEmail(device_policy_.policy_data().username()), - true); + InitOwner(device_policy_.policy_data().username(), true); device_policy_.policy_data().set_management_mode( em::PolicyData::CONSUMER_MANAGED); device_policy_.policy_data().set_request_token("test request token");
diff --git a/chrome/browser/chromeos/settings/device_settings_service_unittest.cc b/chrome/browser/chromeos/settings/device_settings_service_unittest.cc index a2e7b56..78cd3f90 100644 --- a/chrome/browser/chromeos/settings/device_settings_service_unittest.cc +++ b/chrome/browser/chromeos/settings/device_settings_service_unittest.cc
@@ -170,8 +170,7 @@ device_settings_service_.status()); owner_key_util_->SetPublicKeyFromPrivateKey(*device_policy_.GetSigningKey()); - InitOwner(AccountId::FromUserEmail(device_policy_.policy_data().username()), - true); + InitOwner(device_policy_.policy_data().username(), true); device_settings_service_.Store( device_policy_.GetCopy(), base::Bind(&DeviceSettingsServiceTest::SetOperationCompleted, @@ -244,8 +243,7 @@ EXPECT_EQ(DeviceSettingsService::OWNERSHIP_TAKEN, ownership_status_); owner_key_util_->SetPrivateKey(device_policy_.GetSigningKey()); - InitOwner(AccountId::FromUserEmail(device_policy_.policy_data().username()), - true); + InitOwner(device_policy_.policy_data().username(), true); device_settings_service_.GetOwnershipStatusAsync( base::Bind(&DeviceSettingsServiceTest::SetOwnershipStatus, base::Unretained(this))); @@ -269,7 +267,7 @@ device_settings_service_.GetOwnershipStatus()); const std::string& user_id = device_policy_.policy_data().username(); - InitOwner(AccountId::FromUserEmail(user_id), false); + InitOwner(user_id, false); OwnerSettingsServiceChromeOS* service = OwnerSettingsServiceChromeOSFactory::GetForBrowserContext(profile_.get()); ASSERT_TRUE(service); @@ -314,7 +312,7 @@ const std::string& user_id = device_policy_.policy_data().username(); owner_key_util_->SetPublicKeyFromPrivateKey(*device_policy_.GetSigningKey()); - InitOwner(AccountId::FromUserEmail(user_id), false); + InitOwner(user_id, false); OwnerSettingsServiceChromeOS* service = OwnerSettingsServiceChromeOSFactory::GetForBrowserContext(profile_.get()); ASSERT_TRUE(service); @@ -350,7 +348,7 @@ const std::string& user_id = device_policy_.policy_data().username(); owner_key_util_->SetPublicKeyFromPrivateKey(*device_policy_.GetSigningKey()); - InitOwner(AccountId::FromUserEmail(user_id), false); + InitOwner(user_id, false); OwnerSettingsServiceChromeOS* service = OwnerSettingsServiceChromeOSFactory::GetForBrowserContext(profile_.get()); ASSERT_TRUE(service); @@ -394,8 +392,7 @@ owner_key_util_->SetPublicKeyFromPrivateKey(*device_policy_.GetSigningKey()); owner_key_util_->SetPrivateKey(device_policy_.GetSigningKey()); - InitOwner(AccountId::FromUserEmail(device_policy_.policy_data().username()), - true); + InitOwner(device_policy_.policy_data().username(), true); ReloadDeviceSettings(); FlushDeviceSettings(); @@ -441,8 +438,7 @@ EXPECT_CALL(observer_, OwnershipStatusChanged()).Times(1); EXPECT_CALL(observer_, DeviceSettingsUpdated()).Times(1); owner_key_util_->SetPublicKeyFromPrivateKey(*device_policy_.GetSigningKey()); - InitOwner(AccountId::FromUserEmail(device_policy_.policy_data().username()), - true); + InitOwner(device_policy_.policy_data().username(), true); ReloadDeviceSettings(); Mock::VerifyAndClearExpectations(&observer_);
diff --git a/chrome/browser/chromeos/settings/device_settings_test_helper.cc b/chrome/browser/chromeos/settings/device_settings_test_helper.cc index f61155c..45236d8 100644 --- a/chrome/browser/chromeos/settings/device_settings_test_helper.cc +++ b/chrome/browser/chromeos/settings/device_settings_test_helper.cc
@@ -246,12 +246,12 @@ FlushDeviceSettings(); } -void DeviceSettingsTestBase::InitOwner(const AccountId& account_id, +void DeviceSettingsTestBase::InitOwner(const std::string& user_id, bool tpm_is_ready) { - const user_manager::User* user = user_manager_->FindUser(account_id); + const user_manager::User* user = user_manager_->FindUser(user_id); if (!user) { - user = user_manager_->AddUser(account_id); - profile_->set_profile_name(account_id.GetUserEmail()); + user = user_manager_->AddUser(user_id); + profile_->set_profile_name(user_id); ProfileHelper::Get()->SetUserToProfileMappingForTesting(user, profile_.get());
diff --git a/chrome/browser/chromeos/settings/device_settings_test_helper.h b/chrome/browser/chromeos/settings/device_settings_test_helper.h index 565116a..823c0881 100644 --- a/chrome/browser/chromeos/settings/device_settings_test_helper.h +++ b/chrome/browser/chromeos/settings/device_settings_test_helper.h
@@ -170,7 +170,7 @@ // |device_settings_service_| and flushes the resulting load operation. void ReloadDeviceSettings(); - void InitOwner(const AccountId& account_id, bool tpm_is_ready); + void InitOwner(const std::string& user_id, bool tpm_is_ready); content::TestBrowserThreadBundle thread_bundle_;
diff --git a/chrome/browser/chromeos/status/data_promo_notification_unittest.cc b/chrome/browser/chromeos/status/data_promo_notification_unittest.cc index 9eaede3..0b79555 100644 --- a/chrome/browser/chromeos/status/data_promo_notification_unittest.cc +++ b/chrome/browser/chromeos/status/data_promo_notification_unittest.cc
@@ -86,9 +86,8 @@ protected: void SetupUser() { scoped_ptr<FakeChromeUserManager> user_manager(new FakeChromeUserManager()); - const AccountId test_account_id(AccountId::FromUserEmail(kTestUserName)); - user_manager->AddUser(test_account_id); - user_manager->LoginUser(test_account_id); + user_manager->AddUser(kTestUserName); + user_manager->LoginUser(kTestUserName); user_manager_enabler_.reset( new ScopedUserManagerEnabler(user_manager.release()));
diff --git a/chrome/browser/chromeos/system/device_disabling_manager_unittest.cc b/chrome/browser/chromeos/system/device_disabling_manager_unittest.cc index 2fcf87d..d01d4dd 100644 --- a/chrome/browser/chromeos/system/device_disabling_manager_unittest.cc +++ b/chrome/browser/chromeos/system/device_disabling_manager_unittest.cc
@@ -112,7 +112,7 @@ } void DeviceDisablingManagerTestBase::LogIn() { - fake_user_manager_.AddUser(AccountId::FromUserEmail(kTestUser)); + fake_user_manager_.AddUser(kTestUser); } // Base class for tests that verify device disabling behavior during OOBE, when
diff --git a/chrome/browser/chromeos/system/tray_accessibility_browsertest.cc b/chrome/browser/chromeos/system/tray_accessibility_browsertest.cc index b6e2b8a..2badedad 100644 --- a/chrome/browser/chromeos/system/tray_accessibility_browsertest.cc +++ b/chrome/browser/chromeos/system/tray_accessibility_browsertest.cc
@@ -272,8 +272,7 @@ EXPECT_EQ(ash::user::LOGGED_IN_NONE, GetLoginStatus()); user_manager::UserManager::Get()->UserLoggedIn( - AccountId::FromUserEmail("owner@invalid.domain"), "owner@invalid.domain", - true); + "owner@invalid.domain", "owner@invalid.domain", true); user_manager::UserManager::Get()->SessionStarted(); EXPECT_EQ(ash::user::LOGGED_IN_USER, GetLoginStatus()); @@ -286,8 +285,7 @@ EXPECT_FALSE(IsTrayIconVisible()); user_manager::UserManager::Get()->UserLoggedIn( - AccountId::FromUserEmail("owner@invalid.domain"), "owner@invalid.domain", - true); + "owner@invalid.domain", "owner@invalid.domain", true); user_manager::UserManager::Get()->SessionStarted(); // Confirms that the icon is invisible just after login. @@ -352,8 +350,7 @@ IN_PROC_BROWSER_TEST_P(TrayAccessibilityTest, ShowMenu) { // Login user_manager::UserManager::Get()->UserLoggedIn( - AccountId::FromUserEmail("owner@invalid.domain"), "owner@invalid.domain", - true); + "owner@invalid.domain", "owner@invalid.domain", true); user_manager::UserManager::Get()->SessionStarted(); SetShowAccessibilityOptionsInSystemTrayMenu(false); @@ -421,8 +418,7 @@ IN_PROC_BROWSER_TEST_P(TrayAccessibilityTest, ShowMenuWithShowMenuOption) { // Login user_manager::UserManager::Get()->UserLoggedIn( - AccountId::FromUserEmail("owner@invalid.domain"), "owner@invalid.domain", - true); + "owner@invalid.domain", "owner@invalid.domain", true); user_manager::UserManager::Get()->SessionStarted(); SetShowAccessibilityOptionsInSystemTrayMenu(true);
diff --git a/chrome/browser/devtools/devtools_embedder_message_dispatcher.cc b/chrome/browser/devtools/devtools_embedder_message_dispatcher.cc index 2a45c02..0d5d585 100644 --- a/chrome/browser/devtools/devtools_embedder_message_dispatcher.cc +++ b/chrome/browser/devtools/devtools_embedder_message_dispatcher.cc
@@ -192,8 +192,9 @@ &Delegate::SetDevicesUpdatesEnabled, delegate); d->RegisterHandler("performActionOnRemotePage", &Delegate::PerformActionOnRemotePage, delegate); - d->RegisterHandler("sendMessageToBrowser", - &Delegate::SendMessageToBrowser, delegate); + d->RegisterHandler("dispatchProtocolMessage", + &Delegate::DispatchProtocolMessageFromDevToolsFrontend, + delegate); d->RegisterHandler("recordEnumeratedHistogram", &Delegate::RecordEnumeratedHistogram, delegate); d->RegisterHandlerWithCallback("sendJsonRequest",
diff --git a/chrome/browser/devtools/devtools_embedder_message_dispatcher.h b/chrome/browser/devtools/devtools_embedder_message_dispatcher.h index ebcee67..35300818 100644 --- a/chrome/browser/devtools/devtools_embedder_message_dispatcher.h +++ b/chrome/browser/devtools/devtools_embedder_message_dispatcher.h
@@ -77,7 +77,8 @@ const std::string& value) = 0; virtual void RemovePreference(const std::string& name) = 0; virtual void ClearPreferences() = 0; - virtual void SendMessageToBrowser(const std::string& message) = 0; + virtual void DispatchProtocolMessageFromDevToolsFrontend( + const std::string& message) = 0; virtual void RecordEnumeratedHistogram(const std::string& name, int sample, int boundary_value) = 0;
diff --git a/chrome/browser/devtools/devtools_ui_bindings.cc b/chrome/browser/devtools/devtools_ui_bindings.cc index e410a7b..1cb42bd 100644 --- a/chrome/browser/devtools/devtools_ui_bindings.cc +++ b/chrome/browser/devtools/devtools_ui_bindings.cc
@@ -330,8 +330,10 @@ const GURL& url, content::NavigationController::ReloadType reload_type) { devtools_bindings_->frontend_host_.reset( - content::DevToolsFrontendHost::Create(web_contents()->GetMainFrame(), - devtools_bindings_)); + content::DevToolsFrontendHost::Create( + web_contents()->GetMainFrame(), + base::Bind(&DevToolsUIBindings::HandleMessageFromDevToolsFrontend, + base::Unretained(devtools_bindings_)))); } void DevToolsUIBindings::FrontendWebContentsObserver:: @@ -496,7 +498,9 @@ DevToolsEmbedderMessageDispatcher::CreateForDevToolsFrontend(this)); frontend_host_.reset(content::DevToolsFrontendHost::Create( - web_contents_->GetMainFrame(), this)); + web_contents_->GetMainFrame(), + base::Bind(&DevToolsUIBindings::HandleMessageFromDevToolsFrontend, + base::Unretained(this)))); } DevToolsUIBindings::~DevToolsUIBindings() { @@ -551,12 +555,6 @@ params); } -void DevToolsUIBindings::HandleMessageFromDevToolsFrontendToBackend( - const std::string& message) { - if (agent_host_.get()) - agent_host_->DispatchProtocolMessage(message); -} - // content::DevToolsAgentHostClient implementation -------------------------- void DevToolsUIBindings::DispatchProtocolMessage( content::DevToolsAgentHost* agent_host, const std::string& message) { @@ -874,7 +872,8 @@ update.Get()->Clear(); } -void DevToolsUIBindings::SendMessageToBrowser(const std::string& message) { +void DevToolsUIBindings::DispatchProtocolMessageFromDevToolsFrontend( + const std::string& message) { if (agent_host_.get()) agent_host_->DispatchProtocolMessage(message); }
diff --git a/chrome/browser/devtools/devtools_ui_bindings.h b/chrome/browser/devtools/devtools_ui_bindings.h index 05e01bd..e9486924 100644 --- a/chrome/browser/devtools/devtools_ui_bindings.h +++ b/chrome/browser/devtools/devtools_ui_bindings.h
@@ -33,8 +33,7 @@ } // Base implementation of DevTools bindings around front-end. -class DevToolsUIBindings :public content::DevToolsFrontendHost::Delegate, - public DevToolsEmbedderMessageDispatcher::Delegate, +class DevToolsUIBindings : public DevToolsEmbedderMessageDispatcher::Delegate, public DevToolsAndroidBridge::DeviceCountListener, public content::DevToolsAgentHostClient, public net::URLFetcherDelegate, @@ -83,10 +82,7 @@ private: friend class WebSocketAPIChannel; - // content::DevToolsFrontendHost::Delegate implementation. - void HandleMessageFromDevToolsFrontend(const std::string& message) override; - void HandleMessageFromDevToolsFrontendToBackend( - const std::string& message) override; + void HandleMessageFromDevToolsFrontend(const std::string& message); // content::DevToolsAgentHostClient implementation. void DispatchProtocolMessage(content::DevToolsAgentHost* agent_host, @@ -134,7 +130,8 @@ void SetDevicesUpdatesEnabled(bool enabled) override; void PerformActionOnRemotePage(const std::string& page_id, const std::string& action) override; - void SendMessageToBrowser(const std::string& message) override; + void DispatchProtocolMessageFromDevToolsFrontend( + const std::string& message) override; void RecordEnumeratedHistogram(const std::string& name, int sample, int boundary_value) override;
diff --git a/chrome/browser/download/notification/download_notification_browsertest.cc b/chrome/browser/download/notification/download_notification_browsertest.cc index e2698d7..b6578d40 100644 --- a/chrome/browser/download/notification/download_notification_browsertest.cc +++ b/chrome/browser/download/notification/download_notification_browsertest.cc
@@ -1134,9 +1134,8 @@ user_manager::UserManager* const user_manager = user_manager::UserManager::Get(); if (log_in) - user_manager->UserLoggedIn(AccountId::FromUserEmail(info.email), - info.hash, false); - user_manager->SaveUserDisplayName(AccountId::FromUserEmail(info.email), + user_manager->UserLoggedIn(info.email, info.hash, false); + user_manager->SaveUserDisplayName(info.email, base::UTF8ToUTF16(info.display_name)); SigninManagerFactory::GetForProfile( chromeos::ProfileHelper::GetProfileByUserIdHash(info.hash))
diff --git a/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_apitest_chromeos.cc b/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_apitest_chromeos.cc index de9428f..963f0fd 100644 --- a/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_apitest_chromeos.cc +++ b/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_apitest_chromeos.cc
@@ -10,7 +10,6 @@ #include "chrome/browser/chromeos/ownership/fake_owner_settings_service.h" #include "chrome/browser/chromeos/settings/scoped_cros_settings_test_helper.h" #include "chrome/browser/extensions/extension_apitest.h" -#include "components/signin/core/account_id/account_id.h" #include "content/public/test/browser_test.h" #include "extensions/common/switches.h" #include "testing/gmock/include/gmock/gmock.h" @@ -56,10 +55,9 @@ user_manager_enabler_.reset( new chromeos::ScopedUserManagerEnabler(fake_user_manager_)); - const AccountId kiosk_account_id( - AccountId::FromUserEmail("kiosk@foobar.com")); - fake_user_manager_->AddKioskAppUser(kiosk_account_id); - fake_user_manager_->LoginUser(kiosk_account_id); + const std::string kKiosLogin = "kiosk@foobar.com"; + fake_user_manager_->AddKioskAppUser(kKiosLogin); + fake_user_manager_->LoginUser(kKiosLogin); } void SetAutoLaunchApp() {
diff --git a/chrome/browser/extensions/api/braille_display_private/braille_display_private_apitest.cc b/chrome/browser/extensions/api/braille_display_private/braille_display_private_apitest.cc index dba4fe3f..c3358868 100644 --- a/chrome/browser/extensions/api/braille_display_private/braille_display_private_apitest.cc +++ b/chrome/browser/extensions/api/braille_display_private/braille_display_private_apitest.cc
@@ -321,7 +321,7 @@ scoped_ptr<ScreenLockerTester> tester(ScreenLocker::GetTester()); // Log in. user_manager::UserManager::Get()->UserLoggedIn( - AccountId::FromUserEmail(kTestUserName), kTestUserName, true); + kTestUserName, kTestUserName, true); user_manager::UserManager::Get()->SessionStarted(); Profile* profile = ProfileManager::GetActiveUserProfile(); ASSERT_FALSE(
diff --git a/chrome/browser/extensions/api/file_system/file_system_api_unittest.cc b/chrome/browser/extensions/api/file_system/file_system_api_unittest.cc index 62b2775..e6df024d 100644 --- a/chrome/browser/extensions/api/file_system/file_system_api_unittest.cc +++ b/chrome/browser/extensions/api/file_system/file_system_api_unittest.cc
@@ -366,10 +366,8 @@ .SetBoolean("kiosk_enabled", true) .SetBoolean("kiosk_only", true)) .Build()); - user_manager_->AddKioskAppUser( - AccountId::FromUserEmail(auto_launch_kiosk_app->id())); - user_manager_->LoginUser( - AccountId::FromUserEmail(auto_launch_kiosk_app->id())); + user_manager_->AddKioskAppUser(auto_launch_kiosk_app->id()); + user_manager_->LoginUser(auto_launch_kiosk_app->id()); TestingConsentProviderDelegate delegate; delegate.SetIsAutoLaunched(true); @@ -395,8 +393,7 @@ .SetBoolean("kiosk_enabled", true) .SetBoolean("kiosk_only", true)) .Build()); - user_manager_->KioskAppLoggedIn( - AccountId::FromUserEmail(manual_launch_kiosk_app->id())); + user_manager_->KioskAppLoggedIn(manual_launch_kiosk_app->id()); { TestingConsentProviderDelegate delegate; delegate.SetDialogButton(ui::DIALOG_BUTTON_OK);
diff --git a/chrome/browser/extensions/api/file_system/file_system_apitest_chromeos.cc b/chrome/browser/extensions/api/file_system/file_system_apitest_chromeos.cc index 17f4dff..ca86c43 100644 --- a/chrome/browser/extensions/api/file_system/file_system_apitest_chromeos.cc +++ b/chrome/browser/extensions/api/file_system/file_system_apitest_chromeos.cc
@@ -265,10 +265,9 @@ user_manager_enabler_.reset( new chromeos::ScopedUserManagerEnabler(fake_user_manager_)); - const AccountId kiosk_app_account_id = - AccountId::FromUserEmail("kiosk@foobar.com"); - fake_user_manager_->AddKioskAppUser(kiosk_app_account_id); - fake_user_manager_->LoginUser(kiosk_app_account_id); + const std::string kKioskLogin = "kiosk@foobar.com"; + fake_user_manager_->AddKioskAppUser(kKioskLogin); + fake_user_manager_->LoginUser(kKioskLogin); } };
diff --git a/chrome/browser/extensions/api/settings_private/prefs_util.cc b/chrome/browser/extensions/api/settings_private/prefs_util.cc index 3cced57..b2c8a3c 100644 --- a/chrome/browser/extensions/api/settings_private/prefs_util.cc +++ b/chrome/browser/extensions/api/settings_private/prefs_util.cc
@@ -283,8 +283,8 @@ settings_private::PolicySource::POLICY_SOURCE_OWNER; pref_object->policy_enforcement = settings_private::PolicyEnforcement::POLICY_ENFORCEMENT_ENFORCED; - pref_object->policy_source_name.reset(new std::string( - user_manager::UserManager::Get()->GetOwnerAccountId().GetUserEmail())); + pref_object->policy_source_name.reset( + new std::string(user_manager::UserManager::Get()->GetOwnerEmail())); return pref_object.Pass(); } #endif
diff --git a/chrome/browser/extensions/crx_installer_browsertest.cc b/chrome/browser/extensions/crx_installer_browsertest.cc index 3321e784..4656593 100644 --- a/chrome/browser/extensions/crx_installer_browsertest.cc +++ b/chrome/browser/extensions/crx_installer_browsertest.cc
@@ -535,9 +535,8 @@ // lifetime of |user_manager|. chromeos::FakeChromeUserManager* fake_user_manager = new chromeos::FakeChromeUserManager(); - const AccountId account_id(AccountId::FromUserEmail("example@example.com")); - fake_user_manager->AddKioskAppUser(account_id); - fake_user_manager->LoginUser(account_id); + fake_user_manager->AddKioskAppUser("example@example.com"); + fake_user_manager->LoginUser("example@example.com"); chromeos::ScopedUserManagerEnabler scoped_user_manager(fake_user_manager); EXPECT_TRUE(InstallExtension(crx_path, 1)); #endif
diff --git a/chrome/browser/extensions/extension_assets_manager_chromeos.cc b/chrome/browser/extensions/extension_assets_manager_chromeos.cc index 5498941d..8fc3425 100644 --- a/chrome/browser/extensions/extension_assets_manager_chromeos.cc +++ b/chrome/browser/extensions/extension_assets_manager_chromeos.cc
@@ -287,8 +287,7 @@ return; } - if (user_manager->IsUserNonCryptohomeDataEphemeral( - AccountId::FromUserEmail(user_id)) || + if (user_manager->IsUserNonCryptohomeDataEphemeral(user_id) || !user_manager->IsLoggedInAsUserWithGaiaAccount()) { // Don't cache anything in shared location for ephemeral user or special // user types. @@ -531,8 +530,7 @@ NOTREACHED(); return false; } - const user_manager::User* user = - user_manager->FindUser(AccountId::FromUserEmail(user_id)); + const user_manager::User* user = user_manager->FindUser(user_id); bool not_used = false; if (!user) { not_used = true;
diff --git a/chrome/browser/extensions/extension_garbage_collector_chromeos_unittest.cc b/chrome/browser/extensions/extension_garbage_collector_chromeos_unittest.cc index 76371fc..d314314 100644 --- a/chrome/browser/extensions/extension_garbage_collector_chromeos_unittest.cc +++ b/chrome/browser/extensions/extension_garbage_collector_chromeos_unittest.cc
@@ -69,8 +69,8 @@ user_manager_enabler_.reset(new chromeos::ScopedUserManagerEnabler( new chromeos::FakeChromeUserManager)); - GetFakeUserManager()->AddUser(chromeos::login::StubAccountId()); - GetFakeUserManager()->LoginUser(chromeos::login::StubAccountId()); + GetFakeUserManager()->AddUser(chromeos::login::kStubUser); + GetFakeUserManager()->LoginUser(chromeos::login::kStubUser); chromeos::ProfileHelper::Get()->SetUserToProfileMappingForTesting( GetFakeUserManager()->GetActiveUser(), profile_.get()); }
diff --git a/chrome/browser/extensions/extension_service_sync_unittest.cc b/chrome/browser/extensions/extension_service_sync_unittest.cc new file mode 100644 index 0000000..b56d633 --- /dev/null +++ b/chrome/browser/extensions/extension_service_sync_unittest.cc
@@ -0,0 +1,1719 @@ +// 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 <string> + +#include "base/bind.h" +#include "base/command_line.h" +#include "base/files/file_util.h" +#include "base/memory/scoped_ptr.h" +#include "base/memory/weak_ptr.h" +#include "base/metrics/field_trial.h" +#include "base/test/mock_entropy_provider.h" +#include "chrome/browser/extensions/component_loader.h" +#include "chrome/browser/extensions/extension_service.h" +#include "chrome/browser/extensions/extension_service_test_with_install.h" +#include "chrome/browser/extensions/extension_sync_data.h" +#include "chrome/browser/extensions/extension_sync_service.h" +#include "chrome/browser/extensions/extension_util.h" +#include "chrome/browser/extensions/updater/extension_updater.h" +#include "chrome/browser/sync/profile_sync_service.h" +#include "chrome/browser/sync/profile_sync_service_factory.h" +#include "chrome/common/chrome_constants.h" +#include "chrome/common/chrome_switches.h" +#include "chrome/common/extensions/sync_helper.h" +#include "chrome/test/base/testing_profile.h" +#include "extensions/browser/app_sorting.h" +#include "extensions/browser/extension_prefs.h" +#include "extensions/browser/extension_registry.h" +#include "extensions/browser/extension_system.h" +#include "extensions/browser/management_policy.h" +#include "extensions/browser/test_management_policy.h" +#include "extensions/common/constants.h" +#include "extensions/common/manifest_url_handlers.h" +#include "extensions/common/permissions/permission_set.h" +#include "sync/api/fake_sync_change_processor.h" +#include "sync/api/sync_data.h" +#include "sync/api/sync_error_factory_mock.h" +#include "testing/gtest/include/gtest/gtest.h" + +#if defined(ENABLE_SUPERVISED_USERS) +#include "chrome/browser/supervised_user/permission_request_creator.h" +#include "chrome/browser/supervised_user/supervised_user_constants.h" +#include "chrome/browser/supervised_user/supervised_user_service.h" +#include "chrome/browser/supervised_user/supervised_user_service_factory.h" +#endif + +using extensions::AppSorting; +using extensions::Extension; +using extensions::ExtensionPrefs; +using extensions::ExtensionSyncData; +using extensions::ExtensionSystem; +using extensions::Manifest; +using extensions::PermissionSet; + +const char good0[] = "behllobkkfkfnphdnhnkndlbkcpglgmj"; +const char good2[] = "bjafgdebaacbbbecmhlhpofkepfkgcpa"; +const char good_crx[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf"; +const char page_action[] = "obcimlgaoabeegjmmpldobjndiealpln"; +const char theme2_crx[] = "pjpgmfcmabopnnfonnhmdjglfpjjfkbf"; + +class ExtensionServiceSyncTest + : public extensions::ExtensionServiceTestWithInstall { + public: + void MockSyncStartFlare(bool* was_called, + syncer::ModelType* model_type_passed_in, + syncer::ModelType model_type) { + *was_called = true; + *model_type_passed_in = model_type; + } + + protected: + // Paths to some of the fake extensions. + base::FilePath good0_path() { + return data_dir() + .AppendASCII("good") + .AppendASCII("Extensions") + .AppendASCII(good0) + .AppendASCII("1.0.0.0"); + } + + ExtensionSyncService* extension_sync_service() { + return ExtensionSyncService::Get(profile()); + } +}; + +TEST_F(ExtensionServiceSyncTest, DeferredSyncStartupPreInstalledComponent) { + InitializeEmptyExtensionService(); + + bool flare_was_called = false; + syncer::ModelType triggered_type(syncer::UNSPECIFIED); + base::WeakPtrFactory<ExtensionServiceSyncTest> factory(this); + extension_sync_service()->SetSyncStartFlareForTesting( + base::Bind(&ExtensionServiceSyncTest::MockSyncStartFlare, + factory.GetWeakPtr(), + &flare_was_called, // Safe due to WeakPtrFactory scope. + &triggered_type)); // Safe due to WeakPtrFactory scope. + + // Install a component extension. + std::string manifest; + ASSERT_TRUE(base::ReadFileToString( + good0_path().Append(extensions::kManifestFilename), &manifest)); + service()->component_loader()->Add(manifest, good0_path()); + ASSERT_FALSE(service()->is_ready()); + service()->Init(); + ASSERT_TRUE(service()->is_ready()); + + // Extensions added before service is_ready() don't trigger sync startup. + EXPECT_FALSE(flare_was_called); + ASSERT_EQ(syncer::UNSPECIFIED, triggered_type); +} + +TEST_F(ExtensionServiceSyncTest, DeferredSyncStartupPreInstalledNormal) { + InitializeGoodInstalledExtensionService(); + + bool flare_was_called = false; + syncer::ModelType triggered_type(syncer::UNSPECIFIED); + base::WeakPtrFactory<ExtensionServiceSyncTest> factory(this); + extension_sync_service()->SetSyncStartFlareForTesting( + base::Bind(&ExtensionServiceSyncTest::MockSyncStartFlare, + factory.GetWeakPtr(), + &flare_was_called, // Safe due to WeakPtrFactory scope. + &triggered_type)); // Safe due to WeakPtrFactory scope. + + ASSERT_FALSE(service()->is_ready()); + service()->Init(); + ASSERT_EQ(3u, loaded_.size()); + ASSERT_TRUE(service()->is_ready()); + + // Extensions added before service is_ready() don't trigger sync startup. + EXPECT_FALSE(flare_was_called); + ASSERT_EQ(syncer::UNSPECIFIED, triggered_type); +} + +TEST_F(ExtensionServiceSyncTest, DeferredSyncStartupOnInstall) { + InitializeEmptyExtensionService(); + service()->Init(); + ASSERT_TRUE(service()->is_ready()); + + bool flare_was_called = false; + syncer::ModelType triggered_type(syncer::UNSPECIFIED); + base::WeakPtrFactory<ExtensionServiceSyncTest> factory(this); + extension_sync_service()->SetSyncStartFlareForTesting( + base::Bind(&ExtensionServiceSyncTest::MockSyncStartFlare, + factory.GetWeakPtr(), + &flare_was_called, // Safe due to WeakPtrFactory scope. + &triggered_type)); // Safe due to WeakPtrFactory scope. + + base::FilePath path = data_dir().AppendASCII("good.crx"); + InstallCRX(path, INSTALL_NEW); + + EXPECT_TRUE(flare_was_called); + EXPECT_EQ(syncer::EXTENSIONS, triggered_type); + + // Reset. + flare_was_called = false; + triggered_type = syncer::UNSPECIFIED; + + // Once sync starts, flare should no longer be invoked. + extension_sync_service()->MergeDataAndStartSyncing( + syncer::EXTENSIONS, + syncer::SyncDataList(), + scoped_ptr<syncer::SyncChangeProcessor>( + new syncer::FakeSyncChangeProcessor), + scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); + path = data_dir().AppendASCII("page_action.crx"); + InstallCRX(path, INSTALL_NEW); + EXPECT_FALSE(flare_was_called); + ASSERT_EQ(syncer::UNSPECIFIED, triggered_type); +} + +TEST_F(ExtensionServiceSyncTest, DisableExtensionFromSync) { + // Start the extensions service with one external extension already installed. + base::FilePath source_install_dir = + data_dir().AppendASCII("good").AppendASCII("Extensions"); + base::FilePath pref_path = + source_install_dir.DirName().Append(chrome::kPreferencesFilename); + + InitializeInstalledExtensionService(pref_path, source_install_dir); + + // The user has enabled sync. + ProfileSyncService* sync_service = + ProfileSyncServiceFactory::GetForProfile(profile()); + sync_service->SetSyncSetupCompleted(); + + service()->Init(); + ASSERT_TRUE(service()->is_ready()); + + ASSERT_EQ(3u, loaded_.size()); + + // We start enabled. + const Extension* extension = service()->GetExtensionById(good0, true); + ASSERT_TRUE(extension); + ASSERT_TRUE(service()->IsExtensionEnabled(good0)); + + // Sync starts up. + extension_sync_service()->MergeDataAndStartSyncing( + syncer::EXTENSIONS, + syncer::SyncDataList(), + make_scoped_ptr(new syncer::FakeSyncChangeProcessor), + scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); + + // Then sync data arrives telling us to disable |good0|. + ExtensionSyncData disable_good_crx(*extension, false, + Extension::DISABLE_USER_ACTION, false, + false, ExtensionSyncData::BOOLEAN_UNSET); + syncer::SyncChange sync_change(FROM_HERE, + syncer::SyncChange::ACTION_UPDATE, + disable_good_crx.GetSyncData()); + syncer::SyncChangeList list(1, sync_change); + extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); + + ASSERT_FALSE(service()->IsExtensionEnabled(good0)); +} + +TEST_F(ExtensionServiceSyncTest, IgnoreSyncChangesWhenLocalStateIsMoreRecent) { + // Start the extension service with three extensions already installed. + base::FilePath source_install_dir = + data_dir().AppendASCII("good").AppendASCII("Extensions"); + base::FilePath pref_path = + source_install_dir.DirName().Append(chrome::kPreferencesFilename); + + InitializeInstalledExtensionService(pref_path, source_install_dir); + + // The user has enabled sync. + ProfileSyncService* sync_service = + ProfileSyncServiceFactory::GetForProfile(profile()); + sync_service->SetSyncSetupCompleted(); + // Make sure ExtensionSyncService is created, so it'll be notified of changes. + extension_sync_service(); + + service()->Init(); + ASSERT_TRUE(service()->is_ready()); + ASSERT_EQ(3u, loaded_.size()); + + ASSERT_TRUE(service()->IsExtensionEnabled(good0)); + ASSERT_TRUE(service()->IsExtensionEnabled(good2)); + + // Disable and re-enable good0 before first sync data arrives. + service()->DisableExtension(good0, Extension::DISABLE_USER_ACTION); + ASSERT_FALSE(service()->IsExtensionEnabled(good0)); + service()->EnableExtension(good0); + ASSERT_TRUE(service()->IsExtensionEnabled(good0)); + // Disable good2 before first sync data arrives (good1 is considered + // non-syncable because it has plugin permission). + service()->DisableExtension(good2, Extension::DISABLE_USER_ACTION); + ASSERT_FALSE(service()->IsExtensionEnabled(good2)); + + const Extension* extension0 = service()->GetExtensionById(good0, true); + const Extension* extension2 = service()->GetExtensionById(good2, true); + ASSERT_TRUE(extensions::sync_helper::IsSyncable(extension0)); + ASSERT_TRUE(extensions::sync_helper::IsSyncable(extension2)); + + // Now sync data comes in that says to disable good0 and enable good2. + ExtensionSyncData disable_good0(*extension0, false, + Extension::DISABLE_USER_ACTION, false, false, + ExtensionSyncData::BOOLEAN_UNSET); + ExtensionSyncData enable_good2(*extension2, true, Extension::DISABLE_NONE, + false, false, + ExtensionSyncData::BOOLEAN_UNSET); + syncer::SyncDataList sync_data; + sync_data.push_back(disable_good0.GetSyncData()); + sync_data.push_back(enable_good2.GetSyncData()); + extension_sync_service()->MergeDataAndStartSyncing( + syncer::EXTENSIONS, + sync_data, + make_scoped_ptr(new syncer::FakeSyncChangeProcessor), + make_scoped_ptr(new syncer::SyncErrorFactoryMock)); + + // Both sync changes should be ignored, since the local state was changed + // before sync started, and so the local state is considered more recent. + EXPECT_TRUE(service()->IsExtensionEnabled(good0)); + EXPECT_FALSE(service()->IsExtensionEnabled(good2)); +} + +TEST_F(ExtensionServiceSyncTest, GetSyncData) { + InitializeEmptyExtensionService(); + InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW); + const Extension* extension = service()->GetInstalledExtension(good_crx); + ASSERT_TRUE(extension); + + extension_sync_service()->MergeDataAndStartSyncing( + syncer::EXTENSIONS, + syncer::SyncDataList(), + scoped_ptr<syncer::SyncChangeProcessor>( + new syncer::FakeSyncChangeProcessor), + scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); + + syncer::SyncDataList list = + extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS); + ASSERT_EQ(list.size(), 1U); + scoped_ptr<ExtensionSyncData> data = + ExtensionSyncData::CreateFromSyncData(list[0]); + ASSERT_TRUE(data.get()); + EXPECT_EQ(extension->id(), data->id()); + EXPECT_FALSE(data->uninstalled()); + EXPECT_EQ(service()->IsExtensionEnabled(good_crx), data->enabled()); + EXPECT_EQ(extensions::util::IsIncognitoEnabled(good_crx, profile()), + data->incognito_enabled()); + EXPECT_EQ(ExtensionSyncData::BOOLEAN_UNSET, data->all_urls_enabled()); + EXPECT_TRUE(data->version().Equals(*extension->version())); + EXPECT_EQ(extensions::ManifestURL::GetUpdateURL(extension), + data->update_url()); + EXPECT_EQ(extension->name(), data->name()); +} + +TEST_F(ExtensionServiceSyncTest, GetSyncDataTerminated) { + InitializeEmptyExtensionService(); + InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW); + TerminateExtension(good_crx); + const Extension* extension = service()->GetInstalledExtension(good_crx); + ASSERT_TRUE(extension); + + syncer::FakeSyncChangeProcessor processor; + extension_sync_service()->MergeDataAndStartSyncing( + syncer::EXTENSIONS, + syncer::SyncDataList(), + scoped_ptr<syncer::SyncChangeProcessor>( + new syncer::FakeSyncChangeProcessor), + scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); + + syncer::SyncDataList list = + extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS); + ASSERT_EQ(list.size(), 1U); + scoped_ptr<ExtensionSyncData> data = + ExtensionSyncData::CreateFromSyncData(list[0]); + ASSERT_TRUE(data.get()); + EXPECT_EQ(extension->id(), data->id()); + EXPECT_FALSE(data->uninstalled()); + EXPECT_EQ(service()->IsExtensionEnabled(good_crx), data->enabled()); + EXPECT_EQ(extensions::util::IsIncognitoEnabled(good_crx, profile()), + data->incognito_enabled()); + EXPECT_EQ(ExtensionSyncData::BOOLEAN_UNSET, data->all_urls_enabled()); + EXPECT_TRUE(data->version().Equals(*extension->version())); + EXPECT_EQ(extensions::ManifestURL::GetUpdateURL(extension), + data->update_url()); + EXPECT_EQ(extension->name(), data->name()); +} + +TEST_F(ExtensionServiceSyncTest, GetSyncDataFilter) { + InitializeEmptyExtensionService(); + InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW); + const Extension* extension = service()->GetInstalledExtension(good_crx); + ASSERT_TRUE(extension); + + syncer::FakeSyncChangeProcessor processor; + extension_sync_service()->MergeDataAndStartSyncing( + syncer::APPS, + syncer::SyncDataList(), + scoped_ptr<syncer::SyncChangeProcessor>( + new syncer::FakeSyncChangeProcessor), + scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); + + syncer::SyncDataList list = + extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS); + ASSERT_EQ(list.size(), 0U); +} + +TEST_F(ExtensionServiceSyncTest, GetSyncExtensionDataUserSettings) { + InitializeEmptyExtensionService(); + InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW); + const Extension* extension = service()->GetInstalledExtension(good_crx); + ASSERT_TRUE(extension); + + syncer::FakeSyncChangeProcessor processor; + extension_sync_service()->MergeDataAndStartSyncing( + syncer::EXTENSIONS, + syncer::SyncDataList(), + scoped_ptr<syncer::SyncChangeProcessor>( + new syncer::FakeSyncChangeProcessor), + scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); + + { + syncer::SyncDataList list = + extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS); + ASSERT_EQ(list.size(), 1U); + scoped_ptr<ExtensionSyncData> data = + ExtensionSyncData::CreateFromSyncData(list[0]); + ASSERT_TRUE(data.get()); + EXPECT_TRUE(data->enabled()); + EXPECT_FALSE(data->incognito_enabled()); + EXPECT_EQ(ExtensionSyncData::BOOLEAN_UNSET, data->all_urls_enabled()); + } + + service()->DisableExtension(good_crx, Extension::DISABLE_USER_ACTION); + { + syncer::SyncDataList list = + extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS); + ASSERT_EQ(list.size(), 1U); + scoped_ptr<ExtensionSyncData> data = + ExtensionSyncData::CreateFromSyncData(list[0]); + ASSERT_TRUE(data.get()); + EXPECT_FALSE(data->enabled()); + EXPECT_FALSE(data->incognito_enabled()); + EXPECT_EQ(ExtensionSyncData::BOOLEAN_UNSET, data->all_urls_enabled()); + } + + extensions::util::SetIsIncognitoEnabled(good_crx, profile(), true); + extensions::util::SetAllowedScriptingOnAllUrls( + good_crx, profile(), false); + { + syncer::SyncDataList list = + extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS); + ASSERT_EQ(list.size(), 1U); + scoped_ptr<ExtensionSyncData> data = + ExtensionSyncData::CreateFromSyncData(list[0]); + ASSERT_TRUE(data.get()); + EXPECT_FALSE(data->enabled()); + EXPECT_TRUE(data->incognito_enabled()); + EXPECT_EQ(ExtensionSyncData::BOOLEAN_FALSE, data->all_urls_enabled()); + } + + service()->EnableExtension(good_crx); + extensions::util::SetAllowedScriptingOnAllUrls( + good_crx, profile(), true); + { + syncer::SyncDataList list = + extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS); + ASSERT_EQ(list.size(), 1U); + scoped_ptr<ExtensionSyncData> data = + ExtensionSyncData::CreateFromSyncData(list[0]); + ASSERT_TRUE(data.get()); + EXPECT_TRUE(data->enabled()); + EXPECT_TRUE(data->incognito_enabled()); + EXPECT_EQ(ExtensionSyncData::BOOLEAN_TRUE, data->all_urls_enabled()); + } +} + +TEST_F(ExtensionServiceSyncTest, SyncForUninstalledExternalExtension) { + InitializeEmptyExtensionService(); + InstallCRXWithLocation( + data_dir().AppendASCII("good.crx"), Manifest::EXTERNAL_PREF, INSTALL_NEW); + const Extension* extension = service()->GetInstalledExtension(good_crx); + ASSERT_TRUE(extension); + + syncer::FakeSyncChangeProcessor processor; + extension_sync_service()->MergeDataAndStartSyncing( + syncer::EXTENSIONS, + syncer::SyncDataList(), + scoped_ptr<syncer::SyncChangeProcessor>( + new syncer::FakeSyncChangeProcessor), + scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); + + UninstallExtension(good_crx, false); + EXPECT_TRUE( + ExtensionPrefs::Get(profile())->IsExternalExtensionUninstalled(good_crx)); + + sync_pb::EntitySpecifics specifics; + sync_pb::AppSpecifics* app_specifics = specifics.mutable_app(); + sync_pb::ExtensionSpecifics* extension_specifics = + app_specifics->mutable_extension(); + extension_specifics->set_id(good_crx); + extension_specifics->set_version("1.0"); + extension_specifics->set_enabled(true); + + syncer::SyncData sync_data = + syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); + syncer::SyncChange sync_change(FROM_HERE, + syncer::SyncChange::ACTION_UPDATE, + sync_data); + syncer::SyncChangeList list(1); + list[0] = sync_change; + + extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); + EXPECT_TRUE( + ExtensionPrefs::Get(profile())->IsExternalExtensionUninstalled(good_crx)); +} + +TEST_F(ExtensionServiceSyncTest, GetSyncAppDataUserSettings) { + InitializeEmptyExtensionService(); + const Extension* app = + PackAndInstallCRX(data_dir().AppendASCII("app"), INSTALL_NEW); + ASSERT_TRUE(app); + ASSERT_TRUE(app->is_app()); + + syncer::FakeSyncChangeProcessor processor; + extension_sync_service()->MergeDataAndStartSyncing( + syncer::APPS, + syncer::SyncDataList(), + scoped_ptr<syncer::SyncChangeProcessor>( + new syncer::FakeSyncChangeProcessor), + scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); + + syncer::StringOrdinal initial_ordinal = + syncer::StringOrdinal::CreateInitialOrdinal(); + { + syncer::SyncDataList list = + extension_sync_service()->GetAllSyncData(syncer::APPS); + ASSERT_EQ(list.size(), 1U); + + scoped_ptr<ExtensionSyncData> app_sync_data = + ExtensionSyncData::CreateFromSyncData(list[0]); + EXPECT_TRUE(initial_ordinal.Equals(app_sync_data->app_launch_ordinal())); + EXPECT_TRUE(initial_ordinal.Equals(app_sync_data->page_ordinal())); + } + + AppSorting* sorting = ExtensionPrefs::Get(profile())->app_sorting(); + sorting->SetAppLaunchOrdinal(app->id(), initial_ordinal.CreateAfter()); + { + syncer::SyncDataList list = + extension_sync_service()->GetAllSyncData(syncer::APPS); + ASSERT_EQ(list.size(), 1U); + + scoped_ptr<ExtensionSyncData> app_sync_data = + ExtensionSyncData::CreateFromSyncData(list[0]); + ASSERT_TRUE(app_sync_data.get()); + EXPECT_TRUE(initial_ordinal.LessThan(app_sync_data->app_launch_ordinal())); + EXPECT_TRUE(initial_ordinal.Equals(app_sync_data->page_ordinal())); + } + + sorting->SetPageOrdinal(app->id(), initial_ordinal.CreateAfter()); + { + syncer::SyncDataList list = + extension_sync_service()->GetAllSyncData(syncer::APPS); + ASSERT_EQ(list.size(), 1U); + + scoped_ptr<ExtensionSyncData> app_sync_data = + ExtensionSyncData::CreateFromSyncData(list[0]); + ASSERT_TRUE(app_sync_data.get()); + EXPECT_TRUE(initial_ordinal.LessThan(app_sync_data->app_launch_ordinal())); + EXPECT_TRUE(initial_ordinal.LessThan(app_sync_data->page_ordinal())); + } +} + +// TODO (rdevlin.cronin): The OnExtensionMoved() method has been removed from +// ExtensionService, so this test probably needs a new home. Unfortunately, it +// relies pretty heavily on things like InitializeExtension[Sync]Service() and +// PackAndInstallCRX(). When we clean up a bit more, this should move out. +TEST_F(ExtensionServiceSyncTest, GetSyncAppDataUserSettingsOnExtensionMoved) { + InitializeEmptyExtensionService(); + const size_t kAppCount = 3; + const Extension* apps[kAppCount]; + apps[0] = PackAndInstallCRX(data_dir().AppendASCII("app1"), INSTALL_NEW); + apps[1] = PackAndInstallCRX(data_dir().AppendASCII("app2"), INSTALL_NEW); + apps[2] = PackAndInstallCRX(data_dir().AppendASCII("app4"), INSTALL_NEW); + for (size_t i = 0; i < kAppCount; ++i) { + ASSERT_TRUE(apps[i]); + ASSERT_TRUE(apps[i]->is_app()); + } + + syncer::FakeSyncChangeProcessor processor; + extension_sync_service()->MergeDataAndStartSyncing( + syncer::APPS, + syncer::SyncDataList(), + scoped_ptr<syncer::SyncChangeProcessor>( + new syncer::FakeSyncChangeProcessor), + scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); + + ExtensionPrefs::Get(service()->GetBrowserContext()) + ->app_sorting() + ->OnExtensionMoved(apps[0]->id(), apps[1]->id(), apps[2]->id()); + { + syncer::SyncDataList list = + extension_sync_service()->GetAllSyncData(syncer::APPS); + ASSERT_EQ(list.size(), 3U); + + scoped_ptr<ExtensionSyncData> data[kAppCount]; + for (size_t i = 0; i < kAppCount; ++i) { + data[i] = ExtensionSyncData::CreateFromSyncData(list[i]); + ASSERT_TRUE(data[i].get()); + } + + // The sync data is not always in the same order our apps were installed in, + // so we do that sorting here so we can make sure the values are changed as + // expected. + syncer::StringOrdinal app_launch_ordinals[kAppCount]; + for (size_t i = 0; i < kAppCount; ++i) { + for (size_t j = 0; j < kAppCount; ++j) { + if (apps[i]->id() == data[j]->id()) + app_launch_ordinals[i] = data[j]->app_launch_ordinal(); + } + } + + EXPECT_TRUE(app_launch_ordinals[1].LessThan(app_launch_ordinals[0])); + EXPECT_TRUE(app_launch_ordinals[0].LessThan(app_launch_ordinals[2])); + } +} + +TEST_F(ExtensionServiceSyncTest, GetSyncDataList) { + InitializeEmptyExtensionService(); + InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW); + InstallCRX(data_dir().AppendASCII("page_action.crx"), INSTALL_NEW); + InstallCRX(data_dir().AppendASCII("theme.crx"), INSTALL_NEW); + InstallCRX(data_dir().AppendASCII("theme2.crx"), INSTALL_NEW); + + syncer::FakeSyncChangeProcessor processor; + extension_sync_service()->MergeDataAndStartSyncing( + syncer::APPS, + syncer::SyncDataList(), + scoped_ptr<syncer::SyncChangeProcessor>( + new syncer::FakeSyncChangeProcessor), + scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); + extension_sync_service()->MergeDataAndStartSyncing( + syncer::EXTENSIONS, + syncer::SyncDataList(), + scoped_ptr<syncer::SyncChangeProcessor>( + new syncer::FakeSyncChangeProcessor), + scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); + + service()->DisableExtension(page_action, Extension::DISABLE_USER_ACTION); + TerminateExtension(theme2_crx); + + EXPECT_EQ(0u, extension_sync_service()->GetAllSyncData(syncer::APPS).size()); + EXPECT_EQ( + 2u, extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS).size()); +} + +TEST_F(ExtensionServiceSyncTest, ProcessSyncDataUninstall) { + InitializeEmptyExtensionService(); + syncer::FakeSyncChangeProcessor processor; + extension_sync_service()->MergeDataAndStartSyncing( + syncer::EXTENSIONS, + syncer::SyncDataList(), + scoped_ptr<syncer::SyncChangeProcessor>( + new syncer::FakeSyncChangeProcessor), + scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); + + sync_pb::EntitySpecifics specifics; + sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension(); + ext_specifics->set_id(good_crx); + ext_specifics->set_version("1.0"); + syncer::SyncData sync_data = + syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); + syncer::SyncChange sync_change(FROM_HERE, + syncer::SyncChange::ACTION_DELETE, + sync_data); + syncer::SyncChangeList list(1); + list[0] = sync_change; + + // Should do nothing. + extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); + EXPECT_FALSE(service()->GetExtensionById(good_crx, true)); + + // Install the extension. + base::FilePath extension_path = data_dir().AppendASCII("good.crx"); + InstallCRX(extension_path, INSTALL_NEW); + EXPECT_TRUE(service()->GetExtensionById(good_crx, true)); + + // Should uninstall the extension. + extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); + EXPECT_FALSE(service()->GetExtensionById(good_crx, true)); + + // Should again do nothing. + extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); + EXPECT_FALSE(service()->GetExtensionById(good_crx, true)); +} + +TEST_F(ExtensionServiceSyncTest, ProcessSyncDataWrongType) { + InitializeEmptyExtensionService(); + + // Install the extension. + base::FilePath extension_path = data_dir().AppendASCII("good.crx"); + InstallCRX(extension_path, INSTALL_NEW); + EXPECT_TRUE(service()->GetExtensionById(good_crx, true)); + + sync_pb::EntitySpecifics specifics; + sync_pb::AppSpecifics* app_specifics = specifics.mutable_app(); + sync_pb::ExtensionSpecifics* extension_specifics = + app_specifics->mutable_extension(); + extension_specifics->set_id(good_crx); + extension_specifics->set_version( + service()->GetInstalledExtension(good_crx)->version()->GetString()); + + { + extension_specifics->set_enabled(true); + syncer::SyncData sync_data = + syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); + syncer::SyncChange sync_change(FROM_HERE, + syncer::SyncChange::ACTION_DELETE, + sync_data); + syncer::SyncChangeList list(1); + list[0] = sync_change; + + // Should do nothing + extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); + EXPECT_TRUE(service()->GetExtensionById(good_crx, true)); + } + + { + extension_specifics->set_enabled(false); + syncer::SyncData sync_data = + syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); + syncer::SyncChange sync_change(FROM_HERE, + syncer::SyncChange::ACTION_UPDATE, + sync_data); + syncer::SyncChangeList list(1); + list[0] = sync_change; + + // Should again do nothing. + extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); + EXPECT_TRUE(service()->GetExtensionById(good_crx, false)); + } +} + +TEST_F(ExtensionServiceSyncTest, ProcessSyncDataSettings) { + InitializeEmptyExtensionService(); + syncer::FakeSyncChangeProcessor processor; + extension_sync_service()->MergeDataAndStartSyncing( + syncer::EXTENSIONS, + syncer::SyncDataList(), + scoped_ptr<syncer::SyncChangeProcessor>( + new syncer::FakeSyncChangeProcessor), + scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); + + InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW); + EXPECT_TRUE(service()->IsExtensionEnabled(good_crx)); + EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile())); + EXPECT_FALSE(extensions::util::HasSetAllowedScriptingOnAllUrls( + good_crx, profile())); + const bool kDefaultAllowedScripting = + extensions::util::DefaultAllowedScriptingOnAllUrls(); + EXPECT_EQ(kDefaultAllowedScripting, + extensions::util::AllowedScriptingOnAllUrls(good_crx, profile())); + + sync_pb::EntitySpecifics specifics; + sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension(); + ext_specifics->set_id(good_crx); + ext_specifics->set_version( + service()->GetInstalledExtension(good_crx)->version()->GetString()); + ext_specifics->set_enabled(false); + + { + syncer::SyncData sync_data = + syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); + syncer::SyncChange sync_change(FROM_HERE, + syncer::SyncChange::ACTION_UPDATE, + sync_data); + syncer::SyncChangeList list(1); + list[0] = sync_change; + extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); + EXPECT_FALSE(service()->IsExtensionEnabled(good_crx)); + EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile())); + EXPECT_FALSE(extensions::util::HasSetAllowedScriptingOnAllUrls( + good_crx, profile())); + EXPECT_EQ(kDefaultAllowedScripting, + extensions::util::AllowedScriptingOnAllUrls(good_crx, profile())); + } + + { + ext_specifics->set_enabled(true); + ext_specifics->set_incognito_enabled(true); + syncer::SyncData sync_data = + syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); + syncer::SyncChange sync_change(FROM_HERE, + syncer::SyncChange::ACTION_UPDATE, + sync_data); + syncer::SyncChangeList list(1); + list[0] = sync_change; + extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); + EXPECT_TRUE(service()->IsExtensionEnabled(good_crx)); + EXPECT_TRUE(extensions::util::IsIncognitoEnabled(good_crx, profile())); + } + + { + ext_specifics->set_enabled(false); + ext_specifics->set_incognito_enabled(true); + syncer::SyncData sync_data = + syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); + syncer::SyncChange sync_change(FROM_HERE, + syncer::SyncChange::ACTION_UPDATE, + sync_data); + syncer::SyncChangeList list(1); + list[0] = sync_change; + extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); + EXPECT_FALSE(service()->IsExtensionEnabled(good_crx)); + EXPECT_TRUE(extensions::util::IsIncognitoEnabled(good_crx, profile())); + } + + { + ext_specifics->set_enabled(true); + ext_specifics->set_all_urls_enabled(!kDefaultAllowedScripting); + syncer::SyncData sync_data = + syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); + syncer::SyncChange sync_change(FROM_HERE, + syncer::SyncChange::ACTION_UPDATE, + sync_data); + syncer::SyncChangeList list(1); + list[0] = sync_change; + extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); + EXPECT_TRUE(service()->IsExtensionEnabled(good_crx)); + EXPECT_TRUE(extensions::util::HasSetAllowedScriptingOnAllUrls( + good_crx, profile())); + EXPECT_EQ(!kDefaultAllowedScripting, + extensions::util::AllowedScriptingOnAllUrls(good_crx, profile())); + } + + { + ext_specifics->set_all_urls_enabled(kDefaultAllowedScripting); + syncer::SyncData sync_data = + syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); + syncer::SyncChange sync_change(FROM_HERE, + syncer::SyncChange::ACTION_UPDATE, + sync_data); + syncer::SyncChangeList list(1); + list[0] = sync_change; + extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); + EXPECT_TRUE(service()->IsExtensionEnabled(good_crx)); + EXPECT_TRUE(extensions::util::HasSetAllowedScriptingOnAllUrls( + good_crx, profile())); + EXPECT_EQ(kDefaultAllowedScripting, + extensions::util::AllowedScriptingOnAllUrls(good_crx, profile())); + } + + EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(good_crx)); +} + +TEST_F(ExtensionServiceSyncTest, ProcessSyncDataNewExtension) { + InitializeEmptyExtensionService(); + syncer::FakeSyncChangeProcessor processor; + extension_sync_service()->MergeDataAndStartSyncing( + syncer::EXTENSIONS, + syncer::SyncDataList(), + scoped_ptr<syncer::SyncChangeProcessor>( + new syncer::FakeSyncChangeProcessor), + scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); + + const base::FilePath path = data_dir().AppendASCII("good.crx"); + const ExtensionPrefs* prefs = ExtensionPrefs::Get(profile()); + + struct TestCase { + const char* name; // For failure output only. + bool sync_enabled; // The "enabled" flag coming in from Sync. + // The disable reason(s) coming in from Sync, or -1 for "not set". + int sync_disable_reasons; + // The disable reason(s) that should be set on the installed extension. + // This will usually be the same as |sync_disable_reasons|, but see the + // "Legacy" case. + int expect_disable_reasons; + // Whether the extension's permissions should be auto-granted during + // installation. + bool expect_permissions_granted; + } test_cases[] = { + // Standard case: Extension comes in enabled; permissions should be granted + // during installation. + { "Standard", true, 0, 0, true }, + // If the extension comes in disabled, its permissions should still be + // granted (the user already approved them on another machine). + { "Disabled", false, Extension::DISABLE_USER_ACTION, + Extension::DISABLE_USER_ACTION, true }, + // Legacy case (<M45): No disable reasons come in from Sync (see + // crbug.com/484214). After installation, the reason should be set to + // DISABLE_UNKNOWN_FROM_SYNC. + { "Legacy", false, -1, Extension::DISABLE_UNKNOWN_FROM_SYNC, true }, + // If the extension came in disabled due to a permissions increase, then the + // user has *not* approved the permissions, and they shouldn't be granted. + // crbug.com/484214 + { "PermissionsIncrease", false, Extension::DISABLE_PERMISSIONS_INCREASE, + Extension::DISABLE_PERMISSIONS_INCREASE, false }, + }; + + for (const TestCase& test_case : test_cases) { + SCOPED_TRACE(test_case.name); + + sync_pb::EntitySpecifics specifics; + sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension(); + ext_specifics->set_id(good_crx); + ext_specifics->set_version(base::Version("1").GetString()); + ext_specifics->set_enabled(test_case.sync_enabled); + if (test_case.sync_disable_reasons != -1) + ext_specifics->set_disable_reasons(test_case.sync_disable_reasons); + + syncer::SyncData sync_data = + syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); + syncer::SyncChange sync_change(FROM_HERE, + syncer::SyncChange::ACTION_UPDATE, + sync_data); + syncer::SyncChangeList list(1, sync_change); + extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); + + ASSERT_TRUE(service()->pending_extension_manager()->IsIdPending(good_crx)); + UpdateExtension(good_crx, path, test_case.sync_enabled ? ENABLED + : DISABLED); + EXPECT_EQ(test_case.expect_disable_reasons, + prefs->GetDisableReasons(good_crx)); + scoped_ptr<const PermissionSet> permissions = + prefs->GetGrantedPermissions(good_crx); + EXPECT_EQ(test_case.expect_permissions_granted, !permissions->IsEmpty()); + ASSERT_FALSE(service()->pending_extension_manager()->IsIdPending(good_crx)); + + // Remove the extension again, so we can install it again for the next case. + UninstallExtension(good_crx, false, + test_case.sync_enabled ? Extension::ENABLED + : Extension::DISABLED); + } +} + +TEST_F(ExtensionServiceSyncTest, ProcessSyncDataTerminatedExtension) { + InitializeExtensionServiceWithUpdater(); + syncer::FakeSyncChangeProcessor processor; + extension_sync_service()->MergeDataAndStartSyncing( + syncer::EXTENSIONS, + syncer::SyncDataList(), + scoped_ptr<syncer::SyncChangeProcessor>( + new syncer::FakeSyncChangeProcessor), + scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); + + InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW); + TerminateExtension(good_crx); + EXPECT_TRUE(service()->IsExtensionEnabled(good_crx)); + EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile())); + + sync_pb::EntitySpecifics specifics; + sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension(); + ext_specifics->set_id(good_crx); + ext_specifics->set_version( + service()->GetInstalledExtension(good_crx)->version()->GetString()); + ext_specifics->set_enabled(false); + ext_specifics->set_incognito_enabled(true); + syncer::SyncData sync_data = + syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); + syncer::SyncChange sync_change(FROM_HERE, + syncer::SyncChange::ACTION_UPDATE, + sync_data); + syncer::SyncChangeList list(1); + list[0] = sync_change; + + extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); + EXPECT_FALSE(service()->IsExtensionEnabled(good_crx)); + EXPECT_TRUE(extensions::util::IsIncognitoEnabled(good_crx, profile())); + + EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(good_crx)); +} + +TEST_F(ExtensionServiceSyncTest, ProcessSyncDataVersionCheck) { + InitializeExtensionServiceWithUpdater(); + syncer::FakeSyncChangeProcessor processor; + extension_sync_service()->MergeDataAndStartSyncing( + syncer::EXTENSIONS, + syncer::SyncDataList(), + scoped_ptr<syncer::SyncChangeProcessor>( + new syncer::FakeSyncChangeProcessor), + scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); + + InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW); + EXPECT_TRUE(service()->IsExtensionEnabled(good_crx)); + EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile())); + + sync_pb::EntitySpecifics specifics; + sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension(); + ext_specifics->set_id(good_crx); + ext_specifics->set_enabled(true); + + const base::Version installed_version = + *service()->GetInstalledExtension(good_crx)->version(); + + { + ext_specifics->set_version(installed_version.GetString()); + syncer::SyncData sync_data = + syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); + syncer::SyncChange sync_change(FROM_HERE, + syncer::SyncChange::ACTION_UPDATE, + sync_data); + syncer::SyncChangeList list(1, sync_change); + + // Should do nothing if extension version == sync version. + extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); + EXPECT_FALSE(service()->updater()->WillCheckSoon()); + // Make sure the version we'll send back to sync didn't change. + syncer::SyncDataList data = + extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS); + ASSERT_EQ(1u, data.size()); + scoped_ptr<ExtensionSyncData> extension_data = + ExtensionSyncData::CreateFromSyncData(data[0]); + ASSERT_TRUE(extension_data); + EXPECT_TRUE(installed_version.Equals(extension_data->version())); + } + + // Should do nothing if extension version > sync version. + { + ext_specifics->set_version("0.0.0.0"); + syncer::SyncData sync_data = + syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); + syncer::SyncChange sync_change(FROM_HERE, + syncer::SyncChange::ACTION_UPDATE, + sync_data); + syncer::SyncChangeList list(1, sync_change); + + extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); + EXPECT_FALSE(service()->updater()->WillCheckSoon()); + // Make sure the version we'll send back to sync didn't change. + syncer::SyncDataList data = + extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS); + ASSERT_EQ(1u, data.size()); + scoped_ptr<ExtensionSyncData> extension_data = + ExtensionSyncData::CreateFromSyncData(data[0]); + ASSERT_TRUE(extension_data); + EXPECT_TRUE(installed_version.Equals(extension_data->version())); + } + + // Should kick off an update if extension version < sync version. + { + const base::Version new_version("9.9.9.9"); + ext_specifics->set_version(new_version.GetString()); + syncer::SyncData sync_data = + syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); + syncer::SyncChange sync_change(FROM_HERE, + syncer::SyncChange::ACTION_UPDATE, + sync_data); + syncer::SyncChangeList list(1, sync_change); + + extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); + EXPECT_TRUE(service()->updater()->WillCheckSoon()); + // Make sure that we'll send the NEW version back to sync, even though we + // haven't actually updated yet. This is to prevent the data in sync from + // flip-flopping back and forth until all clients are up to date. + syncer::SyncDataList data = + extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS); + ASSERT_EQ(1u, data.size()); + scoped_ptr<ExtensionSyncData> extension_data = + ExtensionSyncData::CreateFromSyncData(data[0]); + ASSERT_TRUE(extension_data); + EXPECT_TRUE(new_version.Equals(extension_data->version())); + } + + EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(good_crx)); +} + +TEST_F(ExtensionServiceSyncTest, ProcessSyncDataNotInstalled) { + InitializeExtensionServiceWithUpdater(); + syncer::FakeSyncChangeProcessor processor; + extension_sync_service()->MergeDataAndStartSyncing( + syncer::EXTENSIONS, + syncer::SyncDataList(), + scoped_ptr<syncer::SyncChangeProcessor>( + new syncer::FakeSyncChangeProcessor), + scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); + + sync_pb::EntitySpecifics specifics; + sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension(); + ext_specifics->set_id(good_crx); + ext_specifics->set_enabled(false); + ext_specifics->set_incognito_enabled(true); + ext_specifics->set_update_url("http://www.google.com/"); + ext_specifics->set_version("1.2.3.4"); + syncer::SyncData sync_data = + syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); + syncer::SyncChange sync_change(FROM_HERE, + syncer::SyncChange::ACTION_UPDATE, + sync_data); + syncer::SyncChangeList list(1); + list[0] = sync_change; + + EXPECT_TRUE(service()->IsExtensionEnabled(good_crx)); + EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile())); + extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); + EXPECT_TRUE(service()->updater()->WillCheckSoon()); + EXPECT_FALSE(service()->IsExtensionEnabled(good_crx)); + EXPECT_TRUE(extensions::util::IsIncognitoEnabled(good_crx, profile())); + + const extensions::PendingExtensionInfo* info; + EXPECT_TRUE( + (info = service()->pending_extension_manager()->GetById(good_crx))); + EXPECT_EQ(ext_specifics->update_url(), info->update_url().spec()); + EXPECT_TRUE(info->is_from_sync()); + EXPECT_EQ(Manifest::INTERNAL, info->install_source()); + // TODO(akalin): Figure out a way to test |info.ShouldAllowInstall()|. +} + +TEST_F(ExtensionServiceSyncTest, ProcessSyncDataEnableDisable) { + InitializeEmptyExtensionService(); + extension_sync_service()->MergeDataAndStartSyncing( + syncer::EXTENSIONS, + syncer::SyncDataList(), + scoped_ptr<syncer::SyncChangeProcessor>( + new syncer::FakeSyncChangeProcessor), + scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); + + const ExtensionPrefs* prefs = ExtensionPrefs::Get(profile()); + + struct TestCase { + const char* name; // For failure output only. + // Set of disable reasons before any Sync data comes in. If this is != 0, + // the extension is disabled. + int previous_disable_reasons; + bool sync_enable; // The enabled flag coming in from Sync. + // The disable reason(s) coming in from Sync, or -1 for "not set". + int sync_disable_reasons; + // The expected set of disable reasons after processing the Sync update. The + // extension should be disabled iff this is != 0. + int expect_disable_reasons; + } test_cases[] = { + { "NopEnable", 0, true, 0, 0 }, + { "NopDisable", Extension::DISABLE_USER_ACTION, false, + Extension::DISABLE_USER_ACTION, Extension::DISABLE_USER_ACTION }, + { "Disable", 0, false, Extension::DISABLE_USER_ACTION, + Extension::DISABLE_USER_ACTION }, + { "DisableLegacy", 0, false, -1, Extension::DISABLE_UNKNOWN_FROM_SYNC }, + { "AddDisableReason", Extension::DISABLE_REMOTE_INSTALL, false, + Extension::DISABLE_REMOTE_INSTALL | Extension::DISABLE_USER_ACTION, + Extension::DISABLE_REMOTE_INSTALL | Extension::DISABLE_USER_ACTION }, + { "AddDisableReasonLegacy", Extension::DISABLE_USER_ACTION, false, -1, + Extension::DISABLE_USER_ACTION | Extension::DISABLE_UNKNOWN_FROM_SYNC}, + { "RemoveDisableReason", + Extension::DISABLE_REMOTE_INSTALL | Extension::DISABLE_USER_ACTION, false, + Extension::DISABLE_USER_ACTION, Extension::DISABLE_USER_ACTION }, + { "Enable", Extension::DISABLE_USER_ACTION, true, 0, 0 }, + { "EnableLegacy", Extension::DISABLE_USER_ACTION, true, -1, 0 }, + }; + + for (const TestCase& test_case : test_cases) { + SCOPED_TRACE(test_case.name); + + std::string id; + std::string version; + // Don't keep |extension| around longer than necessary. + { + const Extension* extension = + InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW); + // The extension should now be installed and enabled. + ASSERT_TRUE(extension); + id = extension->id(); + version = extension->VersionString(); + } + ASSERT_TRUE(registry()->enabled_extensions().Contains(id)); + + // Disable it if the test case says so. + if (test_case.previous_disable_reasons) { + service()->DisableExtension(id, test_case.previous_disable_reasons); + ASSERT_TRUE(registry()->disabled_extensions().Contains(id)); + } + + // Now a sync update comes in. + sync_pb::EntitySpecifics specifics; + sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension(); + ext_specifics->set_id(id); + ext_specifics->set_enabled(test_case.sync_enable); + ext_specifics->set_version(version); + if (test_case.sync_disable_reasons != -1) + ext_specifics->set_disable_reasons(test_case.sync_disable_reasons); + + syncer::SyncData sync_data = + syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); + syncer::SyncChange sync_change(FROM_HERE, + syncer::SyncChange::ACTION_UPDATE, + sync_data); + syncer::SyncChangeList list(1, sync_change); + extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); + + // Check expectations. + const bool expect_enabled = !test_case.expect_disable_reasons; + EXPECT_EQ(expect_enabled, service()->IsExtensionEnabled(id)); + EXPECT_EQ(test_case.expect_disable_reasons, prefs->GetDisableReasons(id)); + + // Remove the extension again, so we can install it again for the next case. + UninstallExtension(id, false, expect_enabled ? Extension::ENABLED + : Extension::DISABLED); + } +} + +TEST_F(ExtensionServiceSyncTest, ProcessSyncDataDeferredEnable) { + InitializeEmptyExtensionService(); + extension_sync_service()->MergeDataAndStartSyncing( + syncer::EXTENSIONS, + syncer::SyncDataList(), + scoped_ptr<syncer::SyncChangeProcessor>( + new syncer::FakeSyncChangeProcessor), + scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); + + base::FilePath base_path = data_dir().AppendASCII("permissions_increase"); + base::FilePath pem_path = base_path.AppendASCII("permissions.pem"); + + base::FilePath path = base_path.AppendASCII("v1"); + const Extension* extension = PackAndInstallCRX(path, pem_path, INSTALL_NEW); + // The extension must now be installed and enabled. + ASSERT_TRUE(extension); + ASSERT_TRUE(registry()->enabled_extensions().Contains(extension->id())); + + // Save the id, as the extension object will be destroyed during updating. + std::string id = extension->id(); + + // Update to a new version with increased permissions. + path = base_path.AppendASCII("v2"); + PackCRXAndUpdateExtension(id, path, pem_path, DISABLED); + + // Now a sync update comes in, telling us to re-enable a *newer* version. + sync_pb::EntitySpecifics specifics; + sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension(); + ext_specifics->set_id(id); + ext_specifics->set_version("3"); + ext_specifics->set_enabled(true); + ext_specifics->set_disable_reasons(Extension::DISABLE_NONE); + + syncer::SyncData sync_data = + syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); + syncer::SyncChange sync_change(FROM_HERE, + syncer::SyncChange::ACTION_UPDATE, + sync_data); + syncer::SyncChangeList list(1, sync_change); + extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); + + // Since the version didn't match, the extension should still be disabled. + EXPECT_TRUE(registry()->disabled_extensions().Contains(id)); + + // After we update to the matching version, the extension should get enabled. + path = base_path.AppendASCII("v3"); + PackCRXAndUpdateExtension(id, path, pem_path, ENABLED); +} + +TEST_F(ExtensionServiceSyncTest, ProcessSyncDataPermissionApproval) { + // This is the update URL specified in the test extension. Setting it here is + // necessary to make it considered syncable. + base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( + switches::kAppsGalleryUpdateURL, + "http://localhost/autoupdate/updates.xml"); + + InitializeEmptyExtensionService(); + extension_sync_service()->MergeDataAndStartSyncing( + syncer::EXTENSIONS, + syncer::SyncDataList(), + scoped_ptr<syncer::SyncChangeProcessor>( + new syncer::FakeSyncChangeProcessor), + scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); + + const base::FilePath base_path = + data_dir().AppendASCII("permissions_increase"); + const base::FilePath pem_path = base_path.AppendASCII("permissions.pem"); + const base::FilePath path_v1 = base_path.AppendASCII("v1"); + const base::FilePath path_v2 = base_path.AppendASCII("v2"); + + base::ScopedTempDir crx_dir; + ASSERT_TRUE(crx_dir.CreateUniqueTempDir()); + const base::FilePath crx_path_v1 = crx_dir.path().AppendASCII("temp1.crx"); + PackCRX(path_v1, pem_path, crx_path_v1); + const base::FilePath crx_path_v2 = crx_dir.path().AppendASCII("temp2.crx"); + PackCRX(path_v2, pem_path, crx_path_v2); + + const std::string v1("1"); + const std::string v2("2"); + + const ExtensionPrefs* prefs = ExtensionPrefs::Get(profile()); + + struct TestCase { + const char* name; // For failure output only. + const std::string& sync_version; // The version coming in from Sync. + // The disable reason(s) coming in from Sync, or -1 for "not set". + int sync_disable_reasons; + // The expected set of disable reasons after processing the Sync update. The + // extension should be enabled iff this is 0. + int expect_disable_reasons; + // Whether the extension's permissions should be auto-granted. + bool expect_permissions_granted; + } test_cases[] = { + // Sync tells us to re-enable an older version. No permissions should be + // granted, since we can't be sure if the user actually approved the right + // set of permissions. + { "OldVersion", v1, 0, Extension::DISABLE_PERMISSIONS_INCREASE, false }, + // Legacy case: Sync tells us to re-enable the extension, but doesn't + // specify disable reasons. No permissions should be granted. + { "Legacy", v2, -1, Extension::DISABLE_PERMISSIONS_INCREASE, false }, + // Sync tells us to re-enable the extension and explicitly removes the + // disable reasons. Now the extension should have its permissions granted. + { "GrantPermissions", v2, 0, Extension::DISABLE_NONE, true }, + }; + + for (const TestCase& test_case : test_cases) { + SCOPED_TRACE(test_case.name); + + std::string id; + // Don't keep |extension| around longer than necessary (it'll be destroyed + // during updating). + { + const Extension* extension = InstallCRX(crx_path_v1, INSTALL_NEW); + // The extension should now be installed and enabled. + ASSERT_TRUE(extension); + ASSERT_EQ(v1, extension->VersionString()); + id = extension->id(); + } + ASSERT_TRUE(registry()->enabled_extensions().Contains(id)); + + scoped_ptr<const PermissionSet> granted_permissions_v1 = + prefs->GetGrantedPermissions(id); + + // Update to a new version with increased permissions. + UpdateExtension(id, crx_path_v2, DISABLED); + + // Now the extension should be disabled due to a permissions increase. + { + const Extension* extension = + registry()->disabled_extensions().GetByID(id); + ASSERT_TRUE(extension); + ASSERT_EQ(v2, extension->VersionString()); + } + ASSERT_TRUE(prefs->HasDisableReason( + id, Extension::DISABLE_PERMISSIONS_INCREASE)); + + // No new permissions should have been granted. + scoped_ptr<const PermissionSet> granted_permissions_v2 = + prefs->GetGrantedPermissions(id); + ASSERT_EQ(*granted_permissions_v1, *granted_permissions_v2); + + // Now a sync update comes in. + sync_pb::EntitySpecifics specifics; + sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension(); + ext_specifics->set_id(id); + ext_specifics->set_enabled(true); + ext_specifics->set_version(test_case.sync_version); + if (test_case.sync_disable_reasons != -1) + ext_specifics->set_disable_reasons(test_case.sync_disable_reasons); + + syncer::SyncData sync_data = + syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); + syncer::SyncChange sync_change(FROM_HERE, + syncer::SyncChange::ACTION_UPDATE, + sync_data); + syncer::SyncChangeList list(1, sync_change); + extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); + + // Check expectations. + const bool expect_enabled = !test_case.expect_disable_reasons; + EXPECT_EQ(expect_enabled, service()->IsExtensionEnabled(id)); + EXPECT_EQ(test_case.expect_disable_reasons, prefs->GetDisableReasons(id)); + scoped_ptr<const PermissionSet> granted_permissions = + prefs->GetGrantedPermissions(id); + if (test_case.expect_permissions_granted) { + scoped_ptr<const PermissionSet> active_permissions = + prefs->GetActivePermissions(id); + EXPECT_EQ(*granted_permissions, *active_permissions); + } else { + EXPECT_EQ(*granted_permissions, *granted_permissions_v1); + } + + // Remove the extension again, so we can install it again for the next case. + UninstallExtension(id, false, expect_enabled ? Extension::ENABLED + : Extension::DISABLED); + } +} + +#if defined(ENABLE_SUPERVISED_USERS) + +class ExtensionServiceTestSupervised : public ExtensionServiceSyncTest, + public SupervisedUserService::Delegate { + public: + void SetUp() override { + ExtensionServiceSyncTest::SetUp(); + + // This is the update URL specified in the permissions test extension. + // Setting it here is necessary to make the extension considered syncable. + base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( + switches::kAppsGalleryUpdateURL, + "http://localhost/autoupdate/updates.xml"); + } + + void TearDown() override { + supervised_user_service()->SetDelegate(nullptr); + + ExtensionServiceSyncTest::TearDown(); + } + + protected: + void InitServices(bool profile_is_supervised) { + ExtensionServiceInitParams params = CreateDefaultInitParams(); + params.profile_is_supervised = profile_is_supervised; + InitializeExtensionService(params); + + supervised_user_service()->SetDelegate(this); + supervised_user_service()->Init(); + } + + std::string InstallPermissionsTestExtension() { + const std::string version("1"); + + const Extension* extension = + PackAndInstallCRX(dir_path(version), pem_path(), INSTALL_NEW, + Extension::WAS_INSTALLED_BY_CUSTODIAN); + // The extension must now be installed and enabled. + EXPECT_TRUE(extension); + EXPECT_TRUE(registry()->enabled_extensions().Contains(extension->id())); + EXPECT_EQ(version, extension->VersionString()); + + return extension->id(); + } + + void UpdatePermissionsTestExtension(const std::string& id, + const std::string& version, + UpdateState expected_state) { + PackCRXAndUpdateExtension(id, dir_path(version), pem_path(), + expected_state); + const Extension* extension = registry()->GetInstalledExtension(id); + ASSERT_TRUE(extension); + // The version should have been updated. + EXPECT_EQ(version, extension->VersionString()); + } + + SupervisedUserService* supervised_user_service() { + return SupervisedUserServiceFactory::GetForProfile(profile()); + } + + static std::string UpdateRequestId(const std::string& extension_id, + const std::string& version) { + return SupervisedUserService::GetExtensionUpdateRequestId( + extension_id, base::Version(version)); + } + + private: + // This prevents the legacy supervised user init code from running. + bool SetActive(bool active) override { return true; } + + base::FilePath base_path() const { + return data_dir().AppendASCII("permissions_increase"); + } + base::FilePath dir_path(const std::string& version) const { + return base_path().AppendASCII("v" + version); + } + base::FilePath pem_path() const { + return base_path().AppendASCII("permissions.pem"); + } +}; + +class MockPermissionRequestCreator : public PermissionRequestCreator { + public: + MockPermissionRequestCreator() {} + ~MockPermissionRequestCreator() override {} + + bool IsEnabled() const override { return true; } + + void CreateURLAccessRequest(const GURL& url_requested, + const SuccessCallback& callback) override { + FAIL(); + } + + MOCK_METHOD2(CreateExtensionUpdateRequest, + void(const std::string& id, + const SupervisedUserService::SuccessCallback& callback)); + + private: + DISALLOW_COPY_AND_ASSIGN(MockPermissionRequestCreator); +}; + +TEST_F(ExtensionServiceTestSupervised, InstallOnlyAllowedByCustodian) { + InitServices(true /* profile_is_supervised */); + + base::FilePath path1 = data_dir().AppendASCII("good.crx"); + base::FilePath path2 = data_dir().AppendASCII("good2048.crx"); + const Extension* extensions[] = { + InstallCRX(path1, INSTALL_FAILED), + InstallCRX(path2, INSTALL_NEW, Extension::WAS_INSTALLED_BY_CUSTODIAN) + }; + + // Only the extension with the "installed by custodian" flag should have been + // installed and enabled. + EXPECT_FALSE(extensions[0]); + ASSERT_TRUE(extensions[1]); + EXPECT_TRUE(registry()->enabled_extensions().Contains(extensions[1]->id())); +} + +TEST_F(ExtensionServiceTestSupervised, PreinstalledExtension) { + InitServices(false /* profile_is_supervised */); + + // Install an extension. + base::FilePath path = data_dir().AppendASCII("good.crx"); + const Extension* extension = InstallCRX(path, INSTALL_NEW); + std::string id = extension->id(); + + // Now make the profile supervised. + profile()->AsTestingProfile()->SetSupervisedUserId( + supervised_users::kChildAccountSUID); + + // The extension should not be enabled anymore. + EXPECT_FALSE(registry()->enabled_extensions().Contains(id)); +} + +TEST_F(ExtensionServiceTestSupervised, UpdateWithoutPermissionIncrease) { + InitServices(true /* profile_is_supervised */); + + base::FilePath base_path = data_dir().AppendASCII("autoupdate"); + base::FilePath pem_path = base_path.AppendASCII("key.pem"); + + const Extension* extension = + PackAndInstallCRX(base_path.AppendASCII("v1"), pem_path, INSTALL_NEW, + Extension::WAS_INSTALLED_BY_CUSTODIAN); + // The extension must now be installed and enabled. + ASSERT_TRUE(extension); + ASSERT_TRUE(registry()->enabled_extensions().Contains(extension->id())); + + // Save the id, as the extension object will be destroyed during updating. + std::string id = extension->id(); + + std::string old_version = extension->VersionString(); + + // Update to a new version. + PackCRXAndUpdateExtension(id, base_path.AppendASCII("v2"), pem_path, ENABLED); + + // The extension should still be there and enabled. + extension = registry()->enabled_extensions().GetByID(id); + ASSERT_TRUE(extension); + // The version should have changed. + EXPECT_NE(extension->VersionString(), old_version); +} + +TEST_F(ExtensionServiceTestSupervised, UpdateWithPermissionIncreaseNoApproval) { + // Explicitly disable the "need custodian approval" field trial. + base::FieldTrialList field_trial_list(new base::MockEntropyProvider()); + base::FieldTrialList::CreateFieldTrial( + "SupervisedUserExtensionPermissionIncrease", ""); + + InitServices(true /* profile_is_supervised */); + + MockPermissionRequestCreator* creator = new MockPermissionRequestCreator; + supervised_user_service()->AddPermissionRequestCreator( + make_scoped_ptr(creator)); + + std::string id = InstallPermissionsTestExtension(); + + // Update to a new version with increased permissions. + // Since we don't require the custodian's approval, no permission request + // should be created. + const std::string version2("2"); + EXPECT_CALL(*creator, CreateExtensionUpdateRequest( + UpdateRequestId(id, version2), testing::_)) + .Times(0); + UpdatePermissionsTestExtension(id, version2, DISABLED); +} + +TEST_F(ExtensionServiceTestSupervised, + UpdateWithPermissionIncreaseApprovalOldVersion) { + // Explicitly enable the "need custodian approval" field trial. + base::FieldTrialList field_trial_list(new base::MockEntropyProvider()); + base::FieldTrialList::CreateFieldTrial( + "SupervisedUserExtensionPermissionIncrease", "NeedCustodianApproval"); + + InitServices(true /* profile_is_supervised */); + + MockPermissionRequestCreator* creator = new MockPermissionRequestCreator; + supervised_user_service()->AddPermissionRequestCreator( + make_scoped_ptr(creator)); + + const std::string version1("1"); + const std::string version2("2"); + + std::string id = InstallPermissionsTestExtension(); + + // Update to a new version with increased permissions. + EXPECT_CALL(*creator, CreateExtensionUpdateRequest( + UpdateRequestId(id, version2), testing::_)); + UpdatePermissionsTestExtension(id, version2, DISABLED); + + // Simulate a custodian approval for re-enabling the extension coming in + // through Sync, but set the old version. This can happen when there already + // was a pending request for an earlier version of the extension. + sync_pb::EntitySpecifics specifics; + sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension(); + ext_specifics->set_id(id); + ext_specifics->set_enabled(true); + ext_specifics->set_disable_reasons(Extension::DISABLE_NONE); + ext_specifics->set_installed_by_custodian(true); + ext_specifics->set_version(version1); + + // Attempting to re-enable an old version should result in a permission + // request for the current version. + EXPECT_CALL(*creator, CreateExtensionUpdateRequest( + UpdateRequestId(id, version2), testing::_)); + + syncer::SyncData sync_data = + syncer::SyncData::CreateLocalData(id, "Name", specifics); + syncer::SyncChange sync_change(FROM_HERE, syncer::SyncChange::ACTION_UPDATE, + sync_data); + syncer::SyncChangeList change_list(1, sync_change); + extension_sync_service()->ProcessSyncChanges(FROM_HERE, change_list); + // The re-enable should be ignored, since the version doesn't match. + EXPECT_FALSE(registry()->enabled_extensions().Contains(id)); + EXPECT_FALSE(extension_sync_service()->HasPendingReenable( + id, base::Version(version1))); + EXPECT_FALSE(extension_sync_service()->HasPendingReenable( + id, base::Version(version2))); +} + +TEST_F(ExtensionServiceTestSupervised, + UpdateWithPermissionIncreaseApprovalMatchingVersion) { + // Explicitly enable the "need custodian approval" field trial. + base::FieldTrialList field_trial_list(new base::MockEntropyProvider()); + base::FieldTrialList::CreateFieldTrial( + "SupervisedUserExtensionPermissionIncrease", "NeedCustodianApproval"); + + InitServices(true /* profile_is_supervised */); + + MockPermissionRequestCreator* creator = new MockPermissionRequestCreator; + supervised_user_service()->AddPermissionRequestCreator( + make_scoped_ptr(creator)); + + std::string id = InstallPermissionsTestExtension(); + + // Update to a new version with increased permissions. + const std::string version2("2"); + EXPECT_CALL(*creator, CreateExtensionUpdateRequest( + UpdateRequestId(id, version2), testing::_)); + UpdatePermissionsTestExtension(id, version2, DISABLED); + + // Simulate a custodian approval for re-enabling the extension coming in + // through Sync. + sync_pb::EntitySpecifics specifics; + sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension(); + ext_specifics->set_id(id); + ext_specifics->set_enabled(true); + ext_specifics->set_disable_reasons(Extension::DISABLE_NONE); + ext_specifics->set_installed_by_custodian(true); + ext_specifics->set_version(version2); + + syncer::SyncData sync_data = + syncer::SyncData::CreateLocalData(id, "Name", specifics); + syncer::SyncChange sync_change(FROM_HERE, syncer::SyncChange::ACTION_UPDATE, + sync_data); + syncer::SyncChangeList change_list(1, sync_change); + extension_sync_service()->ProcessSyncChanges(FROM_HERE, change_list); + // The extension should have gotten re-enabled. + EXPECT_TRUE(registry()->enabled_extensions().Contains(id)); +} + +TEST_F(ExtensionServiceTestSupervised, + UpdateWithPermissionIncreaseApprovalNewVersion) { + // Explicitly enable the "need custodian approval" field trial. + base::FieldTrialList field_trial_list(new base::MockEntropyProvider()); + base::FieldTrialList::CreateFieldTrial( + "SupervisedUserExtensionPermissionIncrease", "NeedCustodianApproval"); + + InitServices(true /* profile_is_supervised */); + + MockPermissionRequestCreator* creator = new MockPermissionRequestCreator; + supervised_user_service()->AddPermissionRequestCreator( + make_scoped_ptr(creator)); + + std::string id = InstallPermissionsTestExtension(); + + // Update to a new version with increased permissions. + const std::string version2("2"); + EXPECT_CALL(*creator, CreateExtensionUpdateRequest( + UpdateRequestId(id, version2), testing::_)); + UpdatePermissionsTestExtension(id, version2, DISABLED); + + // Simulate a custodian approval for re-enabling the extension coming in + // through Sync. Set a newer version than we have installed. + const std::string version3("3"); + sync_pb::EntitySpecifics specifics; + sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension(); + ext_specifics->set_id(id); + ext_specifics->set_enabled(true); + ext_specifics->set_disable_reasons(Extension::DISABLE_NONE); + ext_specifics->set_installed_by_custodian(true); + ext_specifics->set_version(version3); + + // This should *not* result in a new permission request. + EXPECT_CALL(*creator, CreateExtensionUpdateRequest( + UpdateRequestId(id, version3), testing::_)) + .Times(0); + + syncer::SyncData sync_data = + syncer::SyncData::CreateLocalData(id, "Name", specifics); + syncer::SyncChange sync_change(FROM_HERE, syncer::SyncChange::ACTION_UPDATE, + sync_data); + syncer::SyncChangeList change_list(1, sync_change); + extension_sync_service()->ProcessSyncChanges(FROM_HERE, change_list); + // The re-enable should be delayed until the extension is updated to the + // matching version. + EXPECT_FALSE(registry()->enabled_extensions().Contains(id)); + EXPECT_TRUE(extension_sync_service()->HasPendingReenable( + id, base::Version(version3))); + + // Update to the matching version. Now the extension should get enabled. + UpdatePermissionsTestExtension(id, version3, ENABLED); +} + +TEST_F(ExtensionServiceSyncTest, SyncUninstallByCustodianSkipsPolicy) { + InitializeEmptyExtensionService(); + extension_sync_service()->MergeDataAndStartSyncing( + syncer::EXTENSIONS, + syncer::SyncDataList(), + scoped_ptr<syncer::SyncChangeProcessor>( + new syncer::FakeSyncChangeProcessor), + scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); + + // Install two extensions. + base::FilePath path1 = data_dir().AppendASCII("good.crx"); + base::FilePath path2 = data_dir().AppendASCII("good2048.crx"); + const Extension* extensions[] = { + InstallCRX(path1, INSTALL_NEW), + InstallCRX(path2, INSTALL_NEW, Extension::WAS_INSTALLED_BY_CUSTODIAN) + }; + + // Add a policy provider that will disallow any changes. + extensions::TestManagementPolicyProvider provider( + extensions::TestManagementPolicyProvider::PROHIBIT_MODIFY_STATUS); + ExtensionSystem::Get( + browser_context())->management_policy()->RegisterProvider(&provider); + + // Create a sync deletion for each extension. + syncer::SyncChangeList change_list; + for (size_t i = 0; i < arraysize(extensions); i++) { + const std::string& id = extensions[i]->id(); + sync_pb::EntitySpecifics specifics; + sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension(); + ext_specifics->set_id(id); + ext_specifics->set_version("1.0"); + ext_specifics->set_installed_by_custodian( + extensions[i]->was_installed_by_custodian()); + syncer::SyncData sync_data = + syncer::SyncData::CreateLocalData(id, "Name", specifics); + change_list.push_back(syncer::SyncChange(FROM_HERE, + syncer::SyncChange::ACTION_DELETE, + sync_data)); + } + + // Save the extension ids, as uninstalling destroys the Extension instance. + std::string extension_ids[] = { + extensions[0]->id(), + extensions[1]->id() + }; + + // Now apply the uninstallations. + extension_sync_service()->ProcessSyncChanges(FROM_HERE, change_list); + + // Uninstalling the extension without installed_by_custodian should have been + // blocked by policy, so it should still be there. + EXPECT_TRUE(registry()->enabled_extensions().Contains(extension_ids[0])); + + // But installed_by_custodian should result in bypassing the policy check. + EXPECT_FALSE( + registry()->GenerateInstalledExtensionsSet()->Contains(extension_ids[1])); +} + +#endif // defined(ENABLE_SUPERVISED_USERS)
diff --git a/chrome/browser/extensions/extension_service_test_base.cc b/chrome/browser/extensions/extension_service_test_base.cc index 7e8052c..9276721 100644 --- a/chrome/browser/extensions/extension_service_test_base.cc +++ b/chrome/browser/extensions/extension_service_test_base.cc
@@ -8,6 +8,8 @@ #include "base/files/file_util.h" #include "base/memory/ref_counted.h" #include "base/path_service.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/stringprintf.h" #include "base/thread_task_runner_handle.h" #include "chrome/browser/extensions/component_loader.h" #include "chrome/browser/extensions/extension_error_reporter.h" @@ -187,6 +189,93 @@ thread_bundle_.reset(new content::TestBrowserThreadBundle(options)); } +size_t ExtensionServiceTestBase::GetPrefKeyCount() { + const base::DictionaryValue* dict = + profile()->GetPrefs()->GetDictionary("extensions.settings"); + if (!dict) { + ADD_FAILURE(); + return 0; + } + return dict->size(); +} + +void ExtensionServiceTestBase::ValidatePrefKeyCount(size_t count) { + EXPECT_EQ(count, GetPrefKeyCount()); +} + +testing::AssertionResult ExtensionServiceTestBase::ValidateBooleanPref( + const std::string& extension_id, + const std::string& pref_path, + bool expected_val) { + std::string msg = base::StringPrintf("while checking: %s %s == %s", + extension_id.c_str(), pref_path.c_str(), + expected_val ? "true" : "false"); + + PrefService* prefs = profile()->GetPrefs(); + const base::DictionaryValue* dict = + prefs->GetDictionary("extensions.settings"); + if (!dict) { + return testing::AssertionFailure() + << "extension.settings does not exist " << msg; + } + + const base::DictionaryValue* pref = NULL; + if (!dict->GetDictionary(extension_id, &pref)) { + return testing::AssertionFailure() + << "extension pref does not exist " << msg; + } + + bool val = false; + if (!pref->GetBoolean(pref_path, &val)) { + return testing::AssertionFailure() + << pref_path << " pref not found " << msg; + } + + return expected_val == val + ? testing::AssertionSuccess() + : testing::AssertionFailure() << "base::Value is incorrect " << msg; +} + +void ExtensionServiceTestBase::ValidateIntegerPref( + const std::string& extension_id, + const std::string& pref_path, + int expected_val) { + std::string msg = base::StringPrintf("while checking: %s %s == %s", + extension_id.c_str(), pref_path.c_str(), + base::IntToString(expected_val).c_str()); + + PrefService* prefs = profile()->GetPrefs(); + const base::DictionaryValue* dict = + prefs->GetDictionary("extensions.settings"); + ASSERT_TRUE(dict != NULL) << msg; + const base::DictionaryValue* pref = NULL; + ASSERT_TRUE(dict->GetDictionary(extension_id, &pref)) << msg; + EXPECT_TRUE(pref != NULL) << msg; + int val; + ASSERT_TRUE(pref->GetInteger(pref_path, &val)) << msg; + EXPECT_EQ(expected_val, val) << msg; +} + +void ExtensionServiceTestBase::ValidateStringPref( + const std::string& extension_id, + const std::string& pref_path, + const std::string& expected_val) { + std::string msg = base::StringPrintf("while checking: %s.manifest.%s == %s", + extension_id.c_str(), pref_path.c_str(), + expected_val.c_str()); + + const base::DictionaryValue* dict = + profile()->GetPrefs()->GetDictionary("extensions.settings"); + ASSERT_TRUE(dict != NULL) << msg; + const base::DictionaryValue* pref = NULL; + std::string manifest_path = extension_id + ".manifest"; + ASSERT_TRUE(dict->GetDictionary(manifest_path, &pref)) << msg; + EXPECT_TRUE(pref != NULL) << msg; + std::string val; + ASSERT_TRUE(pref->GetString(pref_path, &val)) << msg; + EXPECT_EQ(expected_val, val) << msg; +} + void ExtensionServiceTestBase::SetUp() { ExtensionErrorReporter::GetInstance()->ClearErrors(); }
diff --git a/chrome/browser/extensions/extension_service_test_base.h b/chrome/browser/extensions/extension_service_test_base.h index 85b4d3c4..0cb4778 100644 --- a/chrome/browser/extensions/extension_service_test_base.h +++ b/chrome/browser/extensions/extension_service_test_base.h
@@ -5,9 +5,12 @@ #ifndef CHROME_BROWSER_EXTENSIONS_EXTENSION_SERVICE_TEST_BASE_H_ #define CHROME_BROWSER_EXTENSIONS_EXTENSION_SERVICE_TEST_BASE_H_ +#include <string> + #include "base/at_exit.h" #include "base/files/file_path.h" #include "base/files/scoped_temp_dir.h" +#include "base/macros.h" #include "base/memory/scoped_ptr.h" #include "chrome/test/base/scoped_testing_local_state.h" #include "content/public/test/test_browser_thread_bundle.h" @@ -89,6 +92,20 @@ // Resets the browser thread bundle to one with |options|. void ResetThreadBundle(int options); + // Helpers to check the existence and values of extension prefs. + size_t GetPrefKeyCount(); + void ValidatePrefKeyCount(size_t count); + testing::AssertionResult ValidateBooleanPref( + const std::string& extension_id, + const std::string& pref_path, + bool expected_val); + void ValidateIntegerPref(const std::string& extension_id, + const std::string& pref_path, + int expected_val); + void ValidateStringPref(const std::string& extension_id, + const std::string& pref_path, + const std::string& expected_val); + // TODO(rdevlin.cronin): Pull out more methods from ExtensionServiceTest that // are commonly used and/or reimplemented. For instance, methods to install // extensions from various locations, etc. @@ -148,6 +165,8 @@ chromeos::ScopedTestCrosSettings test_cros_settings_; chromeos::ScopedTestUserManager test_user_manager_; #endif + + DISALLOW_COPY_AND_ASSIGN(ExtensionServiceTestBase); }; } // namespace extensions
diff --git a/chrome/browser/extensions/extension_service_test_with_install.cc b/chrome/browser/extensions/extension_service_test_with_install.cc new file mode 100644 index 0000000..ab0120e --- /dev/null +++ b/chrome/browser/extensions/extension_service_test_with_install.cc
@@ -0,0 +1,450 @@ +// 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 "chrome/browser/extensions/extension_service_test_with_install.h" + +#include "base/files/file_util.h" +#include "base/strings/utf_string_conversions.h" +#include "chrome/browser/extensions/crx_installer.h" +#include "chrome/browser/extensions/extension_creator.h" +#include "chrome/browser/extensions/extension_error_reporter.h" +#include "chrome/browser/profiles/profile.h" +#include "content/public/browser/notification_service.h" +#include "extensions/browser/extension_registry.h" +#include "extensions/browser/notification_types.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace extensions { + +namespace { + +struct ExtensionsOrder { + bool operator()(const scoped_refptr<const Extension>& a, + const scoped_refptr<const Extension>& b) { + return a->name() < b->name(); + } +}; + +// Helper method to set up a WindowedNotificationObserver to wait for a +// specific CrxInstaller to finish if we don't know the value of the +// |installer| yet. +bool IsCrxInstallerDone(extensions::CrxInstaller** installer, + const content::NotificationSource& source, + const content::NotificationDetails& details) { + return content::Source<extensions::CrxInstaller>(source).ptr() == *installer; +} + +} // namespace + +ExtensionServiceTestWithInstall::ExtensionServiceTestWithInstall() + : installed_(nullptr), + was_update_(false), + unloaded_reason_(UnloadedExtensionInfo::REASON_UNDEFINED), + expected_extensions_count_(0), + override_external_install_prompt_( + FeatureSwitch::prompt_for_external_extensions(), + false) { + // TODO(treib,devlin): This should use ExtensionRegistryObserver instead. + registrar_.Add(this, + extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED, + content::NotificationService::AllSources()); + registrar_.Add(this, + extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED, + content::NotificationService::AllSources()); + registrar_.Add( + this, + extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED, + content::NotificationService::AllSources()); +} + +ExtensionServiceTestWithInstall::~ExtensionServiceTestWithInstall() {} + +// static +std::vector<base::string16> ExtensionServiceTestWithInstall::GetErrors() { + const std::vector<base::string16>* errors = + ExtensionErrorReporter::GetInstance()->GetErrors(); + std::vector<base::string16> ret_val; + + for (const base::string16& error : *errors) { + std::string utf8_error = base::UTF16ToUTF8(error); + if (utf8_error.find(".svn") == std::string::npos) { + ret_val.push_back(error); + } + } + + // The tests rely on the errors being in a certain order, which can vary + // depending on how filesystem iteration works. + std::stable_sort(ret_val.begin(), ret_val.end()); + + return ret_val; +} + +void ExtensionServiceTestWithInstall::PackCRX(const base::FilePath& dir_path, + const base::FilePath& pem_path, + const base::FilePath& crx_path) { + // Use the existing pem key, if provided. + base::FilePath pem_output_path; + if (pem_path.value().empty()) { + pem_output_path = crx_path.DirName().AppendASCII("temp.pem"); + } else { + ASSERT_TRUE(base::PathExists(pem_path)); + } + + ASSERT_TRUE(base::DeleteFile(crx_path, false)); + + scoped_ptr<ExtensionCreator> creator(new ExtensionCreator()); + ASSERT_TRUE(creator->Run(dir_path, + crx_path, + pem_path, + pem_output_path, + ExtensionCreator::kOverwriteCRX)); + + ASSERT_TRUE(base::PathExists(crx_path)); +} + +const Extension* ExtensionServiceTestWithInstall::PackAndInstallCRX( + const base::FilePath& dir_path, + const base::FilePath& pem_path, + InstallState install_state, + int creation_flags) { + base::FilePath crx_path; + base::ScopedTempDir temp_dir; + EXPECT_TRUE(temp_dir.CreateUniqueTempDir()); + crx_path = temp_dir.path().AppendASCII("temp.crx"); + + PackCRX(dir_path, pem_path, crx_path); + return InstallCRX(crx_path, install_state, creation_flags); +} + +const Extension* ExtensionServiceTestWithInstall::PackAndInstallCRX( + const base::FilePath& dir_path, + const base::FilePath& pem_path, + InstallState install_state) { + return PackAndInstallCRX(dir_path, pem_path, install_state, + Extension::NO_FLAGS); +} + +const Extension* ExtensionServiceTestWithInstall::PackAndInstallCRX( + const base::FilePath& dir_path, + InstallState install_state) { + return PackAndInstallCRX(dir_path, base::FilePath(), install_state, + Extension::NO_FLAGS); +} + +// Attempts to install an extension. Use INSTALL_FAILED if the installation +// is expected to fail. +// If |install_state| is INSTALL_UPDATED, and |expected_old_name| is +// non-empty, expects that the existing extension's title was +// |expected_old_name|. +const Extension* ExtensionServiceTestWithInstall::InstallCRX( + const base::FilePath& path, + InstallState install_state, + int creation_flags, + const std::string& expected_old_name) { + InstallCRXInternal(path, creation_flags); + return VerifyCrxInstall(path, install_state, expected_old_name); +} + +// Attempts to install an extension. Use INSTALL_FAILED if the installation +// is expected to fail. +const Extension* ExtensionServiceTestWithInstall::InstallCRX( + const base::FilePath& path, + InstallState install_state, + int creation_flags) { + return InstallCRX(path, install_state, creation_flags, std::string()); +} + +// Attempts to install an extension. Use INSTALL_FAILED if the installation +// is expected to fail. +const Extension* ExtensionServiceTestWithInstall::InstallCRX( + const base::FilePath& path, + InstallState install_state) { + return InstallCRX(path, install_state, Extension::NO_FLAGS); +} + +const Extension* ExtensionServiceTestWithInstall::InstallCRXFromWebStore( + const base::FilePath& path, + InstallState install_state) { + InstallCRXInternal(path, Extension::FROM_WEBSTORE); + return VerifyCrxInstall(path, install_state); +} + +const Extension* ExtensionServiceTestWithInstall::InstallCRXWithLocation( + const base::FilePath& crx_path, + Manifest::Location install_location, + InstallState install_state) { + EXPECT_TRUE(base::PathExists(crx_path)) + << "Path does not exist: "<< crx_path.value().c_str(); + // no client (silent install) + scoped_refptr<CrxInstaller> installer( + CrxInstaller::CreateSilent(service())); + installer->set_install_source(install_location); + + content::WindowedNotificationObserver observer( + extensions::NOTIFICATION_CRX_INSTALLER_DONE, + content::NotificationService::AllSources()); + installer->InstallCrx(crx_path); + observer.Wait(); + + return VerifyCrxInstall(crx_path, install_state); +} + +const Extension* ExtensionServiceTestWithInstall::VerifyCrxInstall( + const base::FilePath& path, + InstallState install_state) { + return VerifyCrxInstall(path, install_state, std::string()); +} + +const Extension* ExtensionServiceTestWithInstall::VerifyCrxInstall( + const base::FilePath& path, + InstallState install_state, + const std::string& expected_old_name) { + std::vector<base::string16> errors = GetErrors(); + const Extension* extension = NULL; + if (install_state != INSTALL_FAILED) { + if (install_state == INSTALL_NEW) + ++expected_extensions_count_; + + EXPECT_TRUE(installed_) << path.value(); + // If and only if INSTALL_UPDATED, it should have the is_update flag. + EXPECT_EQ(install_state == INSTALL_UPDATED, was_update_) + << path.value(); + // If INSTALL_UPDATED, old_name_ should match the given string. + if (install_state == INSTALL_UPDATED && !expected_old_name.empty()) + EXPECT_EQ(expected_old_name, old_name_); + EXPECT_EQ(0u, errors.size()) << path.value(); + + if (install_state == INSTALL_WITHOUT_LOAD) { + EXPECT_EQ(0u, loaded_.size()) << path.value(); + } else { + EXPECT_EQ(1u, loaded_.size()) << path.value(); + size_t actual_extension_count = + registry()->enabled_extensions().size() + + registry()->disabled_extensions().size(); + EXPECT_EQ(expected_extensions_count_, actual_extension_count) << + path.value(); + extension = loaded_[0].get(); + EXPECT_TRUE(service()->GetExtensionById(extension->id(), false)) + << path.value(); + } + + for (std::vector<base::string16>::iterator err = errors.begin(); + err != errors.end(); ++err) { + LOG(ERROR) << *err; + } + } else { + EXPECT_FALSE(installed_) << path.value(); + EXPECT_EQ(0u, loaded_.size()) << path.value(); + EXPECT_EQ(1u, errors.size()) << path.value(); + } + + installed_ = NULL; + was_update_ = false; + old_name_ = ""; + loaded_.clear(); + ExtensionErrorReporter::GetInstance()->ClearErrors(); + return extension; +} + +void ExtensionServiceTestWithInstall::PackCRXAndUpdateExtension( + const std::string& id, + const base::FilePath& dir_path, + const base::FilePath& pem_path, + UpdateState expected_state) { + base::ScopedTempDir temp_dir; + EXPECT_TRUE(temp_dir.CreateUniqueTempDir()); + base::FilePath crx_path = temp_dir.path().AppendASCII("temp.crx"); + + PackCRX(dir_path, pem_path, crx_path); + UpdateExtension(id, crx_path, expected_state); +} + +void ExtensionServiceTestWithInstall::UpdateExtension( + const std::string& id, + const base::FilePath& in_path, + UpdateState expected_state) { + ASSERT_TRUE(base::PathExists(in_path)); + + // We need to copy this to a temporary location because Update() will delete + // it. + base::FilePath path = temp_dir().path(); + path = path.Append(in_path.BaseName()); + ASSERT_TRUE(base::CopyFile(in_path, path)); + + int previous_enabled_extension_count = + registry()->enabled_extensions().size(); + int previous_installed_extension_count = + previous_enabled_extension_count + + registry()->disabled_extensions().size(); + + extensions::CrxInstaller* installer = NULL; + content::WindowedNotificationObserver observer( + extensions::NOTIFICATION_CRX_INSTALLER_DONE, + base::Bind(&IsCrxInstallerDone, &installer)); + service()->UpdateExtension(extensions::CRXFileInfo(id, path), true, + &installer); + + if (installer) + observer.Wait(); + else + base::RunLoop().RunUntilIdle(); + + std::vector<base::string16> errors = GetErrors(); + int error_count = errors.size(); + int enabled_extension_count = registry()->enabled_extensions().size(); + int installed_extension_count = + enabled_extension_count + registry()->disabled_extensions().size(); + + int expected_error_count = (expected_state == FAILED) ? 1 : 0; + EXPECT_EQ(expected_error_count, error_count) << path.value(); + + if (expected_state <= FAILED) { + EXPECT_EQ(previous_enabled_extension_count, + enabled_extension_count); + EXPECT_EQ(previous_installed_extension_count, + installed_extension_count); + } else { + int expected_installed_extension_count = + (expected_state >= INSTALLED) ? 1 : 0; + int expected_enabled_extension_count = + (expected_state >= ENABLED) ? 1 : 0; + EXPECT_EQ(expected_installed_extension_count, + installed_extension_count); + EXPECT_EQ(expected_enabled_extension_count, + enabled_extension_count); + } + + // Update() should the temporary input file. + EXPECT_FALSE(base::PathExists(path)); +} + +void ExtensionServiceTestWithInstall::UninstallExtension(const std::string& id, + bool use_helper) { + UninstallExtension(id, use_helper, Extension::ENABLED); +} + +void ExtensionServiceTestWithInstall::UninstallExtension( + const std::string& id, + bool use_helper, + Extension::State expected_state) { + // Verify that the extension is installed. + base::FilePath extension_path = extensions_install_dir().AppendASCII(id); + EXPECT_TRUE(base::PathExists(extension_path)); + size_t pref_key_count = GetPrefKeyCount(); + EXPECT_GT(pref_key_count, 0u); + ValidateIntegerPref(id, "state", expected_state); + + // Uninstall it. + if (use_helper) { + EXPECT_TRUE(ExtensionService::UninstallExtensionHelper( + service(), id, extensions::UNINSTALL_REASON_FOR_TESTING)); + } else { + EXPECT_TRUE(service()->UninstallExtension( + id, + extensions::UNINSTALL_REASON_FOR_TESTING, + base::Bind(&base::DoNothing), + NULL)); + } + --expected_extensions_count_; + + // We should get an unload notification. + EXPECT_FALSE(unloaded_id_.empty()); + EXPECT_EQ(id, unloaded_id_); + + // Verify uninstalled state. + size_t new_pref_key_count = GetPrefKeyCount(); + if (new_pref_key_count == pref_key_count) { + ValidateIntegerPref(id, "state", + Extension::EXTERNAL_EXTENSION_UNINSTALLED); + } else { + EXPECT_EQ(new_pref_key_count, pref_key_count - 1); + } + + // The extension should not be in the service anymore. + EXPECT_FALSE(service()->GetInstalledExtension(id)); + base::RunLoop().RunUntilIdle(); + + // The directory should be gone. + EXPECT_FALSE(base::PathExists(extension_path)); +} + +void ExtensionServiceTestWithInstall::TerminateExtension( + const std::string& id) { + const Extension* extension = service()->GetInstalledExtension(id); + if (!extension) { + ADD_FAILURE(); + return; + } + service()->TrackTerminatedExtensionForTest(extension); +} + +void ExtensionServiceTestWithInstall::Observe( + int type, + const content::NotificationSource& source, + const content::NotificationDetails& details) { + switch (type) { + case extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED: { + const Extension* extension = + content::Details<const Extension>(details).ptr(); + loaded_.push_back(make_scoped_refptr(extension)); + // The tests rely on the errors being in a certain order, which can vary + // depending on how filesystem iteration works. + std::stable_sort(loaded_.begin(), loaded_.end(), ExtensionsOrder()); + break; + } + + case extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED: { + UnloadedExtensionInfo* unloaded_info = + content::Details<UnloadedExtensionInfo>(details).ptr(); + const Extension* e = unloaded_info->extension; + unloaded_id_ = e->id(); + unloaded_reason_ = unloaded_info->reason; + extensions::ExtensionList::iterator i = + std::find(loaded_.begin(), loaded_.end(), e); + // TODO(erikkay) fix so this can be an assert. Right now the tests + // are manually calling clear() on loaded_, so this isn't doable. + if (i == loaded_.end()) + return; + loaded_.erase(i); + break; + } + case extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED: { + const extensions::InstalledExtensionInfo* installed_info = + content::Details<const extensions::InstalledExtensionInfo>(details) + .ptr(); + installed_ = installed_info->extension; + was_update_ = installed_info->is_update; + old_name_ = installed_info->old_name; + break; + } + + default: + DCHECK(false); + } +} + +// Create a CrxInstaller and install the CRX file. +// Instead of calling this method yourself, use InstallCRX(), which does extra +// error checking. +void ExtensionServiceTestWithInstall::InstallCRXInternal( + const base::FilePath& crx_path, + int creation_flags) { + ASSERT_TRUE(base::PathExists(crx_path)) + << "Path does not exist: "<< crx_path.value().c_str(); + scoped_refptr<CrxInstaller> installer( + CrxInstaller::CreateSilent(service())); + installer->set_creation_flags(creation_flags); + if (!(creation_flags & Extension::WAS_INSTALLED_BY_DEFAULT)) + installer->set_allow_silent_install(true); + + content::WindowedNotificationObserver observer( + extensions::NOTIFICATION_CRX_INSTALLER_DONE, + content::Source<extensions::CrxInstaller>(installer.get())); + + installer->InstallCrx(crx_path); + + observer.Wait(); +} + +} // namespace extensions
diff --git a/chrome/browser/extensions/extension_service_test_with_install.h b/chrome/browser/extensions/extension_service_test_with_install.h new file mode 100644 index 0000000..cfafca28 --- /dev/null +++ b/chrome/browser/extensions/extension_service_test_with_install.h
@@ -0,0 +1,133 @@ +// 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 CHROME_BROWSER_EXTENSIONS_EXTENSION_SERVICE_TEST_WITH_INSTALL_H_ +#define CHROME_BROWSER_EXTENSIONS_EXTENSION_SERVICE_TEST_WITH_INSTALL_H_ + +#include <string> + +#include "base/files/file_path.h" +#include "base/macros.h" +#include "chrome/browser/extensions/extension_service_test_base.h" +#include "content/public/browser/notification_observer.h" +#include "content/public/browser/notification_registrar.h" +#include "extensions/common/extension.h" +#include "extensions/common/feature_switch.h" + +namespace extensions { + +// An enhancement of ExtensionServiceTestBase that provides helpers to install, +// update, and uninstall extensions. +class ExtensionServiceTestWithInstall : public ExtensionServiceTestBase, + public content::NotificationObserver { + public: + ExtensionServiceTestWithInstall(); + ~ExtensionServiceTestWithInstall() override; + + protected: + static std::vector<base::string16> GetErrors(); + + void PackCRX(const base::FilePath& dir_path, + const base::FilePath& pem_path, + const base::FilePath& crx_path); + + enum InstallState { + INSTALL_FAILED, + INSTALL_UPDATED, + INSTALL_NEW, + INSTALL_WITHOUT_LOAD, + }; + + const Extension* PackAndInstallCRX(const base::FilePath& dir_path, + const base::FilePath& pem_path, + InstallState install_state, + int creation_flags); + const Extension* PackAndInstallCRX(const base::FilePath& dir_path, + const base::FilePath& pem_path, + InstallState install_state); + const Extension* PackAndInstallCRX(const base::FilePath& dir_path, + InstallState install_state); + + const Extension* InstallCRX(const base::FilePath& path, + InstallState install_state, + int creation_flags, + const std::string& expected_old_name); + const Extension* InstallCRX(const base::FilePath& path, + InstallState install_state, + int creation_flags); + const Extension* InstallCRX(const base::FilePath& path, + InstallState install_state); + const Extension* InstallCRXFromWebStore(const base::FilePath& path, + InstallState install_state); + const Extension* InstallCRXWithLocation(const base::FilePath& crx_path, + Manifest::Location install_location, + InstallState install_state); + + // Verifies the result of a CRX installation. Used by InstallCRX. Set the + // |install_state| to INSTALL_FAILED if the installation is expected to fail. + // Returns an Extension pointer if the install succeeded, null otherwise. + const Extension* VerifyCrxInstall(const base::FilePath& path, + InstallState install_state); + + // Verifies the result of a CRX installation. Used by InstallCRX. Set the + // |install_state| to INSTALL_FAILED if the installation is expected to fail. + // If |install_state| is INSTALL_UPDATED, and |expected_old_name| is + // non-empty, expects that the existing extension's title was + // |expected_old_name|. + // Returns an Extension pointer if the install succeeded, null otherwise. + const Extension* VerifyCrxInstall(const base::FilePath& path, + InstallState install_state, + const std::string& expected_old_name); + + enum UpdateState { + FAILED_SILENTLY, + FAILED, + UPDATED, + INSTALLED, + DISABLED, + ENABLED + }; + + void PackCRXAndUpdateExtension(const std::string& id, + const base::FilePath& dir_path, + const base::FilePath& pem_path, + UpdateState expected_state); + + void UpdateExtension(const std::string& id, + const base::FilePath& in_path, + UpdateState expected_state); + + void UninstallExtension(const std::string& id, bool use_helper); + void UninstallExtension(const std::string& id, + bool use_helper, + Extension::State expected_state); + + void TerminateExtension(const std::string& id); + + // TODO(treib,devlin): Make these private and add accessors as needed. + extensions::ExtensionList loaded_; + const Extension* installed_; + bool was_update_; + std::string old_name_; + std::string unloaded_id_; + UnloadedExtensionInfo::Reason unloaded_reason_; + + private: + void Observe(int type, + const content::NotificationSource& source, + const content::NotificationDetails& details) override; + + void InstallCRXInternal(const base::FilePath& crx_path, int creation_flags); + + content::NotificationRegistrar registrar_; + size_t expected_extensions_count_; + + FeatureSwitch::ScopedOverride override_external_install_prompt_; + + DISALLOW_COPY_AND_ASSIGN(ExtensionServiceTestWithInstall); +}; + +} // namespace extensions + +#endif // CHROME_BROWSER_EXTENSIONS_EXTENSION_SERVICE_TEST_WITH_INSTALL_H_
diff --git a/chrome/browser/extensions/extension_service_unittest.cc b/chrome/browser/extensions/extension_service_unittest.cc index 55feea1..fe34252 100644 --- a/chrome/browser/extensions/extension_service_unittest.cc +++ b/chrome/browser/extensions/extension_service_unittest.cc
@@ -3,7 +3,9 @@ // found in the LICENSE file. #include <algorithm> +#include <map> #include <set> +#include <string> #include <vector> #include "base/at_exit.h" @@ -19,7 +21,6 @@ #include "base/location.h" #include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" -#include "base/metrics/field_trial.h" #include "base/prefs/scoped_user_pref_update.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" @@ -28,7 +29,6 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" -#include "base/test/mock_entropy_provider.h" #include "base/thread_task_runner_handle.h" #include "base/version.h" #include "chrome/browser/browser_process.h" @@ -44,9 +44,8 @@ #include "chrome/browser/extensions/extension_management_test_util.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_service_test_base.h" +#include "chrome/browser/extensions/extension_service_test_with_install.h" #include "chrome/browser/extensions/extension_special_storage_policy.h" -#include "chrome/browser/extensions/extension_sync_data.h" -#include "chrome/browser/extensions/extension_sync_service.h" #include "chrome/browser/extensions/extension_util.h" #include "chrome/browser/extensions/external_install_error.h" #include "chrome/browser/extensions/external_install_manager.h" @@ -65,14 +64,11 @@ #include "chrome/browser/extensions/updater/extension_updater.h" #include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/policy/profile_policy_connector_factory.h" -#include "chrome/browser/sync/profile_sync_service.h" -#include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/api/plugins/plugins_handler.h" #include "chrome/common/extensions/manifest_handlers/app_launch_info.h" #include "chrome/common/extensions/manifest_handlers/content_scripts_handler.h" -#include "chrome/common/extensions/sync_helper.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/scoped_browser_locale.h" @@ -84,7 +80,6 @@ #include "content/public/browser/dom_storage_context.h" #include "content/public/browser/gpu_data_manager.h" #include "content/public/browser/indexed_db_context.h" -#include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/plugin_service.h" #include "content/public/browser/render_process_host.h" @@ -107,7 +102,6 @@ #include "extensions/common/extension_builder.h" #include "extensions/common/extension_l10n_util.h" #include "extensions/common/extension_resource.h" -#include "extensions/common/feature_switch.h" #include "extensions/common/manifest_constants.h" #include "extensions/common/manifest_handlers/background_info.h" #include "extensions/common/manifest_handlers/permissions_parser.h" @@ -128,28 +122,14 @@ #include "storage/browser/database/database_tracker.h" #include "storage/browser/quota/quota_manager.h" #include "storage/common/database/database_identifier.h" -#include "sync/api/fake_sync_change_processor.h" #include "sync/api/string_ordinal.h" -#include "sync/api/sync_data.h" -#include "sync/api/sync_error_factory.h" -#include "sync/api/sync_error_factory_mock.h" -#include "sync/api/syncable_service.h" -#include "sync/protocol/app_specifics.pb.h" -#include "sync/protocol/extension_specifics.pb.h" -#include "sync/protocol/sync.pb.h" +#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/material_design/material_design_controller.h" #include "url/gurl.h" -#if defined(ENABLE_SUPERVISED_USERS) -#include "chrome/browser/supervised_user/permission_request_creator.h" -#include "chrome/browser/supervised_user/supervised_user_constants.h" -#include "chrome/browser/supervised_user/supervised_user_service.h" -#include "chrome/browser/supervised_user/supervised_user_service_factory.h" -#endif - #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/login/users/scoped_test_user_manager.h" #include "chrome/browser/chromeos/settings/cros_settings.h" @@ -161,9 +141,6 @@ #define ENABLE_BLACKLIST_TESTS #endif -using base::DictionaryValue; -using base::ListValue; -using base::Value; using content::BrowserContext; using content::BrowserThread; using content::DOMStorageContext; @@ -179,7 +156,6 @@ using extensions::ExtensionPrefs; using extensions::ExtensionRegistry; using extensions::ExtensionResource; -using extensions::ExtensionSyncData; using extensions::ExtensionSystem; using extensions::FakeSafeBrowsingDatabaseManager; using extensions::FeatureSwitch; @@ -208,33 +184,6 @@ const char updates_from_webstore[] = "akjooamlhcgeopfifcmlggaebeocgokj"; const char permissions_blocklist[] = "noffkehfcaggllbcojjbopcmlhcnhcdn"; -struct ExtensionsOrder { - bool operator()(const scoped_refptr<const Extension>& a, - const scoped_refptr<const Extension>& b) { - return a->name() < b->name(); - } -}; - -static std::vector<base::string16> GetErrors() { - const std::vector<base::string16>* errors = - ExtensionErrorReporter::GetInstance()->GetErrors(); - std::vector<base::string16> ret_val; - - for (std::vector<base::string16>::const_iterator iter = errors->begin(); - iter != errors->end(); ++iter) { - std::string utf8_error = base::UTF16ToUTF8(*iter); - if (utf8_error.find(".svn") == std::string::npos) { - ret_val.push_back(*iter); - } - } - - // The tests rely on the errors being in a certain order, which can vary - // depending on how filesystem iteration works. - std::stable_sort(ret_val.begin(), ret_val.end()); - - return ret_val; -} - static void AddPattern(URLPatternSet* extent, const std::string& pattern) { int schemes = URLPattern::SCHEME_ALL; extent->AddPattern(URLPattern(schemes, pattern)); @@ -480,95 +429,16 @@ DISALLOW_COPY_AND_ASSIGN(MockProviderVisitor); }; -class ExtensionServiceTest : public extensions::ExtensionServiceTestBase, - public content::NotificationObserver { +class ExtensionServiceTest + : public extensions::ExtensionServiceTestWithInstall { public: - ExtensionServiceTest() - : unloaded_reason_(UnloadedExtensionInfo::REASON_UNDEFINED), - installed_(NULL), - was_update_(false), - override_external_install_prompt_( - FeatureSwitch::prompt_for_external_extensions(), - false), - expected_extensions_count_(0) { - registrar_.Add(this, - extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED, - content::NotificationService::AllSources()); - registrar_.Add(this, - extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED, - content::NotificationService::AllSources()); - registrar_.Add( - this, - extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED, - content::NotificationService::AllSources()); - } - - void Observe(int type, - const content::NotificationSource& source, - const content::NotificationDetails& details) override { - switch (type) { - case extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED: { - const Extension* extension = - content::Details<const Extension>(details).ptr(); - loaded_.push_back(make_scoped_refptr(extension)); - // The tests rely on the errors being in a certain order, which can vary - // depending on how filesystem iteration works. - std::stable_sort(loaded_.begin(), loaded_.end(), ExtensionsOrder()); - break; - } - - case extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED: { - UnloadedExtensionInfo* unloaded_info = - content::Details<UnloadedExtensionInfo>(details).ptr(); - const Extension* e = unloaded_info->extension; - unloaded_id_ = e->id(); - unloaded_reason_ = unloaded_info->reason; - extensions::ExtensionList::iterator i = - std::find(loaded_.begin(), loaded_.end(), e); - // TODO(erikkay) fix so this can be an assert. Right now the tests - // are manually calling clear() on loaded_, so this isn't doable. - if (i == loaded_.end()) - return; - loaded_.erase(i); - break; - } - case extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED: { - const extensions::InstalledExtensionInfo* installed_info = - content::Details<const extensions::InstalledExtensionInfo>(details) - .ptr(); - installed_ = installed_info->extension; - was_update_ = installed_info->is_update; - old_name_ = installed_info->old_name; - break; - } - - default: - DCHECK(false); - } - } - void AddMockExternalProvider( extensions::ExternalProviderInterface* provider) { service()->AddProviderForTesting(provider); } - void MockSyncStartFlare(bool* was_called, - syncer::ModelType* model_type_passed_in, - syncer::ModelType model_type) { - *was_called = true; - *model_type_passed_in = model_type; - } - protected: // Paths to some of the fake extensions. - base::FilePath good0_path() { - return data_dir() - .AppendASCII("good") - .AppendASCII("Extensions") - .AppendASCII(good0) - .AppendASCII("1.0.0.0"); - } - base::FilePath good1_path() { return data_dir() .AppendASCII("good") @@ -588,188 +458,6 @@ void TestExternalProvider(MockExtensionProvider* provider, Manifest::Location location); - void PackCRX(const base::FilePath& dir_path, - const base::FilePath& pem_path, - const base::FilePath& crx_path) { - // Use the existing pem key, if provided. - base::FilePath pem_output_path; - if (pem_path.value().empty()) { - pem_output_path = crx_path.DirName().AppendASCII("temp.pem"); - } else { - ASSERT_TRUE(base::PathExists(pem_path)); - } - - ASSERT_TRUE(base::DeleteFile(crx_path, false)); - - scoped_ptr<ExtensionCreator> creator(new ExtensionCreator()); - ASSERT_TRUE(creator->Run(dir_path, - crx_path, - pem_path, - pem_output_path, - ExtensionCreator::kOverwriteCRX)); - - ASSERT_TRUE(base::PathExists(crx_path)); - } - - enum InstallState { - INSTALL_FAILED, - INSTALL_UPDATED, - INSTALL_NEW, - INSTALL_WITHOUT_LOAD, - }; - - const Extension* PackAndInstallCRX(const base::FilePath& dir_path, - const base::FilePath& pem_path, - InstallState install_state, - int creation_flags) { - base::FilePath crx_path; - base::ScopedTempDir temp_dir; - EXPECT_TRUE(temp_dir.CreateUniqueTempDir()); - crx_path = temp_dir.path().AppendASCII("temp.crx"); - - PackCRX(dir_path, pem_path, crx_path); - return InstallCRX(crx_path, install_state, creation_flags); - } - - const Extension* PackAndInstallCRX(const base::FilePath& dir_path, - const base::FilePath& pem_path, - InstallState install_state) { - return PackAndInstallCRX(dir_path, pem_path, install_state, - Extension::NO_FLAGS); - } - - const Extension* PackAndInstallCRX(const base::FilePath& dir_path, - InstallState install_state) { - return PackAndInstallCRX(dir_path, base::FilePath(), install_state, - Extension::NO_FLAGS); - } - - // Attempts to install an extension. Use INSTALL_FAILED if the installation - // is expected to fail. - // If |install_state| is INSTALL_UPDATED, and |expected_old_name| is - // non-empty, expects that the existing extension's title was - // |expected_old_name|. - const Extension* InstallCRX(const base::FilePath& path, - InstallState install_state, - int creation_flags, - const std::string& expected_old_name) { - InstallCRXInternal(path, creation_flags); - return VerifyCrxInstall(path, install_state, expected_old_name); - } - - // Attempts to install an extension. Use INSTALL_FAILED if the installation - // is expected to fail. - const Extension* InstallCRX(const base::FilePath& path, - InstallState install_state, - int creation_flags) { - return InstallCRX(path, install_state, creation_flags, std::string()); - } - - // Attempts to install an extension. Use INSTALL_FAILED if the installation - // is expected to fail. - const Extension* InstallCRX(const base::FilePath& path, - InstallState install_state) { - return InstallCRX(path, install_state, Extension::NO_FLAGS); - } - - const Extension* InstallCRXFromWebStore(const base::FilePath& path, - InstallState install_state) { - InstallCRXInternal(path, Extension::FROM_WEBSTORE); - return VerifyCrxInstall(path, install_state); - } - - const Extension* InstallCRXWithLocation(const base::FilePath& crx_path, - Manifest::Location install_location, - InstallState install_state) { - EXPECT_TRUE(base::PathExists(crx_path)) - << "Path does not exist: "<< crx_path.value().c_str(); - // no client (silent install) - scoped_refptr<CrxInstaller> installer( - CrxInstaller::CreateSilent(service())); - installer->set_install_source(install_location); - - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); - installer->InstallCrx(crx_path); - observer.Wait(); - - return VerifyCrxInstall(crx_path, install_state); - } - - // Verifies the result of a CRX installation. Used by InstallCRX. Set the - // |install_state| to INSTALL_FAILED if the installation is expected to fail. - // Returns an Extension pointer if the install succeeded, NULL otherwise. - const Extension* VerifyCrxInstall(const base::FilePath& path, - InstallState install_state) { - return VerifyCrxInstall(path, install_state, std::string()); - } - - // Verifies the result of a CRX installation. Used by InstallCRX. Set the - // |install_state| to INSTALL_FAILED if the installation is expected to fail. - // If |install_state| is INSTALL_UPDATED, and |expected_old_name| is - // non-empty, expects that the existing extension's title was - // |expected_old_name|. - // Returns an Extension pointer if the install succeeded, NULL otherwise. - const Extension* VerifyCrxInstall(const base::FilePath& path, - InstallState install_state, - const std::string& expected_old_name) { - std::vector<base::string16> errors = GetErrors(); - const Extension* extension = NULL; - if (install_state != INSTALL_FAILED) { - if (install_state == INSTALL_NEW) - ++expected_extensions_count_; - - EXPECT_TRUE(installed_) << path.value(); - // If and only if INSTALL_UPDATED, it should have the is_update flag. - EXPECT_EQ(install_state == INSTALL_UPDATED, was_update_) - << path.value(); - // If INSTALL_UPDATED, old_name_ should match the given string. - if (install_state == INSTALL_UPDATED && !expected_old_name.empty()) - EXPECT_EQ(expected_old_name, old_name_); - EXPECT_EQ(0u, errors.size()) << path.value(); - - if (install_state == INSTALL_WITHOUT_LOAD) { - EXPECT_EQ(0u, loaded_.size()) << path.value(); - } else { - EXPECT_EQ(1u, loaded_.size()) << path.value(); - size_t actual_extension_count = - registry()->enabled_extensions().size() + - registry()->disabled_extensions().size(); - EXPECT_EQ(expected_extensions_count_, actual_extension_count) << - path.value(); - extension = loaded_[0].get(); - EXPECT_TRUE(service()->GetExtensionById(extension->id(), false)) - << path.value(); - } - - for (std::vector<base::string16>::iterator err = errors.begin(); - err != errors.end(); ++err) { - LOG(ERROR) << *err; - } - } else { - EXPECT_FALSE(installed_) << path.value(); - EXPECT_EQ(0u, loaded_.size()) << path.value(); - EXPECT_EQ(1u, errors.size()) << path.value(); - } - - installed_ = NULL; - was_update_ = false; - old_name_ = ""; - loaded_.clear(); - ExtensionErrorReporter::GetInstance()->ClearErrors(); - return extension; - } - - enum UpdateState { - FAILED_SILENTLY, - FAILED, - UPDATED, - INSTALLED, - DISABLED, - ENABLED - }; - void BlackListWebGL() { static const std::string json_blacklist = "{\n" @@ -797,95 +485,6 @@ perms_updater.AddPermissions(extension, all_optional_permissions); } - // Helper method to set up a WindowedNotificationObserver to wait for a - // specific CrxInstaller to finish if we don't know the value of the - // |installer| yet. - static bool IsCrxInstallerDone(extensions::CrxInstaller** installer, - const content::NotificationSource& source, - const content::NotificationDetails& details) { - return content::Source<extensions::CrxInstaller>(source).ptr() == - *installer; - } - - void PackCRXAndUpdateExtension(const std::string& id, - const base::FilePath& dir_path, - const base::FilePath& pem_path, - UpdateState expected_state) { - base::ScopedTempDir temp_dir; - EXPECT_TRUE(temp_dir.CreateUniqueTempDir()); - base::FilePath crx_path = temp_dir.path().AppendASCII("temp.crx"); - - PackCRX(dir_path, pem_path, crx_path); - UpdateExtension(id, crx_path, expected_state); - } - - void UpdateExtension(const std::string& id, - const base::FilePath& in_path, - UpdateState expected_state) { - ASSERT_TRUE(base::PathExists(in_path)); - - // We need to copy this to a temporary location because Update() will delete - // it. - base::FilePath path = temp_dir().path(); - path = path.Append(in_path.BaseName()); - ASSERT_TRUE(base::CopyFile(in_path, path)); - - int previous_enabled_extension_count = - registry()->enabled_extensions().size(); - int previous_installed_extension_count = - previous_enabled_extension_count + - registry()->disabled_extensions().size(); - - extensions::CrxInstaller* installer = NULL; - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - base::Bind(&IsCrxInstallerDone, &installer)); - service()->UpdateExtension(extensions::CRXFileInfo(id, path), true, - &installer); - - if (installer) - observer.Wait(); - else - base::RunLoop().RunUntilIdle(); - - std::vector<base::string16> errors = GetErrors(); - int error_count = errors.size(); - int enabled_extension_count = registry()->enabled_extensions().size(); - int installed_extension_count = - enabled_extension_count + registry()->disabled_extensions().size(); - - int expected_error_count = (expected_state == FAILED) ? 1 : 0; - EXPECT_EQ(expected_error_count, error_count) << path.value(); - - if (expected_state <= FAILED) { - EXPECT_EQ(previous_enabled_extension_count, - enabled_extension_count); - EXPECT_EQ(previous_installed_extension_count, - installed_extension_count); - } else { - int expected_installed_extension_count = - (expected_state >= INSTALLED) ? 1 : 0; - int expected_enabled_extension_count = - (expected_state >= ENABLED) ? 1 : 0; - EXPECT_EQ(expected_installed_extension_count, - installed_extension_count); - EXPECT_EQ(expected_enabled_extension_count, - enabled_extension_count); - } - - // Update() should the temporary input file. - EXPECT_FALSE(base::PathExists(path)); - } - - void TerminateExtension(const std::string& id) { - const Extension* extension = service()->GetInstalledExtension(id); - if (!extension) { - ADD_FAILURE(); - return; - } - service()->TrackTerminatedExtensionForTest(extension); - } - testing::AssertionResult IsBlocked(const std::string& id) { scoped_ptr<extensions::ExtensionSet> all_unblocked_extensions = registry()->GenerateInstalledExtensionsSet( @@ -919,103 +518,6 @@ ASSERT_FALSE(IsBlocked(extension_id)); } - size_t GetPrefKeyCount() { - const base::DictionaryValue* dict = - profile()->GetPrefs()->GetDictionary("extensions.settings"); - if (!dict) { - ADD_FAILURE(); - return 0; - } - return dict->size(); - } - - void UninstallExtension(const std::string& id, bool use_helper) { - UninstallExtension(id, use_helper, Extension::ENABLED); - } - - void UninstallExtension(const std::string& id, bool use_helper, - Extension::State expected_state) { - // Verify that the extension is installed. - base::FilePath extension_path = extensions_install_dir().AppendASCII(id); - EXPECT_TRUE(base::PathExists(extension_path)); - size_t pref_key_count = GetPrefKeyCount(); - EXPECT_GT(pref_key_count, 0u); - ValidateIntegerPref(id, "state", expected_state); - - // Uninstall it. - if (use_helper) { - EXPECT_TRUE(ExtensionService::UninstallExtensionHelper( - service(), id, extensions::UNINSTALL_REASON_FOR_TESTING)); - } else { - EXPECT_TRUE(service()->UninstallExtension( - id, - extensions::UNINSTALL_REASON_FOR_TESTING, - base::Bind(&base::DoNothing), - NULL)); - } - --expected_extensions_count_; - - // We should get an unload notification. - EXPECT_FALSE(unloaded_id_.empty()); - EXPECT_EQ(id, unloaded_id_); - - // Verify uninstalled state. - size_t new_pref_key_count = GetPrefKeyCount(); - if (new_pref_key_count == pref_key_count) { - ValidateIntegerPref(id, "state", - Extension::EXTERNAL_EXTENSION_UNINSTALLED); - } else { - EXPECT_EQ(new_pref_key_count, pref_key_count - 1); - } - - // The extension should not be in the service anymore. - EXPECT_FALSE(service()->GetInstalledExtension(id)); - base::RunLoop().RunUntilIdle(); - - // The directory should be gone. - EXPECT_FALSE(base::PathExists(extension_path)); - } - - void ValidatePrefKeyCount(size_t count) { - EXPECT_EQ(count, GetPrefKeyCount()); - } - - testing::AssertionResult ValidateBooleanPref( - const std::string& extension_id, - const std::string& pref_path, - bool expected_val) { - std::string msg = "while checking: "; - msg += extension_id; - msg += " "; - msg += pref_path; - msg += " == "; - msg += expected_val ? "true" : "false"; - - PrefService* prefs = profile()->GetPrefs(); - const base::DictionaryValue* dict = - prefs->GetDictionary("extensions.settings"); - if (!dict) { - return testing::AssertionFailure() - << "extension.settings does not exist " << msg; - } - - const base::DictionaryValue* pref = NULL; - if (!dict->GetDictionary(extension_id, &pref)) { - return testing::AssertionFailure() - << "extension pref does not exist " << msg; - } - - bool val; - if (!pref->GetBoolean(pref_path, &val)) { - return testing::AssertionFailure() - << pref_path << " pref not found " << msg; - } - - return expected_val == val - ? testing::AssertionSuccess() - : testing::AssertionFailure() << "base::Value is incorrect " << msg; - } - bool IsPrefExist(const std::string& extension_id, const std::string& pref_path) { const base::DictionaryValue* dict = @@ -1035,50 +537,6 @@ return true; } - void ValidateIntegerPref(const std::string& extension_id, - const std::string& pref_path, - int expected_val) { - std::string msg = " while checking: "; - msg += extension_id; - msg += " "; - msg += pref_path; - msg += " == "; - msg += base::IntToString(expected_val); - - PrefService* prefs = profile()->GetPrefs(); - const base::DictionaryValue* dict = - prefs->GetDictionary("extensions.settings"); - ASSERT_TRUE(dict != NULL) << msg; - const base::DictionaryValue* pref = NULL; - ASSERT_TRUE(dict->GetDictionary(extension_id, &pref)) << msg; - EXPECT_TRUE(pref != NULL) << msg; - int val; - ASSERT_TRUE(pref->GetInteger(pref_path, &val)) << msg; - EXPECT_EQ(expected_val, val) << msg; - } - - void ValidateStringPref(const std::string& extension_id, - const std::string& pref_path, - const std::string& expected_val) { - std::string msg = " while checking: "; - msg += extension_id; - msg += ".manifest."; - msg += pref_path; - msg += " == "; - msg += expected_val; - - const base::DictionaryValue* dict = - profile()->GetPrefs()->GetDictionary("extensions.settings"); - ASSERT_TRUE(dict != NULL) << msg; - const base::DictionaryValue* pref = NULL; - std::string manifest_path = extension_id + ".manifest"; - ASSERT_TRUE(dict->GetDictionary(manifest_path, &pref)) << msg; - EXPECT_TRUE(pref != NULL) << msg; - std::string val; - ASSERT_TRUE(pref->GetString(pref_path, &val)) << msg; - EXPECT_EQ(expected_val, val) << msg; - } - void SetPref(const std::string& extension_id, const std::string& pref_path, base::Value* value, @@ -1161,49 +619,9 @@ return ExtensionSystem::Get(browser_context())->management_policy(); } - ExtensionSyncService* extension_sync_service() { - return ExtensionSyncService::Get(profile()); - } - protected: typedef extensions::ExtensionManagementPrefUpdater< syncable_prefs::TestingPrefServiceSyncable> ManagementPrefUpdater; - extensions::ExtensionList loaded_; - std::string unloaded_id_; - UnloadedExtensionInfo::Reason unloaded_reason_; - const Extension* installed_; - bool was_update_; - std::string old_name_; - FeatureSwitch::ScopedOverride override_external_install_prompt_; - - private: - // Create a CrxInstaller and install the CRX file. - // Instead of calling this method yourself, use InstallCRX(), which does extra - // error checking. - void InstallCRXInternal(const base::FilePath& crx_path) { - InstallCRXInternal(crx_path, Extension::NO_FLAGS); - } - - void InstallCRXInternal(const base::FilePath& crx_path, int creation_flags) { - ASSERT_TRUE(base::PathExists(crx_path)) - << "Path does not exist: "<< crx_path.value().c_str(); - scoped_refptr<CrxInstaller> installer( - CrxInstaller::CreateSilent(service())); - installer->set_creation_flags(creation_flags); - if (!(creation_flags & Extension::WAS_INSTALLED_BY_DEFAULT)) - installer->set_allow_silent_install(true); - - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::Source<extensions::CrxInstaller>(installer.get())); - - installer->InstallCrx(crx_path); - - observer.Wait(); - } - - size_t expected_extensions_count_; - content::NotificationRegistrar registrar_; }; // Receives notifications from a PackExtensionJob, indicating either that @@ -2778,7 +2196,6 @@ // Tests that updating preserves extension location. TEST_F(ExtensionServiceTest, UpdateExtensionPreservesLocation) { InitializeEmptyExtensionService(); - base::FilePath path = data_dir().AppendASCII("good.crx"); const Extension* good = @@ -5829,1637 +5246,6 @@ EXPECT_EQ(extension_id, (*registry()->enabled_extensions().begin())->id()); } -TEST_F(ExtensionServiceTest, DeferredSyncStartupPreInstalledComponent) { - InitializeEmptyExtensionService(); - - bool flare_was_called = false; - syncer::ModelType triggered_type(syncer::UNSPECIFIED); - base::WeakPtrFactory<ExtensionServiceTest> factory(this); - extension_sync_service()->SetSyncStartFlareForTesting( - base::Bind(&ExtensionServiceTest::MockSyncStartFlare, - factory.GetWeakPtr(), - &flare_was_called, // Safe due to WeakPtrFactory scope. - &triggered_type)); // Safe due to WeakPtrFactory scope. - - // Install a component extension. - std::string manifest; - ASSERT_TRUE(base::ReadFileToString( - good0_path().Append(extensions::kManifestFilename), &manifest)); - service()->component_loader()->Add(manifest, good0_path()); - ASSERT_FALSE(service()->is_ready()); - service()->Init(); - ASSERT_TRUE(service()->is_ready()); - - // Extensions added before service is_ready() don't trigger sync startup. - EXPECT_FALSE(flare_was_called); - ASSERT_EQ(syncer::UNSPECIFIED, triggered_type); -} - -TEST_F(ExtensionServiceTest, DeferredSyncStartupPreInstalledNormal) { - InitializeGoodInstalledExtensionService(); - - bool flare_was_called = false; - syncer::ModelType triggered_type(syncer::UNSPECIFIED); - base::WeakPtrFactory<ExtensionServiceTest> factory(this); - extension_sync_service()->SetSyncStartFlareForTesting( - base::Bind(&ExtensionServiceTest::MockSyncStartFlare, - factory.GetWeakPtr(), - &flare_was_called, // Safe due to WeakPtrFactory scope. - &triggered_type)); // Safe due to WeakPtrFactory scope. - - ASSERT_FALSE(service()->is_ready()); - service()->Init(); - ASSERT_EQ(3u, loaded_.size()); - ASSERT_TRUE(service()->is_ready()); - - // Extensions added before service is_ready() don't trigger sync startup. - EXPECT_FALSE(flare_was_called); - ASSERT_EQ(syncer::UNSPECIFIED, triggered_type); -} - -TEST_F(ExtensionServiceTest, DeferredSyncStartupOnInstall) { - InitializeEmptyExtensionService(); - service()->Init(); - ASSERT_TRUE(service()->is_ready()); - - bool flare_was_called = false; - syncer::ModelType triggered_type(syncer::UNSPECIFIED); - base::WeakPtrFactory<ExtensionServiceTest> factory(this); - extension_sync_service()->SetSyncStartFlareForTesting( - base::Bind(&ExtensionServiceTest::MockSyncStartFlare, - factory.GetWeakPtr(), - &flare_was_called, // Safe due to WeakPtrFactory scope. - &triggered_type)); // Safe due to WeakPtrFactory scope. - - base::FilePath path = data_dir().AppendASCII("good.crx"); - InstallCRX(path, INSTALL_NEW); - - EXPECT_TRUE(flare_was_called); - EXPECT_EQ(syncer::EXTENSIONS, triggered_type); - - // Reset. - flare_was_called = false; - triggered_type = syncer::UNSPECIFIED; - - // Once sync starts, flare should no longer be invoked. - extension_sync_service()->MergeDataAndStartSyncing( - syncer::EXTENSIONS, - syncer::SyncDataList(), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::FakeSyncChangeProcessor), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - path = data_dir().AppendASCII("page_action.crx"); - InstallCRX(path, INSTALL_NEW); - EXPECT_FALSE(flare_was_called); - ASSERT_EQ(syncer::UNSPECIFIED, triggered_type); -} - -TEST_F(ExtensionServiceTest, DisableExtensionFromSync) { - // Start the extensions service with one external extension already installed. - base::FilePath source_install_dir = - data_dir().AppendASCII("good").AppendASCII("Extensions"); - base::FilePath pref_path = - source_install_dir.DirName().Append(chrome::kPreferencesFilename); - - InitializeInstalledExtensionService(pref_path, source_install_dir); - - // The user has enabled sync. - ProfileSyncService* sync_service = - ProfileSyncServiceFactory::GetForProfile(profile()); - sync_service->SetSyncSetupCompleted(); - - service()->Init(); - ASSERT_TRUE(service()->is_ready()); - - ASSERT_EQ(3u, loaded_.size()); - - // We start enabled. - const Extension* extension = service()->GetExtensionById(good0, true); - ASSERT_TRUE(extension); - ASSERT_TRUE(service()->IsExtensionEnabled(good0)); - - // Sync starts up. - extension_sync_service()->MergeDataAndStartSyncing( - syncer::EXTENSIONS, - syncer::SyncDataList(), - make_scoped_ptr(new syncer::FakeSyncChangeProcessor), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - // Then sync data arrives telling us to disable |good0|. - ExtensionSyncData disable_good_crx(*extension, false, - Extension::DISABLE_USER_ACTION, false, - false, ExtensionSyncData::BOOLEAN_UNSET); - syncer::SyncChange sync_change(FROM_HERE, - syncer::SyncChange::ACTION_UPDATE, - disable_good_crx.GetSyncData()); - syncer::SyncChangeList list(1, sync_change); - extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); - - ASSERT_FALSE(service()->IsExtensionEnabled(good0)); -} - -TEST_F(ExtensionServiceTest, IgnoreSyncChangesWhenLocalStateIsMoreRecent) { - // Start the extension service with three extensions already installed. - base::FilePath source_install_dir = - data_dir().AppendASCII("good").AppendASCII("Extensions"); - base::FilePath pref_path = - source_install_dir.DirName().Append(chrome::kPreferencesFilename); - - InitializeInstalledExtensionService(pref_path, source_install_dir); - - // The user has enabled sync. - ProfileSyncService* sync_service = - ProfileSyncServiceFactory::GetForProfile(profile()); - sync_service->SetSyncSetupCompleted(); - // Make sure ExtensionSyncService is created, so it'll be notified of changes. - extension_sync_service(); - - service()->Init(); - ASSERT_TRUE(service()->is_ready()); - ASSERT_EQ(3u, loaded_.size()); - - ASSERT_TRUE(service()->IsExtensionEnabled(good0)); - ASSERT_TRUE(service()->IsExtensionEnabled(good2)); - - // Disable and re-enable good0 before first sync data arrives. - service()->DisableExtension(good0, Extension::DISABLE_USER_ACTION); - ASSERT_FALSE(service()->IsExtensionEnabled(good0)); - service()->EnableExtension(good0); - ASSERT_TRUE(service()->IsExtensionEnabled(good0)); - // Disable good2 before first sync data arrives (good1 is considered - // non-syncable because it has plugin permission). - service()->DisableExtension(good2, Extension::DISABLE_USER_ACTION); - ASSERT_FALSE(service()->IsExtensionEnabled(good2)); - - const Extension* extension0 = service()->GetExtensionById(good0, true); - const Extension* extension2 = service()->GetExtensionById(good2, true); - ASSERT_TRUE(extensions::sync_helper::IsSyncable(extension0)); - ASSERT_TRUE(extensions::sync_helper::IsSyncable(extension2)); - - // Now sync data comes in that says to disable good0 and enable good2. - ExtensionSyncData disable_good0(*extension0, false, - Extension::DISABLE_USER_ACTION, false, false, - ExtensionSyncData::BOOLEAN_UNSET); - ExtensionSyncData enable_good2(*extension2, true, Extension::DISABLE_NONE, - false, false, - ExtensionSyncData::BOOLEAN_UNSET); - syncer::SyncDataList sync_data; - sync_data.push_back(disable_good0.GetSyncData()); - sync_data.push_back(enable_good2.GetSyncData()); - extension_sync_service()->MergeDataAndStartSyncing( - syncer::EXTENSIONS, - sync_data, - make_scoped_ptr(new syncer::FakeSyncChangeProcessor), - make_scoped_ptr(new syncer::SyncErrorFactoryMock)); - - // Both sync changes should be ignored, since the local state was changed - // before sync started, and so the local state is considered more recent. - EXPECT_TRUE(service()->IsExtensionEnabled(good0)); - EXPECT_FALSE(service()->IsExtensionEnabled(good2)); -} - -TEST_F(ExtensionServiceTest, GetSyncData) { - InitializeEmptyExtensionService(); - InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW); - const Extension* extension = service()->GetInstalledExtension(good_crx); - ASSERT_TRUE(extension); - - extension_sync_service()->MergeDataAndStartSyncing( - syncer::EXTENSIONS, - syncer::SyncDataList(), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::FakeSyncChangeProcessor), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - syncer::SyncDataList list = - extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS); - ASSERT_EQ(list.size(), 1U); - scoped_ptr<ExtensionSyncData> data = - ExtensionSyncData::CreateFromSyncData(list[0]); - ASSERT_TRUE(data.get()); - EXPECT_EQ(extension->id(), data->id()); - EXPECT_FALSE(data->uninstalled()); - EXPECT_EQ(service()->IsExtensionEnabled(good_crx), data->enabled()); - EXPECT_EQ(extensions::util::IsIncognitoEnabled(good_crx, profile()), - data->incognito_enabled()); - EXPECT_EQ(ExtensionSyncData::BOOLEAN_UNSET, data->all_urls_enabled()); - EXPECT_TRUE(data->version().Equals(*extension->version())); - EXPECT_EQ(extensions::ManifestURL::GetUpdateURL(extension), - data->update_url()); - EXPECT_EQ(extension->name(), data->name()); -} - -TEST_F(ExtensionServiceTest, GetSyncDataTerminated) { - InitializeEmptyExtensionService(); - InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW); - TerminateExtension(good_crx); - const Extension* extension = service()->GetInstalledExtension(good_crx); - ASSERT_TRUE(extension); - - syncer::FakeSyncChangeProcessor processor; - extension_sync_service()->MergeDataAndStartSyncing( - syncer::EXTENSIONS, - syncer::SyncDataList(), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::FakeSyncChangeProcessor), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - syncer::SyncDataList list = - extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS); - ASSERT_EQ(list.size(), 1U); - scoped_ptr<ExtensionSyncData> data = - ExtensionSyncData::CreateFromSyncData(list[0]); - ASSERT_TRUE(data.get()); - EXPECT_EQ(extension->id(), data->id()); - EXPECT_FALSE(data->uninstalled()); - EXPECT_EQ(service()->IsExtensionEnabled(good_crx), data->enabled()); - EXPECT_EQ(extensions::util::IsIncognitoEnabled(good_crx, profile()), - data->incognito_enabled()); - EXPECT_EQ(ExtensionSyncData::BOOLEAN_UNSET, data->all_urls_enabled()); - EXPECT_TRUE(data->version().Equals(*extension->version())); - EXPECT_EQ(extensions::ManifestURL::GetUpdateURL(extension), - data->update_url()); - EXPECT_EQ(extension->name(), data->name()); -} - -TEST_F(ExtensionServiceTest, GetSyncDataFilter) { - InitializeEmptyExtensionService(); - InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW); - const Extension* extension = service()->GetInstalledExtension(good_crx); - ASSERT_TRUE(extension); - - syncer::FakeSyncChangeProcessor processor; - extension_sync_service()->MergeDataAndStartSyncing( - syncer::APPS, - syncer::SyncDataList(), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::FakeSyncChangeProcessor), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - syncer::SyncDataList list = - extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS); - ASSERT_EQ(list.size(), 0U); -} - -TEST_F(ExtensionServiceTest, GetSyncExtensionDataUserSettings) { - InitializeEmptyExtensionService(); - InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW); - const Extension* extension = service()->GetInstalledExtension(good_crx); - ASSERT_TRUE(extension); - - syncer::FakeSyncChangeProcessor processor; - extension_sync_service()->MergeDataAndStartSyncing( - syncer::EXTENSIONS, - syncer::SyncDataList(), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::FakeSyncChangeProcessor), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - { - syncer::SyncDataList list = - extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS); - ASSERT_EQ(list.size(), 1U); - scoped_ptr<ExtensionSyncData> data = - ExtensionSyncData::CreateFromSyncData(list[0]); - ASSERT_TRUE(data.get()); - EXPECT_TRUE(data->enabled()); - EXPECT_FALSE(data->incognito_enabled()); - EXPECT_EQ(ExtensionSyncData::BOOLEAN_UNSET, data->all_urls_enabled()); - } - - service()->DisableExtension(good_crx, Extension::DISABLE_USER_ACTION); - { - syncer::SyncDataList list = - extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS); - ASSERT_EQ(list.size(), 1U); - scoped_ptr<ExtensionSyncData> data = - ExtensionSyncData::CreateFromSyncData(list[0]); - ASSERT_TRUE(data.get()); - EXPECT_FALSE(data->enabled()); - EXPECT_FALSE(data->incognito_enabled()); - EXPECT_EQ(ExtensionSyncData::BOOLEAN_UNSET, data->all_urls_enabled()); - } - - extensions::util::SetIsIncognitoEnabled(good_crx, profile(), true); - extensions::util::SetAllowedScriptingOnAllUrls( - good_crx, profile(), false); - { - syncer::SyncDataList list = - extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS); - ASSERT_EQ(list.size(), 1U); - scoped_ptr<ExtensionSyncData> data = - ExtensionSyncData::CreateFromSyncData(list[0]); - ASSERT_TRUE(data.get()); - EXPECT_FALSE(data->enabled()); - EXPECT_TRUE(data->incognito_enabled()); - EXPECT_EQ(ExtensionSyncData::BOOLEAN_FALSE, data->all_urls_enabled()); - } - - service()->EnableExtension(good_crx); - extensions::util::SetAllowedScriptingOnAllUrls( - good_crx, profile(), true); - { - syncer::SyncDataList list = - extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS); - ASSERT_EQ(list.size(), 1U); - scoped_ptr<ExtensionSyncData> data = - ExtensionSyncData::CreateFromSyncData(list[0]); - ASSERT_TRUE(data.get()); - EXPECT_TRUE(data->enabled()); - EXPECT_TRUE(data->incognito_enabled()); - EXPECT_EQ(ExtensionSyncData::BOOLEAN_TRUE, data->all_urls_enabled()); - } -} - -TEST_F(ExtensionServiceTest, SyncForUninstalledExternalExtension) { - InitializeEmptyExtensionService(); - InstallCRXWithLocation( - data_dir().AppendASCII("good.crx"), Manifest::EXTERNAL_PREF, INSTALL_NEW); - const Extension* extension = service()->GetInstalledExtension(good_crx); - ASSERT_TRUE(extension); - - syncer::FakeSyncChangeProcessor processor; - extension_sync_service()->MergeDataAndStartSyncing( - syncer::EXTENSIONS, - syncer::SyncDataList(), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::FakeSyncChangeProcessor), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - UninstallExtension(good_crx, false); - EXPECT_TRUE( - ExtensionPrefs::Get(profile())->IsExternalExtensionUninstalled(good_crx)); - - sync_pb::EntitySpecifics specifics; - sync_pb::AppSpecifics* app_specifics = specifics.mutable_app(); - sync_pb::ExtensionSpecifics* extension_specifics = - app_specifics->mutable_extension(); - extension_specifics->set_id(good_crx); - extension_specifics->set_version("1.0"); - extension_specifics->set_enabled(true); - - syncer::SyncData sync_data = - syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); - syncer::SyncChange sync_change(FROM_HERE, - syncer::SyncChange::ACTION_UPDATE, - sync_data); - syncer::SyncChangeList list(1); - list[0] = sync_change; - - extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); - EXPECT_TRUE( - ExtensionPrefs::Get(profile())->IsExternalExtensionUninstalled(good_crx)); -} - -TEST_F(ExtensionServiceTest, GetSyncAppDataUserSettings) { - InitializeEmptyExtensionService(); - const Extension* app = - PackAndInstallCRX(data_dir().AppendASCII("app"), INSTALL_NEW); - ASSERT_TRUE(app); - ASSERT_TRUE(app->is_app()); - - syncer::FakeSyncChangeProcessor processor; - extension_sync_service()->MergeDataAndStartSyncing( - syncer::APPS, - syncer::SyncDataList(), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::FakeSyncChangeProcessor), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - syncer::StringOrdinal initial_ordinal = - syncer::StringOrdinal::CreateInitialOrdinal(); - { - syncer::SyncDataList list = - extension_sync_service()->GetAllSyncData(syncer::APPS); - ASSERT_EQ(list.size(), 1U); - - scoped_ptr<ExtensionSyncData> app_sync_data = - ExtensionSyncData::CreateFromSyncData(list[0]); - EXPECT_TRUE(initial_ordinal.Equals(app_sync_data->app_launch_ordinal())); - EXPECT_TRUE(initial_ordinal.Equals(app_sync_data->page_ordinal())); - } - - AppSorting* sorting = ExtensionPrefs::Get(profile())->app_sorting(); - sorting->SetAppLaunchOrdinal(app->id(), initial_ordinal.CreateAfter()); - { - syncer::SyncDataList list = - extension_sync_service()->GetAllSyncData(syncer::APPS); - ASSERT_EQ(list.size(), 1U); - - scoped_ptr<ExtensionSyncData> app_sync_data = - ExtensionSyncData::CreateFromSyncData(list[0]); - ASSERT_TRUE(app_sync_data.get()); - EXPECT_TRUE(initial_ordinal.LessThan(app_sync_data->app_launch_ordinal())); - EXPECT_TRUE(initial_ordinal.Equals(app_sync_data->page_ordinal())); - } - - sorting->SetPageOrdinal(app->id(), initial_ordinal.CreateAfter()); - { - syncer::SyncDataList list = - extension_sync_service()->GetAllSyncData(syncer::APPS); - ASSERT_EQ(list.size(), 1U); - - scoped_ptr<ExtensionSyncData> app_sync_data = - ExtensionSyncData::CreateFromSyncData(list[0]); - ASSERT_TRUE(app_sync_data.get()); - EXPECT_TRUE(initial_ordinal.LessThan(app_sync_data->app_launch_ordinal())); - EXPECT_TRUE(initial_ordinal.LessThan(app_sync_data->page_ordinal())); - } -} - -// TODO (rdevlin.cronin): The OnExtensionMoved() method has been removed from -// ExtensionService, so this test probably needs a new home. Unfortunately, it -// relies pretty heavily on things like InitializeExtension[Sync]Service() and -// PackAndInstallCRX(). When we clean up a bit more, this should move out. -TEST_F(ExtensionServiceTest, GetSyncAppDataUserSettingsOnExtensionMoved) { - InitializeEmptyExtensionService(); - const size_t kAppCount = 3; - const Extension* apps[kAppCount]; - apps[0] = PackAndInstallCRX(data_dir().AppendASCII("app1"), INSTALL_NEW); - apps[1] = PackAndInstallCRX(data_dir().AppendASCII("app2"), INSTALL_NEW); - apps[2] = PackAndInstallCRX(data_dir().AppendASCII("app4"), INSTALL_NEW); - for (size_t i = 0; i < kAppCount; ++i) { - ASSERT_TRUE(apps[i]); - ASSERT_TRUE(apps[i]->is_app()); - } - - syncer::FakeSyncChangeProcessor processor; - extension_sync_service()->MergeDataAndStartSyncing( - syncer::APPS, - syncer::SyncDataList(), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::FakeSyncChangeProcessor), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - ExtensionPrefs::Get(service()->GetBrowserContext()) - ->app_sorting() - ->OnExtensionMoved(apps[0]->id(), apps[1]->id(), apps[2]->id()); - { - syncer::SyncDataList list = - extension_sync_service()->GetAllSyncData(syncer::APPS); - ASSERT_EQ(list.size(), 3U); - - scoped_ptr<ExtensionSyncData> data[kAppCount]; - for (size_t i = 0; i < kAppCount; ++i) { - data[i] = ExtensionSyncData::CreateFromSyncData(list[i]); - ASSERT_TRUE(data[i].get()); - } - - // The sync data is not always in the same order our apps were installed in, - // so we do that sorting here so we can make sure the values are changed as - // expected. - syncer::StringOrdinal app_launch_ordinals[kAppCount]; - for (size_t i = 0; i < kAppCount; ++i) { - for (size_t j = 0; j < kAppCount; ++j) { - if (apps[i]->id() == data[j]->id()) - app_launch_ordinals[i] = data[j]->app_launch_ordinal(); - } - } - - EXPECT_TRUE(app_launch_ordinals[1].LessThan(app_launch_ordinals[0])); - EXPECT_TRUE(app_launch_ordinals[0].LessThan(app_launch_ordinals[2])); - } -} - -TEST_F(ExtensionServiceTest, GetSyncDataList) { - InitializeEmptyExtensionService(); - InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW); - InstallCRX(data_dir().AppendASCII("page_action.crx"), INSTALL_NEW); - InstallCRX(data_dir().AppendASCII("theme.crx"), INSTALL_NEW); - InstallCRX(data_dir().AppendASCII("theme2.crx"), INSTALL_NEW); - - syncer::FakeSyncChangeProcessor processor; - extension_sync_service()->MergeDataAndStartSyncing( - syncer::APPS, - syncer::SyncDataList(), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::FakeSyncChangeProcessor), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - extension_sync_service()->MergeDataAndStartSyncing( - syncer::EXTENSIONS, - syncer::SyncDataList(), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::FakeSyncChangeProcessor), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - service()->DisableExtension(page_action, Extension::DISABLE_USER_ACTION); - TerminateExtension(theme2_crx); - - EXPECT_EQ(0u, extension_sync_service()->GetAllSyncData(syncer::APPS).size()); - EXPECT_EQ( - 2u, extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS).size()); -} - -TEST_F(ExtensionServiceTest, ProcessSyncDataUninstall) { - InitializeEmptyExtensionService(); - syncer::FakeSyncChangeProcessor processor; - extension_sync_service()->MergeDataAndStartSyncing( - syncer::EXTENSIONS, - syncer::SyncDataList(), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::FakeSyncChangeProcessor), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - sync_pb::EntitySpecifics specifics; - sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension(); - ext_specifics->set_id(good_crx); - ext_specifics->set_version("1.0"); - syncer::SyncData sync_data = - syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); - syncer::SyncChange sync_change(FROM_HERE, - syncer::SyncChange::ACTION_DELETE, - sync_data); - syncer::SyncChangeList list(1); - list[0] = sync_change; - - // Should do nothing. - extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); - EXPECT_FALSE(service()->GetExtensionById(good_crx, true)); - - // Install the extension. - base::FilePath extension_path = data_dir().AppendASCII("good.crx"); - InstallCRX(extension_path, INSTALL_NEW); - EXPECT_TRUE(service()->GetExtensionById(good_crx, true)); - - // Should uninstall the extension. - extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); - EXPECT_FALSE(service()->GetExtensionById(good_crx, true)); - - // Should again do nothing. - extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); - EXPECT_FALSE(service()->GetExtensionById(good_crx, true)); -} - -TEST_F(ExtensionServiceTest, ProcessSyncDataWrongType) { - InitializeEmptyExtensionService(); - - // Install the extension. - base::FilePath extension_path = data_dir().AppendASCII("good.crx"); - InstallCRX(extension_path, INSTALL_NEW); - EXPECT_TRUE(service()->GetExtensionById(good_crx, true)); - - sync_pb::EntitySpecifics specifics; - sync_pb::AppSpecifics* app_specifics = specifics.mutable_app(); - sync_pb::ExtensionSpecifics* extension_specifics = - app_specifics->mutable_extension(); - extension_specifics->set_id(good_crx); - extension_specifics->set_version( - service()->GetInstalledExtension(good_crx)->version()->GetString()); - - { - extension_specifics->set_enabled(true); - syncer::SyncData sync_data = - syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); - syncer::SyncChange sync_change(FROM_HERE, - syncer::SyncChange::ACTION_DELETE, - sync_data); - syncer::SyncChangeList list(1); - list[0] = sync_change; - - // Should do nothing - extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); - EXPECT_TRUE(service()->GetExtensionById(good_crx, true)); - } - - { - extension_specifics->set_enabled(false); - syncer::SyncData sync_data = - syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); - syncer::SyncChange sync_change(FROM_HERE, - syncer::SyncChange::ACTION_UPDATE, - sync_data); - syncer::SyncChangeList list(1); - list[0] = sync_change; - - // Should again do nothing. - extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); - EXPECT_TRUE(service()->GetExtensionById(good_crx, false)); - } -} - -TEST_F(ExtensionServiceTest, ProcessSyncDataSettings) { - InitializeEmptyExtensionService(); - syncer::FakeSyncChangeProcessor processor; - extension_sync_service()->MergeDataAndStartSyncing( - syncer::EXTENSIONS, - syncer::SyncDataList(), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::FakeSyncChangeProcessor), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW); - EXPECT_TRUE(service()->IsExtensionEnabled(good_crx)); - EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile())); - EXPECT_FALSE(extensions::util::HasSetAllowedScriptingOnAllUrls( - good_crx, profile())); - const bool kDefaultAllowedScripting = - extensions::util::DefaultAllowedScriptingOnAllUrls(); - EXPECT_EQ(kDefaultAllowedScripting, - extensions::util::AllowedScriptingOnAllUrls(good_crx, profile())); - - sync_pb::EntitySpecifics specifics; - sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension(); - ext_specifics->set_id(good_crx); - ext_specifics->set_version( - service()->GetInstalledExtension(good_crx)->version()->GetString()); - ext_specifics->set_enabled(false); - - { - syncer::SyncData sync_data = - syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); - syncer::SyncChange sync_change(FROM_HERE, - syncer::SyncChange::ACTION_UPDATE, - sync_data); - syncer::SyncChangeList list(1); - list[0] = sync_change; - extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); - EXPECT_FALSE(service()->IsExtensionEnabled(good_crx)); - EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile())); - EXPECT_FALSE(extensions::util::HasSetAllowedScriptingOnAllUrls( - good_crx, profile())); - EXPECT_EQ(kDefaultAllowedScripting, - extensions::util::AllowedScriptingOnAllUrls(good_crx, profile())); - } - - { - ext_specifics->set_enabled(true); - ext_specifics->set_incognito_enabled(true); - syncer::SyncData sync_data = - syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); - syncer::SyncChange sync_change(FROM_HERE, - syncer::SyncChange::ACTION_UPDATE, - sync_data); - syncer::SyncChangeList list(1); - list[0] = sync_change; - extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); - EXPECT_TRUE(service()->IsExtensionEnabled(good_crx)); - EXPECT_TRUE(extensions::util::IsIncognitoEnabled(good_crx, profile())); - } - - { - ext_specifics->set_enabled(false); - ext_specifics->set_incognito_enabled(true); - syncer::SyncData sync_data = - syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); - syncer::SyncChange sync_change(FROM_HERE, - syncer::SyncChange::ACTION_UPDATE, - sync_data); - syncer::SyncChangeList list(1); - list[0] = sync_change; - extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); - EXPECT_FALSE(service()->IsExtensionEnabled(good_crx)); - EXPECT_TRUE(extensions::util::IsIncognitoEnabled(good_crx, profile())); - } - - { - ext_specifics->set_enabled(true); - ext_specifics->set_all_urls_enabled(!kDefaultAllowedScripting); - syncer::SyncData sync_data = - syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); - syncer::SyncChange sync_change(FROM_HERE, - syncer::SyncChange::ACTION_UPDATE, - sync_data); - syncer::SyncChangeList list(1); - list[0] = sync_change; - extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); - EXPECT_TRUE(service()->IsExtensionEnabled(good_crx)); - EXPECT_TRUE(extensions::util::HasSetAllowedScriptingOnAllUrls( - good_crx, profile())); - EXPECT_EQ(!kDefaultAllowedScripting, - extensions::util::AllowedScriptingOnAllUrls(good_crx, profile())); - } - - { - ext_specifics->set_all_urls_enabled(kDefaultAllowedScripting); - syncer::SyncData sync_data = - syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); - syncer::SyncChange sync_change(FROM_HERE, - syncer::SyncChange::ACTION_UPDATE, - sync_data); - syncer::SyncChangeList list(1); - list[0] = sync_change; - extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); - EXPECT_TRUE(service()->IsExtensionEnabled(good_crx)); - EXPECT_TRUE(extensions::util::HasSetAllowedScriptingOnAllUrls( - good_crx, profile())); - EXPECT_EQ(kDefaultAllowedScripting, - extensions::util::AllowedScriptingOnAllUrls(good_crx, profile())); - } - - EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(good_crx)); -} - -TEST_F(ExtensionServiceTest, ProcessSyncDataNewExtension) { - InitializeEmptyExtensionService(); - syncer::FakeSyncChangeProcessor processor; - extension_sync_service()->MergeDataAndStartSyncing( - syncer::EXTENSIONS, - syncer::SyncDataList(), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::FakeSyncChangeProcessor), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - const base::FilePath path = data_dir().AppendASCII("good.crx"); - const ExtensionPrefs* prefs = ExtensionPrefs::Get(profile()); - - struct TestCase { - const char* name; // For failure output only. - bool sync_enabled; // The "enabled" flag coming in from Sync. - // The disable reason(s) coming in from Sync, or -1 for "not set". - int sync_disable_reasons; - // The disable reason(s) that should be set on the installed extension. - // This will usually be the same as |sync_disable_reasons|, but see the - // "Legacy" case. - int expect_disable_reasons; - // Whether the extension's permissions should be auto-granted during - // installation. - bool expect_permissions_granted; - } test_cases[] = { - // Standard case: Extension comes in enabled; permissions should be granted - // during installation. - { "Standard", true, 0, 0, true }, - // If the extension comes in disabled, its permissions should still be - // granted (the user already approved them on another machine). - { "Disabled", false, Extension::DISABLE_USER_ACTION, - Extension::DISABLE_USER_ACTION, true }, - // Legacy case (<M45): No disable reasons come in from Sync (see - // crbug.com/484214). After installation, the reason should be set to - // DISABLE_UNKNOWN_FROM_SYNC. - { "Legacy", false, -1, Extension::DISABLE_UNKNOWN_FROM_SYNC, true }, - // If the extension came in disabled due to a permissions increase, then the - // user has *not* approved the permissions, and they shouldn't be granted. - // crbug.com/484214 - { "PermissionsIncrease", false, Extension::DISABLE_PERMISSIONS_INCREASE, - Extension::DISABLE_PERMISSIONS_INCREASE, false }, - }; - - for (const TestCase& test_case : test_cases) { - SCOPED_TRACE(test_case.name); - - sync_pb::EntitySpecifics specifics; - sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension(); - ext_specifics->set_id(good_crx); - ext_specifics->set_version(base::Version("1").GetString()); - ext_specifics->set_enabled(test_case.sync_enabled); - if (test_case.sync_disable_reasons != -1) - ext_specifics->set_disable_reasons(test_case.sync_disable_reasons); - - syncer::SyncData sync_data = - syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); - syncer::SyncChange sync_change(FROM_HERE, - syncer::SyncChange::ACTION_UPDATE, - sync_data); - syncer::SyncChangeList list(1, sync_change); - extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); - - ASSERT_TRUE(service()->pending_extension_manager()->IsIdPending(good_crx)); - UpdateExtension(good_crx, path, test_case.sync_enabled ? ENABLED - : DISABLED); - EXPECT_EQ(test_case.expect_disable_reasons, - prefs->GetDisableReasons(good_crx)); - scoped_ptr<const PermissionSet> permissions = - prefs->GetGrantedPermissions(good_crx); - EXPECT_EQ(test_case.expect_permissions_granted, !permissions->IsEmpty()); - ASSERT_FALSE(service()->pending_extension_manager()->IsIdPending(good_crx)); - - // Remove the extension again, so we can install it again for the next case. - UninstallExtension(good_crx, false, - test_case.sync_enabled ? Extension::ENABLED - : Extension::DISABLED); - } -} - -TEST_F(ExtensionServiceTest, ProcessSyncDataTerminatedExtension) { - InitializeExtensionServiceWithUpdater(); - syncer::FakeSyncChangeProcessor processor; - extension_sync_service()->MergeDataAndStartSyncing( - syncer::EXTENSIONS, - syncer::SyncDataList(), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::FakeSyncChangeProcessor), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW); - TerminateExtension(good_crx); - EXPECT_TRUE(service()->IsExtensionEnabled(good_crx)); - EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile())); - - sync_pb::EntitySpecifics specifics; - sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension(); - ext_specifics->set_id(good_crx); - ext_specifics->set_version( - service()->GetInstalledExtension(good_crx)->version()->GetString()); - ext_specifics->set_enabled(false); - ext_specifics->set_incognito_enabled(true); - syncer::SyncData sync_data = - syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); - syncer::SyncChange sync_change(FROM_HERE, - syncer::SyncChange::ACTION_UPDATE, - sync_data); - syncer::SyncChangeList list(1); - list[0] = sync_change; - - extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); - EXPECT_FALSE(service()->IsExtensionEnabled(good_crx)); - EXPECT_TRUE(extensions::util::IsIncognitoEnabled(good_crx, profile())); - - EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(good_crx)); -} - -TEST_F(ExtensionServiceTest, ProcessSyncDataVersionCheck) { - InitializeExtensionServiceWithUpdater(); - syncer::FakeSyncChangeProcessor processor; - extension_sync_service()->MergeDataAndStartSyncing( - syncer::EXTENSIONS, - syncer::SyncDataList(), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::FakeSyncChangeProcessor), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW); - EXPECT_TRUE(service()->IsExtensionEnabled(good_crx)); - EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile())); - - sync_pb::EntitySpecifics specifics; - sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension(); - ext_specifics->set_id(good_crx); - ext_specifics->set_enabled(true); - - const base::Version installed_version = - *service()->GetInstalledExtension(good_crx)->version(); - - { - ext_specifics->set_version(installed_version.GetString()); - syncer::SyncData sync_data = - syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); - syncer::SyncChange sync_change(FROM_HERE, - syncer::SyncChange::ACTION_UPDATE, - sync_data); - syncer::SyncChangeList list(1, sync_change); - - // Should do nothing if extension version == sync version. - extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); - EXPECT_FALSE(service()->updater()->WillCheckSoon()); - // Make sure the version we'll send back to sync didn't change. - syncer::SyncDataList data = - extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS); - ASSERT_EQ(1u, data.size()); - scoped_ptr<ExtensionSyncData> extension_data = - ExtensionSyncData::CreateFromSyncData(data[0]); - ASSERT_TRUE(extension_data); - EXPECT_TRUE(installed_version.Equals(extension_data->version())); - } - - // Should do nothing if extension version > sync version. - { - ext_specifics->set_version("0.0.0.0"); - syncer::SyncData sync_data = - syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); - syncer::SyncChange sync_change(FROM_HERE, - syncer::SyncChange::ACTION_UPDATE, - sync_data); - syncer::SyncChangeList list(1, sync_change); - - extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); - EXPECT_FALSE(service()->updater()->WillCheckSoon()); - // Make sure the version we'll send back to sync didn't change. - syncer::SyncDataList data = - extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS); - ASSERT_EQ(1u, data.size()); - scoped_ptr<ExtensionSyncData> extension_data = - ExtensionSyncData::CreateFromSyncData(data[0]); - ASSERT_TRUE(extension_data); - EXPECT_TRUE(installed_version.Equals(extension_data->version())); - } - - // Should kick off an update if extension version < sync version. - { - const base::Version new_version("9.9.9.9"); - ext_specifics->set_version(new_version.GetString()); - syncer::SyncData sync_data = - syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); - syncer::SyncChange sync_change(FROM_HERE, - syncer::SyncChange::ACTION_UPDATE, - sync_data); - syncer::SyncChangeList list(1, sync_change); - - extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); - EXPECT_TRUE(service()->updater()->WillCheckSoon()); - // Make sure that we'll send the NEW version back to sync, even though we - // haven't actually updated yet. This is to prevent the data in sync from - // flip-flopping back and forth until all clients are up to date. - syncer::SyncDataList data = - extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS); - ASSERT_EQ(1u, data.size()); - scoped_ptr<ExtensionSyncData> extension_data = - ExtensionSyncData::CreateFromSyncData(data[0]); - ASSERT_TRUE(extension_data); - EXPECT_TRUE(new_version.Equals(extension_data->version())); - } - - EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(good_crx)); -} - -TEST_F(ExtensionServiceTest, ProcessSyncDataNotInstalled) { - InitializeExtensionServiceWithUpdater(); - syncer::FakeSyncChangeProcessor processor; - extension_sync_service()->MergeDataAndStartSyncing( - syncer::EXTENSIONS, - syncer::SyncDataList(), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::FakeSyncChangeProcessor), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - sync_pb::EntitySpecifics specifics; - sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension(); - ext_specifics->set_id(good_crx); - ext_specifics->set_enabled(false); - ext_specifics->set_incognito_enabled(true); - ext_specifics->set_update_url("http://www.google.com/"); - ext_specifics->set_version("1.2.3.4"); - syncer::SyncData sync_data = - syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); - syncer::SyncChange sync_change(FROM_HERE, - syncer::SyncChange::ACTION_UPDATE, - sync_data); - syncer::SyncChangeList list(1); - list[0] = sync_change; - - EXPECT_TRUE(service()->IsExtensionEnabled(good_crx)); - EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile())); - extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); - EXPECT_TRUE(service()->updater()->WillCheckSoon()); - EXPECT_FALSE(service()->IsExtensionEnabled(good_crx)); - EXPECT_TRUE(extensions::util::IsIncognitoEnabled(good_crx, profile())); - - const extensions::PendingExtensionInfo* info; - EXPECT_TRUE( - (info = service()->pending_extension_manager()->GetById(good_crx))); - EXPECT_EQ(ext_specifics->update_url(), info->update_url().spec()); - EXPECT_TRUE(info->is_from_sync()); - EXPECT_EQ(Manifest::INTERNAL, info->install_source()); - // TODO(akalin): Figure out a way to test |info.ShouldAllowInstall()|. -} - -TEST_F(ExtensionServiceTest, ProcessSyncDataEnableDisable) { - InitializeEmptyExtensionService(); - extension_sync_service()->MergeDataAndStartSyncing( - syncer::EXTENSIONS, - syncer::SyncDataList(), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::FakeSyncChangeProcessor), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - const ExtensionPrefs* prefs = ExtensionPrefs::Get(profile()); - - struct TestCase { - const char* name; // For failure output only. - // Set of disable reasons before any Sync data comes in. If this is != 0, - // the extension is disabled. - int previous_disable_reasons; - bool sync_enable; // The enabled flag coming in from Sync. - // The disable reason(s) coming in from Sync, or -1 for "not set". - int sync_disable_reasons; - // The expected set of disable reasons after processing the Sync update. The - // extension should be disabled iff this is != 0. - int expect_disable_reasons; - } test_cases[] = { - { "NopEnable", 0, true, 0, 0 }, - { "NopDisable", Extension::DISABLE_USER_ACTION, false, - Extension::DISABLE_USER_ACTION, Extension::DISABLE_USER_ACTION }, - { "Disable", 0, false, Extension::DISABLE_USER_ACTION, - Extension::DISABLE_USER_ACTION }, - { "DisableLegacy", 0, false, -1, Extension::DISABLE_UNKNOWN_FROM_SYNC }, - { "AddDisableReason", Extension::DISABLE_REMOTE_INSTALL, false, - Extension::DISABLE_REMOTE_INSTALL | Extension::DISABLE_USER_ACTION, - Extension::DISABLE_REMOTE_INSTALL | Extension::DISABLE_USER_ACTION }, - { "AddDisableReasonLegacy", Extension::DISABLE_USER_ACTION, false, -1, - Extension::DISABLE_USER_ACTION | Extension::DISABLE_UNKNOWN_FROM_SYNC}, - { "RemoveDisableReason", - Extension::DISABLE_REMOTE_INSTALL | Extension::DISABLE_USER_ACTION, false, - Extension::DISABLE_USER_ACTION, Extension::DISABLE_USER_ACTION }, - { "Enable", Extension::DISABLE_USER_ACTION, true, 0, 0 }, - { "EnableLegacy", Extension::DISABLE_USER_ACTION, true, -1, 0 }, - }; - - for (const TestCase& test_case : test_cases) { - SCOPED_TRACE(test_case.name); - - std::string id; - std::string version; - // Don't keep |extension| around longer than necessary. - { - const Extension* extension = - InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW); - // The extension should now be installed and enabled. - ASSERT_TRUE(extension); - id = extension->id(); - version = extension->VersionString(); - } - ASSERT_TRUE(registry()->enabled_extensions().Contains(id)); - - // Disable it if the test case says so. - if (test_case.previous_disable_reasons) { - service()->DisableExtension(id, test_case.previous_disable_reasons); - ASSERT_TRUE(registry()->disabled_extensions().Contains(id)); - } - - // Now a sync update comes in. - sync_pb::EntitySpecifics specifics; - sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension(); - ext_specifics->set_id(id); - ext_specifics->set_enabled(test_case.sync_enable); - ext_specifics->set_version(version); - if (test_case.sync_disable_reasons != -1) - ext_specifics->set_disable_reasons(test_case.sync_disable_reasons); - - syncer::SyncData sync_data = - syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); - syncer::SyncChange sync_change(FROM_HERE, - syncer::SyncChange::ACTION_UPDATE, - sync_data); - syncer::SyncChangeList list(1, sync_change); - extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); - - // Check expectations. - const bool expect_enabled = !test_case.expect_disable_reasons; - EXPECT_EQ(expect_enabled, service()->IsExtensionEnabled(id)); - EXPECT_EQ(test_case.expect_disable_reasons, prefs->GetDisableReasons(id)); - - // Remove the extension again, so we can install it again for the next case. - UninstallExtension(id, false, expect_enabled ? Extension::ENABLED - : Extension::DISABLED); - } -} - -TEST_F(ExtensionServiceTest, ProcessSyncDataDeferredEnable) { - InitializeEmptyExtensionService(); - extension_sync_service()->MergeDataAndStartSyncing( - syncer::EXTENSIONS, - syncer::SyncDataList(), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::FakeSyncChangeProcessor), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - base::FilePath base_path = data_dir().AppendASCII("permissions_increase"); - base::FilePath pem_path = base_path.AppendASCII("permissions.pem"); - - base::FilePath path = base_path.AppendASCII("v1"); - const Extension* extension = PackAndInstallCRX(path, pem_path, INSTALL_NEW); - // The extension must now be installed and enabled. - ASSERT_TRUE(extension); - ASSERT_TRUE(registry()->enabled_extensions().Contains(extension->id())); - - // Save the id, as the extension object will be destroyed during updating. - std::string id = extension->id(); - - // Update to a new version with increased permissions. - path = base_path.AppendASCII("v2"); - PackCRXAndUpdateExtension(id, path, pem_path, DISABLED); - - // Now a sync update comes in, telling us to re-enable a *newer* version. - sync_pb::EntitySpecifics specifics; - sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension(); - ext_specifics->set_id(id); - ext_specifics->set_version("3"); - ext_specifics->set_enabled(true); - ext_specifics->set_disable_reasons(Extension::DISABLE_NONE); - - syncer::SyncData sync_data = - syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); - syncer::SyncChange sync_change(FROM_HERE, - syncer::SyncChange::ACTION_UPDATE, - sync_data); - syncer::SyncChangeList list(1, sync_change); - extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); - - // Since the version didn't match, the extension should still be disabled. - EXPECT_TRUE(registry()->disabled_extensions().Contains(id)); - - // After we update to the matching version, the extension should get enabled. - path = base_path.AppendASCII("v3"); - PackCRXAndUpdateExtension(id, path, pem_path, ENABLED); -} - -TEST_F(ExtensionServiceTest, ProcessSyncDataPermissionApproval) { - // This is the update URL specified in the test extension. Setting it here is - // necessary to make it considered syncable. - base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( - switches::kAppsGalleryUpdateURL, - "http://localhost/autoupdate/updates.xml"); - - InitializeEmptyExtensionService(); - extension_sync_service()->MergeDataAndStartSyncing( - syncer::EXTENSIONS, - syncer::SyncDataList(), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::FakeSyncChangeProcessor), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - const base::FilePath base_path = - data_dir().AppendASCII("permissions_increase"); - const base::FilePath pem_path = base_path.AppendASCII("permissions.pem"); - const base::FilePath path_v1 = base_path.AppendASCII("v1"); - const base::FilePath path_v2 = base_path.AppendASCII("v2"); - - base::ScopedTempDir crx_dir; - ASSERT_TRUE(crx_dir.CreateUniqueTempDir()); - const base::FilePath crx_path_v1 = crx_dir.path().AppendASCII("temp1.crx"); - PackCRX(path_v1, pem_path, crx_path_v1); - const base::FilePath crx_path_v2 = crx_dir.path().AppendASCII("temp2.crx"); - PackCRX(path_v2, pem_path, crx_path_v2); - - const std::string v1("1"); - const std::string v2("2"); - - const ExtensionPrefs* prefs = ExtensionPrefs::Get(profile()); - - struct TestCase { - const char* name; // For failure output only. - const std::string& sync_version; // The version coming in from Sync. - // The disable reason(s) coming in from Sync, or -1 for "not set". - int sync_disable_reasons; - // The expected set of disable reasons after processing the Sync update. The - // extension should be enabled iff this is 0. - int expect_disable_reasons; - // Whether the extension's permissions should be auto-granted. - bool expect_permissions_granted; - } test_cases[] = { - // Sync tells us to re-enable an older version. No permissions should be - // granted, since we can't be sure if the user actually approved the right - // set of permissions. - { "OldVersion", v1, 0, Extension::DISABLE_PERMISSIONS_INCREASE, false }, - // Legacy case: Sync tells us to re-enable the extension, but doesn't - // specify disable reasons. No permissions should be granted. - { "Legacy", v2, -1, Extension::DISABLE_PERMISSIONS_INCREASE, false }, - // Sync tells us to re-enable the extension and explicitly removes the - // disable reasons. Now the extension should have its permissions granted. - { "GrantPermissions", v2, 0, Extension::DISABLE_NONE, true }, - }; - - for (const TestCase& test_case : test_cases) { - SCOPED_TRACE(test_case.name); - - std::string id; - // Don't keep |extension| around longer than necessary (it'll be destroyed - // during updating). - { - const Extension* extension = InstallCRX(crx_path_v1, INSTALL_NEW); - // The extension should now be installed and enabled. - ASSERT_TRUE(extension); - ASSERT_EQ(v1, extension->VersionString()); - id = extension->id(); - } - ASSERT_TRUE(registry()->enabled_extensions().Contains(id)); - - scoped_ptr<const PermissionSet> granted_permissions_v1 = - prefs->GetGrantedPermissions(id); - - // Update to a new version with increased permissions. - UpdateExtension(id, crx_path_v2, DISABLED); - - // Now the extension should be disabled due to a permissions increase. - { - const Extension* extension = - registry()->disabled_extensions().GetByID(id); - ASSERT_TRUE(extension); - ASSERT_EQ(v2, extension->VersionString()); - } - ASSERT_TRUE(prefs->HasDisableReason( - id, Extension::DISABLE_PERMISSIONS_INCREASE)); - - // No new permissions should have been granted. - scoped_ptr<const PermissionSet> granted_permissions_v2 = - prefs->GetGrantedPermissions(id); - ASSERT_EQ(*granted_permissions_v1, *granted_permissions_v2); - - // Now a sync update comes in. - sync_pb::EntitySpecifics specifics; - sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension(); - ext_specifics->set_id(id); - ext_specifics->set_enabled(true); - ext_specifics->set_version(test_case.sync_version); - if (test_case.sync_disable_reasons != -1) - ext_specifics->set_disable_reasons(test_case.sync_disable_reasons); - - syncer::SyncData sync_data = - syncer::SyncData::CreateLocalData(good_crx, "Name", specifics); - syncer::SyncChange sync_change(FROM_HERE, - syncer::SyncChange::ACTION_UPDATE, - sync_data); - syncer::SyncChangeList list(1, sync_change); - extension_sync_service()->ProcessSyncChanges(FROM_HERE, list); - - // Check expectations. - const bool expect_enabled = !test_case.expect_disable_reasons; - EXPECT_EQ(expect_enabled, service()->IsExtensionEnabled(id)); - EXPECT_EQ(test_case.expect_disable_reasons, prefs->GetDisableReasons(id)); - scoped_ptr<const PermissionSet> granted_permissions = - prefs->GetGrantedPermissions(id); - if (test_case.expect_permissions_granted) { - scoped_ptr<const PermissionSet> active_permissions = - prefs->GetActivePermissions(id); - EXPECT_EQ(*granted_permissions, *active_permissions); - } else { - EXPECT_EQ(*granted_permissions, *granted_permissions_v1); - } - - // Remove the extension again, so we can install it again for the next case. - UninstallExtension(id, false, expect_enabled ? Extension::ENABLED - : Extension::DISABLED); - } -} - -#if defined(ENABLE_SUPERVISED_USERS) -class ExtensionServiceTestSupervised : public ExtensionServiceTest, - public SupervisedUserService::Delegate { - public: - void SetUp() override { - ExtensionServiceTest::SetUp(); - - // This is the update URL specified in the permissions test extension. - // Setting it here is necessary to make the extension considered syncable. - base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( - switches::kAppsGalleryUpdateURL, - "http://localhost/autoupdate/updates.xml"); - } - - void TearDown() override { - supervised_user_service()->SetDelegate(nullptr); - - ExtensionServiceTest::TearDown(); - } - - protected: - void InitServices(bool profile_is_supervised) { - ExtensionServiceInitParams params = CreateDefaultInitParams(); - params.profile_is_supervised = profile_is_supervised; - InitializeExtensionService(params); - - supervised_user_service()->SetDelegate(this); - supervised_user_service()->Init(); - } - - std::string InstallPermissionsTestExtension() { - const std::string version("1"); - - const Extension* extension = - PackAndInstallCRX(dir_path(version), pem_path(), INSTALL_NEW, - Extension::WAS_INSTALLED_BY_CUSTODIAN); - // The extension must now be installed and enabled. - EXPECT_TRUE(extension); - EXPECT_TRUE(registry()->enabled_extensions().Contains(extension->id())); - EXPECT_EQ(version, extension->VersionString()); - - return extension->id(); - } - - void UpdatePermissionsTestExtension(const std::string& id, - const std::string& version, - UpdateState expected_state) { - PackCRXAndUpdateExtension(id, dir_path(version), pem_path(), - expected_state); - const Extension* extension = registry()->GetInstalledExtension(id); - ASSERT_TRUE(extension); - // The version should have been updated. - EXPECT_EQ(version, extension->VersionString()); - } - - SupervisedUserService* supervised_user_service() { - return SupervisedUserServiceFactory::GetForProfile(profile()); - } - - static std::string UpdateRequestId(const std::string& extension_id, - const std::string& version) { - return SupervisedUserService::GetExtensionUpdateRequestId( - extension_id, base::Version(version)); - } - - private: - // This prevents the legacy supervised user init code from running. - bool SetActive(bool active) override { return true; } - - base::FilePath base_path() const { - return data_dir().AppendASCII("permissions_increase"); - } - base::FilePath dir_path(const std::string& version) const { - return base_path().AppendASCII("v" + version); - } - base::FilePath pem_path() const { - return base_path().AppendASCII("permissions.pem"); - } -}; - -class MockPermissionRequestCreator : public PermissionRequestCreator { - public: - MockPermissionRequestCreator() {} - ~MockPermissionRequestCreator() override {} - - bool IsEnabled() const override { return true; } - - void CreateURLAccessRequest(const GURL& url_requested, - const SuccessCallback& callback) override { - FAIL(); - } - - MOCK_METHOD2(CreateExtensionUpdateRequest, - void(const std::string& id, - const SupervisedUserService::SuccessCallback& callback)); - - private: - DISALLOW_COPY_AND_ASSIGN(MockPermissionRequestCreator); -}; - -TEST_F(ExtensionServiceTestSupervised, InstallOnlyAllowedByCustodian) { - InitServices(true /* profile_is_supervised */); - - base::FilePath path1 = data_dir().AppendASCII("good.crx"); - base::FilePath path2 = data_dir().AppendASCII("good2048.crx"); - const Extension* extensions[] = { - InstallCRX(path1, INSTALL_FAILED), - InstallCRX(path2, INSTALL_NEW, Extension::WAS_INSTALLED_BY_CUSTODIAN) - }; - - // Only the extension with the "installed by custodian" flag should have been - // installed and enabled. - EXPECT_FALSE(extensions[0]); - ASSERT_TRUE(extensions[1]); - EXPECT_TRUE(registry()->enabled_extensions().Contains(extensions[1]->id())); -} - -TEST_F(ExtensionServiceTestSupervised, PreinstalledExtension) { - InitServices(false /* profile_is_supervised */); - - // Install an extension. - base::FilePath path = data_dir().AppendASCII("good.crx"); - const Extension* extension = InstallCRX(path, INSTALL_NEW); - std::string id = extension->id(); - - // Now make the profile supervised. - profile()->AsTestingProfile()->SetSupervisedUserId( - supervised_users::kChildAccountSUID); - - // The extension should not be enabled anymore. - EXPECT_FALSE(registry()->enabled_extensions().Contains(id)); -} - -TEST_F(ExtensionServiceTestSupervised, UpdateWithoutPermissionIncrease) { - InitServices(true /* profile_is_supervised */); - - base::FilePath base_path = data_dir().AppendASCII("autoupdate"); - base::FilePath pem_path = base_path.AppendASCII("key.pem"); - - const Extension* extension = - PackAndInstallCRX(base_path.AppendASCII("v1"), pem_path, INSTALL_NEW, - Extension::WAS_INSTALLED_BY_CUSTODIAN); - // The extension must now be installed and enabled. - ASSERT_TRUE(extension); - ASSERT_TRUE(registry()->enabled_extensions().Contains(extension->id())); - - // Save the id, as the extension object will be destroyed during updating. - std::string id = extension->id(); - - std::string old_version = extension->VersionString(); - - // Update to a new version. - PackCRXAndUpdateExtension(id, base_path.AppendASCII("v2"), pem_path, ENABLED); - - // The extension should still be there and enabled. - extension = registry()->enabled_extensions().GetByID(id); - ASSERT_TRUE(extension); - // The version should have changed. - EXPECT_NE(extension->VersionString(), old_version); -} - -TEST_F(ExtensionServiceTestSupervised, UpdateWithPermissionIncreaseNoApproval) { - // Explicitly disable the "need custodian approval" field trial. - base::FieldTrialList field_trial_list(new base::MockEntropyProvider()); - base::FieldTrialList::CreateFieldTrial( - "SupervisedUserExtensionPermissionIncrease", ""); - - InitServices(true /* profile_is_supervised */); - - MockPermissionRequestCreator* creator = new MockPermissionRequestCreator; - supervised_user_service()->AddPermissionRequestCreator( - make_scoped_ptr(creator)); - - std::string id = InstallPermissionsTestExtension(); - - // Update to a new version with increased permissions. - // Since we don't require the custodian's approval, no permission request - // should be created. - const std::string version2("2"); - EXPECT_CALL(*creator, CreateExtensionUpdateRequest( - UpdateRequestId(id, version2), testing::_)) - .Times(0); - UpdatePermissionsTestExtension(id, version2, DISABLED); -} - -TEST_F(ExtensionServiceTestSupervised, - UpdateWithPermissionIncreaseApprovalOldVersion) { - // Explicitly enable the "need custodian approval" field trial. - base::FieldTrialList field_trial_list(new base::MockEntropyProvider()); - base::FieldTrialList::CreateFieldTrial( - "SupervisedUserExtensionPermissionIncrease", "NeedCustodianApproval"); - - InitServices(true /* profile_is_supervised */); - - MockPermissionRequestCreator* creator = new MockPermissionRequestCreator; - supervised_user_service()->AddPermissionRequestCreator( - make_scoped_ptr(creator)); - - const std::string version1("1"); - const std::string version2("2"); - - std::string id = InstallPermissionsTestExtension(); - - // Update to a new version with increased permissions. - EXPECT_CALL(*creator, CreateExtensionUpdateRequest( - UpdateRequestId(id, version2), testing::_)); - UpdatePermissionsTestExtension(id, version2, DISABLED); - - // Simulate a custodian approval for re-enabling the extension coming in - // through Sync, but set the old version. This can happen when there already - // was a pending request for an earlier version of the extension. - sync_pb::EntitySpecifics specifics; - sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension(); - ext_specifics->set_id(id); - ext_specifics->set_enabled(true); - ext_specifics->set_disable_reasons(Extension::DISABLE_NONE); - ext_specifics->set_installed_by_custodian(true); - ext_specifics->set_version(version1); - - // Attempting to re-enable an old version should result in a permission - // request for the current version. - EXPECT_CALL(*creator, CreateExtensionUpdateRequest( - UpdateRequestId(id, version2), testing::_)); - - syncer::SyncData sync_data = - syncer::SyncData::CreateLocalData(id, "Name", specifics); - syncer::SyncChange sync_change(FROM_HERE, syncer::SyncChange::ACTION_UPDATE, - sync_data); - syncer::SyncChangeList change_list(1, sync_change); - extension_sync_service()->ProcessSyncChanges(FROM_HERE, change_list); - // The re-enable should be ignored, since the version doesn't match. - EXPECT_FALSE(registry()->enabled_extensions().Contains(id)); - EXPECT_FALSE(extension_sync_service()->HasPendingReenable( - id, base::Version(version1))); - EXPECT_FALSE(extension_sync_service()->HasPendingReenable( - id, base::Version(version2))); -} - -TEST_F(ExtensionServiceTestSupervised, - UpdateWithPermissionIncreaseApprovalMatchingVersion) { - // Explicitly enable the "need custodian approval" field trial. - base::FieldTrialList field_trial_list(new base::MockEntropyProvider()); - base::FieldTrialList::CreateFieldTrial( - "SupervisedUserExtensionPermissionIncrease", "NeedCustodianApproval"); - - InitServices(true /* profile_is_supervised */); - - MockPermissionRequestCreator* creator = new MockPermissionRequestCreator; - supervised_user_service()->AddPermissionRequestCreator( - make_scoped_ptr(creator)); - - std::string id = InstallPermissionsTestExtension(); - - // Update to a new version with increased permissions. - const std::string version2("2"); - EXPECT_CALL(*creator, CreateExtensionUpdateRequest( - UpdateRequestId(id, version2), testing::_)); - UpdatePermissionsTestExtension(id, version2, DISABLED); - - // Simulate a custodian approval for re-enabling the extension coming in - // through Sync. - sync_pb::EntitySpecifics specifics; - sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension(); - ext_specifics->set_id(id); - ext_specifics->set_enabled(true); - ext_specifics->set_disable_reasons(Extension::DISABLE_NONE); - ext_specifics->set_installed_by_custodian(true); - ext_specifics->set_version(version2); - - syncer::SyncData sync_data = - syncer::SyncData::CreateLocalData(id, "Name", specifics); - syncer::SyncChange sync_change(FROM_HERE, syncer::SyncChange::ACTION_UPDATE, - sync_data); - syncer::SyncChangeList change_list(1, sync_change); - extension_sync_service()->ProcessSyncChanges(FROM_HERE, change_list); - // The extension should have gotten re-enabled. - EXPECT_TRUE(registry()->enabled_extensions().Contains(id)); -} - -TEST_F(ExtensionServiceTestSupervised, - UpdateWithPermissionIncreaseApprovalNewVersion) { - // Explicitly enable the "need custodian approval" field trial. - base::FieldTrialList field_trial_list(new base::MockEntropyProvider()); - base::FieldTrialList::CreateFieldTrial( - "SupervisedUserExtensionPermissionIncrease", "NeedCustodianApproval"); - - InitServices(true /* profile_is_supervised */); - - MockPermissionRequestCreator* creator = new MockPermissionRequestCreator; - supervised_user_service()->AddPermissionRequestCreator( - make_scoped_ptr(creator)); - - std::string id = InstallPermissionsTestExtension(); - - // Update to a new version with increased permissions. - const std::string version2("2"); - EXPECT_CALL(*creator, CreateExtensionUpdateRequest( - UpdateRequestId(id, version2), testing::_)); - UpdatePermissionsTestExtension(id, version2, DISABLED); - - // Simulate a custodian approval for re-enabling the extension coming in - // through Sync. Set a newer version than we have installed. - const std::string version3("3"); - sync_pb::EntitySpecifics specifics; - sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension(); - ext_specifics->set_id(id); - ext_specifics->set_enabled(true); - ext_specifics->set_disable_reasons(Extension::DISABLE_NONE); - ext_specifics->set_installed_by_custodian(true); - ext_specifics->set_version(version3); - - // This should *not* result in a new permission request. - EXPECT_CALL(*creator, CreateExtensionUpdateRequest( - UpdateRequestId(id, version3), testing::_)) - .Times(0); - - syncer::SyncData sync_data = - syncer::SyncData::CreateLocalData(id, "Name", specifics); - syncer::SyncChange sync_change(FROM_HERE, syncer::SyncChange::ACTION_UPDATE, - sync_data); - syncer::SyncChangeList change_list(1, sync_change); - extension_sync_service()->ProcessSyncChanges(FROM_HERE, change_list); - // The re-enable should be delayed until the extension is updated to the - // matching version. - EXPECT_FALSE(registry()->enabled_extensions().Contains(id)); - EXPECT_TRUE(extension_sync_service()->HasPendingReenable( - id, base::Version(version3))); - - // Update to the matching version. Now the extension should get enabled. - UpdatePermissionsTestExtension(id, version3, ENABLED); -} - -TEST_F(ExtensionServiceTest, SyncUninstallByCustodianSkipsPolicy) { - InitializeEmptyExtensionService(); - extension_sync_service()->MergeDataAndStartSyncing( - syncer::EXTENSIONS, - syncer::SyncDataList(), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::FakeSyncChangeProcessor), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - // Install two extensions. - base::FilePath path1 = data_dir().AppendASCII("good.crx"); - base::FilePath path2 = data_dir().AppendASCII("good2048.crx"); - const Extension* extensions[] = { - InstallCRX(path1, INSTALL_NEW), - InstallCRX(path2, INSTALL_NEW, Extension::WAS_INSTALLED_BY_CUSTODIAN) - }; - - // Add a policy provider that will disallow any changes. - extensions::TestManagementPolicyProvider provider( - extensions::TestManagementPolicyProvider::PROHIBIT_MODIFY_STATUS); - GetManagementPolicy()->RegisterProvider(&provider); - - // Create a sync deletion for each extension. - syncer::SyncChangeList change_list; - for (size_t i = 0; i < arraysize(extensions); i++) { - const std::string& id = extensions[i]->id(); - sync_pb::EntitySpecifics specifics; - sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension(); - ext_specifics->set_id(id); - ext_specifics->set_version("1.0"); - ext_specifics->set_installed_by_custodian( - extensions[i]->was_installed_by_custodian()); - syncer::SyncData sync_data = - syncer::SyncData::CreateLocalData(id, "Name", specifics); - change_list.push_back(syncer::SyncChange(FROM_HERE, - syncer::SyncChange::ACTION_DELETE, - sync_data)); - } - - // Save the extension ids, as uninstalling destroys the Extension instance. - std::string extension_ids[] = { - extensions[0]->id(), - extensions[1]->id() - }; - - // Now apply the uninstallations. - extension_sync_service()->ProcessSyncChanges(FROM_HERE, change_list); - - // Uninstalling the extension without installed_by_custodian should have been - // blocked by policy, so it should still be there. - EXPECT_TRUE(registry()->enabled_extensions().Contains(extension_ids[0])); - - // But installed_by_custodian should result in bypassing the policy check. - EXPECT_FALSE( - registry()->GenerateInstalledExtensionsSet()->Contains(extension_ids[1])); -} -#endif // defined(ENABLE_SUPERVISED_USERS) - TEST_F(ExtensionServiceTest, InstallPriorityExternalUpdateUrl) { InitializeEmptyExtensionService();
diff --git a/chrome/browser/google/google_update_win.cc b/chrome/browser/google/google_update_win.cc index 97d354a..0671501a 100644 --- a/chrome/browser/google/google_update_win.cc +++ b/chrome/browser/google/google_update_win.cc
@@ -403,6 +403,12 @@ installer_exit_code_); } } + + // Clear the driver before calling the delegates because they might call + // BeginUpdateCheck() and they must not add themselves to the current + // instance of UpdateCheckDriver, which is currently being destroyed. + driver_ = nullptr; + for (const auto& delegate : delegates_) { if (delegate) { if (status_ == UPGRADE_ERROR) @@ -413,8 +419,6 @@ delegate->OnUpdateCheckComplete(new_version_); } } - - driver_ = nullptr; } void UpdateCheckDriver::BeginUpdateCheck() {
diff --git a/chrome/browser/memory/tab_manager_web_contents_data.cc b/chrome/browser/memory/tab_manager_web_contents_data.cc index 42e31f7..eb51466f 100644 --- a/chrome/browser/memory/tab_manager_web_contents_data.cc +++ b/chrome/browser/memory/tab_manager_web_contents_data.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/memory/tab_manager_web_contents_data.h" #include "base/metrics/histogram.h" +#include "chrome/browser/browser_process.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/web_contents.h" @@ -26,6 +27,23 @@ SetDiscardState(false); } +void TabManager::WebContentsData::WebContentsDestroyed() { + // If Chrome is shutting down, ignore this event. + if (g_browser_process->IsShuttingDown()) + return; + + // If the tab has been previously discarded but is not currently discarded + // (ie. it has been reloaded), we want to record the time it took between the + // reload event and the closing of the tab. + if (tab_data_.discard_count_ > 0 && !tab_data_.is_discarded_) { + auto delta = base::TimeTicks::Now() - tab_data_.last_reload_time_; + // Capped to one day for now, will adjust if necessary. + UMA_HISTOGRAM_CUSTOM_TIMES("TabManager.Discarding.ReloadToCloseTime", delta, + base::TimeDelta::FromSeconds(1), + base::TimeDelta::FromDays(1), 100); + } +} + bool TabManager::WebContentsData::IsDiscarded() { return tab_data_.is_discarded_; } @@ -40,6 +58,7 @@ UMA_HISTOGRAM_CUSTOM_TIMES("TabManager.Discarding.DiscardToReloadTime", delta, base::TimeDelta::FromSeconds(1), base::TimeDelta::FromDays(1), 100); + tab_data_.last_reload_time_ = base::TimeTicks::Now(); } else if (!tab_data_.is_discarded_ && state) { static int discard_count = 0; UMA_HISTOGRAM_CUSTOM_COUNTS("TabManager.Discarding.DiscardCount", @@ -90,6 +109,8 @@ : is_discarded_(false), discard_count_(0), is_recently_audible_(false), - last_audio_change_time_(TimeTicks::UnixEpoch()) {} + last_audio_change_time_(TimeTicks::UnixEpoch()), + last_discard_time_(TimeTicks::UnixEpoch()), + last_reload_time_(TimeTicks::UnixEpoch()) {} } // namespace memory
diff --git a/chrome/browser/memory/tab_manager_web_contents_data.h b/chrome/browser/memory/tab_manager_web_contents_data.h index 11d28af..0427d51 100644 --- a/chrome/browser/memory/tab_manager_web_contents_data.h +++ b/chrome/browser/memory/tab_manager_web_contents_data.h
@@ -28,6 +28,7 @@ // WebContentsObserver implementation: void DidStartLoading() override; + void WebContentsDestroyed() override; // Returns true if |web_contents| has been discarded to save memory. bool IsDiscarded(); @@ -73,6 +74,8 @@ base::TimeTicks last_audio_change_time_; // The last time the tab was discarded. base::TimeTicks last_discard_time_; + // The last time the tab was reloaded after being discarded. + base::TimeTicks last_reload_time_; }; Data tab_data_;
diff --git a/chrome/browser/memory_details.cc b/chrome/browser/memory_details.cc index fbf669df..b210f92 100644 --- a/chrome/browser/memory_details.cc +++ b/chrome/browser/memory_details.cc
@@ -216,83 +216,102 @@ #endif ProcessData* const chrome_browser = ChromeBrowser(); + + // First pass, collate the widgets by process ID. + std::map<base::ProcessId, std::vector<RenderWidgetHost*>> widgets_by_pid; + scoped_ptr<content::RenderWidgetHostIterator> widget_it( + RenderWidgetHost::GetRenderWidgetHosts()); + while (content::RenderWidgetHost* widget = widget_it->GetNextHost()) { + // Ignore processes that don't have a connection, such as crashed tabs. + if (!widget->GetProcess()->HasConnection()) + continue; + base::ProcessId pid = base::GetProcId(widget->GetProcess()->GetHandle()); + widgets_by_pid[pid].push_back(widget); + } + // Get more information about the process. - for (size_t index = 0; index < chrome_browser->processes.size(); - index++) { - // Check if it's a renderer, if so get the list of page titles in it and - // check if it's a diagnostics-related process. We skip about:memory pages. - // Iterate the RenderProcessHosts to find the tab contents. - ProcessMemoryInformation& process = - chrome_browser->processes[index]; - - scoped_ptr<content::RenderWidgetHostIterator> widgets( - RenderWidgetHost::GetRenderWidgetHosts()); - while (content::RenderWidgetHost* widget = widgets->GetNextHost()) { - content::RenderProcessHost* render_process_host = - widget->GetProcess(); - DCHECK(render_process_host); - // Ignore processes that don't have a connection, such as crashed tabs. - if (!render_process_host->HasConnection() || - process.pid != base::GetProcId(render_process_host->GetHandle())) { - continue; - } - - // The RenderProcessHost may host multiple WebContentses. Any - // of them which contain diagnostics information make the whole - // process be considered a diagnostics process. - RenderViewHost* host = RenderViewHost::From(widget); - if (!host) - continue; - + for (ProcessMemoryInformation& process : chrome_browser->processes) { + // If there's at least one widget in the process, it is some kind of + // renderer process belonging to this browser. All these widgets will share + // a RenderProcessHost. + content::RenderProcessHost* render_process_host = nullptr; + if (!widgets_by_pid[process.pid].empty()) { + // Mark it as a normal renderer process, if we don't refine it to some + // other |renderer_type| later. process.process_type = content::PROCESS_TYPE_RENDERER; - bool is_extension = false; + process.renderer_type = ProcessMemoryInformation::RENDERER_NORMAL; + render_process_host = widgets_by_pid[process.pid].front()->GetProcess(); + } + #if defined(ENABLE_EXTENSIONS) + // Determine if this is an extension process. + bool process_is_for_extensions = false; + if (render_process_host) { content::BrowserContext* context = render_process_host->GetBrowserContext(); extensions::ExtensionRegistry* extension_registry = extensions::ExtensionRegistry::Get(context); - extensions::ProcessMap* extension_process_map = + extensions::ProcessMap* process_map = extensions::ProcessMap::Get(context); - is_extension = extension_process_map->Contains( - host->GetProcess()->GetID()); + int rph_id = render_process_host->GetID(); + process_is_for_extensions = process_map->Contains(rph_id); + + // For our purposes, don't count processes containing only hosted apps + // as extension processes. See also: crbug.com/102533. + for (auto& extension_id : process_map->GetExtensionsInProcess(rph_id)) { + const Extension* extension = + extension_registry->enabled_extensions().GetByID(extension_id); + if (extension && !extension->is_hosted_app()) { + process.renderer_type = ProcessMemoryInformation::RENDERER_EXTENSION; + break; + } + } + } #endif - WebContents* contents = WebContents::FromRenderViewHost(host); - GURL url; - if (contents) { - url = contents->GetURL(); - SiteData* site_data = - &chrome_browser->site_data[contents->GetBrowserContext()]; - SiteDetails::CollectSiteInfo(contents, site_data); + // Use the list of widgets to iterate over the WebContents instances whose + // main RenderFrameHosts are in |process|. Refine our determination of the + // |process.renderer_type|, and record the page titles. + for (content::RenderWidgetHost* widget : widgets_by_pid[process.pid]) { + DCHECK_EQ(render_process_host, widget->GetProcess()); + + RenderViewHost* rvh = RenderViewHost::From(widget); + if (!rvh) + continue; + + WebContents* contents = WebContents::FromRenderViewHost(rvh); + + // Assume that an RVH without a web contents is an interstitial. + if (!contents) { + process.renderer_type = ProcessMemoryInformation::RENDERER_INTERSTITIAL; + continue; } -#if defined(ENABLE_EXTENSIONS) - extensions::ViewType type = extensions::GetViewType(contents); -#endif - if (host->GetEnabledBindings() & content::BINDINGS_POLICY_WEB_UI) { + + // If this is a RVH for a subframe; skip it to avoid double-counting the + // WebContents. + if (rvh != contents->GetRenderViewHost()) + continue; + + // The rest of this block will happen only once per WebContents. + GURL page_url = contents->GetLastCommittedURL(); + SiteData& site_data = + chrome_browser->site_data[contents->GetBrowserContext()]; + SiteDetails::CollectSiteInfo(contents, &site_data); + + bool is_webui = + rvh->GetEnabledBindings() & content::BINDINGS_POLICY_WEB_UI; + + if (is_webui) { process.renderer_type = ProcessMemoryInformation::RENDERER_CHROME; - } else if (is_extension) { -#if defined(ENABLE_EXTENSIONS) - // For our purposes, don't count processes containing only hosted apps - // as extension processes. See also: crbug.com/102533. - std::set<std::string> extension_ids = - extension_process_map->GetExtensionsInProcess( - host->GetProcess()->GetID()); - for (std::set<std::string>::iterator iter = extension_ids.begin(); - iter != extension_ids.end(); ++iter) { - const Extension* extension = - extension_registry->enabled_extensions().GetByID(*iter); - if (extension && !extension->is_hosted_app()) { - process.renderer_type = - ProcessMemoryInformation::RENDERER_EXTENSION; - break; - } - } -#endif } + #if defined(ENABLE_EXTENSIONS) - if (is_extension) { + if (!is_webui && process_is_for_extensions) { const Extension* extension = - extension_registry->enabled_extensions().GetByID(url.host()); + extensions::ExtensionRegistry::Get( + render_process_host->GetBrowserContext()) + ->enabled_extensions() + .GetByID(page_url.host()); if (extension) { base::string16 title = base::UTF8ToUTF16(extension->name()); process.titles.push_back(title); @@ -301,33 +320,24 @@ continue; } } -#endif - if (!contents) { - process.renderer_type = - ProcessMemoryInformation::RENDERER_INTERSTITIAL; - continue; - } - -#if defined(ENABLE_EXTENSIONS) + extensions::ViewType type = extensions::GetViewType(contents); if (type == extensions::VIEW_TYPE_BACKGROUND_CONTENTS) { - process.titles.push_back(base::UTF8ToUTF16(url.spec())); + process.titles.push_back(base::UTF8ToUTF16(page_url.spec())); process.renderer_type = ProcessMemoryInformation::RENDERER_BACKGROUND_APP; continue; } #endif - // Since we have a WebContents and and the renderer type hasn't been - // set yet, it must be a normal tabbed renderer. - if (process.renderer_type == ProcessMemoryInformation::RENDERER_UNKNOWN) - process.renderer_type = ProcessMemoryInformation::RENDERER_NORMAL; - base::string16 title = contents->GetTitle(); if (!title.length()) title = l10n_util::GetStringUTF16(IDS_DEFAULT_TAB_TITLE); process.titles.push_back(title); + // The presence of a single WebContents with a diagnostics page will make + // the whole process be considered a diagnostics process. + // // We need to check the pending entry as well as the virtual_url to // see if it's a chrome://memory URL (we don't want to count these in // the total memory usage of the browser). @@ -363,15 +373,12 @@ } // Get rid of other Chrome processes that are from a different profile. - for (size_t index = 0; index < chrome_browser->processes.size(); - index++) { - if (chrome_browser->processes[index].process_type == - content::PROCESS_TYPE_UNKNOWN) { - chrome_browser->processes.erase( - chrome_browser->processes.begin() + index); - index--; - } - } + auto is_unknown = [](ProcessMemoryInformation& process) { + return process.process_type == content::PROCESS_TYPE_UNKNOWN; + }; + auto& vector = chrome_browser->processes; + vector.erase(std::remove_if(vector.begin(), vector.end(), is_unknown), + vector.end()); OnDetailsAvailable(); }
diff --git a/chrome/browser/metrics/chromeos_metrics_provider_unittest.cc b/chrome/browser/metrics/chromeos_metrics_provider_unittest.cc index f0fc27d..19d02b2 100644 --- a/chrome/browser/metrics/chromeos_metrics_provider_unittest.cc +++ b/chrome/browser/metrics/chromeos_metrics_provider_unittest.cc
@@ -115,20 +115,20 @@ }; TEST_F(ChromeOSMetricsProviderTest, MultiProfileUserCount) { - const AccountId account_id1(AccountId::FromUserEmail("user1@example.com")); - const AccountId account_id2(AccountId::FromUserEmail("user2@example.com")); - const AccountId account_id3(AccountId::FromUserEmail("user3@example.com")); + std::string user1("user1@example.com"); + std::string user2("user2@example.com"); + std::string user3("user3@example.com"); // |scoped_enabler| takes over the lifetime of |user_manager|. chromeos::FakeChromeUserManager* user_manager = new chromeos::FakeChromeUserManager(); chromeos::ScopedUserManagerEnabler scoped_enabler(user_manager); - user_manager->AddKioskAppUser(account_id1); - user_manager->AddKioskAppUser(account_id2); - user_manager->AddKioskAppUser(account_id3); + user_manager->AddKioskAppUser(user1); + user_manager->AddKioskAppUser(user2); + user_manager->AddKioskAppUser(user3); - user_manager->LoginUser(account_id1); - user_manager->LoginUser(account_id3); + user_manager->LoginUser(user1); + user_manager->LoginUser(user3); ChromeOSMetricsProvider provider; provider.OnDidCreateMetricsLog(); @@ -138,19 +138,19 @@ } TEST_F(ChromeOSMetricsProviderTest, MultiProfileCountInvalidated) { - const AccountId account_id1(AccountId::FromUserEmail("user1@example.com")); - const AccountId account_id2(AccountId::FromUserEmail("user2@example.com")); - const AccountId account_id3(AccountId::FromUserEmail("user3@example.com")); + std::string user1("user1@example.com"); + std::string user2("user2@example.com"); + std::string user3("user3@example.com"); // |scoped_enabler| takes over the lifetime of |user_manager|. chromeos::FakeChromeUserManager* user_manager = new chromeos::FakeChromeUserManager(); chromeos::ScopedUserManagerEnabler scoped_enabler(user_manager); - user_manager->AddKioskAppUser(account_id1); - user_manager->AddKioskAppUser(account_id2); - user_manager->AddKioskAppUser(account_id3); + user_manager->AddKioskAppUser(user1); + user_manager->AddKioskAppUser(user2); + user_manager->AddKioskAppUser(user3); - user_manager->LoginUser(account_id1); + user_manager->LoginUser(user1); ChromeOSMetricsProvider provider; provider.OnDidCreateMetricsLog(); @@ -159,7 +159,7 @@ provider.ProvideSystemProfileMetrics(&system_profile); EXPECT_EQ(1u, system_profile.multi_profile_user_count()); - user_manager->LoginUser(account_id2); + user_manager->LoginUser(user2); provider.ProvideSystemProfileMetrics(&system_profile); EXPECT_EQ(0u, system_profile.multi_profile_user_count()); }
diff --git a/chrome/browser/metrics/first_web_contents_profiler.cc b/chrome/browser/metrics/first_web_contents_profiler.cc index cbeef39..1b3a6800 100644 --- a/chrome/browser/metrics/first_web_contents_profiler.cc +++ b/chrome/browser/metrics/first_web_contents_profiler.cc
@@ -11,9 +11,6 @@ #include "base/location.h" #include "base/logging.h" #include "base/metrics/histogram_macros.h" -#include "base/process/process_info.h" -#include "base/single_thread_task_runner.h" -#include "base/thread_task_runner_handle.h" #include "base/time/time.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_iterator.h" @@ -21,83 +18,8 @@ #include "components/metrics/profiler/tracking_synchronizer.h" #include "components/metrics/proto/profiler_event.pb.h" #include "components/startup_metric_utils/startup_metric_utils.h" -#include "content/public/browser/browser_thread.h" #include "content/public/browser/navigation_handle.h" -namespace { - -// The initial delay for responsiveness prober in milliseconds. -const int kInitialDelayMs = 20; - -// The following is the multiplier is used to delay the probe for -// responsiveness. -const double kBackoffMultiplier = 1.5; - -// The maximum backoff delay in milliseconds. -const int kMaxDelayMs = 250; - -void DelayedRecordUIResponsiveness( - base::HistogramBase* responsiveness_histogram, - base::HistogramBase* unresponsiveness_histogram, - base::Time start_recording_time, - base::TimeDelta next_task_delay); - -// Records the elapsed time for a task to execute a UI task under 1/60s after -// the first WebContent was painted at least once. If after few tries it is -// unable to execute under 1/60s it records the execution time of a task. -void RecordUIResponsiveness(base::HistogramBase* responsiveness_histogram, - base::HistogramBase* unresponsiveness_histogram, - base::Time start_recording_time, - base::Time task_posted_time, - base::TimeDelta next_task_delay) { - DCHECK(!start_recording_time.is_null()); - DCHECK(!task_posted_time.is_null()); - base::Time now = base::Time::Now(); - base::TimeDelta elapsed = now - task_posted_time; - - // Task executed in less then 1/60s. - if (elapsed.InMilliseconds() <= (1000 / 60)) { - responsiveness_histogram->AddTime(now - start_recording_time); - } else if (next_task_delay.InMilliseconds() > kMaxDelayMs) { - // Records elapsed time to execute last task. - unresponsiveness_histogram->AddTime(elapsed); - } else { - base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, - base::Bind(&DelayedRecordUIResponsiveness, responsiveness_histogram, - unresponsiveness_histogram, start_recording_time, - next_task_delay * kBackoffMultiplier), - next_task_delay); - } -} - -// Used for posting |RecordUIResponsiveness| without delay, so that -// |RecordUIResponsiveness| can do more accurate time calculation for elapsed -// time of the task to complete. -void DelayedRecordUIResponsiveness( - base::HistogramBase* responsiveness_histogram, - base::HistogramBase* unresponsiveness_histogram, - base::Time start_recording_time, - base::TimeDelta next_task_delay) { - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&RecordUIResponsiveness, responsiveness_histogram, - unresponsiveness_histogram, start_recording_time, - base::Time::Now(), next_task_delay)); -} - -// Sends the first task for measuring UI Responsiveness. -void MeasureUIResponsiveness(base::HistogramBase* responsiveness_histogram, - base::HistogramBase* unresponsiveness_histogram) { - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::Bind(&RecordUIResponsiveness, responsiveness_histogram, - unresponsiveness_histogram, base::Time::Now(), - base::Time::Now(), - base::TimeDelta::FromMilliseconds(kInitialDelayMs))); -} - -} // namespace - scoped_ptr<FirstWebContentsProfiler> FirstWebContentsProfiler::CreateProfilerForFirstWebContents( Delegate* delegate) { @@ -123,15 +45,7 @@ collected_main_navigation_start_metric_(false), collected_main_navigation_finished_metric_(false), finished_(false), - delegate_(delegate), - responsiveness_histogram_(NULL), - responsiveness_1sec_histogram_(NULL), - responsiveness_10sec_histogram_(NULL), - unresponsiveness_histogram_(NULL), - unresponsiveness_1sec_histogram_(NULL), - unresponsiveness_10sec_histogram_(NULL) { - InitHistograms(); -} + delegate_(delegate) {} void FirstWebContentsProfiler::DidFirstVisuallyNonEmptyPaint() { if (collected_paint_metric_) @@ -151,26 +65,6 @@ metrics::TrackingSynchronizer::OnProfilingPhaseCompleted( metrics::ProfilerEventProto::EVENT_FIRST_NONEMPTY_PAINT); - // Measures responsiveness now. - MeasureUIResponsiveness(responsiveness_histogram_, - unresponsiveness_histogram_); - - // As it was observed that sometimes the task queue can be free immediately - // after the first paint but get overloaded shortly thereafter, here we - // measures responsiveness after 1 second and 10 seconds to observe the - // possible effect of those late tasks. - base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, - base::Bind(&MeasureUIResponsiveness, responsiveness_1sec_histogram_, - unresponsiveness_1sec_histogram_), - base::TimeDelta::FromSeconds(1)); - - base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, - base::Bind(&MeasureUIResponsiveness, responsiveness_10sec_histogram_, - unresponsiveness_10sec_histogram_), - base::TimeDelta::FromSeconds(10)); - if (IsFinishedCollectingMetrics()) FinishedCollectingMetrics(FinishReason::DONE); } @@ -281,47 +175,4 @@ delegate_->ProfilerFinishedCollectingMetrics(); } -void FirstWebContentsProfiler::InitHistograms() { - const std::string responsiveness_histogram_name = - "Startup.FirstWebContents.UIResponsive"; - responsiveness_histogram_ = base::Histogram::FactoryTimeGet( - responsiveness_histogram_name, base::TimeDelta::FromMilliseconds(1), - base::TimeDelta::FromSeconds(60), 100, - base::Histogram::kUmaTargetedHistogramFlag); - - const std::string responsiveness_1sec_histogram_name = - "Startup.FirstWebContents.UIResponsive_1sec"; - responsiveness_1sec_histogram_ = base::Histogram::FactoryTimeGet( - responsiveness_1sec_histogram_name, base::TimeDelta::FromMilliseconds(1), - base::TimeDelta::FromSeconds(60), 100, - base::Histogram::kUmaTargetedHistogramFlag); - - const std::string responsiveness_10sec_histogram_name = - "Startup.FirstWebContents.UIResponsive_10sec"; - responsiveness_10sec_histogram_ = base::Histogram::FactoryTimeGet( - responsiveness_10sec_histogram_name, base::TimeDelta::FromMilliseconds(1), - base::TimeDelta::FromSeconds(60), 100, - base::Histogram::kUmaTargetedHistogramFlag); - - const std::string unresponsiveness_histogram_name = - "Startup.FirstWebContents.UINotResponsive"; - unresponsiveness_histogram_ = base::Histogram::FactoryTimeGet( - unresponsiveness_histogram_name, base::TimeDelta::FromMilliseconds(1), - base::TimeDelta::FromSeconds(60), 100, - base::Histogram::kUmaTargetedHistogramFlag); - - const std::string unresponsiveness_1sec_histogram_name = - "Startup.FirstWebContents.UINotResponsive_1sec"; - unresponsiveness_1sec_histogram_ = base::Histogram::FactoryTimeGet( - unresponsiveness_1sec_histogram_name, - base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromSeconds(60), - 100, base::Histogram::kUmaTargetedHistogramFlag); - - const std::string unresponsiveness_10sec_histogram_name = - "Startup.FirstWebContents.UINotResponsive_10sec"; - unresponsiveness_10sec_histogram_ = base::Histogram::FactoryTimeGet( - unresponsiveness_10sec_histogram_name, - base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromSeconds(60), - 100, base::Histogram::kUmaTargetedHistogramFlag); -} #endif // !defined(OS_ANDROID)
diff --git a/chrome/browser/metrics/first_web_contents_profiler.h b/chrome/browser/metrics/first_web_contents_profiler.h index d0cf306d..d35c98a 100644 --- a/chrome/browser/metrics/first_web_contents_profiler.h +++ b/chrome/browser/metrics/first_web_contents_profiler.h
@@ -6,7 +6,6 @@ #define CHROME_BROWSER_METRICS_FIRST_WEB_CONTENTS_PROFILER_H_ #include "base/memory/scoped_ptr.h" -#include "base/metrics/histogram.h" #include "content/public/browser/web_contents_observer.h" namespace content { @@ -74,9 +73,6 @@ // metrics. Logs |finish_reason| to UMA. void FinishedCollectingMetrics(FinishReason finish_reason); - // Initialize histograms for unresponsiveness metrics. - void InitHistograms(); - // Whether an attempt was made to collect the "NonEmptyPaint" metric. bool collected_paint_metric_; @@ -97,24 +93,6 @@ // |delegate_| owns |this|. Delegate* delegate_; - // Histogram that keeps track of response times for the watched thread. - base::HistogramBase* responsiveness_histogram_; - - // Histogram that keeps track of response times for the watched thread. - base::HistogramBase* responsiveness_1sec_histogram_; - - // Histogram that keeps track of response times for the watched thread. - base::HistogramBase* responsiveness_10sec_histogram_; - - // Histogram that keeps track of response times for the watched thread. - base::HistogramBase* unresponsiveness_histogram_; - - // Histogram that keeps track of response times for the watched thread. - base::HistogramBase* unresponsiveness_1sec_histogram_; - - // Histogram that keeps track of response times for the watched thread. - base::HistogramBase* unresponsiveness_10sec_histogram_; - DISALLOW_COPY_AND_ASSIGN(FirstWebContentsProfiler); };
diff --git a/chrome/browser/metrics/variations/BUILD.gn b/chrome/browser/metrics/variations/BUILD.gn index ed39b8c..2c421d3ec 100644 --- a/chrome/browser/metrics/variations/BUILD.gn +++ b/chrome/browser/metrics/variations/BUILD.gn
@@ -7,10 +7,26 @@ # GYP version: chrome/chrome_resources.gyp:chrome_ui_string_overrider_factory generate_ui_string_overrider("chrome_ui_string_overrider_factory") { inputs = [ + "$root_gen_dir/chrome/grit/chromium_strings.h", "$root_gen_dir/chrome/grit/generated_resources.h", + "$root_gen_dir/chrome/grit/google_chrome_strings.h", + "$root_gen_dir/chrome/grit/settings_chromium_strings.h", + "$root_gen_dir/chrome/grit/settings_google_chrome_strings.h", + "$root_gen_dir/chrome/grit/settings_strings.h", + "$root_gen_dir/components/strings/grit/components_chromium_strings.h", + "$root_gen_dir/components/strings/grit/components_google_chrome_strings.h", + "$root_gen_dir/components/strings/grit/components_strings.h", ] deps = [ + "//chrome/app:chromium_strings", "//chrome/app:generated_resources", + "//chrome/app:google_chrome_strings", + "//chrome/app:settings_chromium_strings", + "//chrome/app:settings_google_chrome_strings", + "//chrome/app:settings_strings", + "//components/strings:components_chromium_strings", + "//components/strings:components_google_chrome_strings", + "//components/strings:components_strings", ] namespace = "chrome_variations" header_filename = "ui_string_overrider_factory.h"
diff --git a/chrome/browser/net/nss_context_chromeos_browsertest.cc b/chrome/browser/net/nss_context_chromeos_browsertest.cc index 616549c..bcc869c8 100644 --- a/chrome/browser/net/nss_context_chromeos_browsertest.cc +++ b/chrome/browser/net/nss_context_chromeos_browsertest.cc
@@ -136,7 +136,7 @@ // Log in first user and get their DB. LoginUser(kTestUser1); Profile* profile1 = chromeos::ProfileHelper::Get()->GetProfileByUserUnsafe( - user_manager->FindUser(AccountId::FromUserEmail(kTestUser1))); + user_manager->FindUser(kTestUser1)); ASSERT_TRUE(profile1); DBTester tester1(profile1); @@ -148,7 +148,7 @@ AddUser(kTestUser2); Profile* profile2 = chromeos::ProfileHelper::Get()->GetProfileByUserUnsafe( - user_manager->FindUser(AccountId::FromUserEmail(kTestUser2))); + user_manager->FindUser(kTestUser2)); ASSERT_TRUE(profile2); DBTester tester2(profile2);
diff --git a/chrome/browser/notifications/message_center_settings_controller_unittest.cc b/chrome/browser/notifications/message_center_settings_controller_unittest.cc index cb5dc53..2a671d5 100644 --- a/chrome/browser/notifications/message_center_settings_controller_unittest.cc +++ b/chrome/browser/notifications/message_center_settings_controller_unittest.cc
@@ -90,13 +90,13 @@ TestingProfile* profile = MessageCenterSettingsControllerBaseTest::CreateProfile(name); - GetFakeUserManager()->AddUser(AccountId::FromUserEmail(name)); - GetFakeUserManager()->LoginUser(AccountId::FromUserEmail(name)); + GetFakeUserManager()->AddUser(name); + GetFakeUserManager()->LoginUser(name); return profile; } void SwitchActiveUser(const std::string& name) { - GetFakeUserManager()->SwitchActiveUser(AccountId::FromUserEmail(name)); + GetFakeUserManager()->SwitchActiveUser(name); controller()->ActiveUserChanged(GetFakeUserManager()->GetActiveUser()); }
diff --git a/chrome/browser/prerender/prerender_contents.cc b/chrome/browser/prerender/prerender_contents.cc index cd3789c..29910137 100644 --- a/chrome/browser/prerender/prerender_contents.cc +++ b/chrome/browser/prerender/prerender_contents.cc
@@ -525,8 +525,8 @@ session_storage_namespace_id_ != session_storage_namespace->id()) { return false; } - return std::count_if(alias_urls_.begin(), alias_urls_.end(), - std::bind2nd(std::equal_to<GURL>(), url)) != 0; + return std::find(alias_urls_.begin(), alias_urls_.end(), url) != + alias_urls_.end(); } void PrerenderContents::RenderProcessGone(base::TerminationStatus status) {
diff --git a/chrome/browser/profiles/profile_impl.cc b/chrome/browser/profiles/profile_impl.cc index a9c64e2..e029bd8 100644 --- a/chrome/browser/profiles/profile_impl.cc +++ b/chrome/browser/profiles/profile_impl.cc
@@ -1132,8 +1132,8 @@ if (via != APP_LOCALE_CHANGED_VIA_PUBLIC_SESSION_LOGIN) local_state->SetString(prefs::kApplicationLocale, new_locale); - if (user_manager::UserManager::Get()->GetOwnerAccountId() == - chromeos::ProfileHelper::Get()->GetUserByProfile(this)->GetAccountId()) + if (user_manager::UserManager::Get()->GetOwnerEmail() == + chromeos::ProfileHelper::Get()->GetUserByProfile(this)->email()) local_state->SetString(prefs::kOwnerLocale, new_locale); }
diff --git a/chrome/browser/profiles/profile_manager_unittest.cc b/chrome/browser/profiles/profile_manager_unittest.cc index 77e352d..89a2af4f 100644 --- a/chrome/browser/profiles/profile_manager_unittest.cc +++ b/chrome/browser/profiles/profile_manager_unittest.cc
@@ -161,7 +161,7 @@ const std::string user_id_hash = profile_helper->GetUserIdHashByUserIdForTesting(user_id); user_manager::UserManager::Get()->UserLoggedIn( - AccountId::FromUserEmail(user_id), user_id_hash, false); + user_id, user_id_hash, false); g_browser_process->profile_manager()->GetProfile( profile_helper->GetProfilePathByUserIdHash(user_id_hash)); } @@ -227,15 +227,13 @@ profile_manager->GetInitialProfileDir().value()); const char kTestUserName[] = "test-user@example.com"; - const AccountId test_account_id(AccountId::FromUserEmail(kTestUserName)); chromeos::FakeChromeUserManager* user_manager = new chromeos::FakeChromeUserManager(); chromeos::ScopedUserManagerEnabler enabler(user_manager); - const user_manager::User* active_user = - user_manager->AddUser(test_account_id); - user_manager->LoginUser(test_account_id); - user_manager->SwitchActiveUser(test_account_id); + const user_manager::User* active_user = user_manager->AddUser(kTestUserName); + user_manager->LoginUser(kTestUserName); + user_manager->SwitchActiveUser(kTestUserName); profile_manager->Observe( chrome::NOTIFICATION_LOGIN_USER_CHANGED,
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 2036d5c..3891232 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
@@ -49,7 +49,6 @@ #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/profiles/profile_helper.h" -#include "components/signin/core/account_id/account_id.h" #include "components/user_manager/user_manager.h" #endif @@ -110,9 +109,8 @@ #if defined(OS_CHROMEOS) std::string profile_name = base::StringPrintf("NewProfile%d", profile_num); user_manager::UserManager::Get()->UserLoggedIn( - AccountId::FromUserEmail( - base::StringPrintf("user%d@test.com", profile_num)), - profile_name, false); + base::StringPrintf("user%d@test.com", profile_num), profile_name, + false); profile_path = profile_path.Append( chromeos::ProfileHelper::GetUserProfileDir(profile_name).BaseName()); #else
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/background/background.js b/chrome/browser/resources/chromeos/chromevox/chromevox/background/background.js index c61f208..0d3c936 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/background/background.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/background/background.js
@@ -403,7 +403,7 @@ break; case 'toggleChromeVoxVersion': if (global.backgroundObj) { - global.backgroundObj.onGotCommand('toggleChromeVoxVersion'); + global.backgroundObj.onGotCommand('toggleChromeVoxVersion', true); } break; }
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/background/keymaps/next_keymap.json b/chrome/browser/resources/chromeos/chromevox/chromevox/background/keymaps/next_keymap.json index 16765fa7..3aa7300 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/background/keymaps/next_keymap.json +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/background/keymaps/next_keymap.json
@@ -291,6 +291,15 @@ "metaKey": [true] } } + }, + { + "command": "toggleChromeVoxVersion", + "sequence": { + "cvoxModifier": true, + "keys": { + "keyCode": [81] + } + } } ] }
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/background.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/background.js index 94ad645..95e17c4 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/background.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/background.js
@@ -176,13 +176,15 @@ /** * Handles ChromeVox Next commands. * @param {string} command + * @param {boolean=} opt_bypassModeCheck Always tries to execute the command + * regardless of mode. * @return {boolean} True if the command should propagate. */ - onGotCommand: function(command) { + onGotCommand: function(command, opt_bypassModeCheck) { if (!this.currentRange_) return true; - if (this.mode_ == ChromeVoxMode.CLASSIC) + if (this.mode_ == ChromeVoxMode.CLASSIC && !opt_bypassModeCheck) return true; var current = this.currentRange_; @@ -382,7 +384,6 @@ var isClassic = newMode == ChromeVoxMode.CLASSIC || newMode == ChromeVoxMode.COMPAT; - // Leaving unlocalized as 'next' isn't an official name. cvox.ChromeVox.tts.speak(isClassic ? 'classic' : 'next', cvox.QueueMode.FLUSH, {doNotInterrupt: true}); @@ -534,7 +535,6 @@ var node = evt.target; - // Discard focus events on embeddedObject nodes. if (node.role == RoleType.embeddedObject) return;
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/background_test.extjs b/chrome/browser/resources/chromeos/chromevox/cvox2/background/background_test.extjs index 80bb9bf..0ff5e66a 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/background_test.extjs +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/background_test.extjs
@@ -442,3 +442,24 @@ mockFeedback.replay(); }.bind(this)); }); + +TEST_F('BackgroundTest', 'ToggleChromeVoxVersion', function() { + var mockFeedback = this.createMockFeedback(); + this.runWithLoadedTree(this.linksAndHeadingsDoc, function() { + var gotCmd = global.backgroundObj.onGotCommand; + + // The command came from the background keyboard handler. + var togglerFromBackground = gotCmd.bind(gotCmd, 'toggleChromeVoxVersion'); + + // The command came from a content script. + var togglerFromContent = gotCmd.bind(gotCmd, 'toggleChromeVoxVersion', true); + + mockFeedback.call(togglerFromBackground) + .expectSpeech('classic') + .call(togglerFromContent) + .expectSpeech('next') + .call(togglerFromBackground) + .expectSpeech('classic'); + mockFeedback.replay(); + }); +});
diff --git a/chrome/browser/resources/settings/advanced_page/advanced_page.html b/chrome/browser/resources/settings/advanced_page/advanced_page.html index 30eb95d..c1f1fb2 100644 --- a/chrome/browser/resources/settings/advanced_page/advanced_page.html +++ b/chrome/browser/resources/settings/advanced_page/advanced_page.html
@@ -3,6 +3,7 @@ <link rel="import" href="chrome://md-settings/languages_page/languages_page.html"> <link rel="import" href="chrome://md-settings/location_page/location_page.html"> <link rel="import" href="chrome://md-settings/privacy_page/privacy_page.html"> +<link rel="import" href="chrome://md-settings/reset_page/reset_page.html"> <link rel="import" href="chrome://md-settings/settings_page/settings_section.html"> <if expr="chromeos"> @@ -46,6 +47,11 @@ </settings-downloads-page> </settings-section> + <settings-section i18n-values="page-title:resetPageTitle" + current-route="[[currentRoute]]" section="reset"> + <settings-reset-page></settings-reset-page> + </settings-section> + <if expr="chromeos"> <!-- TODO(dbeam): find somewhere to stuff "Add more accessibility features" on desktop. -->
diff --git a/chrome/browser/resources/settings/reset_page/reset_page.css b/chrome/browser/resources/settings/reset_page/reset_page.css new file mode 100644 index 0000000..4db82b8 --- /dev/null +++ b/chrome/browser/resources/settings/reset_page/reset_page.css
@@ -0,0 +1,35 @@ +/* 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. */ + +#resetDialog { + max-width: 500px; + min-width: 300px; +} + +#reset { + -webkit-margin-start: 10px; + -webkit-padding-end: 15px; + -webkit-padding-start: 15px; + background-color: rgb(120, 120, 120); + color: white; +} + +#learnMore, +#cancel { + color: rgb(94, 94, 94); +} + +#explanation { + margin: 10px 0; +} + +#buttonContainer { + margin: 15px 0; +} + +#sendSettings { + background-color: rgb(236, 236, 236); + margin: 0; + padding: 20px; +}
diff --git a/chrome/browser/resources/settings/reset_page/reset_page.html b/chrome/browser/resources/settings/reset_page/reset_page.html new file mode 100644 index 0000000..211a0b8 --- /dev/null +++ b/chrome/browser/resources/settings/reset_page/reset_page.html
@@ -0,0 +1,38 @@ +<link rel="import" href="chrome://resources/polymer/v1_0/polymer/polymer.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/classes/iron-flex-layout.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/paper-checkbox/paper-checkbox.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/paper-dialog/paper-dialog.html"> + +<dom-module id="settings-reset-page"> + <link rel="import" type="css" + href="chrome://md-settings/settings_page/settings_page.css"> + <link rel="import" type="css" href="reset_page.css"> + <template> + <div on-tap="onShowDialog_"> + <div i18n-content="resetPageTitle"></div> + <div i18n-content="resetPageDescription"></div> + </div> + + <paper-dialog modal id="resetDialog" class="layout vertical"> + <div id="top" class="layout vertical"> + <h2 i18n-content="resetPageTitle"></h2> + <div i18n-content="resetPageExplanation" id="explanation"></div> + <div class="layout center horizontal" id="buttonContainer"> + <paper-button on-tap="onLearnMoreTap_" id="learnMore" + i18n-content="learnMore"></paper-button> + <div class="buttons flex-1"> + <paper-button on-tap="onCancelTap_" id="cancel" + i18n-content="cancel"></paper-button> + <paper-button i18n-content="resetPageCommit" on-tap="onResetTap_" + id="reset"></paper-button> + </div> + </div> + </div> + <paper-checkbox id="sendSettings" i18n-content="resetPageFeedback" + checked></paper-checkbox> + </paper-dialog> + + </template> + <script src="reset_page.js"></script> +</dom-module>
diff --git a/chrome/browser/resources/settings/reset_page/reset_page.js b/chrome/browser/resources/settings/reset_page/reset_page.js new file mode 100644 index 0000000..f27b892 --- /dev/null +++ b/chrome/browser/resources/settings/reset_page/reset_page.js
@@ -0,0 +1,45 @@ +// 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. + +/** + * @fileoverview + * 'settings-reset-page' is the settings page containing reset + * settings. + * + * Example: + * + * <iron-animated-pages> + * <settings-reset-page prefs="{{prefs}}"> + * </settings-reset-page> + * ... other pages ... + * </iron-animated-pages> + * + * @group Chrome Settings Elements + * @element settings-reset-page + */ +Polymer({ + is: 'settings-reset-page', + + /** @private */ + onShowDialog_: function() { + this.$.resetDialog.open(); + }, + + /** @private */ + onCancelTap_: function() { + this.$.resetDialog.close(); + }, + + /** @private */ + onResetTap_: function() { + // TODO(dpapad): Set up C++ handlers and figure out when it is OK to close + // the dialog. + this.$.resetDialog.close(); + }, + + /** @private */ + onLearnMoreTap_: function() { + window.open(loadTimeData.getString('resetPageLearnMoreUrl')); + } +});
diff --git a/chrome/browser/resources/settings/settings_resources.grd b/chrome/browser/resources/settings/settings_resources.grd index e5610e1c..99bfd8e2 100644 --- a/chrome/browser/resources/settings/settings_resources.grd +++ b/chrome/browser/resources/settings/settings_resources.grd
@@ -210,6 +210,15 @@ <structure name="IDR_SETTINGS_DOWNLOADS_PAGE_JS" file="downloads_page/downloads_page.js" type="chrome_html" /> + <structure name="IDR_SETTINGS_RESET_PAGE_CSS" + file="reset_page/reset_page.css" + type="chrome_html" /> + <structure name="IDR_SETTINGS_RESET_PAGE_HTML" + file="reset_page/reset_page.html" + type="chrome_html" /> + <structure name="IDR_SETTINGS_RESET_PAGE_JS" + file="reset_page/reset_page.js" + type="chrome_html" /> <structure name="IDR_SETTINGS_LANGUAGES_HTML" file="languages_page/languages.html" type="chrome_html" />
diff --git a/chrome/browser/safe_browsing/incident_reporting/module_integrity_verifier_win_unittest.cc b/chrome/browser/safe_browsing/incident_reporting/module_integrity_verifier_win_unittest.cc index b991eeb..a5d889d 100644 --- a/chrome/browser/safe_browsing/incident_reporting/module_integrity_verifier_win_unittest.cc +++ b/chrome/browser/safe_browsing/incident_reporting/module_integrity_verifier_win_unittest.cc
@@ -31,7 +31,7 @@ explicit ScopedModuleModifier(uint8_t* address) : address_(address) { uint8_t modification[ModificationLength]; std::transform(address, address + ModificationLength, &modification[0], - std::bind2nd(std::plus<uint8_t>(), 1U)); + [](uint8_t byte) { return byte + 1U; }); SIZE_T bytes_written = 0; EXPECT_NE(0, WriteProcessMemory(GetCurrentProcess(), address, @@ -44,7 +44,7 @@ ~ScopedModuleModifier() { uint8_t modification[ModificationLength]; std::transform(address_, address_ + ModificationLength, &modification[0], - std::bind2nd(std::minus<uint8_t>(), 1U)); + [](uint8_t byte) { return byte - 1U; }); SIZE_T bytes_written = 0; EXPECT_NE(0, WriteProcessMemory(GetCurrentProcess(), address_,
diff --git a/chrome/browser/shell_integration_win.cc b/chrome/browser/shell_integration_win.cc index 4089dc47..b26a1c2 100644 --- a/chrome/browser/shell_integration_win.cc +++ b/chrome/browser/shell_integration_win.cc
@@ -285,6 +285,18 @@ return base::StartsWith(group_name, "Enabled", base::CompareCase::SENSITIVE); } +bool RegisterBrowser() { + base::FilePath chrome_exe; + if (!PathService::Get(base::FILE_EXE, &chrome_exe)) { + NOTREACHED() << "Error getting app exe path"; + return false; + } + BrowserDistribution* dist = BrowserDistribution::GetDistribution(); + + return ShellUtil::RegisterChromeBrowser(dist, chrome_exe, base::string16(), + true); +} + } // namespace // static @@ -655,7 +667,7 @@ // default browser. This is the workaround: // 1. Unregister the default browser. // 2. Open "How to make Chrome my default browser" link with openwith.exe. - // 3. Windows will prompt the user with "How would you link to open this?". + // 3. Windows will prompt the user with "How would you like to open this?". // 4. If Chrome is selected, we intercept the attempt to open the URL and // instead call OnSetAsDefaultAttemptComplete(), passing true to indicate // success. @@ -705,6 +717,11 @@ bool ShellIntegration::DefaultBrowserWorker::SetAsDefaultBrowserAsynchronous() { DCHECK(IsSetAsDefaultAsynchronous()); + // Registers chrome.exe as a browser on Windows to make sure it will be shown + // in the "How would you like to open this?" prompt. + if (!RegisterBrowser()) + return false; + ResetDefaultBrowser(); base::CommandLine cmdline(base::FilePath(L"openwith.exe"));
diff --git a/chrome/browser/signin/chrome_signin_client.cc b/chrome/browser/signin/chrome_signin_client.cc index ba280aa1d..0247781 100644 --- a/chrome/browser/signin/chrome_signin_client.cc +++ b/chrome/browser/signin/chrome_signin_client.cc
@@ -64,19 +64,19 @@ if (!user) return; auto* user_manager = user_manager::UserManager::Get(); - const AccountId account_id = user->GetAccountId(); - if (user_manager->GetKnownUserDeviceId(account_id).empty()) { + const std::string& user_id = user->GetUserID(); + if (user_manager->GetKnownUserDeviceId(user_id).empty()) { const std::string legacy_device_id = GetPrefs()->GetString(prefs::kGoogleServicesSigninScopedDeviceId); if (!legacy_device_id.empty()) { // Need to move device ID from the old location to the new one, if it has // not been done yet. - user_manager->SetKnownUserDeviceId(account_id, legacy_device_id); + user_manager->SetKnownUserDeviceId(user_id, legacy_device_id); } else { user_manager->SetKnownUserDeviceId( - account_id, + user_id, GenerateSigninScopedDeviceID( - user_manager->IsUserNonCryptohomeDataEphemeral(account_id))); + user_manager->IsUserNonCryptohomeDataEphemeral(user_id))); } } GetPrefs()->SetString(prefs::kGoogleServicesSigninScopedDeviceId, @@ -154,8 +154,7 @@ return std::string(); const std::string signin_scoped_device_id = - user_manager::UserManager::Get()->GetKnownUserDeviceId( - user->GetAccountId()); + user_manager::UserManager::Get()->GetKnownUserDeviceId(user->GetUserID()); LOG_IF(ERROR, signin_scoped_device_id.empty()) << "Device ID is not set for user."; return signin_scoped_device_id;
diff --git a/chrome/browser/signin/easy_unlock_service.cc b/chrome/browser/signin/easy_unlock_service.cc index be5d300..67bffea0 100644 --- a/chrome/browser/signin/easy_unlock_service.cc +++ b/chrome/browser/signin/easy_unlock_service.cc
@@ -56,7 +56,6 @@ #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/power_manager_client.h" -#include "components/signin/core/account_id/account_id.h" #include "components/user_manager/user_manager.h" #endif @@ -613,9 +612,11 @@ DCHECK(key_manager); key_manager->GetDeviceDataList( - chromeos::UserContext(AccountId::FromUserEmail(user_id)), + chromeos::UserContext(user_id), base::Bind(&EasyUnlockService::OnCryptohomeKeysFetchedForChecking, - weak_ptr_factory_.GetWeakPtr(), user_id, paired_devices)); + weak_ptr_factory_.GetWeakPtr(), + user_id, + paired_devices)); #endif }
diff --git a/chrome/browser/signin/easy_unlock_service_signin_chromeos.cc b/chrome/browser/signin/easy_unlock_service_signin_chromeos.cc index 279b7a7e..fc3c8fb6 100644 --- a/chrome/browser/signin/easy_unlock_service_signin_chromeos.cc +++ b/chrome/browser/signin/easy_unlock_service_signin_chromeos.cc
@@ -88,7 +88,7 @@ DCHECK(key_manager); key_manager->GetDeviceDataList( - chromeos::UserContext(AccountId::FromUserEmail(user_id)), + chromeos::UserContext(user_id), base::Bind(&RetryDataLoadOnError, user_id, backoff_ms, callback)); }
diff --git a/chrome/browser/signin/easy_unlock_service_unittest_chromeos.cc b/chrome/browser/signin/easy_unlock_service_unittest_chromeos.cc index 74367781..ffd15e0 100644 --- a/chrome/browser/signin/easy_unlock_service_unittest_chromeos.cc +++ b/chrome/browser/signin/easy_unlock_service_unittest_chromeos.cc
@@ -21,7 +21,6 @@ #include "chrome/test/base/testing_profile.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/fake_power_manager_client.h" -#include "components/signin/core/account_id/account_id.h" #include "components/signin/core/browser/signin_manager_base.h" #include "components/syncable_prefs/testing_pref_service_syncable.h" #include "content/public/test/test_browser_thread_bundle.h" @@ -219,7 +218,7 @@ ON_CALL(*mock_user_manager_, IsCurrentUserNonCryptohomeDataEphemeral()) .WillByDefault(Return(false)); - SetUpProfile(&profile_, AccountId::FromUserEmail(kTestUserPrimary)); + SetUpProfile(&profile_, kTestUserPrimary); } void TearDown() override { @@ -263,14 +262,13 @@ } void SetUpSecondaryProfile() { - SetUpProfile(&secondary_profile_, - AccountId::FromUserEmail(kTestUserSecondary)); + SetUpProfile(&secondary_profile_, kTestUserSecondary); } private: // Sets up a test profile with a user id. void SetUpProfile(scoped_ptr<TestingProfile>* profile, - const AccountId& account_id) { + const std::string& user_id) { ASSERT_TRUE(profile); ASSERT_FALSE(profile->get()); @@ -279,13 +277,12 @@ &CreateEasyUnlockServiceForTest); *profile = builder.Build(); - mock_user_manager_->AddUser(account_id); - profile->get()->set_profile_name(account_id.GetUserEmail()); + mock_user_manager_->AddUser(user_id); + profile->get()->set_profile_name(user_id); SigninManagerBase* signin_manager = SigninManagerFactory::GetForProfile(profile->get()); - signin_manager->SetAuthenticatedAccountInfo(account_id.GetUserEmail(), - account_id.GetUserEmail()); + signin_manager->SetAuthenticatedAccountInfo(user_id, user_id); } protected:
diff --git a/chrome/browser/site_details.cc b/chrome/browser/site_details.cc index bf9d947..a5daea38 100644 --- a/chrome/browser/site_details.cc +++ b/chrome/browser/site_details.cc
@@ -6,6 +6,7 @@ #include "base/metrics/histogram.h" #include "content/public/browser/browser_thread.h" +#include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #if defined(ENABLE_EXTENSIONS) @@ -14,17 +15,21 @@ #include "extensions/common/extension.h" #endif +using content::BrowserContext; using content::BrowserThread; +using content::RenderFrameHost; using content::RenderProcessHost; using content::SiteInstance; using content::WebContents; namespace { -bool ShouldIsolate(content::BrowserContext* browser_context, - IsolationScenarioType policy, +bool ShouldIsolate(BrowserContext* browser_context, + const IsolationScenario* scenario, const GURL& site) { - switch (policy) { + switch (scenario->policy) { + case ISOLATE_NOTHING: + return false; case ISOLATE_ALL_SITES: return true; case ISOLATE_HTTPS_SITES: @@ -51,26 +56,64 @@ return true; } +// Walk the frame tree and update |scenario|'s data for the given frame. Memoize +// each frame's computed URL in |frame_urls| so it can be reused when visiting +// its children. +void CollectForScenario(std::map<RenderFrameHost*, GURL>* frame_urls, + SiteInstance* primary, + IsolationScenario* scenario, + RenderFrameHost* frame) { + BrowserContext* context = primary->GetBrowserContext(); + + GURL url = frame->GetLastCommittedURL(); + + // Treat about:blank url specially: use the URL on the SiteInstance if it is + // assigned. The rest of this computation must not depend on the + // SiteInstance's URL, since its value reflects the current process model, and + // this computation is simulating other process models. + if (url == GURL(url::kAboutBlankURL) && + !frame->GetSiteInstance()->GetSiteURL().is_empty()) { + url = frame->GetSiteInstance()->GetSiteURL(); + } + + GURL site = SiteInstance::GetSiteForURL(context, url); + bool should_isolate = ShouldIsolate(context, scenario, site); + + // Treat a subframe as part of its parent site if neither needs isolation. + if (!should_isolate && frame->GetParent()) { + GURL parent_site = (*frame_urls)[frame->GetParent()]; + if (!ShouldIsolate(context, scenario, parent_site)) + site = parent_site; + } + + bool process_per_site = + site.is_valid() && + RenderProcessHost::ShouldUseProcessPerSite(context, site); + + // If we don't need a dedicated process, and aren't living in a process- + // per-site process, we are nothing special: collapse our URL to a dummy + // site. + if (!process_per_site && !should_isolate) + site = GURL("http://"); + + // We model process-per-site by only inserting those sites into the first + // browsing instance in which they appear. + if (scenario->sites.insert(site).second || !process_per_site) + scenario->browsing_instance_site_map[primary->GetId()].insert(site); + + // Record our result in |frame_urls| for use by children. + (*frame_urls)[frame] = site; +} + } // namespace IsolationScenario::IsolationScenario() : policy(ISOLATE_ALL_SITES) {} IsolationScenario::~IsolationScenario() {} -void IsolationScenario::CollectSiteInfoForScenario(SiteInstance* primary, - const GURL& site) { - const GURL& isolated = - ShouldIsolate(primary->GetBrowserContext(), policy, site) - ? site - : GURL("http://"); - sites.insert(isolated); - browsing_instance_site_map[primary->GetId()].insert(isolated); -} - SiteData::SiteData() { - scenarios[ISOLATE_ALL_SITES].policy = ISOLATE_ALL_SITES; - scenarios[ISOLATE_HTTPS_SITES].policy = ISOLATE_HTTPS_SITES; - scenarios[ISOLATE_EXTENSIONS].policy = ISOLATE_EXTENSIONS; + for (int i = 0; i <= ISOLATION_SCENARIO_LAST; i++) + scenarios[i].policy = static_cast<IsolationScenarioType>(i); } SiteData::~SiteData() {} @@ -82,8 +125,6 @@ void SiteDetails::CollectSiteInfo(WebContents* contents, SiteData* site_data) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - content::BrowserContext* browser_context = contents->GetBrowserContext(); - // Find the BrowsingInstance this WebContents belongs to by iterating over // the "primary" SiteInstances of each BrowsingInstance we've seen so far. SiteInstance* instance = contents->GetSiteInstance(); @@ -102,19 +143,11 @@ // Now keep track of how many sites we have in this BrowsingInstance (and // overall), including sites in iframes. - for (const GURL& site : contents->GetSitesInTab()) { - // Make sure we don't overcount process-per-site sites, like the NTP or - // extensions, by skipping over them if they're already logged for - // ISOLATE_ALL_SITES. - if (RenderProcessHost::ShouldUseProcessPerSite(browser_context, site) && - site_data->scenarios[ISOLATE_ALL_SITES].sites.find(site) != - site_data->scenarios[ISOLATE_ALL_SITES].sites.end()) { - continue; - } - - for (IsolationScenario& scenario : site_data->scenarios) { - scenario.CollectSiteInfoForScenario(primary, site); - } + for (IsolationScenario& scenario : site_data->scenarios) { + std::map<RenderFrameHost*, GURL> memo; + contents->ForEachFrame( + base::Bind(&CollectForScenario, base::Unretained(&memo), + base::Unretained(primary), base::Unretained(&scenario))); } } @@ -160,6 +193,19 @@ UMA_HISTOGRAM_COUNTS_100( "SiteIsolation.BrowsingInstanceCount", num_browsing_instances); + + // ISOLATE_NOTHING metrics. + UMA_HISTOGRAM_COUNTS_100("SiteIsolation.IsolateNothingProcessCountNoLimit", + num_isolated_site_instances[ISOLATE_NOTHING]); + UMA_HISTOGRAM_COUNTS_100("SiteIsolation.IsolateNothingProcessCountLowerBound", + process_count_lower_bound[ISOLATE_NOTHING]); + UMA_HISTOGRAM_COUNTS_100("SiteIsolation.IsolateNothingProcessCountEstimate", + process_count_estimate[ISOLATE_NOTHING]); + UMA_HISTOGRAM_COUNTS_100( + "SiteIsolation.IsolateNothingTotalProcessCountEstimate", + process_count_estimate[ISOLATE_NOTHING] + non_renderer_process_count); + + // ISOLATE_ALL_SITES metrics. UMA_HISTOGRAM_COUNTS_100("SiteIsolation.IsolateAllSitesProcessCountNoLimit", num_isolated_site_instances[ISOLATE_ALL_SITES]); UMA_HISTOGRAM_COUNTS_100( @@ -167,7 +213,11 @@ process_count_lower_bound[ISOLATE_ALL_SITES]); UMA_HISTOGRAM_COUNTS_100("SiteIsolation.IsolateAllSitesProcessCountEstimate", process_count_estimate[ISOLATE_ALL_SITES]); + UMA_HISTOGRAM_COUNTS_100( + "SiteIsolation.IsolateAllSitesTotalProcessCountEstimate", + process_count_estimate[ISOLATE_ALL_SITES] + non_renderer_process_count); + // ISOLATE_HTTPS_SITES metrics. UMA_HISTOGRAM_COUNTS_100("SiteIsolation.IsolateHttpsSitesProcessCountNoLimit", num_isolated_site_instances[ISOLATE_HTTPS_SITES]); UMA_HISTOGRAM_COUNTS_100( @@ -176,7 +226,11 @@ UMA_HISTOGRAM_COUNTS_100( "SiteIsolation.IsolateHttpsSitesProcessCountEstimate", process_count_estimate[ISOLATE_HTTPS_SITES]); + UMA_HISTOGRAM_COUNTS_100( + "SiteIsolation.IsolateHttpsSitesTotalProcessCountEstimate", + process_count_estimate[ISOLATE_HTTPS_SITES] + non_renderer_process_count); + // ISOLATE_EXTENSIONS metrics. UMA_HISTOGRAM_COUNTS_100("SiteIsolation.IsolateExtensionsProcessCountNoLimit", num_isolated_site_instances[ISOLATE_EXTENSIONS]); UMA_HISTOGRAM_COUNTS_100( @@ -185,14 +239,6 @@ UMA_HISTOGRAM_COUNTS_100( "SiteIsolation.IsolateExtensionsProcessCountEstimate", process_count_estimate[ISOLATE_EXTENSIONS]); - - // Total process count: - UMA_HISTOGRAM_COUNTS_100( - "SiteIsolation.IsolateAllSitesTotalProcessCountEstimate", - process_count_estimate[ISOLATE_ALL_SITES] + non_renderer_process_count); - UMA_HISTOGRAM_COUNTS_100( - "SiteIsolation.IsolateHttpsSitesTotalProcessCountEstimate", - process_count_estimate[ISOLATE_HTTPS_SITES] + non_renderer_process_count); UMA_HISTOGRAM_COUNTS_100( "SiteIsolation.IsolateExtensionsTotalProcessCountEstimate", process_count_estimate[ISOLATE_EXTENSIONS] + non_renderer_process_count);
diff --git a/chrome/browser/site_details.h b/chrome/browser/site_details.h index a8833d26..da613373 100644 --- a/chrome/browser/site_details.h +++ b/chrome/browser/site_details.h
@@ -16,6 +16,7 @@ // This enum represents various alternative process model policies that we want // to evaluate. We'll estimate the process cost of each scenario. enum IsolationScenarioType { + ISOLATE_NOTHING, ISOLATE_ALL_SITES, ISOLATE_HTTPS_SITES, ISOLATE_EXTENSIONS, @@ -28,11 +29,6 @@ IsolationScenario(); ~IsolationScenario(); - void CollectSiteInfoForScenario(content::SiteInstance* primary, - const GURL& site); - void GetProcessCountEstimate(); - void GetProcessCountLowerBound(); - IsolationScenarioType policy; std::set<GURL> sites; BrowsingInstanceSiteMap browsing_instance_site_map;
diff --git a/chrome/browser/site_details_browsertest.cc b/chrome/browser/site_details_browsertest.cc index ae60dc3..a11d9b2 100644 --- a/chrome/browser/site_details_browsertest.cc +++ b/chrome/browser/site_details_browsertest.cc
@@ -56,6 +56,16 @@ // StartFetchAndWait(). base::HistogramTester* uma() { return uma_.get(); } + size_t CountPageTitles() { + size_t count = 0; + for (const ProcessMemoryInformation& process : ChromeBrowser()->processes) { + if (process.process_type == content::PROCESS_TYPE_RENDERER) { + count += process.titles.size(); + } + } + return count; + } + private: ~TestMemoryDetails() override {} @@ -207,11 +217,15 @@ scoped_refptr<TestMemoryDetails> details = new TestMemoryDetails(); details->StartFetchAndWait(); + EXPECT_EQ(1U, details->CountPageTitles()); EXPECT_THAT( details->uma()->GetAllSamples("SiteIsolation.BrowsingInstanceCount"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), + ElementsAre(Bucket(GetRenderProcessCount(), 1))); + EXPECT_THAT(details->uma()->GetAllSamples( + "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountEstimate"), @@ -252,11 +266,15 @@ details = new TestMemoryDetails(); details->StartFetchAndWait(); + EXPECT_EQ(1U, details->CountPageTitles()); EXPECT_THAT( details->uma()->GetAllSamples("SiteIsolation.BrowsingInstanceCount"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), + ElementsAre(Bucket(GetRenderProcessCount(), 1))); + EXPECT_THAT(details->uma()->GetAllSamples( + "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountEstimate"), @@ -296,11 +314,15 @@ details = new TestMemoryDetails(); details->StartFetchAndWait(); + EXPECT_EQ(2U, details->CountPageTitles()); EXPECT_THAT( details->uma()->GetAllSamples("SiteIsolation.BrowsingInstanceCount"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), + ElementsAre(Bucket(GetRenderProcessCount(), 1))); + EXPECT_THAT(details->uma()->GetAllSamples( + "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountEstimate"), @@ -343,6 +365,9 @@ ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), + ElementsAre(Bucket(GetRenderProcessCount(), 1))); + EXPECT_THAT(details->uma()->GetAllSamples( + "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(3, 1))); // Could be 11 if subframe processes were reused across BrowsingInstances. EXPECT_THAT(details->uma()->GetAllSamples( @@ -399,6 +424,9 @@ ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), + ElementsAre(Bucket(GetRenderProcessCount(), 1))); + EXPECT_THAT(details->uma()->GetAllSamples( + "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(3, 1))); // Could be 11 if subframe processes were reused across BrowsingInstances. EXPECT_THAT(details->uma()->GetAllSamples( @@ -439,6 +467,9 @@ details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), + ElementsAre(Bucket(GetRenderProcessCount(), 1))); + EXPECT_THAT(details->uma()->GetAllSamples( + "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), @@ -472,6 +503,9 @@ details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), + ElementsAre(Bucket(GetRenderProcessCount(), 1))); + EXPECT_THAT(details->uma()->GetAllSamples( + "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), @@ -496,6 +530,9 @@ details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), + ElementsAre(Bucket(GetRenderProcessCount(), 1))); + EXPECT_THAT(details->uma()->GetAllSamples( + "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), @@ -517,6 +554,9 @@ details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), + ElementsAre(Bucket(GetRenderProcessCount(), 1))); + EXPECT_THAT(details->uma()->GetAllSamples( + "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), @@ -537,6 +577,9 @@ details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), + ElementsAre(Bucket(GetRenderProcessCount(), 1))); + EXPECT_THAT(details->uma()->GetAllSamples( + "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), @@ -557,6 +600,9 @@ details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), + ElementsAre(Bucket(GetRenderProcessCount(), 1))); + EXPECT_THAT(details->uma()->GetAllSamples( + "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), @@ -582,6 +628,9 @@ details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), + ElementsAre(Bucket(GetRenderProcessCount(), 1))); + EXPECT_THAT(details->uma()->GetAllSamples( + "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), @@ -603,6 +652,9 @@ details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), + ElementsAre(Bucket(GetRenderProcessCount(), 1))); + EXPECT_THAT(details->uma()->GetAllSamples( + "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), @@ -625,6 +677,9 @@ details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), + ElementsAre(Bucket(GetRenderProcessCount(), 1))); + EXPECT_THAT(details->uma()->GetAllSamples( + "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), @@ -646,6 +701,9 @@ details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), + ElementsAre(Bucket(GetRenderProcessCount(), 1))); + EXPECT_THAT(details->uma()->GetAllSamples( + "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), @@ -676,6 +734,9 @@ details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), + ElementsAre(Bucket(GetRenderProcessCount(), 1))); + EXPECT_THAT(details->uma()->GetAllSamples( + "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), @@ -704,6 +765,9 @@ details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), + ElementsAre(Bucket(GetRenderProcessCount(), 1))); + EXPECT_THAT(details->uma()->GetAllSamples( + "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), @@ -731,6 +795,9 @@ details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), + ElementsAre(Bucket(GetRenderProcessCount(), 1))); + EXPECT_THAT(details->uma()->GetAllSamples( + "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), @@ -763,6 +830,9 @@ details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), + ElementsAre(Bucket(GetRenderProcessCount(), 1))); + EXPECT_THAT(details->uma()->GetAllSamples( + "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), @@ -790,6 +860,9 @@ details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), + ElementsAre(Bucket(GetRenderProcessCount(), 1))); + EXPECT_THAT(details->uma()->GetAllSamples( + "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"),
diff --git a/chrome/browser/ssl/captive_portal_blocking_page.cc b/chrome/browser/ssl/captive_portal_blocking_page.cc index 31562da..652f66a 100644 --- a/chrome/browser/ssl/captive_portal_blocking_page.cc +++ b/chrome/browser/ssl/captive_portal_blocking_page.cc
@@ -182,6 +182,8 @@ if (cert_report_helper_) cert_report_helper_->PopulateExtendedReportingOption(load_time_data); + else + load_time_data->SetBoolean(interstitials::kDisplayCheckBox, false); } void CaptivePortalBlockingPage::CommandReceived(const std::string& command) {
diff --git a/chrome/browser/supervised_user/chromeos/manager_password_service.cc b/chrome/browser/supervised_user/chromeos/manager_password_service.cc index 8dd975f..30f0a05 100644 --- a/chrome/browser/supervised_user/chromeos/manager_password_service.cc +++ b/chrome/browser/supervised_user/chromeos/manager_password_service.cc
@@ -131,7 +131,7 @@ return; } - UserContext manager_key(AccountId::FromUserEmail(user_id)); + UserContext manager_key(user_id); manager_key.SetKey(Key(master_key)); manager_key.SetIsUsingOAuth(false); @@ -240,8 +240,7 @@ void ManagerPasswordService::OnNewManagerKeySuccess( const UserContext& master_key_context) { - VLOG(1) << "Added new master key for " - << master_key_context.GetAccountId().GetUserEmail(); + VLOG(1) << "Added new master key for " << master_key_context.GetUserID(); authenticator_->RemoveKey( master_key_context, kLegacyCryptohomeSupervisedUserKeyLabel, @@ -253,7 +252,7 @@ void ManagerPasswordService::OnOldSupervisedUserKeyDeleted( const UserContext& master_key_context) { VLOG(1) << "Removed old supervised user key for " - << master_key_context.GetAccountId().GetUserEmail(); + << master_key_context.GetUserID(); authenticator_->RemoveKey( master_key_context, kLegacyCryptohomeMasterKeyLabel, @@ -264,8 +263,7 @@ void ManagerPasswordService::OnOldManagerKeyDeleted( const UserContext& master_key_context) { - VLOG(1) << "Removed old master key for " - << master_key_context.GetAccountId().GetUserEmail(); + VLOG(1) << "Removed old master key for " << master_key_context.GetUserID(); } void ManagerPasswordService::Shutdown() {
diff --git a/chrome/browser/supervised_user/supervised_user_service.cc b/chrome/browser/supervised_user/supervised_user_service.cc index 0df5660..38104ccd 100644 --- a/chrome/browser/supervised_user/supervised_user_service.cc +++ b/chrome/browser/supervised_user/supervised_user_service.cc
@@ -851,7 +851,7 @@ // The active user can be NULL in unit tests. if (user_manager::UserManager::Get()->GetActiveUser()) { return UTF16ToUTF8(user_manager::UserManager::Get()->GetUserDisplayName( - user_manager::UserManager::Get()->GetActiveUser()->GetAccountId())); + user_manager::UserManager::Get()->GetActiveUser()->GetUserID())); } return std::string(); #else
diff --git a/chrome/browser/sync/sync_ui_util.cc b/chrome/browser/sync/sync_ui_util.cc index 5c55de9..ca2e8ec 100644 --- a/chrome/browser/sync/sync_ui_util.cc +++ b/chrome/browser/sync/sync_ui_util.cc
@@ -35,7 +35,6 @@ #include "ui/base/l10n/l10n_util.h" #if defined(OS_CHROMEOS) -#include "components/signin/core/account_id/account_id.h" #include "components/user_manager/user_manager.h" #endif // defined(OS_CHROMEOS) @@ -64,7 +63,7 @@ // On CrOS user email is sanitized and then passed to the signin manager. // Original email (containing dots) is stored as "display email". user_display_name = user_manager::UserManager::Get()->GetUserDisplayEmail( - AccountId::FromUserEmail(user_display_name)); + user_display_name); } #endif // defined(OS_CHROMEOS)
diff --git a/chrome/browser/thumbnails/content_analysis.cc b/chrome/browser/thumbnails/content_analysis.cc index 96c93a03..86d28b8 100644 --- a/chrome/browser/thumbnails/content_analysis.cc +++ b/chrome/browser/thumbnails/content_analysis.cc
@@ -165,9 +165,10 @@ current_clip_index / 255.0f + range.first; // Recount, rather than assume. One-offs due to rounding can be very // harmful when eroding / dilating the result. - size_for_threshold = std::count_if( - profile.begin(), profile.end(), - std::bind2nd(std::greater<float>(), current_threshold)); + size_for_threshold = std::count_if(profile.begin(), profile.end(), + [current_threshold](float value) { + return value > current_threshold; + }); } } @@ -612,10 +613,10 @@ int auto_segmented_width = count_if( column_profile.begin(), column_profile.end(), - std::bind2nd(std::greater<float>(), column_threshold)); - int auto_segmented_height = count_if( - row_profile.begin(), row_profile.end(), - std::bind2nd(std::greater<float>(), row_threshold)); + [column_threshold](float value) { return value > column_threshold; }); + int auto_segmented_height = + count_if(row_profile.begin(), row_profile.end(), + [row_threshold](float value) { return value > row_threshold; }); gfx::Size computed_size = AdjustClippingSizeToAspectRatio( target_size, @@ -766,4 +767,4 @@ return ComputeDecimatedImage(source_bitmap, included_rows, included_columns); } -} // thumbnailing_utils +} // namespace thumbnailing_utils
diff --git a/chrome/browser/thumbnails/content_analysis_unittest.cc b/chrome/browser/thumbnails/content_analysis_unittest.cc index b9bb969..87ee82d 100644 --- a/chrome/browser/thumbnails/content_analysis_unittest.cc +++ b/chrome/browser/thumbnails/content_analysis_unittest.cc
@@ -438,10 +438,9 @@ // There should be roughly 50% above and below the threshold. // Random is not really random thanks to srand, so we can sort-of compare. - int above_count = std::count_if( - profile_info.begin(), - profile_info.end(), - std::bind2nd(std::greater<float>(), threshold)); + int above_count = + std::count_if(profile_info.begin(), profile_info.end(), + [threshold](float value) { return value > threshold; }); EXPECT_GT(above_count, 450); // Not much to expect. EXPECT_LT(above_count, 550); @@ -451,18 +450,16 @@ } threshold = AutoSegmentPeaks(profile_info); - above_count = std::count_if( - profile_info.begin(), - profile_info.end(), - std::bind2nd(std::greater<float>(), threshold)); + above_count = + std::count_if(profile_info.begin(), profile_info.end(), + [threshold](float value) { return value > threshold; }); EXPECT_LT(above_count, 500); // Negative y expected to fall below threshold. // Expect two peaks around between 0 and 250 and 500 and 750. std::vector<bool> thresholded_values(profile_info.size(), false); - std::transform(profile_info.begin(), - profile_info.end(), + std::transform(profile_info.begin(), profile_info.end(), thresholded_values.begin(), - std::bind2nd(std::greater<float>(), threshold)); + [threshold](float value) { return value > threshold; }); EXPECT_TRUE(thresholded_values[125]); EXPECT_TRUE(thresholded_values[625]); int transitions = 0; @@ -481,37 +478,21 @@ std::vector<float> columns_profile(kColumnCount); std::srand(42); - std::generate(rows_profile.begin(), rows_profile.end(), std::rand); - std::generate(columns_profile.begin(), columns_profile.end(), std::rand); - - // Bring noise level to 0-1. - std::transform(rows_profile.begin(), - rows_profile.end(), - rows_profile.begin(), - std::bind2nd(std::divides<float>(), RAND_MAX)); - std::transform(columns_profile.begin(), - columns_profile.end(), - columns_profile.begin(), - std::bind2nd(std::divides<float>(), RAND_MAX)); - - // Set up values to 0-1. - std::transform(rows_profile.begin(), - rows_profile.end(), - rows_profile.begin(), - std::bind2nd(std::plus<float>(), 1.0f)); - std::transform(columns_profile.begin(), - columns_profile.end(), - columns_profile.begin(), - std::bind2nd(std::plus<float>(), 1.0f)); + std::generate(rows_profile.begin(), rows_profile.end(), []() { + return std::rand() / static_cast<float>(RAND_MAX) + 1.f; + }); + std::generate(columns_profile.begin(), columns_profile.end(), []() { + return std::rand() / static_cast<float>(RAND_MAX) + 1.f; + }); std::transform(rows_profile.begin() + 300, rows_profile.begin() + 450, rows_profile.begin() + 300, - std::bind2nd(std::plus<float>(), 8.0f)); + [](float value) { return value + 8.f; }); std::transform(columns_profile.begin() + 400, columns_profile.begin() + 1000, columns_profile.begin() + 400, - std::bind2nd(std::plus<float>(), 10.0f)); + [](float value) { return value + 10.f; }); // Make sure that threshold falls somewhere reasonable. float row_threshold = AutoSegmentPeaks(rows_profile); @@ -521,7 +502,7 @@ int row_above_count = std::count_if( rows_profile.begin(), rows_profile.end(), - std::bind2nd(std::greater<float>(), row_threshold)); + [row_threshold](float value) { return value > row_threshold; }); EXPECT_EQ(row_above_count, 150); float column_threshold = AutoSegmentPeaks(columns_profile); @@ -531,7 +512,7 @@ int column_above_count = std::count_if( columns_profile.begin(), columns_profile.end(), - std::bind2nd(std::greater<float>(), column_threshold)); + [column_threshold](float value) { return value > column_threshold; }); EXPECT_EQ(column_above_count, 600); @@ -696,7 +677,7 @@ int histogram[256] = {}; color_utils::BuildLumaHistogram(result, histogram); int non_zero_color_count = std::count_if( - histogram, histogram + 256, std::bind2nd(std::greater<int>(), 0)); + histogram, histogram + 256, [](int value) { return value > 0; }); EXPECT_GT(non_zero_color_count, 4); }
diff --git a/chrome/browser/translate/translate_manager_browsertest.cc b/chrome/browser/translate/translate_manager_browsertest.cc index 7dab3ef..e30b1bce 100644 --- a/chrome/browser/translate/translate_manager_browsertest.cc +++ b/chrome/browser/translate/translate_manager_browsertest.cc
@@ -15,9 +15,91 @@ #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/translate/core/common/language_detection_details.h" +#include "content/public/browser/notification_service.h" #include "url/gurl.h" -class TranslateManagerBrowserTest : public InProcessBrowserTest {}; +class TranslateManagerBrowserTest : public InProcessBrowserTest { + public: + TranslateManagerBrowserTest() {} + ~TranslateManagerBrowserTest() override {} + + std::string GetLanguageFor(content::WebContents* web_contents) { + translate::LanguageDetectionDetails details; + content::Source<content::WebContents> source(web_contents); + language_detected_signal_->GetDetailsFor(source.map_key(), &details); + return details.adopted_language; + } + + void WaitUntilLanguageDetected() { language_detected_signal_->Wait(); } + + void ResetObserver() { + language_detected_signal_.reset(new LangageDetectionObserver( + chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED, + content::NotificationService::AllSources())); + } + + protected: + // InProcessBrowserTest members. + void SetUp() override { + scoped_ptr<test::CldDataHarness> cld_data_harness = + test::CldDataHarnessFactory::Get()->CreateCldDataHarness(); + ASSERT_NO_FATAL_FAILURE(cld_data_harness->Init()); + InProcessBrowserTest::SetUp(); + } + void SetUpOnMainThread() override { + ResetObserver(); + InProcessBrowserTest::SetUpOnMainThread(); + } + + private: + using LangageDetectionObserver = + ui_test_utils::WindowedNotificationObserverWithDetails< + translate::LanguageDetectionDetails>; + + scoped_ptr<LangageDetectionObserver> language_detected_signal_; +}; + +// Tests that the CLD (Compact Language Detection) works properly. +IN_PROC_BROWSER_TEST_F(TranslateManagerBrowserTest, PageLanguageDetection) { + ASSERT_TRUE(test_server()->Start()); + + // The InProcessBrowserTest opens a new tab, let's wait for that first. + WaitUntilLanguageDetected(); + + content::WebContents* current_web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + + std::string adopted_language = GetLanguageFor(current_web_contents); + EXPECT_EQ("und", adopted_language); + + // Open a new tab with a page in English. + AddTabAtIndex(0, GURL(test_server()->GetURL("files/english_page.html")), + ui::PAGE_TRANSITION_TYPED); + + ResetObserver(); + + current_web_contents = browser()->tab_strip_model()->GetActiveWebContents(); + ChromeTranslateClient* chrome_translate_client = + ChromeTranslateClient::FromWebContents(current_web_contents); + + WaitUntilLanguageDetected(); + adopted_language = GetLanguageFor(current_web_contents); + EXPECT_EQ("en", adopted_language); + EXPECT_EQ("en", + chrome_translate_client->GetLanguageState().original_language()); + + ResetObserver(); + + // Now navigate to a page in French. + ui_test_utils::NavigateToURL( + browser(), GURL(test_server()->GetURL("files/french_page.html"))); + + WaitUntilLanguageDetected(); + adopted_language = GetLanguageFor(current_web_contents); + EXPECT_EQ("fr", adopted_language); + EXPECT_EQ("fr", + chrome_translate_client->GetLanguageState().original_language()); +} // Test is flaky on Win http://crbug.com/166334 #if defined(OS_WIN) @@ -29,31 +111,28 @@ // settings. IN_PROC_BROWSER_TEST_F(TranslateManagerBrowserTest, MAYBE_PRE_TranslateSessionRestore) { - scoped_ptr<test::CldDataHarness> cld_data_harness = - test::CldDataHarnessFactory::Get()->CreateCldDataHarness(); - ASSERT_NO_FATAL_FAILURE(cld_data_harness->Init()); SessionStartupPref pref(SessionStartupPref::LAST); SessionStartupPref::SetStartupPref(browser()->profile(), pref); + WaitUntilLanguageDetected(); + content::WebContents* current_web_contents = browser()->tab_strip_model()->GetActiveWebContents(); ChromeTranslateClient* chrome_translate_client = ChromeTranslateClient::FromWebContents(current_web_contents); - content::Source<content::WebContents> source(current_web_contents); - ui_test_utils::WindowedNotificationObserverWithDetails< - translate::LanguageDetectionDetails> - fr_language_detected_signal(chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED, - source); + std::string adopted_language = GetLanguageFor(current_web_contents); + EXPECT_EQ("und", adopted_language); + + ResetObserver(); GURL french_url = ui_test_utils::GetTestUrl( base::FilePath(), base::FilePath(FILE_PATH_LITERAL("french_page.html"))); ui_test_utils::NavigateToURL(browser(), french_url); - fr_language_detected_signal.Wait(); - translate::LanguageDetectionDetails details; - EXPECT_TRUE(fr_language_detected_signal.GetDetailsFor( - source.map_key(), &details)); - EXPECT_EQ("fr", details.adopted_language); + + WaitUntilLanguageDetected(); + adopted_language = GetLanguageFor(current_web_contents); + EXPECT_EQ("fr", adopted_language); EXPECT_EQ("fr", chrome_translate_client->GetLanguageState().original_language()); } @@ -65,16 +144,28 @@ #endif IN_PROC_BROWSER_TEST_F(TranslateManagerBrowserTest, MAYBE_TranslateSessionRestore) { - scoped_ptr<test::CldDataHarness> cld_data_harness = - test::CldDataHarnessFactory::Get()->CreateCldDataHarness(); - ASSERT_NO_FATAL_FAILURE(cld_data_harness->Init()); - content::WebContents* current_web_contents = - browser()->tab_strip_model()->GetActiveWebContents(); - content::Source<content::WebContents> source(current_web_contents); + WaitUntilLanguageDetected(); - ui_test_utils::WindowedNotificationObserverWithDetails< - translate::LanguageDetectionDetails> - fr_language_detected_signal(chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED, - source); - fr_language_detected_signal.Wait(); + content::WebContents* active_web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + std::string active_adopted_language = GetLanguageFor(active_web_contents); + + content::WebContents* restored_web_contents = + browser()->tab_strip_model()->GetWebContentsAt(0); + std::string restored_adopted_language = GetLanguageFor(restored_web_contents); + + // One of the tabs could be still loading, let's check on that and wait, + // if necessary. + if (active_adopted_language.empty()) { + ResetObserver(); + WaitUntilLanguageDetected(); + active_adopted_language = GetLanguageFor(active_web_contents); + } else if (restored_adopted_language.empty()) { + ResetObserver(); + WaitUntilLanguageDetected(); + restored_adopted_language = GetLanguageFor(restored_web_contents); + } + + EXPECT_EQ("fr", restored_adopted_language); + EXPECT_EQ("und", active_adopted_language); }
diff --git a/chrome/browser/ui/ash/launcher/chrome_launcher_controller_unittest.cc b/chrome/browser/ui/ash/launcher/chrome_launcher_controller_unittest.cc index 6d3d08c..44eded23 100644 --- a/chrome/browser/ui/ash/launcher/chrome_launcher_controller_unittest.cc +++ b/chrome/browser/ui/ash/launcher/chrome_launcher_controller_unittest.cc
@@ -63,7 +63,6 @@ #include "chrome/common/chrome_switches.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile_manager.h" -#include "components/signin/core/account_id/account_id.h" #include "components/user_manager/fake_user_manager.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/test/test_utils.h" @@ -809,23 +808,22 @@ // Creates a profile for a given |user_name|. Note that this class will keep // the ownership of the created object. TestingProfile* CreateMultiUserProfile(const std::string& user_name) { - const std::string email_string = user_name + "@example.com"; - const AccountId account_id(AccountId::FromUserEmail(email_string)); + std::string email_string = user_name + "@example.com"; static_cast<ash::test::TestSessionStateDelegate*>( ash::Shell::GetInstance()->session_state_delegate()) - ->AddUser(account_id.GetUserEmail()); + ->AddUser(email_string); // Add a user to the fake user manager. - session_delegate()->AddUser(account_id.GetUserEmail()); - GetFakeUserManager()->AddUser(account_id); + session_delegate()->AddUser(email_string); + GetFakeUserManager()->AddUser(email_string); - GetFakeUserManager()->LoginUser(account_id); + GetFakeUserManager()->LoginUser(email_string); TestingProfile* profile = - profile_manager()->CreateTestingProfile(account_id.GetUserEmail()); + profile_manager()->CreateTestingProfile(email_string); EXPECT_TRUE(profile); // Remember the profile name so that we can destroy it upon destruction. - created_profiles_[profile] = account_id.GetUserEmail(); + created_profiles_[profile] = email_string; if (chrome::MultiUserWindowManager::GetInstance()) chrome::MultiUserWindowManager::GetInstance()->AddUser(profile); if (launcher_controller_) @@ -835,19 +833,18 @@ // Switch to another user. void SwitchActiveUser(const std::string& name) { - const AccountId account_id(AccountId::FromUserEmail(name)); - session_delegate()->SwitchActiveUser(account_id.GetUserEmail()); - GetFakeUserManager()->SwitchActiveUser(account_id); + session_delegate()->SwitchActiveUser(name); + GetFakeUserManager()->SwitchActiveUser(name); chrome::MultiUserWindowManagerChromeOS* manager = static_cast<chrome::MultiUserWindowManagerChromeOS*>( chrome::MultiUserWindowManager::GetInstance()); manager->SetAnimationSpeedForTest( chrome::MultiUserWindowManagerChromeOS::ANIMATION_SPEED_DISABLED); - manager->ActiveUserChanged(account_id.GetUserEmail()); - launcher_controller_->browser_status_monitor_for_test()->ActiveUserChanged( - account_id.GetUserEmail()); - launcher_controller_->app_window_controller_for_test()->ActiveUserChanged( - account_id.GetUserEmail()); + manager->ActiveUserChanged(name); + launcher_controller_->browser_status_monitor_for_test()-> + ActiveUserChanged(name); + launcher_controller_->app_window_controller_for_test()-> + ActiveUserChanged(name); } // Creates a browser with a |profile| and load a tab with a |title| and |url|.
diff --git a/chrome/browser/ui/ash/multi_user/multi_user_context_menu_chromeos.cc b/chrome/browser/ui/ash/multi_user/multi_user_context_menu_chromeos.cc index 7d808f1..41738b9 100644 --- a/chrome/browser/ui/ash/multi_user/multi_user_context_menu_chromeos.cc +++ b/chrome/browser/ui/ash/multi_user/multi_user_context_menu_chromeos.cc
@@ -19,7 +19,6 @@ #include "chrome/browser/ui/ash/multi_user/multi_user_window_manager.h" #include "chrome/common/pref_names.h" #include "chrome/grit/generated_resources.h" -#include "components/signin/core/account_id/account_id.h" #include "components/user_manager/user.h" #include "components/user_manager/user_manager.h" #include "ui/aura/window.h" @@ -96,7 +95,7 @@ return model.Pass(); } -void OnAcceptTeleportWarning(const AccountId& account_id, +void OnAcceptTeleportWarning(const std::string& user_id, aura::Window* window_, bool no_show_again) { PrefService* pref = ProfileManager::GetActiveUserProfile()->GetPrefs(); @@ -105,8 +104,8 @@ ash::MultiProfileUMA::RecordTeleportAction( ash::MultiProfileUMA::TELEPORT_WINDOW_CAPTION_MENU); - chrome::MultiUserWindowManager::GetInstance()->ShowWindowForUser( - window_, account_id.GetUserEmail()); + chrome::MultiUserWindowManager::GetInstance()->ShowWindowForUser(window_, + user_id); } void ExecuteVisitDesktopCommand(int command_id, aura::Window* window) { @@ -115,14 +114,14 @@ case IDC_VISIT_DESKTOP_OF_LRU_USER_3: { // When running the multi user mode on Chrome OS, windows can "visit" // another user's desktop. - const AccountId account_id = + const std::string& user_id = ash::Shell::GetInstance() ->session_state_delegate() ->GetUserInfo(IDC_VISIT_DESKTOP_OF_LRU_USER_2 == command_id ? 1 : 2) - ->GetAccountId(); + ->GetUserID(); base::Callback<void(bool)> on_accept = - base::Bind(&OnAcceptTeleportWarning, account_id, window); + base::Bind(&OnAcceptTeleportWarning, user_id, window); // Don't show warning dialog if any logged in user in multi-profiles // session dismissed it.
diff --git a/chrome/browser/ui/ash/multi_user/multi_user_notification_blocker_chromeos_unittest.cc b/chrome/browser/ui/ash/multi_user/multi_user_notification_blocker_chromeos_unittest.cc index f68e6fc..1f3c67fe 100644 --- a/chrome/browser/ui/ash/multi_user/multi_user_notification_blocker_chromeos_unittest.cc +++ b/chrome/browser/ui/ash/multi_user/multi_user_notification_blocker_chromeos_unittest.cc
@@ -82,8 +82,7 @@ return ash::Shell::GetInstance() ->session_state_delegate() ->GetUserInfo(0) - ->GetAccountId() - .GetUserEmail(); + ->GetUserID(); } const message_center::NotificationBlocker* blocker() {
diff --git a/chrome/browser/ui/ash/multi_user/multi_user_window_manager.cc b/chrome/browser/ui/ash/multi_user/multi_user_window_manager.cc index 11da278..497ebe47 100644 --- a/chrome/browser/ui/ash/multi_user/multi_user_window_manager.cc +++ b/chrome/browser/ui/ash/multi_user/multi_user_window_manager.cc
@@ -14,7 +14,6 @@ #include "ash/shell.h" #include "ash/shell_delegate.h" #include "chrome/browser/ui/ash/multi_user/multi_user_window_manager_chromeos.h" -#include "components/signin/core/account_id/account_id.h" #include "components/user_manager/user_info.h" #endif @@ -47,8 +46,7 @@ new MultiUserWindowManagerChromeOS(ash::Shell::GetInstance() ->session_state_delegate() ->GetUserInfo(0) - ->GetAccountId() - .GetUserEmail()); + ->GetUserID()); g_instance = manager; manager->Init(); multi_user_mode_ = MULTI_PROFILE_MODE_SEPARATED;
diff --git a/chrome/browser/ui/ash/multi_user/multi_user_window_manager_chromeos_unittest.cc b/chrome/browser/ui/ash/multi_user/multi_user_window_manager_chromeos_unittest.cc index 4faee0c..7cf0ea87 100644 --- a/chrome/browser/ui/ash/multi_user/multi_user_window_manager_chromeos_unittest.cc +++ b/chrome/browser/ui/ash/multi_user/multi_user_window_manager_chromeos_unittest.cc
@@ -55,9 +55,9 @@ const user_manager::UserManager* user_manager = user_manager::UserManager::Get(); const user_manager::User* active_user = user_manager->GetActiveUser(); - return active_user ? multi_user_util::GetProfileFromUserID( - active_user->GetAccountId().GetUserEmail()) - : NULL; + return active_user + ? multi_user_util::GetProfileFromUserID(active_user->GetUserID()) + : NULL; } content::BrowserContext* GetBrowserContextByIndex( @@ -158,9 +158,8 @@ TestingProfileManager* profile_manager() { return profile_manager_.get(); } const user_manager::User* AddTestUser(const std::string& user_email) { - const user_manager::User* user = - fake_user_manager_->AddUser(AccountId::FromUserEmail(user_email)); - fake_user_manager_->LoginUser(AccountId::FromUserEmail(user_email)); + const user_manager::User* user = fake_user_manager_->AddUser(user_email); + fake_user_manager_->LoginUser(user_email); session_state_delegate_->AddUser(user_email); TestingProfile* profile = profile_manager()->CreateTestingProfile(user_email); @@ -199,13 +198,12 @@ // The test session state observer does not automatically call the window // manager. This function gets the current user from it and also sets it to // the multi user window manager. - AccountId GetAndValidateCurrentUserFromSessionStateObserver() { - const AccountId account_id = - session_state_delegate()->GetActiveUserInfo()->GetAccountId(); - if (account_id.GetUserEmail() != - multi_user_window_manager_->GetCurrentUserForTest()) - multi_user_window_manager()->ActiveUserChanged(account_id.GetUserEmail()); - return account_id; + std::string GetAndValidateCurrentUserFromSessionStateObserver() { + const std::string& user = + session_state_delegate()->GetActiveUserInfo()->GetUserID(); + if (user != multi_user_window_manager_->GetCurrentUserForTest()) + multi_user_window_manager()->ActiveUserChanged(user); + return user; } // Initiate a user transition. @@ -798,17 +796,11 @@ // Making the window system modal should not change anything. MakeWindowSystemModal(window(0)); - EXPECT_EQ("a", session_state_delegate() - ->GetActiveUserInfo() - ->GetAccountId() - .GetUserEmail()); + EXPECT_EQ("a", session_state_delegate()->GetActiveUserInfo()->GetUserID()); // Making the window owned by user B should switch users. multi_user_window_manager()->SetWindowOwner(window(0), "b"); - EXPECT_EQ("b", session_state_delegate() - ->GetActiveUserInfo() - ->GetAccountId() - .GetUserEmail()); + EXPECT_EQ("b", session_state_delegate()->GetActiveUserInfo()->GetUserID()); } // Test that a system modal dialog will not switch desktop if active user has @@ -819,17 +811,11 @@ // Making the window system modal should not change anything. MakeWindowSystemModal(window(0)); - EXPECT_EQ("a", session_state_delegate() - ->GetActiveUserInfo() - ->GetAccountId() - .GetUserEmail()); + EXPECT_EQ("a", session_state_delegate()->GetActiveUserInfo()->GetUserID()); // Making the window owned by user a should not switch users. multi_user_window_manager()->SetWindowOwner(window(0), "a"); - EXPECT_EQ("a", session_state_delegate() - ->GetActiveUserInfo() - ->GetAccountId() - .GetUserEmail()); + EXPECT_EQ("a", session_state_delegate()->GetActiveUserInfo()->GetUserID()); } // Test that a system modal dialog will not switch if shown on correct desktop @@ -845,10 +831,7 @@ MakeWindowSystemModal(window(0)); // Showing the window should trigger no user switch. window(0)->Show(); - EXPECT_EQ("a", session_state_delegate() - ->GetActiveUserInfo() - ->GetAccountId() - .GetUserEmail()); + EXPECT_EQ("a", session_state_delegate()->GetActiveUserInfo()->GetUserID()); } // Test that a system modal dialog will switch if shown on incorrect desktop but @@ -864,10 +847,7 @@ MakeWindowSystemModal(window(0)); // Showing the window should trigger a user switch. window(0)->Show(); - EXPECT_EQ("b", session_state_delegate() - ->GetActiveUserInfo() - ->GetAccountId() - .GetUserEmail()); + EXPECT_EQ("b", session_state_delegate()->GetActiveUserInfo()->GetUserID()); } // Test that using the full user switch animations are working as expected. @@ -1149,31 +1129,26 @@ EXPECT_EQ("S[a], H[b], H[c]", GetStatus()); // SetWindowOwner should not have changed the active user. - EXPECT_EQ("a", - GetAndValidateCurrentUserFromSessionStateObserver().GetUserEmail()); + EXPECT_EQ("a", GetAndValidateCurrentUserFromSessionStateObserver()); // Check that teleporting the window of the currently active user will // teleport to the new desktop. multi_user_window_manager()->ShowWindowForUser(window(0), "b"); - EXPECT_EQ("b", - GetAndValidateCurrentUserFromSessionStateObserver().GetUserEmail()); + EXPECT_EQ("b", GetAndValidateCurrentUserFromSessionStateObserver()); EXPECT_EQ("S[a,b], S[b], H[c]", GetStatus()); // Check that teleporting a window from a currently inactive user will not // trigger a switch. multi_user_window_manager()->ShowWindowForUser(window(2), "a"); - EXPECT_EQ("b", - GetAndValidateCurrentUserFromSessionStateObserver().GetUserEmail()); + EXPECT_EQ("b", GetAndValidateCurrentUserFromSessionStateObserver()); EXPECT_EQ("S[a,b], S[b], H[c,a]", GetStatus()); multi_user_window_manager()->ShowWindowForUser(window(2), "b"); - EXPECT_EQ("b", - GetAndValidateCurrentUserFromSessionStateObserver().GetUserEmail()); + EXPECT_EQ("b", GetAndValidateCurrentUserFromSessionStateObserver()); EXPECT_EQ("S[a,b], S[b], S[c,b]", GetStatus()); // Check that teleporting back will also change the desktop. multi_user_window_manager()->ShowWindowForUser(window(2), "c"); - EXPECT_EQ("c", - GetAndValidateCurrentUserFromSessionStateObserver().GetUserEmail()); + EXPECT_EQ("c", GetAndValidateCurrentUserFromSessionStateObserver()); EXPECT_EQ("H[a,b], H[b], S[c]", GetStatus()); } @@ -1329,7 +1304,7 @@ wm::GetWindowState(window(2))->Minimize(); // Windows belonging to user2 (window #2 and #3) can't be activated by user1. - user_manager()->SwitchActiveUser(AccountId::FromUserEmail(user1)); + user_manager()->SwitchActiveUser(user1); multi_user_window_manager()->ActiveUserChanged(user1); EXPECT_TRUE(::wm::CanActivateWindow(window(0))); EXPECT_TRUE(::wm::CanActivateWindow(window(1))); @@ -1337,7 +1312,7 @@ EXPECT_FALSE(::wm::CanActivateWindow(window(3))); // Windows belonging to user1 (window #0 and #1) can't be activated by user2. - user_manager()->SwitchActiveUser(AccountId::FromUserEmail(user2)); + user_manager()->SwitchActiveUser(user2); multi_user_window_manager()->ActiveUserChanged(user2); EXPECT_FALSE(::wm::CanActivateWindow(window(0))); EXPECT_FALSE(::wm::CanActivateWindow(window(1))); @@ -1358,7 +1333,7 @@ multi_user_window_manager()->SetWindowOwner(window(0), user1); multi_user_window_manager()->SetWindowOwner(window(1), user2); - user_manager()->SwitchActiveUser(AccountId::FromUserEmail(user1)); + user_manager()->SwitchActiveUser(user1); multi_user_window_manager()->ActiveUserChanged(user1); EXPECT_TRUE(::wm::CanActivateWindow(window(0))); EXPECT_FALSE(::wm::CanActivateWindow(window(1))); @@ -1369,7 +1344,7 @@ EXPECT_FALSE(::wm::CanActivateWindow(window(0))); // Test that window #0 can be activated by user2. - user_manager()->SwitchActiveUser(AccountId::FromUserEmail(user2)); + user_manager()->SwitchActiveUser(user2); multi_user_window_manager()->ActiveUserChanged(user2); EXPECT_TRUE(::wm::CanActivateWindow(window(0))); EXPECT_TRUE(::wm::CanActivateWindow(window(1)));
diff --git a/chrome/browser/ui/ash/session_state_delegate_chromeos.cc b/chrome/browser/ui/ash/session_state_delegate_chromeos.cc index c37dd6d..e144b7d 100644 --- a/chrome/browser/ui/ash/session_state_delegate_chromeos.cc +++ b/chrome/browser/ui/ash/session_state_delegate_chromeos.cc
@@ -26,7 +26,6 @@ #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/session_manager_client.h" #include "chromeos/login/login_state.h" -#include "components/signin/core/account_id/account_id.h" #include "components/user_manager/user.h" #include "components/user_manager/user_info.h" #include "components/user_manager/user_manager.h" @@ -270,8 +269,7 @@ } void DoSwitchUser(const std::string& user_id) { - user_manager::UserManager::Get()->SwitchActiveUser( - AccountId::FromUserEmail(user_id)); + user_manager::UserManager::Get()->SwitchActiveUser(user_id); } void SessionStateDelegateChromeos::TryToSwitchUser(
diff --git a/chrome/browser/ui/ash/session_state_delegate_chromeos_unittest.cc b/chrome/browser/ui/ash/session_state_delegate_chromeos_unittest.cc index 04a620f..6d58b79 100644 --- a/chrome/browser/ui/ash/session_state_delegate_chromeos_unittest.cc +++ b/chrome/browser/ui/ash/session_state_delegate_chromeos_unittest.cc
@@ -19,7 +19,6 @@ #include "chrome/common/pref_names.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile_manager.h" -#include "components/signin/core/account_id/account_id.h" #include "components/user_manager/user_manager.h" #include "content/public/test/test_browser_thread_bundle.h" #include "net/cert/x509_certificate.h" @@ -82,9 +81,9 @@ } // Add and log in a user to the session. - void UserAddedToSession(std::string user) { - user_manager()->AddUser(AccountId::FromUserEmail(user)); - user_manager()->LoginUser(AccountId::FromUserEmail(user)); + void UserAddedToSession(const std::string& user) { + user_manager()->AddUser(user); + user_manager()->LoginUser(user); } // Get the active user. @@ -102,13 +101,12 @@ new TestingProfileManager(TestingBrowserProcess::GetGlobal())); ASSERT_TRUE(profile_manager_->SetUp()); - const AccountId account_id(AccountId::FromUserEmail(kUser)); - const user_manager::User* user = user_manager()->AddUser(account_id); + const std::string user_email(kUser); + const user_manager::User* user = user_manager()->AddUser(user_email); // Note that user profiles are created after user login in reality. - user_profile_ = - profile_manager_->CreateTestingProfile(account_id.GetUserEmail()); - user_profile_->set_profile_name(account_id.GetUserEmail()); + user_profile_ = profile_manager_->CreateTestingProfile(user_email); + user_profile_->set_profile_name(user_email); chromeos::ProfileHelper::Get()->SetUserToProfileMappingForTesting( user, user_profile_); } @@ -174,8 +172,8 @@ InitForMultiProfile(); EXPECT_TRUE( session_state_delegate()->IsMultiProfileAllowedByPrimaryUserPolicy()); - const AccountId account_id(AccountId::FromUserEmail(kUser)); - user_manager()->LoginUser(account_id); + const std::string user_email(kUser); + user_manager()->LoginUser(user_email); EXPECT_TRUE( session_state_delegate()->IsMultiProfileAllowedByPrimaryUserPolicy()); @@ -190,12 +188,11 @@ TEST_F(SessionStateDelegateChromeOSTest, MultiProfileDisallowedByPolicyCertificates) { InitForMultiProfile(); - const AccountId account_id(AccountId::FromUserEmail(kUser)); - user_manager()->LoginUser(account_id); + const std::string user_email(kUser); + user_manager()->LoginUser(user_email); EXPECT_TRUE( session_state_delegate()->IsMultiProfileAllowedByPrimaryUserPolicy()); - policy::PolicyCertServiceFactory::SetUsedPolicyCertificates( - account_id.GetUserEmail()); + policy::PolicyCertServiceFactory::SetUsedPolicyCertificates(user_email); EXPECT_FALSE( session_state_delegate()->IsMultiProfileAllowedByPrimaryUserPolicy()); @@ -207,8 +204,8 @@ TEST_F(SessionStateDelegateChromeOSTest, MultiProfileDisallowedByPrimaryUserCertificatesInMemory) { InitForMultiProfile(); - const AccountId account_id(AccountId::FromUserEmail(kUser)); - user_manager()->LoginUser(account_id); + const std::string user_email(kUser); + user_manager()->LoginUser(user_email); EXPECT_TRUE( session_state_delegate()->IsMultiProfileAllowedByPrimaryUserPolicy()); cert_verifier_.reset(new policy::PolicyCertVerifier(base::Closure())); @@ -242,8 +239,8 @@ EXPECT_TRUE( session_state_delegate()->CanAddUserToMultiProfile(&add_user_error)); - const AccountId account_id(AccountId::FromUserEmail(kUser)); - user_manager()->LoginUser(account_id); + const std::string user_email(kUser); + user_manager()->LoginUser(user_email); while (session_state_delegate()->NumberOfLoggedInUsers() < session_state_delegate()->GetMaximumNumberOfLoggedInUsers()) { UserAddedToSession("bb@b.b"); @@ -263,8 +260,8 @@ EXPECT_TRUE( session_state_delegate()->CanAddUserToMultiProfile(&add_user_error)); - const AccountId account_id(AccountId::FromUserEmail(kUser)); - user_manager()->LoginUser(account_id); + const std::string user_email(kUser); + user_manager()->LoginUser(user_email); UserAddedToSession("bb@b.b"); EXPECT_FALSE( session_state_delegate()->CanAddUserToMultiProfile(&add_user_error)); @@ -280,12 +277,12 @@ EXPECT_TRUE( session_state_delegate()->CanAddUserToMultiProfile(&add_user_error)); - const AccountId account_id(AccountId::FromUserEmail(kUser)); - user_manager()->LoginUser(account_id); + const std::string user_email(kUser); + user_manager()->LoginUser(user_email); user_profile_->GetPrefs()->SetString( prefs::kMultiProfileUserBehavior, chromeos::MultiProfileUserController::kBehaviorNotAllowed); - user_manager()->AddUser(AccountId::FromUserEmail("bb@b.b")); + user_manager()->AddUser("bb@b.b"); EXPECT_FALSE( session_state_delegate()->CanAddUserToMultiProfile(&add_user_error)); EXPECT_EQ(ash::SessionStateDelegate::ADD_USER_ERROR_NOT_ALLOWED_PRIMARY_USER,
diff --git a/chrome/browser/ui/ash/system_tray_delegate_chromeos.cc b/chrome/browser/ui/ash/system_tray_delegate_chromeos.cc index 55d34c0..f0cfb39 100644 --- a/chrome/browser/ui/ash/system_tray_delegate_chromeos.cc +++ b/chrome/browser/ui/ash/system_tray_delegate_chromeos.cc
@@ -820,8 +820,8 @@ SystemTrayDelegateChromeOS::GetUserAccountsDelegate( const std::string& user_id) { if (!accounts_delegates_.contains(user_id)) { - const user_manager::User* user = user_manager::UserManager::Get()->FindUser( - AccountId::FromUserEmail(user_id)); + const user_manager::User* user = + user_manager::UserManager::Get()->FindUser(user_id); Profile* user_profile = ProfileHelper::Get()->GetProfileByUserUnsafe(user); CHECK(user_profile); accounts_delegates_.set(
diff --git a/chrome/browser/ui/ash/system_tray_delegate_chromeos_browsertest_chromeos.cc b/chrome/browser/ui/ash/system_tray_delegate_chromeos_browsertest_chromeos.cc index 6d28e8e..47827b7 100644 --- a/chrome/browser/ui/ash/system_tray_delegate_chromeos_browsertest_chromeos.cc +++ b/chrome/browser/ui/ash/system_tray_delegate_chromeos_browsertest_chromeos.cc
@@ -79,47 +79,42 @@ class SystemTrayDelegateChromeOSTest : public LoginManagerTest { protected: SystemTrayDelegateChromeOSTest() - : LoginManagerTest(false /* should_launch_browser */), - account_id1_(AccountId::FromUserEmail(kUser1)), - account_id2_(AccountId::FromUserEmail(kUser2)) {} + : LoginManagerTest(false /* should_launch_browser */) {} ~SystemTrayDelegateChromeOSTest() override {} - void SetupUserProfile(const AccountId& account_id, bool use_24_hour_clock) { + void SetupUserProfile(const std::string& user_name, bool use_24_hour_clock) { const user_manager::User* user = - user_manager::UserManager::Get()->FindUser(account_id); + user_manager::UserManager::Get()->FindUser(user_name); Profile* profile = ProfileHelper::Get()->GetProfileByUser(user); profile->GetPrefs()->SetBoolean(prefs::kUse24HourClock, use_24_hour_clock); } - const AccountId account_id1_; - const AccountId account_id2_; - private: DISALLOW_COPY_AND_ASSIGN(SystemTrayDelegateChromeOSTest); }; IN_PROC_BROWSER_TEST_F(SystemTrayDelegateChromeOSTest, PRE_TestMultiProfile24HourClock) { - RegisterUser(account_id1_.GetUserEmail()); - RegisterUser(account_id2_.GetUserEmail()); + RegisterUser(kUser1); + RegisterUser(kUser2); StartupUtils::MarkOobeCompleted(); } // Test that clock type is taken from user profile for current active user. IN_PROC_BROWSER_TEST_F(SystemTrayDelegateChromeOSTest, TestMultiProfile24HourClock) { - LoginUser(account_id1_.GetUserEmail()); - SetupUserProfile(account_id1_, true /* Use_24_hour_clock. */); + LoginUser(kUser1); + SetupUserProfile(kUser1, true /* Use_24_hour_clock. */); CreateDefaultView(); EXPECT_EQ(base::k24HourClock, GetHourType()); UserAddingScreen::Get()->Start(); content::RunAllPendingInMessageLoop(); - AddUser(account_id2_.GetUserEmail()); - SetupUserProfile(account_id2_, false /* Use_24_hour_clock. */); + AddUser(kUser2); + SetupUserProfile(kUser2, false /* Use_24_hour_clock. */); CreateDefaultView(); EXPECT_EQ(base::k12HourClock, GetHourType()); - user_manager::UserManager::Get()->SwitchActiveUser(account_id1_); + user_manager::UserManager::Get()->SwitchActiveUser(kUser1); CreateDefaultView(); EXPECT_EQ(base::k24HourClock, GetHourType()); }
diff --git a/chrome/browser/ui/browser_browsertest.cc b/chrome/browser/ui/browser_browsertest.cc index 0da74d4e..d08ac091 100644 --- a/chrome/browser/ui/browser_browsertest.cc +++ b/chrome/browser/ui/browser_browsertest.cc
@@ -1604,54 +1604,6 @@ DevToolsWindowTesting::CloseDevToolsWindowSync(devtools_window); } -// Tests that the CLD (Compact Language Detection) works properly. -IN_PROC_BROWSER_TEST_F(BrowserTest, PageLanguageDetection) { - scoped_ptr<test::CldDataHarness> cld_data_harness = - test::CldDataHarnessFactory::Get()->CreateCldDataHarness(); - ASSERT_NO_FATAL_FAILURE(cld_data_harness->Init()); - ASSERT_TRUE(test_server()->Start()); - - translate::LanguageDetectionDetails details; - - // Open a new tab with a page in English. - AddTabAtIndex(0, GURL(test_server()->GetURL("files/english_page.html")), - ui::PAGE_TRANSITION_TYPED); - - WebContents* current_web_contents = - browser()->tab_strip_model()->GetActiveWebContents(); - ChromeTranslateClient* chrome_translate_client = - ChromeTranslateClient::FromWebContents(current_web_contents); - content::Source<WebContents> source(current_web_contents); - - ui_test_utils::WindowedNotificationObserverWithDetails< - translate::LanguageDetectionDetails> - en_language_detected_signal(chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED, - source); - EXPECT_EQ("", - chrome_translate_client->GetLanguageState().original_language()); - en_language_detected_signal.Wait(); - EXPECT_TRUE(en_language_detected_signal.GetDetailsFor( - source.map_key(), &details)); - EXPECT_EQ("en", details.adopted_language); - EXPECT_EQ("en", - chrome_translate_client->GetLanguageState().original_language()); - - // Now navigate to a page in French. - ui_test_utils::WindowedNotificationObserverWithDetails< - translate::LanguageDetectionDetails> - fr_language_detected_signal(chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED, - source); - ui_test_utils::NavigateToURL( - browser(), GURL(test_server()->GetURL("files/french_page.html"))); - fr_language_detected_signal.Wait(); - details.adopted_language.clear(); - EXPECT_TRUE(fr_language_detected_signal.GetDetailsFor( - source.map_key(), &details)); - EXPECT_EQ("fr", details.adopted_language); - EXPECT_EQ("fr", - chrome_translate_client->GetLanguageState().original_language()); -} - // Chromeos defaults to restoring the last session, so this test isn't // applicable. #if !defined(OS_CHROMEOS)
diff --git a/chrome/browser/ui/cocoa/location_bar/manage_passwords_decoration.mm b/chrome/browser/ui/cocoa/location_bar/manage_passwords_decoration.mm index e32dff4..57320bd 100644 --- a/chrome/browser/ui/cocoa/location_bar/manage_passwords_decoration.mm +++ b/chrome/browser/ui/cocoa/location_bar/manage_passwords_decoration.mm
@@ -8,7 +8,7 @@ #include "chrome/browser/command_updater.h" #include "chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h" #include "chrome/browser/ui/cocoa/omnibox/omnibox_view_mac.h" -#include "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_cocoa.h" +#include "chrome/browser/ui/cocoa/passwords/passwords_bubble_cocoa.h" #include "ui/base/l10n/l10n_util_mac.h" // ManagePasswordsIconCocoa
diff --git a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_account_chooser_view_controller.h b/chrome/browser/ui/cocoa/passwords/account_chooser_view_controller.h similarity index 79% rename from chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_account_chooser_view_controller.h rename to chrome/browser/ui/cocoa/passwords/account_chooser_view_controller.h index bdb327a..5ca1d70d 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_account_chooser_view_controller.h +++ b/chrome/browser/ui/cocoa/passwords/account_chooser_view_controller.h
@@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_BUBBLE_ACCOUNT_CHOOSER_VIEW_CONTROLLER_H_ -#define CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_BUBBLE_ACCOUNT_CHOOSER_VIEW_CONTROLLER_H_ +#ifndef CHROME_BROWSER_UI_COCOA_PASSWORDS_ACCOUNT_CHOOSER_VIEW_CONTROLLER_H_ +#define CHROME_BROWSER_UI_COCOA_PASSWORDS_ACCOUNT_CHOOSER_VIEW_CONTROLLER_H_ #import <Cocoa/Cocoa.h> #include "base/mac/scoped_nsobject.h" +#import "chrome/browser/ui/cocoa/passwords/base_passwords_content_view_controller.h" #import "chrome/browser/ui/cocoa/passwords/credential_item_view.h" -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_content_view_controller.h" @class AccountAvatarFetcherManager; @class BubbleCombobox; @@ -43,4 +43,4 @@ delegate:(id<ManagePasswordsBubbleContentViewDelegate>)delegate; @end -#endif // CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_BUBBLE_ACCOUNT_CHOOSER_VIEW_CONTROLLER_H_ +#endif // CHROME_BROWSER_UI_COCOA_PASSWORDS_ACCOUNT_CHOOSER_VIEW_CONTROLLER_H_
diff --git a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_account_chooser_view_controller.mm b/chrome/browser/ui/cocoa/passwords/account_chooser_view_controller.mm similarity index 98% rename from chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_account_chooser_view_controller.mm rename to chrome/browser/ui/cocoa/passwords/account_chooser_view_controller.mm index 7ef9911..78ccd3a 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_account_chooser_view_controller.mm +++ b/chrome/browser/ui/cocoa/passwords/account_chooser_view_controller.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 "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_account_chooser_view_controller.h" +#import "chrome/browser/ui/cocoa/passwords/account_chooser_view_controller.h" #include <cmath>
diff --git a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_account_chooser_view_controller_unittest.mm b/chrome/browser/ui/cocoa/passwords/account_chooser_view_controller_unittest.mm similarity index 96% rename from chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_account_chooser_view_controller_unittest.mm rename to chrome/browser/ui/cocoa/passwords/account_chooser_view_controller_unittest.mm index 7a07cee3..2cc4dbaa 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_account_chooser_view_controller_unittest.mm +++ b/chrome/browser/ui/cocoa/passwords/account_chooser_view_controller_unittest.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 "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_account_chooser_view_controller.h" +#import "chrome/browser/ui/cocoa/passwords/account_chooser_view_controller.h" #include "base/mac/foundation_util.h" #include "base/memory/scoped_vector.h" @@ -11,8 +11,8 @@ #import "chrome/browser/ui/cocoa/bubble_combobox.h" #include "chrome/browser/ui/cocoa/cocoa_test_helper.h" #import "chrome/browser/ui/cocoa/passwords/account_avatar_fetcher_manager.h" -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_account_chooser_view_controller.h" -#include "chrome/browser/ui/cocoa/passwords/manage_passwords_controller_test.h" +#import "chrome/browser/ui/cocoa/passwords/account_chooser_view_controller.h" +#include "chrome/browser/ui/cocoa/passwords/base_passwords_controller_test.h" #include "chrome/browser/ui/passwords/account_chooser_more_combobox_model.h" #include "chrome/browser/ui/passwords/manage_passwords_bubble_model.h" #include "chrome/browser/ui/passwords/manage_passwords_ui_controller_mock.h"
diff --git a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_auto_signin_view_controller.h b/chrome/browser/ui/cocoa/passwords/auto_signin_view_controller.h similarity index 71% rename from chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_auto_signin_view_controller.h rename to chrome/browser/ui/cocoa/passwords/auto_signin_view_controller.h index 0eb4078..1293184 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_auto_signin_view_controller.h +++ b/chrome/browser/ui/cocoa/passwords/auto_signin_view_controller.h
@@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_BUBBLE_AUTO_SIGNIN_VIEW_CONTROLLER_H_ -#define CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_BUBBLE_AUTO_SIGNIN_VIEW_CONTROLLER_H_ +#ifndef CHROME_BROWSER_UI_COCOA_PASSWORDS_AUTO_SIGNIN_VIEW_CONTROLLER_H_ +#define CHROME_BROWSER_UI_COCOA_PASSWORDS_AUTO_SIGNIN_VIEW_CONTROLLER_H_ #import <Cocoa/Cocoa.h> #include "base/mac/scoped_nsobject.h" #include "base/memory/scoped_ptr.h" -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_content_view_controller.h" +#import "chrome/browser/ui/cocoa/passwords/base_passwords_content_view_controller.h" @class AccountAvatarFetcherManager; @class CredentialItemView; @@ -32,4 +32,4 @@ delegate:(id<ManagePasswordsBubbleContentViewDelegate>)delegate; @end -#endif // CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_BUBBLE_AUTO_SIGNIN_VIEW_CONTROLLER_H_ +#endif // CHROME_BROWSER_UI_COCOA_PASSWORDS_AUTO_SIGNIN_VIEW_CONTROLLER_H_
diff --git a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_auto_signin_view_controller.mm b/chrome/browser/ui/cocoa/passwords/auto_signin_view_controller.mm similarity index 97% rename from chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_auto_signin_view_controller.mm rename to chrome/browser/ui/cocoa/passwords/auto_signin_view_controller.mm index fdd9a77..b716129 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_auto_signin_view_controller.mm +++ b/chrome/browser/ui/cocoa/passwords/auto_signin_view_controller.mm
@@ -4,7 +4,7 @@ #include <algorithm> -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_auto_signin_view_controller.h" +#import "chrome/browser/ui/cocoa/passwords/auto_signin_view_controller.h" #include "base/mac/bind_objc_block.h" #include "base/strings/sys_string_conversions.h"
diff --git a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_content_view_controller.h b/chrome/browser/ui/cocoa/passwords/base_passwords_content_view_controller.h similarity index 84% rename from chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_content_view_controller.h rename to chrome/browser/ui/cocoa/passwords/base_passwords_content_view_controller.h index ca078e76..e8fa0ab7 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_content_view_controller.h +++ b/chrome/browser/ui/cocoa/passwords/base_passwords_content_view_controller.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_BUBBLE_CONTENT_VIEW_CONTROLLER_H_ -#define CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_BUBBLE_CONTENT_VIEW_CONTROLLER_H_ +#ifndef CHROME_BROWSER_UI_COCOA_PASSWORDS_BASE_PASSWORDS_CONTENT_VIEW_CONTROLLER_H_ +#define CHROME_BROWSER_UI_COCOA_PASSWORDS_BASE_PASSWORDS_CONTENT_VIEW_CONTROLLER_H_ #import <Cocoa/Cocoa.h> @@ -48,4 +48,4 @@ @end -#endif // CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_BUBBLE_CONTENT_VIEW_CONTROLLER_H_ +#endif // CHROME_BROWSER_UI_COCOA_PASSWORDS_BASE_PASSWORDS_CONTENT_VIEW_CONTROLLER_H_
diff --git a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_content_view_controller.mm b/chrome/browser/ui/cocoa/passwords/base_passwords_content_view_controller.mm similarity index 95% rename from chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_content_view_controller.mm rename to chrome/browser/ui/cocoa/passwords/base_passwords_content_view_controller.mm index 818d10f..3098120 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_content_view_controller.mm +++ b/chrome/browser/ui/cocoa/passwords/base_passwords_content_view_controller.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 "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_content_view_controller.h" +#import "chrome/browser/ui/cocoa/passwords/base_passwords_content_view_controller.h" #include "base/logging.h" #include "base/mac/scoped_nsobject.h"
diff --git a/chrome/browser/ui/cocoa/passwords/manage_passwords_controller_test.h b/chrome/browser/ui/cocoa/passwords/base_passwords_controller_test.h similarity index 78% rename from chrome/browser/ui/cocoa/passwords/manage_passwords_controller_test.h rename to chrome/browser/ui/cocoa/passwords/base_passwords_controller_test.h index 4a471d6..df9c21f 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_passwords_controller_test.h +++ b/chrome/browser/ui/cocoa/passwords/base_passwords_controller_test.h
@@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_CONTROLLER_TEST_H_ -#define CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_CONTROLLER_TEST_H_ +#ifndef CHROME_BROWSER_UI_COCOA_PASSWORDS_BASE_PASSWORDS_CONTROLLER_TEST_H_ +#define CHROME_BROWSER_UI_COCOA_PASSWORDS_BASE_PASSWORDS_CONTROLLER_TEST_H_ #include "chrome/browser/ui/cocoa/cocoa_profile_test.h" #include "chrome/browser/ui/cocoa/cocoa_test_helper.h" -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_content_view_controller.h" +#import "chrome/browser/ui/cocoa/passwords/base_passwords_content_view_controller.h" namespace content { class WebContents; @@ -40,4 +40,4 @@ @property(readonly, nonatomic) BOOL dismissed; @end -#endif // CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_CONTROLLER_TEST_H_ +#endif // CHROME_BROWSER_UI_COCOA_PASSWORDS_BASE_PASSWORDS_CONTROLLER_TEST_H_
diff --git a/chrome/browser/ui/cocoa/passwords/manage_passwords_controller_test.mm b/chrome/browser/ui/cocoa/passwords/base_passwords_controller_test.mm similarity index 94% rename from chrome/browser/ui/cocoa/passwords/manage_passwords_controller_test.mm rename to chrome/browser/ui/cocoa/passwords/base_passwords_controller_test.mm index fd4e2f6f..a5738f25 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_passwords_controller_test.mm +++ b/chrome/browser/ui/cocoa/passwords/base_passwords_controller_test.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. -#include "chrome/browser/ui/cocoa/passwords/manage_passwords_controller_test.h" +#include "chrome/browser/ui/cocoa/passwords/base_passwords_controller_test.h" #include "chrome/browser/ui/passwords/manage_passwords_bubble_model.h" #include "chrome/browser/ui/passwords/manage_passwords_ui_controller_mock.h"
diff --git a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_confirmation_view_controller.h b/chrome/browser/ui/cocoa/passwords/confirmation_password_saved_view_controller.h similarity index 71% rename from chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_confirmation_view_controller.h rename to chrome/browser/ui/cocoa/passwords/confirmation_password_saved_view_controller.h index e22e3f7e..6fadc639 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_confirmation_view_controller.h +++ b/chrome/browser/ui/cocoa/passwords/confirmation_password_saved_view_controller.h
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_BUBBLE_CONFIRMATION_VIEW_CONTROLLER_H_ -#define CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_BUBBLE_CONFIRMATION_VIEW_CONTROLLER_H_ +#ifndef CHROME_BROWSER_UI_COCOA_PASSWORDS_CONFIRMATION_PASSWORD_SAVED_VIEW_CONTROLLER_H_ +#define CHROME_BROWSER_UI_COCOA_PASSWORDS_CONFIRMATION_PASSWORD_SAVED_VIEW_CONTROLLER_H_ #import <Cocoa/Cocoa.h> #include "base/mac/scoped_nsobject.h" -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_content_view_controller.h" +#import "chrome/browser/ui/cocoa/passwords/base_passwords_content_view_controller.h" @class HyperlinkTextView; class ManagePasswordsBubbleModel; @@ -30,4 +30,4 @@ @property(readonly) NSButton* okButton; @end -#endif // CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_BUBBLE_CONFIRMATION_VIEW_CONTROLLER_H_ +#endif // CHROME_BROWSER_UI_COCOA_PASSWORDS_CONFIRMATION_PASSWORD_SAVED_VIEW_CONTROLLER_H_
diff --git a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_confirmation_view_controller.mm b/chrome/browser/ui/cocoa/passwords/confirmation_password_saved_view_controller.mm similarity index 97% rename from chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_confirmation_view_controller.mm rename to chrome/browser/ui/cocoa/passwords/confirmation_password_saved_view_controller.mm index c8afe4a..a3076c83 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_confirmation_view_controller.mm +++ b/chrome/browser/ui/cocoa/passwords/confirmation_password_saved_view_controller.mm
@@ -4,7 +4,7 @@ #include <algorithm> -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_confirmation_view_controller.h" +#import "chrome/browser/ui/cocoa/passwords/confirmation_password_saved_view_controller.h" #include "base/strings/sys_string_conversions.h" #include "chrome/browser/ui/chrome_style.h"
diff --git a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_confirmation_view_controller_unittest.mm b/chrome/browser/ui/cocoa/passwords/confirmation_password_saved_view_controller_unittest.mm similarity index 91% rename from chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_confirmation_view_controller_unittest.mm rename to chrome/browser/ui/cocoa/passwords/confirmation_password_saved_view_controller_unittest.mm index 0da190c..487ec8c 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_confirmation_view_controller_unittest.mm +++ b/chrome/browser/ui/cocoa/passwords/confirmation_password_saved_view_controller_unittest.mm
@@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_confirmation_view_controller.h" +#import "chrome/browser/ui/cocoa/passwords/confirmation_password_saved_view_controller.h" #include "base/mac/scoped_nsobject.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" #import "chrome/browser/ui/cocoa/bubble_combobox.h" #include "chrome/browser/ui/cocoa/cocoa_test_helper.h" -#include "chrome/browser/ui/cocoa/passwords/manage_passwords_controller_test.h" +#include "chrome/browser/ui/cocoa/passwords/base_passwords_controller_test.h" #include "chrome/browser/ui/passwords/manage_passwords_bubble_model.h" #include "chrome/browser/ui/passwords/manage_passwords_ui_controller_mock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/ui/cocoa/passwords/manage_credential_item_view_controller.h b/chrome/browser/ui/cocoa/passwords/manage_credential_item_view_controller.h deleted file mode 100644 index aca8748..0000000 --- a/chrome/browser/ui/cocoa/passwords/manage_credential_item_view_controller.h +++ /dev/null
@@ -1,50 +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 CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_CREDENTIAL_ITEM_VIEW_CONTROLLER_H_ -#define CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_CREDENTIAL_ITEM_VIEW_CONTROLLER_H_ - -#import <Cocoa/Cocoa.h> - -#include "base/mac/scoped_nsobject.h" -#include "components/autofill/core/common/password_form.h" - -@protocol CredentialItemDelegate; -@class CredentialItemView; -@class HoverImageButton; -class ManagePasswordsBubbleModel; - -@interface ManageCredentialItemView : NSView { - base::scoped_nsobject<CredentialItemView> credentialItem_; - base::scoped_nsobject<HoverImageButton> deleteButton_; -} -- (id)initWithPasswordForm:(const autofill::PasswordForm&)passwordForm - delegate:(id<CredentialItemDelegate>)delegate - target:(id)target - action:(SEL)action; -@end - -@interface DeletedCredentialItemView : NSView { - base::scoped_nsobject<NSButton> undoButton_; -} -- (id)initWithTarget:(id)target action:(SEL)action; -@end - -@interface ManageCredentialItemViewController : NSViewController { - base::scoped_nsobject<NSView> contentView_; - autofill::PasswordForm passwordForm_; - ManagePasswordsBubbleModel* model_; - id<CredentialItemDelegate> delegate_; // Weak. -} -- (id)initWithPasswordForm:(const autofill::PasswordForm&)passwordForm - model:(ManagePasswordsBubbleModel*)model - delegate:(id<CredentialItemDelegate>)delegate; -@end - -@interface ManageCredentialItemViewController (Testing) -@property(nonatomic, readonly) const autofill::PasswordForm& passwordForm; -@property(nonatomic, readonly) NSView* contentView; -@end - -#endif // CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_CREDENTIAL_ITEM_VIEW_CONTROLLER_H_
diff --git a/chrome/browser/ui/cocoa/passwords/manage_credential_item_view_controller.mm b/chrome/browser/ui/cocoa/passwords/manage_credential_item_view_controller.mm deleted file mode 100644 index 62c3ff5d..0000000 --- a/chrome/browser/ui/cocoa/passwords/manage_credential_item_view_controller.mm +++ /dev/null
@@ -1,219 +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. - -#import "chrome/browser/ui/cocoa/passwords/manage_credential_item_view_controller.h" - -#include <algorithm> - -#include "base/i18n/rtl.h" -#include "chrome/browser/ui/chrome_style.h" -#import "chrome/browser/ui/cocoa/passwords/credential_item_view.h" -#include "chrome/browser/ui/passwords/manage_passwords_bubble_model.h" -#include "components/password_manager/core/common/password_manager_ui.h" -#include "grit/components_strings.h" -#include "grit/generated_resources.h" -#include "skia/ext/skia_utils_mac.h" -#import "ui/base/cocoa/controls/hyperlink_button_cell.h" -#import "ui/base/cocoa/hover_image_button.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/gfx/image/image.h" -#include "ui/resources/grit/ui_resources.h" - -namespace { - -// Horizontal space betweeen subviews of a credential item. -const CGFloat kItemSubviewsHorizontalSpacing = 20.0f; - -// Lays out |leftSubview| and |rightSubview| within |item| so that they stick -// to the left and right sides of |item|, respectively, and resizes |item| to -// hold them. Flipped in RTL. -void LayOutItem(NSView* item, NSView* leftSubview, NSView* rightSubview) { - const CGFloat width = NSWidth([leftSubview frame]) + - kItemSubviewsHorizontalSpacing + - NSWidth([rightSubview frame]); - const CGFloat height = - std::max(NSHeight([leftSubview frame]), NSHeight([rightSubview frame])); - [item setFrameSize:NSMakeSize(width, height)]; - [leftSubview - setFrameOrigin:NSMakePoint(base::i18n::IsRTL() - ? width - NSWidth([leftSubview frame]) - : 0, - 0)]; - [rightSubview - setFrameOrigin:NSMakePoint( - base::i18n::IsRTL() - ? 0 - : width - NSWidth([rightSubview frame]), - (height - NSHeight([rightSubview frame])) / 2.0f)]; - [leftSubview setAutoresizingMask:NSViewWidthSizable | - (base::i18n::IsRTL() ? NSViewMinXMargin - : NSViewMaxXMargin)]; - [rightSubview setAutoresizingMask:(base::i18n::IsRTL() ? NSViewMaxXMargin - : NSViewMinXMargin)]; -} -} // namespace - -@implementation ManageCredentialItemView : NSView - -- (id)initWithPasswordForm:(const autofill::PasswordForm&)passwordForm - delegate:(id<CredentialItemDelegate>)delegate - target:(id)target - action:(SEL)action { - if ((self = [super initWithFrame:NSZeroRect])) { - - // ---------------------------------------------- - // | | John Q. Facebooker | | - // | icon | john@somewhere.com | X | - // | | | | - // ---------------------------------------------- - - // Create the views. - credentialItem_.reset([[CredentialItemView alloc] - initWithPasswordForm:passwordForm - credentialType:password_manager::CredentialType:: - CREDENTIAL_TYPE_PASSWORD - style:password_manager_mac::CredentialItemStyle:: - ACCOUNT_CHOOSER - delegate:delegate]); - [self addSubview:credentialItem_]; - - deleteButton_.reset([[HoverImageButton alloc] - initWithFrame:NSMakeRect(0, 0, chrome_style::GetCloseButtonSize(), - chrome_style::GetCloseButtonSize())]); - [deleteButton_ setBordered:NO]; - [[deleteButton_ cell] setHighlightsBy:NSNoCellMask]; - ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance(); - [deleteButton_ - setDefaultImage:bundle.GetNativeImageNamed(IDR_CLOSE_2).ToNSImage()]; - [deleteButton_ - setHoverImage:bundle.GetNativeImageNamed(IDR_CLOSE_2_H).ToNSImage()]; - [deleteButton_ - setPressedImage:bundle.GetNativeImageNamed(IDR_CLOSE_2_P).ToNSImage()]; - [deleteButton_ setTarget:target]; - [deleteButton_ setAction:action]; - [self addSubview:deleteButton_]; - - LayOutItem(self, credentialItem_, deleteButton_); - } - return self; -} - -@end - -@implementation DeletedCredentialItemView : NSView -- (id)initWithTarget:(id)target action:(SEL)action { - if ((self = [super initWithFrame:NSZeroRect])) { - - // ---------------------------------------------- - // | Such-and-such has been deleted. [Undo] - // ---------------------------------------------- - - // Create the views. - base::scoped_nsobject<NSTextField> explanationLabel( - [[NSTextField alloc] initWithFrame:NSZeroRect]); - [explanationLabel - setStringValue:l10n_util::GetNSString(IDS_MANAGE_PASSWORDS_DELETED)]; - NSFont* font = ResourceBundle::GetSharedInstance() - .GetFontList(ResourceBundle::SmallFont) - .GetPrimaryFont() - .GetNativeFont(); - [explanationLabel setFont:font]; - [explanationLabel setEditable:NO]; - [explanationLabel setSelectable:NO]; - [explanationLabel setDrawsBackground:NO]; - [explanationLabel setBezeled:NO]; - [explanationLabel sizeToFit]; - [self addSubview:explanationLabel]; - - undoButton_.reset([[NSButton alloc] initWithFrame:NSZeroRect]); - base::scoped_nsobject<HyperlinkButtonCell> cell([[HyperlinkButtonCell alloc] - initTextCell:l10n_util::GetNSString(IDS_MANAGE_PASSWORDS_UNDO)]); - [cell setControlSize:NSSmallControlSize]; - [cell setShouldUnderline:NO]; - [cell setUnderlineOnHover:NO]; - [cell setTextColor:gfx::SkColorToCalibratedNSColor( - chrome_style::GetLinkColor())]; - [undoButton_ setCell:cell.get()]; - [undoButton_ sizeToFit]; - [undoButton_ setTarget:target]; - [undoButton_ setAction:action]; - [self addSubview:undoButton_]; - - LayOutItem(self, explanationLabel, undoButton_); - } - return self; -} - -@end - -@interface ManageCredentialItemViewController() -- (void)deleteCredential:(id)sender; -- (void)undoDelete:(id)sender; -@end - -@implementation ManageCredentialItemViewController -- (id)initWithPasswordForm:(const autofill::PasswordForm&)passwordForm - model:(ManagePasswordsBubbleModel*)model - delegate:(id<CredentialItemDelegate>)delegate { - if ((self = [super initWithNibName:nil bundle:nil])) { - passwordForm_ = passwordForm; - model_ = model; - delegate_ = delegate; - [self changeToManageView]; - } - return self; -} - -- (void)performLayout { - [self view].subviews = @[ contentView_ ]; - [[self view] setFrameSize:[contentView_ frame].size]; - [contentView_ setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; -} - -- (void)loadView { - [self setView:[[[NSView alloc] initWithFrame:NSZeroRect] autorelease]]; - [self performLayout]; -} - -- (void)deleteCredential:(id)sender { - model_->OnPasswordAction(passwordForm_, - ManagePasswordsBubbleModel::REMOVE_PASSWORD); - [self changeToDeletedView]; - [self performLayout]; -} - -- (void)undoDelete:(id)sender { - model_->OnPasswordAction(passwordForm_, - ManagePasswordsBubbleModel::ADD_PASSWORD); - [self changeToManageView]; - [self performLayout]; -} - -- (void)changeToManageView { - contentView_.reset([[ManageCredentialItemView alloc] - initWithPasswordForm:passwordForm_ - delegate:delegate_ - target:self - action:@selector(deleteCredential:)]); -} - -- (void)changeToDeletedView { - contentView_.reset([[DeletedCredentialItemView alloc] - initWithTarget:self - action:@selector(undoDelete:)]); -} -@end - -@implementation ManageCredentialItemViewController (Testing) - -- (const autofill::PasswordForm&)passwordForm { - return passwordForm_; -} - -- (NSView*)contentView { - return contentView_.get(); -} - -@end
diff --git a/chrome/browser/ui/cocoa/passwords/manage_credential_item_view_controller_unittest.mm b/chrome/browser/ui/cocoa/passwords/manage_credential_item_view_controller_unittest.mm deleted file mode 100644 index 4cad2329..0000000 --- a/chrome/browser/ui/cocoa/passwords/manage_credential_item_view_controller_unittest.mm +++ /dev/null
@@ -1,141 +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. - -#import "chrome/browser/ui/cocoa/passwords/manage_credential_item_view_controller.h" - -#include "base/mac/foundation_util.h" -#include "base/strings/utf_string_conversions.h" -#include "chrome/browser/password_manager/password_store_factory.h" -#include "chrome/browser/ui/cocoa/passwords/manage_passwords_controller_test.h" -#include "chrome/browser/ui/passwords/manage_passwords_bubble_model.h" -#include "chrome/browser/ui/passwords/manage_passwords_ui_controller_mock.h" -#include "components/password_manager/core/browser/mock_password_store.h" -#include "components/password_manager/core/browser/password_manager_test_utils.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "testing/gtest_mac.h" -#import "ui/base/cocoa/hover_image_button.h" - -@interface ManageCredentialItemView (Testing) -@property(nonatomic, readonly) HoverImageButton* deleteButton; -@property(nonatomic, readonly) CredentialItemView* credentialItem; -@end - -@implementation ManageCredentialItemView (Testing) - -- (CredentialItemView*)credentialItem { - return credentialItem_.get(); -} - -- (HoverImageButton*)deleteButton { - return deleteButton_.get(); -} - -@end - -@interface DeletedCredentialItemView (Testing) -@property(nonatomic, readonly) NSButton* undoButton; -@end - -@implementation DeletedCredentialItemView (Testing) - -- (NSButton*)undoButton { - return undoButton_.get(); -} - -@end - -namespace { - -autofill::PasswordForm TestForm() { - autofill::PasswordForm form; - form.username_value = base::ASCIIToUTF16("bob.boblaw@lawblog.com"); - form.display_name = base::ASCIIToUTF16("Bob Boblaw"); - return form; -} - -MATCHER_P(PasswordFormEq, form, "") { - return form.username_value == arg.username_value && - form.display_name == arg.display_name; -} - -class ManageCredentialItemViewControllerTest - : public ManagePasswordsControllerTest { - public: - ManageCredentialItemViewControllerTest() : controller_(nil) {} - - void SetUp() override { - ManagePasswordsControllerTest::SetUp(); - PasswordStoreFactory::GetInstance()->SetTestingFactory( - profile(), - password_manager::BuildPasswordStoreService< - content::BrowserContext, password_manager::MockPasswordStore>); - ui_controller()->SetPendingPassword(TestForm()); - [[test_window() contentView] addSubview:[controller() view]]; - } - - ManageCredentialItemViewController* controller() { - if (!controller_) { - controller_.reset([[ManageCredentialItemViewController alloc] - initWithPasswordForm:TestForm() - model:model() - delegate:nil]); - } - return controller_.get(); - } - - password_manager::MockPasswordStore* mockStore() { - password_manager::PasswordStore* store = - PasswordStoreFactory::GetForProfile( - profile(), ServiceAccessType::EXPLICIT_ACCESS).get(); - password_manager::MockPasswordStore* mockStore = - static_cast<password_manager::MockPasswordStore*>(store); - return mockStore; - } - - private: - base::scoped_nsobject<ManageCredentialItemViewController> controller_; - DISALLOW_COPY_AND_ASSIGN(ManageCredentialItemViewControllerTest); -}; - -TEST_VIEW(ManageCredentialItemViewControllerTest, [controller() view]); - -TEST_F(ManageCredentialItemViewControllerTest, ShouldStartWithCredentialView) { - EXPECT_NSEQ([ManageCredentialItemView class], - [[controller() contentView] class]); - EXPECT_EQ(TestForm(), [controller() passwordForm]); -} - -TEST_F(ManageCredentialItemViewControllerTest, - DeleteShouldDeleteAndShowDeletedView) { - model()->set_state(password_manager::ui::MANAGE_STATE); - - ManageCredentialItemView* itemView = - base::mac::ObjCCastStrict<ManageCredentialItemView>( - [controller() contentView]); - EXPECT_CALL(*mockStore(), RemoveLogin(PasswordFormEq(TestForm()))); - [itemView.deleteButton performClick:nil]; - EXPECT_NSEQ([DeletedCredentialItemView class], - [[controller() contentView] class]); -} - -TEST_F(ManageCredentialItemViewControllerTest, - UndoShouldUndoAndShowCredentialView) { - model()->set_state(password_manager::ui::MANAGE_STATE); - - ManageCredentialItemView* itemView = - base::mac::ObjCCastStrict<ManageCredentialItemView>( - [controller() contentView]); - EXPECT_CALL(*mockStore(), RemoveLogin(PasswordFormEq(TestForm()))); - [itemView.deleteButton performClick:nil]; - - DeletedCredentialItemView* deletedView = - base::mac::ObjCCastStrict<DeletedCredentialItemView>( - [controller() contentView]); - EXPECT_CALL(*mockStore(), AddLogin(PasswordFormEq(TestForm()))); - [deletedView.undoButton performClick:nil]; - EXPECT_NSEQ([ManageCredentialItemView class], - [[controller() contentView] class]); -} - -} // namespace
diff --git a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_manage_view_controller.h b/chrome/browser/ui/cocoa/passwords/manage_passwords_view_controller.h similarity index 78% rename from chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_manage_view_controller.h rename to chrome/browser/ui/cocoa/passwords/manage_passwords_view_controller.h index f3b9b0fd..edcee8a3 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_manage_view_controller.h +++ b/chrome/browser/ui/cocoa/passwords/manage_passwords_view_controller.h
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_BUBBLE_MANAGE_VIEW_CONTROLLER_H_ -#define CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_BUBBLE_MANAGE_VIEW_CONTROLLER_H_ +#ifndef CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_VIEW_CONTROLLER_H_ +#define CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_VIEW_CONTROLLER_H_ #import <Cocoa/Cocoa.h> #include "base/mac/scoped_nsobject.h" -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_content_view_controller.h" +#import "chrome/browser/ui/cocoa/passwords/base_passwords_content_view_controller.h" class ManagePasswordsBubbleModel; @class PasswordsListViewController; @@ -39,4 +39,4 @@ @property(readonly) PasswordsListViewController* passwordsListController; @end -#endif // CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_BUBBLE_MANAGE_VIEW_CONTROLLER_H_ +#endif // CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_VIEW_CONTROLLER_H_
diff --git a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_manage_view_controller.mm b/chrome/browser/ui/cocoa/passwords/manage_passwords_view_controller.mm similarity index 96% rename from chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_manage_view_controller.mm rename to chrome/browser/ui/cocoa/passwords/manage_passwords_view_controller.mm index 7e872ef..ca55fc7 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_manage_view_controller.mm +++ b/chrome/browser/ui/cocoa/passwords/manage_passwords_view_controller.mm
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_manage_view_controller.h" +#import "chrome/browser/ui/cocoa/passwords/manage_passwords_view_controller.h" #include <cmath> #include "base/strings/sys_string_conversions.h" #include "chrome/browser/ui/chrome_style.h" -#import "chrome/browser/ui/cocoa/passwords/manage_password_item_view_controller.h" +#import "chrome/browser/ui/cocoa/passwords/passwords_list_view_controller.h" #include "chrome/browser/ui/passwords/manage_passwords_bubble_model.h" #include "grit/generated_resources.h" #include "skia/ext/skia_utils_mac.h"
diff --git a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_manage_view_controller_unittest.mm b/chrome/browser/ui/cocoa/passwords/manage_passwords_view_controller_unittest.mm similarity index 93% rename from chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_manage_view_controller_unittest.mm rename to chrome/browser/ui/cocoa/passwords/manage_passwords_view_controller_unittest.mm index 3859954..3c983a6 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_manage_view_controller_unittest.mm +++ b/chrome/browser/ui/cocoa/passwords/manage_passwords_view_controller_unittest.mm
@@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_manage_view_controller.h" +#import "chrome/browser/ui/cocoa/passwords/manage_passwords_view_controller.h" #include "base/mac/foundation_util.h" #include "base/memory/scoped_ptr.h" #include "base/strings/utf_string_conversions.h" -#import "chrome/browser/ui/cocoa/passwords/manage_password_item_view_controller.h" -#include "chrome/browser/ui/cocoa/passwords/manage_passwords_controller_test.h" +#include "chrome/browser/ui/cocoa/passwords/base_passwords_controller_test.h" #import "chrome/browser/ui/cocoa/passwords/password_item_views.h" +#import "chrome/browser/ui/cocoa/passwords/passwords_list_view_controller.h" #include "chrome/browser/ui/passwords/manage_passwords_bubble_model.h" #include "chrome/browser/ui/passwords/manage_passwords_ui_controller_mock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_browsertest.mm b/chrome/browser/ui/cocoa/passwords/passwords_bubble_browsertest.mm similarity index 94% rename from chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_browsertest.mm rename to chrome/browser/ui/cocoa/passwords/passwords_bubble_browsertest.mm index 3f01f14b..7f63089 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_browsertest.mm +++ b/chrome/browser/ui/cocoa/passwords/passwords_bubble_browsertest.mm
@@ -10,9 +10,9 @@ #import "chrome/browser/ui/cocoa/info_bubble_window.h" #include "chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h" #include "chrome/browser/ui/cocoa/location_bar/manage_passwords_decoration.h" -#include "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_cocoa.h" -#include "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_controller.h" -#include "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_pending_view_controller.h" +#include "chrome/browser/ui/cocoa/passwords/passwords_bubble_cocoa.h" +#include "chrome/browser/ui/cocoa/passwords/passwords_bubble_controller.h" +#include "chrome/browser/ui/cocoa/passwords/pending_password_view_controller.h" #include "chrome/browser/ui/passwords/manage_passwords_test.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "content/public/test/test_utils.h"
diff --git a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_cocoa.h b/chrome/browser/ui/cocoa/passwords/passwords_bubble_cocoa.h similarity index 91% rename from chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_cocoa.h rename to chrome/browser/ui/cocoa/passwords/passwords_bubble_cocoa.h index 0c2a733c..7a39b4c 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_cocoa.h +++ b/chrome/browser/ui/cocoa/passwords/passwords_bubble_cocoa.h
@@ -2,12 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_BUBBLE_COCOA_H_ -#define CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_BUBBLE_COCOA_H_ +#ifndef CHROME_BROWSER_UI_COCOA_PASSWORDS_PASSWORDS_BUBBLE_COCOA_H_ +#define CHROME_BROWSER_UI_COCOA_PASSWORDS_PASSWORDS_BUBBLE_COCOA_H_ #import <Cocoa/Cocoa.h> #include "base/mac/scoped_nsobject.h" +#include "base/macros.h" #import "chrome/browser/ui/passwords/manage_passwords_bubble_model.h" namespace content { @@ -74,4 +75,4 @@ DISALLOW_COPY_AND_ASSIGN(ManagePasswordsBubbleCocoa); }; -#endif // CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_BUBBLE_COCOA_H_ +#endif // CHROME_BROWSER_UI_COCOA_PASSWORDS_PASSWORDS_BUBBLE_COCOA_H_
diff --git a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_cocoa.mm b/chrome/browser/ui/cocoa/passwords/passwords_bubble_cocoa.mm similarity index 96% rename from chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_cocoa.mm rename to chrome/browser/ui/cocoa/passwords/passwords_bubble_cocoa.mm index 8d4baadc..dbdcbb34a 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_cocoa.mm +++ b/chrome/browser/ui/cocoa/passwords/passwords_bubble_cocoa.mm
@@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_cocoa.h" +#import "chrome/browser/ui/cocoa/passwords/passwords_bubble_cocoa.h" #include "base/mac/scoped_block.h" #include "chrome/browser/ui/browser_finder.h" #import "chrome/browser/ui/cocoa/browser_window_controller.h" #include "chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h" #include "chrome/browser/ui/cocoa/location_bar/manage_passwords_decoration.h" -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_controller.h" +#import "chrome/browser/ui/cocoa/passwords/passwords_bubble_controller.h" #include "chrome/browser/ui/passwords/manage_passwords_icon.h" #include "content/public/browser/web_contents.h"
diff --git a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_cocoa_unittest.mm b/chrome/browser/ui/cocoa/passwords/passwords_bubble_cocoa_unittest.mm similarity index 97% rename from chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_cocoa_unittest.mm rename to chrome/browser/ui/cocoa/passwords/passwords_bubble_cocoa_unittest.mm index 63d14fa..4df5dc55 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_cocoa_unittest.mm +++ b/chrome/browser/ui/cocoa/passwords/passwords_bubble_cocoa_unittest.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. -#include "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_cocoa.h" +#include "chrome/browser/ui/cocoa/passwords/passwords_bubble_cocoa.h" #import <Cocoa/Cocoa.h> @@ -17,7 +17,7 @@ #import "chrome/browser/ui/cocoa/info_bubble_window.h" #include "chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h" #include "chrome/browser/ui/cocoa/location_bar/manage_passwords_decoration.h" -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_controller.h" +#import "chrome/browser/ui/cocoa/passwords/passwords_bubble_controller.h" #include "chrome/browser/ui/passwords/manage_passwords_ui_controller_mock.h" #include "chrome/browser/ui/tab_dialogs.h" #include "chrome/browser/ui/tabs/tab_strip_model.h"
diff --git a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_controller.h b/chrome/browser/ui/cocoa/passwords/passwords_bubble_controller.h similarity index 70% rename from chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_controller.h rename to chrome/browser/ui/cocoa/passwords/passwords_bubble_controller.h index 5bb71df..730aa4f 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_controller.h +++ b/chrome/browser/ui/cocoa/passwords/passwords_bubble_controller.h
@@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_BUBBLE_CONTROLLER_H_ -#define CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_BUBBLE_CONTROLLER_H_ +#ifndef CHROME_BROWSER_UI_COCOA_PASSWORDS_PASSWORDS_BUBBLE_CONTROLLER_H_ +#define CHROME_BROWSER_UI_COCOA_PASSWORDS_PASSWORDS_BUBBLE_CONTROLLER_H_ #import <Cocoa/Cocoa.h> #include "base/mac/scoped_nsobject.h" #import "chrome/browser/ui/cocoa/base_bubble_controller.h" -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_content_view_controller.h" -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_pending_view_controller.h" +#import "chrome/browser/ui/cocoa/passwords/base_passwords_content_view_controller.h" +#import "chrome/browser/ui/cocoa/passwords/pending_password_view_controller.h" #include "chrome/browser/ui/passwords/manage_passwords_bubble_model.h" // Controller for the Cocoa manage passwords bubble. Transitions through several @@ -31,4 +31,4 @@ @property(readonly) NSViewController* currentController; @end -#endif // CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_BUBBLE_CONTROLLER_H_ +#endif // CHROME_BROWSER_UI_COCOA_PASSWORDS_PASSWORDS_BUBBLE_CONTROLLER_H_
diff --git a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_controller.mm b/chrome/browser/ui/cocoa/passwords/passwords_bubble_controller.mm similarity index 91% rename from chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_controller.mm rename to chrome/browser/ui/cocoa/passwords/passwords_bubble_controller.mm index e7369e2..d24a5bae 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_controller.mm +++ b/chrome/browser/ui/cocoa/passwords/passwords_bubble_controller.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 "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_controller.h" +#import "chrome/browser/ui/cocoa/passwords/passwords_bubble_controller.h" #include "base/mac/scoped_nsobject.h" #include "chrome/browser/ui/browser_finder.h" @@ -10,10 +10,10 @@ #import "chrome/browser/ui/cocoa/info_bubble_view.h" #import "chrome/browser/ui/cocoa/info_bubble_window.h" #include "chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h" -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_account_chooser_view_controller.h" -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_auto_signin_view_controller.h" -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_confirmation_view_controller.h" -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_manage_view_controller.h" +#import "chrome/browser/ui/cocoa/passwords/account_chooser_view_controller.h" +#import "chrome/browser/ui/cocoa/passwords/auto_signin_view_controller.h" +#import "chrome/browser/ui/cocoa/passwords/confirmation_password_saved_view_controller.h" +#import "chrome/browser/ui/cocoa/passwords/manage_passwords_view_controller.h" #include "ui/base/cocoa/window_size_constants.h" @interface ManagePasswordsBubbleController ()
diff --git a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_controller_unittest.mm b/chrome/browser/ui/cocoa/passwords/passwords_bubble_controller_unittest.mm similarity index 87% rename from chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_controller_unittest.mm rename to chrome/browser/ui/cocoa/passwords/passwords_bubble_controller_unittest.mm index 1cde4a0..bc8315e 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_controller_unittest.mm +++ b/chrome/browser/ui/cocoa/passwords/passwords_bubble_controller_unittest.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. -#include "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_controller.h" +#include "chrome/browser/ui/cocoa/passwords/passwords_bubble_controller.h" #import <Cocoa/Cocoa.h> @@ -12,9 +12,9 @@ #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/cocoa/cocoa_test_helper.h" #import "chrome/browser/ui/cocoa/info_bubble_window.h" -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_manage_view_controller.h" -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_pending_view_controller.h" -#include "chrome/browser/ui/cocoa/passwords/manage_passwords_controller_test.h" +#include "chrome/browser/ui/cocoa/passwords/base_passwords_controller_test.h" +#import "chrome/browser/ui/cocoa/passwords/manage_passwords_view_controller.h" +#import "chrome/browser/ui/cocoa/passwords/pending_password_view_controller.h" #include "chrome/browser/ui/passwords/manage_passwords_bubble_model.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/gtest_mac.h"
diff --git a/chrome/browser/ui/cocoa/passwords/manage_password_item_view_controller.h b/chrome/browser/ui/cocoa/passwords/passwords_list_view_controller.h similarity index 84% rename from chrome/browser/ui/cocoa/passwords/manage_password_item_view_controller.h rename to chrome/browser/ui/cocoa/passwords/passwords_list_view_controller.h index 438d00a..353e427 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_password_item_view_controller.h +++ b/chrome/browser/ui/cocoa/passwords/passwords_list_view_controller.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORD_ITEM_VIEW_CONTROLLER_H_ -#define CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORD_ITEM_VIEW_CONTROLLER_H_ +#ifndef CHROME_BROWSER_UI_COCOA_PASSWORDS_PASSWORDS_LIST_VIEW_CONTROLLER_H_ +#define CHROME_BROWSER_UI_COCOA_PASSWORDS_PASSWORDS_LIST_VIEW_CONTROLLER_H_ #include <vector> @@ -47,4 +47,4 @@ @property(readonly) NSArray* itemViews; @end -#endif // CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORD_ITEM_VIEW_CONTROLLER_H_ +#endif // CHROME_BROWSER_UI_COCOA_PASSWORDS_PASSWORDS_LIST_VIEW_CONTROLLER_H_
diff --git a/chrome/browser/ui/cocoa/passwords/manage_password_item_view_controller.mm b/chrome/browser/ui/cocoa/passwords/passwords_list_view_controller.mm similarity index 98% rename from chrome/browser/ui/cocoa/passwords/manage_password_item_view_controller.mm rename to chrome/browser/ui/cocoa/passwords/passwords_list_view_controller.mm index b7d83a29..ab2f32c6 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_password_item_view_controller.mm +++ b/chrome/browser/ui/cocoa/passwords/passwords_list_view_controller.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 "chrome/browser/ui/cocoa/passwords/manage_password_item_view_controller.h" +#import "chrome/browser/ui/cocoa/passwords/passwords_list_view_controller.h" #include <utility> @@ -12,7 +12,7 @@ #include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/ui/chrome_style.h" -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_content_view_controller.h" +#import "chrome/browser/ui/cocoa/passwords/base_passwords_content_view_controller.h" #import "chrome/browser/ui/cocoa/passwords/password_item_views.h" #include "chrome/browser/ui/passwords/manage_passwords_bubble_model.h" #include "grit/components_strings.h"
diff --git a/chrome/browser/ui/cocoa/passwords/manage_password_item_view_controller_unittest.mm b/chrome/browser/ui/cocoa/passwords/passwords_list_view_controller_unittest.mm similarity index 96% rename from chrome/browser/ui/cocoa/passwords/manage_password_item_view_controller_unittest.mm rename to chrome/browser/ui/cocoa/passwords/passwords_list_view_controller_unittest.mm index 5ecd0806..7f8f3bd 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_password_item_view_controller_unittest.mm +++ b/chrome/browser/ui/cocoa/passwords/passwords_list_view_controller_unittest.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 "chrome/browser/ui/cocoa/passwords/manage_password_item_view_controller.h" +#import "chrome/browser/ui/cocoa/passwords/passwords_list_view_controller.h" #include "base/mac/foundation_util.h" #include "base/mac/scoped_nsobject.h" @@ -10,9 +10,9 @@ #include "base/strings/sys_string_conversions.h" #include "chrome/browser/password_manager/password_store_factory.h" #include "chrome/browser/ui/cocoa/cocoa_test_helper.h" -#import "chrome/browser/ui/cocoa/passwords/manage_password_item_view_controller.h" -#include "chrome/browser/ui/cocoa/passwords/manage_passwords_controller_test.h" +#include "chrome/browser/ui/cocoa/passwords/base_passwords_controller_test.h" #import "chrome/browser/ui/cocoa/passwords/password_item_views.h" +#import "chrome/browser/ui/cocoa/passwords/passwords_list_view_controller.h" #include "chrome/browser/ui/passwords/manage_passwords_bubble_model.h" #include "chrome/browser/ui/passwords/manage_passwords_ui_controller_mock.h" #include "components/password_manager/core/browser/mock_password_store.h"
diff --git a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_pending_view_controller.h b/chrome/browser/ui/cocoa/passwords/pending_password_view_controller.h similarity index 74% rename from chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_pending_view_controller.h rename to chrome/browser/ui/cocoa/passwords/pending_password_view_controller.h index ea0023e..c411cb9a 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_pending_view_controller.h +++ b/chrome/browser/ui/cocoa/passwords/pending_password_view_controller.h
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_BUBBLE_PENDING_VIEW_CONTROLLER_H_ -#define CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_BUBBLE_PENDING_VIEW_CONTROLLER_H_ +#ifndef CHROME_BROWSER_UI_COCOA_PASSWORDS_PENDING_PASSWORD_VIEW_CONTROLLER_H_ +#define CHROME_BROWSER_UI_COCOA_PASSWORDS_PENDING_PASSWORD_VIEW_CONTROLLER_H_ #import <Cocoa/Cocoa.h> #include "base/mac/scoped_nsobject.h" -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_content_view_controller.h" +#import "chrome/browser/ui/cocoa/passwords/base_passwords_content_view_controller.h" class ManagePasswordsBubbleModel; @class PasswordsListViewController; @@ -33,4 +33,4 @@ @property(readonly) NSButton* closeButton; @end -#endif // CHROME_BROWSER_UI_COCOA_PASSWORDS_MANAGE_PASSWORDS_BUBBLE_PENDING_VIEW_CONTROLLER_H_ +#endif // CHROME_BROWSER_UI_COCOA_PASSWORDS_PENDING_PASSWORD_VIEW_CONTROLLER_H_
diff --git a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_pending_view_controller.mm b/chrome/browser/ui/cocoa/passwords/pending_password_view_controller.mm similarity index 97% rename from chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_pending_view_controller.mm rename to chrome/browser/ui/cocoa/passwords/pending_password_view_controller.mm index 5e65bde..58e40cc 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_pending_view_controller.mm +++ b/chrome/browser/ui/cocoa/passwords/pending_password_view_controller.mm
@@ -4,12 +4,12 @@ #include <algorithm> -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_pending_view_controller.h" +#import "chrome/browser/ui/cocoa/passwords/pending_password_view_controller.h" #include "base/strings/sys_string_conversions.h" #include "chrome/browser/ui/chrome_style.h" #import "chrome/browser/ui/cocoa/hover_close_button.h" -#import "chrome/browser/ui/cocoa/passwords/manage_password_item_view_controller.h" +#import "chrome/browser/ui/cocoa/passwords/passwords_list_view_controller.h" #include "chrome/browser/ui/passwords/manage_passwords_bubble_model.h" #include "chrome/grit/generated_resources.h" #include "skia/ext/skia_utils_mac.h"
diff --git a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_pending_view_controller_unittest.mm b/chrome/browser/ui/cocoa/passwords/pending_password_view_controller_unittest.mm similarity index 89% rename from chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_pending_view_controller_unittest.mm rename to chrome/browser/ui/cocoa/passwords/pending_password_view_controller_unittest.mm index 6ee33e9..b2974e2b 100644 --- a/chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_pending_view_controller_unittest.mm +++ b/chrome/browser/ui/cocoa/passwords/pending_password_view_controller_unittest.mm
@@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_pending_view_controller.h" +#import "chrome/browser/ui/cocoa/passwords/pending_password_view_controller.h" #include "base/mac/scoped_nsobject.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" #import "chrome/browser/ui/cocoa/bubble_combobox.h" #include "chrome/browser/ui/cocoa/cocoa_test_helper.h" -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_pending_view_controller.h" -#include "chrome/browser/ui/cocoa/passwords/manage_passwords_controller_test.h" +#include "chrome/browser/ui/cocoa/passwords/base_passwords_controller_test.h" +#import "chrome/browser/ui/cocoa/passwords/pending_password_view_controller.h" #include "chrome/browser/ui/passwords/manage_passwords_bubble_model.h" #include "chrome/browser/ui/passwords/manage_passwords_ui_controller_mock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/ui/cocoa/tab_dialogs_cocoa.mm b/chrome/browser/ui/cocoa/tab_dialogs_cocoa.mm index 49897048..18fd0e9 100644 --- a/chrome/browser/ui/cocoa/tab_dialogs_cocoa.mm +++ b/chrome/browser/ui/cocoa/tab_dialogs_cocoa.mm
@@ -6,7 +6,7 @@ #import "chrome/browser/ui/cocoa/content_settings/collected_cookies_mac.h" #import "chrome/browser/ui/cocoa/hung_renderer_controller.h" -#import "chrome/browser/ui/cocoa/passwords/manage_passwords_bubble_cocoa.h" +#import "chrome/browser/ui/cocoa/passwords/passwords_bubble_cocoa.h" #import "chrome/browser/ui/cocoa/profiles/profile_signin_confirmation_dialog_cocoa.h" #import "chrome/browser/ui/cocoa/validation_message_bubble_cocoa.h" #include "content/public/browser/web_contents.h"
diff --git a/chrome/browser/ui/cocoa/toolbar/toolbar_controller.mm b/chrome/browser/ui/cocoa/toolbar/toolbar_controller.mm index 0ee56ad9..fff83ec 100644 --- a/chrome/browser/ui/cocoa/toolbar/toolbar_controller.mm +++ b/chrome/browser/ui/cocoa/toolbar/toolbar_controller.mm
@@ -145,7 +145,7 @@ - (void)browserActionsVisibilityChanged:(NSNotification*)notification; - (void)browserActionsContainerWillAnimate:(NSNotification*)notification; - (void)adjustLocationSizeBy:(CGFloat)dX animate:(BOOL)animate; -- (void)updateWrenchButtonSeverity:(WrenchIconPainter::Severity)severity +- (void)updateWrenchButtonSeverity:(AppMenuIconPainter::Severity)severity animate:(BOOL)animate; @end @@ -191,7 +191,7 @@ } void UpdateBadgeSeverity(AppMenuBadgeController::BadgeType type, - WrenchIconPainter::Severity severity, + AppMenuIconPainter::Severity severity, bool animate) override { [controller_ updateWrenchButtonSeverity:severity animate:animate]; } @@ -672,7 +672,7 @@ [wrenchButton_ setAttachedMenu:[wrenchMenuController_ menu]]; } -- (void)updateWrenchButtonSeverity:(WrenchIconPainter::Severity)severity +- (void)updateWrenchButtonSeverity:(AppMenuIconPainter::Severity)severity animate:(BOOL)animate { WrenchToolbarButtonCell* cell = base::mac::ObjCCastStrict<WrenchToolbarButtonCell>([wrenchButton_ cell]);
diff --git a/chrome/browser/ui/cocoa/toolbar/wrench_toolbar_button_cell.h b/chrome/browser/ui/cocoa/toolbar/wrench_toolbar_button_cell.h index 26f3615c..ce5f0312 100644 --- a/chrome/browser/ui/cocoa/toolbar/wrench_toolbar_button_cell.h +++ b/chrome/browser/ui/cocoa/toolbar/wrench_toolbar_button_cell.h
@@ -9,19 +9,19 @@ #include "base/memory/scoped_ptr.h" #import "chrome/browser/ui/cocoa/clickhold_button_cell.h" -#include "chrome/browser/ui/toolbar/wrench_icon_painter.h" +#include "chrome/browser/ui/toolbar/app_menu_icon_painter.h" -class WrenchIconPainterDelegateMac; +class AppMenuIconPainterDelegateMac; -// Cell for the wrench toolbar button. This is used to draw the wrench icon +// Cell for the wrench toolbar button. This is used to draw the app menu icon // and paint severity levels. @interface WrenchToolbarButtonCell : ClickHoldButtonCell { @private - scoped_ptr<WrenchIconPainter> wrenchIconPainter_; - scoped_ptr<WrenchIconPainterDelegateMac> delegate_; + scoped_ptr<AppMenuIconPainter> iconPainter_; + scoped_ptr<AppMenuIconPainterDelegateMac> delegate_; } -- (void)setSeverity:(WrenchIconPainter::Severity)severity +- (void)setSeverity:(AppMenuIconPainter::Severity)severity shouldAnimate:(BOOL)shouldAnimate; @end
diff --git a/chrome/browser/ui/cocoa/toolbar/wrench_toolbar_button_cell.mm b/chrome/browser/ui/cocoa/toolbar/wrench_toolbar_button_cell.mm index 9e932b4..1668127 100644 --- a/chrome/browser/ui/cocoa/toolbar/wrench_toolbar_button_cell.mm +++ b/chrome/browser/ui/cocoa/toolbar/wrench_toolbar_button_cell.mm
@@ -8,24 +8,24 @@ #include "ui/gfx/canvas_skia_paint.h" #include "ui/gfx/geometry/rect.h" -class WrenchIconPainterDelegateMac : public WrenchIconPainter::Delegate { +class AppMenuIconPainterDelegateMac : public AppMenuIconPainter::Delegate { public: - explicit WrenchIconPainterDelegateMac(NSCell* cell) : cell_(cell) {} - ~WrenchIconPainterDelegateMac() override {} + explicit AppMenuIconPainterDelegateMac(NSCell* cell) : cell_(cell) {} + ~AppMenuIconPainterDelegateMac() override {} - void ScheduleWrenchIconPaint() override { + void ScheduleAppMenuIconPaint() override { [[cell_ controlView] setNeedsDisplay:YES]; } private: NSCell* cell_; - DISALLOW_COPY_AND_ASSIGN(WrenchIconPainterDelegateMac); + DISALLOW_COPY_AND_ASSIGN(AppMenuIconPainterDelegateMac); }; @interface WrenchToolbarButtonCell () - (void)commonInit; -- (WrenchIconPainter::BezelType)currentBezelType; +- (AppMenuIconPainter::BezelType)currentBezelType; @end @implementation WrenchToolbarButtonCell @@ -51,32 +51,31 @@ [self imageAlphaForWindowState:[controlView window]]); ui::ThemeProvider* themeProvider = [[controlView window] themeProvider]; if (themeProvider) { - wrenchIconPainter_->Paint(&canvas, - [[controlView window] themeProvider], - gfx::Rect(NSRectToCGRect(cellFrame)), - [self currentBezelType]); + iconPainter_->Paint(&canvas, [[controlView window] themeProvider], + gfx::Rect(NSRectToCGRect(cellFrame)), + [self currentBezelType]); } canvas.Restore(); [self drawFocusRingWithFrame:cellFrame inView:controlView]; } -- (void)setSeverity:(WrenchIconPainter::Severity)severity +- (void)setSeverity:(AppMenuIconPainter::Severity)severity shouldAnimate:(BOOL)shouldAnimate { - wrenchIconPainter_->SetSeverity(severity, shouldAnimate); + iconPainter_->SetSeverity(severity, shouldAnimate); } - (void)commonInit { - delegate_.reset(new WrenchIconPainterDelegateMac(self)); - wrenchIconPainter_.reset(new WrenchIconPainter(delegate_.get())); + delegate_.reset(new AppMenuIconPainterDelegateMac(self)); + iconPainter_.reset(new AppMenuIconPainter(delegate_.get())); } -- (WrenchIconPainter::BezelType)currentBezelType { +- (AppMenuIconPainter::BezelType)currentBezelType { if ([self isHighlighted]) - return WrenchIconPainter::BEZEL_PRESSED; + return AppMenuIconPainter::BEZEL_PRESSED; if ([self isMouseInside]) - return WrenchIconPainter::BEZEL_HOVER; - return WrenchIconPainter::BEZEL_NONE; + return AppMenuIconPainter::BEZEL_HOVER; + return AppMenuIconPainter::BEZEL_NONE; } @end
diff --git a/chrome/browser/ui/extensions/extension_installed_bubble.h b/chrome/browser/ui/extensions/extension_installed_bubble.h index a828cce..3f548f8e 100644 --- a/chrome/browser/ui/extensions/extension_installed_bubble.h +++ b/chrome/browser/ui/extensions/extension_installed_bubble.h
@@ -27,7 +27,7 @@ // BROWSER_ACTION -> The browser action icon in the toolbar. // PAGE_ACTION -> A preview of the page action icon in the location // bar which is shown while the Bubble is shown. -// GENERIC -> The wrench menu. This case includes page actions that +// GENERIC -> The app menu. This case includes page actions that // don't specify a default icon. // // ExtensionInstallBubble manages its own lifetime.
diff --git a/chrome/browser/ui/global_error/global_error.cc b/chrome/browser/ui/global_error/global_error.cc index 098d99b0..bcf3c9d 100644 --- a/chrome/browser/ui/global_error/global_error.cc +++ b/chrome/browser/ui/global_error/global_error.cc
@@ -62,7 +62,7 @@ } gfx::Image GlobalErrorWithStandardBubble::GetBubbleViewIcon() { - // If you change this make sure to also change the menu icon and the wrench + // If you change this make sure to also change the menu icon and the app menu // icon color. return ResourceBundle::GetSharedInstance().GetNativeImageNamed( IDR_INPUT_ALERT);
diff --git a/chrome/browser/ui/global_error/global_error.h b/chrome/browser/ui/global_error/global_error.h index 12055c57..df8957ae 100644 --- a/chrome/browser/ui/global_error/global_error.h +++ b/chrome/browser/ui/global_error/global_error.h
@@ -35,7 +35,7 @@ // overridden, this is based on the badge resource ID. virtual Severity GetSeverity(); - // Returns true if a menu item should be added to the wrench menu. + // Returns true if a menu item should be added to the app menu. virtual bool HasMenuItem() = 0; // Returns the command ID for the menu item. virtual int MenuItemCommandID() = 0;
diff --git a/chrome/browser/ui/simple_message_box.h b/chrome/browser/ui/simple_message_box.h index e4a155b..2546d47c 100644 --- a/chrome/browser/ui/simple_message_box.h +++ b/chrome/browser/ui/simple_message_box.h
@@ -27,7 +27,7 @@ // is always app-modal. // // NOTE: In general, you should avoid this since it's usually poor UI. -// We have a variety of other surfaces such as wrench menu notifications and +// We have a variety of other surfaces such as app menu notifications and // infobars; consult the UI leads for a recommendation. MessageBoxResult ShowMessageBox(gfx::NativeWindow parent, const base::string16& title, @@ -39,7 +39,7 @@ // be made modal to the |parent|. (Aura only.) // // NOTE: In general, you should avoid this since it's usually poor UI. -// We have a variety of other surfaces such as wrench menu notifications and +// We have a variety of other surfaces such as app menu notifications and // infobars; consult the UI leads for a recommendation. MessageBoxResult ShowMessageBoxWithButtonText(gfx::NativeWindow parent, const base::string16& title,
diff --git a/chrome/browser/ui/toolbar/app_menu_badge_controller.cc b/chrome/browser/ui/toolbar/app_menu_badge_controller.cc index ee7282b..a96a874 100644 --- a/chrome/browser/ui/toolbar/app_menu_badge_controller.cc +++ b/chrome/browser/ui/toolbar/app_menu_badge_controller.cc
@@ -18,24 +18,24 @@ namespace { // Maps an upgrade level to a severity level. -WrenchIconPainter::Severity SeverityFromUpgradeLevel( +AppMenuIconPainter::Severity SeverityFromUpgradeLevel( UpgradeDetector::UpgradeNotificationAnnoyanceLevel level) { switch (level) { case UpgradeDetector::UPGRADE_ANNOYANCE_NONE: - return WrenchIconPainter::SEVERITY_NONE; + return AppMenuIconPainter::SEVERITY_NONE; case UpgradeDetector::UPGRADE_ANNOYANCE_LOW: - return WrenchIconPainter::SEVERITY_LOW; + return AppMenuIconPainter::SEVERITY_LOW; case UpgradeDetector::UPGRADE_ANNOYANCE_ELEVATED: - return WrenchIconPainter::SEVERITY_MEDIUM; + return AppMenuIconPainter::SEVERITY_MEDIUM; case UpgradeDetector::UPGRADE_ANNOYANCE_HIGH: - return WrenchIconPainter::SEVERITY_HIGH; + return AppMenuIconPainter::SEVERITY_HIGH; case UpgradeDetector::UPGRADE_ANNOYANCE_SEVERE: - return WrenchIconPainter::SEVERITY_HIGH; + return AppMenuIconPainter::SEVERITY_HIGH; case UpgradeDetector::UPGRADE_ANNOYANCE_CRITICAL: - return WrenchIconPainter::SEVERITY_HIGH; + return AppMenuIconPainter::SEVERITY_HIGH; } NOTREACHED(); - return WrenchIconPainter::SEVERITY_NONE; + return AppMenuIconPainter::SEVERITY_NONE; } // Checks if the app menu icon should be animated for the given upgrade level. @@ -111,7 +111,7 @@ if (ShouldShowIncompatibilityWarning()) { delegate_->UpdateBadgeSeverity(BADGE_TYPE_INCOMPATIBILITY_WARNING, - WrenchIconPainter::SEVERITY_MEDIUM, true); + AppMenuIconPainter::SEVERITY_MEDIUM, true); return; } @@ -120,12 +120,12 @@ // If you change the severity here, make sure to also change the menu icon // and the bubble icon. delegate_->UpdateBadgeSeverity(BADGE_TYPE_GLOBAL_ERROR, - WrenchIconPainter::SEVERITY_MEDIUM, true); + AppMenuIconPainter::SEVERITY_MEDIUM, true); return; } delegate_->UpdateBadgeSeverity(BADGE_TYPE_NONE, - WrenchIconPainter::SEVERITY_NONE, true); + AppMenuIconPainter::SEVERITY_NONE, true); } void AppMenuBadgeController::Observe(
diff --git a/chrome/browser/ui/toolbar/app_menu_badge_controller.h b/chrome/browser/ui/toolbar/app_menu_badge_controller.h index 3ce51a28..b8e46a44 100644 --- a/chrome/browser/ui/toolbar/app_menu_badge_controller.h +++ b/chrome/browser/ui/toolbar/app_menu_badge_controller.h
@@ -6,7 +6,7 @@ #define CHROME_BROWSER_UI_TOOLBAR_APP_MENU_BADGE_CONTROLLER_H_ #include "base/macros.h" -#include "chrome/browser/ui/toolbar/wrench_icon_painter.h" +#include "chrome/browser/ui/toolbar/app_menu_icon_painter.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" @@ -32,7 +32,7 @@ // well as specifying whether it should |animate|. The |type| parameter // specifies the type of change (i.e. the source of the notification). virtual void UpdateBadgeSeverity(BadgeType type, - WrenchIconPainter::Severity severity, + AppMenuIconPainter::Severity severity, bool animate) = 0; protected:
diff --git a/chrome/browser/ui/toolbar/wrench_icon_painter.cc b/chrome/browser/ui/toolbar/app_menu_icon_painter.cc similarity index 78% rename from chrome/browser/ui/toolbar/wrench_icon_painter.cc rename to chrome/browser/ui/toolbar/app_menu_icon_painter.cc index d654160..46947320 100644 --- a/chrome/browser/ui/toolbar/wrench_icon_painter.cc +++ b/chrome/browser/ui/toolbar/app_menu_icon_painter.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/ui/toolbar/wrench_icon_painter.h" +#include "chrome/browser/ui/toolbar/app_menu_icon_painter.h" #include <algorithm> @@ -15,14 +15,14 @@ namespace { -// The wrench icon is made up of this many bars stacked vertically. +// The app menu icon is made up of this many bars stacked vertically. const int kBarCount = 3; // |value| is the animation progress from 0 to 1. |index| is the index of the // bar being drawn. This function returns a new progress value (from 0 to 1) // such that bars appear staggered. double GetStaggeredValue(double value, int index) { - // When animating the wrench icon's bars the bars are staggered by this + // When animating the app menu icon's bars the bars are staggered by this // factor. const double kStaggerFactor = 0.15; double maxStaggeredValue = 1.0 - (kBarCount - 1) * kStaggerFactor; @@ -32,19 +32,17 @@ } // namespace -WrenchIconPainter::WrenchIconPainter(Delegate* delegate) - : delegate_(delegate), - severity_(SEVERITY_NONE) { -} +AppMenuIconPainter::AppMenuIconPainter(Delegate* delegate) + : delegate_(delegate), severity_(SEVERITY_NONE) {} -WrenchIconPainter::~WrenchIconPainter() {} +AppMenuIconPainter::~AppMenuIconPainter() {} -void WrenchIconPainter::SetSeverity(Severity severity, bool animate) { +void AppMenuIconPainter::SetSeverity(Severity severity, bool animate) { if (severity_ == severity) return; severity_ = severity; - delegate_->ScheduleWrenchIconPaint(); + delegate_->ScheduleAppMenuIconPaint(); animation_.reset(); if (severity_ == SEVERITY_NONE || !animate) return; @@ -64,10 +62,10 @@ animation_->Start(); } -void WrenchIconPainter::Paint(gfx::Canvas* canvas, - ui::ThemeProvider* theme_provider, - const gfx::Rect& rect, - BezelType bezel_type) { +void AppMenuIconPainter::Paint(gfx::Canvas* canvas, + ui::ThemeProvider* theme_provider, + const gfx::Rect& rect, + BezelType bezel_type) { gfx::Point center = rect.CenterPoint(); // Bezel. @@ -85,8 +83,7 @@ if (resource_id) { gfx::ImageSkia* image = theme_provider->GetImageSkiaNamed(resource_id); - canvas->DrawImageInt(*image, - center.x() - image->width() / 2, + canvas->DrawImageInt(*image, center.x() - image->width() / 2, center.y() - image->height() / 2); } @@ -128,8 +125,8 @@ } } - canvas->DrawImageInt(*image, 0, 0, width, image->height(), - x, y, width, image->height(), false, paint); + canvas->DrawImageInt(*image, 0, 0, width, image->height(), x, y, width, + image->height(), false, paint); y += image->height(); } } @@ -138,11 +135,11 @@ canvas->DrawImageInt(badge_, 0, 0); } -void WrenchIconPainter::AnimationProgressed(const gfx::Animation* animation) { - delegate_->ScheduleWrenchIconPaint(); +void AppMenuIconPainter::AnimationProgressed(const gfx::Animation* animation) { + delegate_->ScheduleAppMenuIconPaint(); } -int WrenchIconPainter::GetCurrentSeverityImageID() const { +int AppMenuIconPainter::GetCurrentSeverityImageID() const { switch (severity_) { case SEVERITY_NONE: return 0;
diff --git a/chrome/browser/ui/toolbar/wrench_icon_painter.h b/chrome/browser/ui/toolbar/app_menu_icon_painter.h similarity index 65% rename from chrome/browser/ui/toolbar/wrench_icon_painter.h rename to chrome/browser/ui/toolbar/app_menu_icon_painter.h index c50d7b2..d06397e 100644 --- a/chrome/browser/ui/toolbar/wrench_icon_painter.h +++ b/chrome/browser/ui/toolbar/app_menu_icon_painter.h
@@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_UI_TOOLBAR_WRENCH_ICON_PAINTER_H_ -#define CHROME_BROWSER_UI_TOOLBAR_WRENCH_ICON_PAINTER_H_ +#ifndef CHROME_BROWSER_UI_TOOLBAR_APP_MENU_ICON_PAINTER_H_ +#define CHROME_BROWSER_UI_TOOLBAR_APP_MENU_ICON_PAINTER_H_ -#include "base/compiler_specific.h" #include "base/gtest_prod_util.h" +#include "base/macros.h" #include "base/memory/scoped_ptr.h" #include "ui/gfx/animation/animation_delegate.h" #include "ui/gfx/image/image_skia.h" @@ -20,9 +20,9 @@ class ThemeProvider; } -// This class is used to draw the wrench icon. It can signify severity levels -// by changing the wrench icon to different colors. -class WrenchIconPainter : gfx::AnimationDelegate { +// This class is used to draw the app menu icon. It can signify severity levels +// by changing the app menu icon to different colors. +class AppMenuIconPainter : gfx::AnimationDelegate { public: enum BezelType { BEZEL_NONE, @@ -39,15 +39,16 @@ class Delegate { public: - virtual void ScheduleWrenchIconPaint() = 0; + virtual void ScheduleAppMenuIconPaint() = 0; + protected: virtual ~Delegate() {} }; - explicit WrenchIconPainter(Delegate* delegate); - ~WrenchIconPainter() override; + explicit AppMenuIconPainter(Delegate* delegate); + ~AppMenuIconPainter() override; - // If |severity| is not |SEVERITY_NONE| then the wrench icon is colored to + // If |severity| is not |SEVERITY_NONE| then the app menu icon is colored to // match the severity level. void SetSeverity(Severity severity, bool animate); @@ -60,7 +61,7 @@ BezelType bezel_type); private: - FRIEND_TEST_ALL_PREFIXES(WrenchIconPainterTest, PaintCallback); + FRIEND_TEST_ALL_PREFIXES(AppMenuIconPainterTest, PaintCallback); // AnimationDelegate: void AnimationProgressed(const gfx::Animation* animation) override; @@ -73,7 +74,7 @@ gfx::ImageSkia badge_; scoped_ptr<gfx::MultiAnimation> animation_; - DISALLOW_COPY_AND_ASSIGN(WrenchIconPainter); + DISALLOW_COPY_AND_ASSIGN(AppMenuIconPainter); }; -#endif // CHROME_BROWSER_UI_TOOLBAR_WRENCH_ICON_PAINTER_H_ +#endif // CHROME_BROWSER_UI_TOOLBAR_APP_MENU_ICON_PAINTER_H_
diff --git a/chrome/browser/ui/toolbar/app_menu_icon_painter_unittest.cc b/chrome/browser/ui/toolbar/app_menu_icon_painter_unittest.cc new file mode 100644 index 0000000..a0fe0de --- /dev/null +++ b/chrome/browser/ui/toolbar/app_menu_icon_painter_unittest.cc
@@ -0,0 +1,70 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/toolbar/app_menu_icon_painter.h" + +#include "chrome/browser/themes/theme_service.h" +#include "chrome/browser/themes/theme_service_factory.h" +#include "chrome/test/base/testing_profile.h" +#include "content/public/test/test_browser_thread_bundle.h" +#include "grit/theme_resources.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "ui/gfx/canvas.h" +#include "ui/gfx/geometry/rect.h" + +class AppMenuIconPainterTest : public testing::Test, + public AppMenuIconPainter::Delegate { + public: + AppMenuIconPainterTest() : schedule_paint_count_(0), painter_(this) { + theme_provider_ = ThemeServiceFactory::GetForProfile(&profile_); + } + + void ScheduleAppMenuIconPaint() override { ++schedule_paint_count_; } + + protected: + // Needed for gfx::Animation and the testing profile. + content::TestBrowserThreadBundle thread_bundle_; + TestingProfile profile_; + int schedule_paint_count_; + ui::ThemeProvider* theme_provider_; + AppMenuIconPainter painter_; + + private: + DISALLOW_COPY_AND_ASSIGN(AppMenuIconPainterTest); +}; + +// Nothing to test here. Just exercise the paint code to verify that nothing +// leaks or crashes. +TEST_F(AppMenuIconPainterTest, Paint) { + gfx::Rect rect(0, 0, 29, 29); + gfx::Canvas canvas(rect.size(), 1.0f, true); + + painter_.Paint(&canvas, theme_provider_, rect, + AppMenuIconPainter::BEZEL_NONE); + painter_.Paint(&canvas, theme_provider_, rect, + AppMenuIconPainter::BEZEL_HOVER); + painter_.Paint(&canvas, theme_provider_, rect, + AppMenuIconPainter::BEZEL_PRESSED); + + painter_.SetSeverity(AppMenuIconPainter::SEVERITY_LOW, true); + painter_.Paint(&canvas, theme_provider_, rect, + AppMenuIconPainter::BEZEL_PRESSED); + painter_.SetSeverity(AppMenuIconPainter::SEVERITY_MEDIUM, true); + painter_.Paint(&canvas, theme_provider_, rect, + AppMenuIconPainter::BEZEL_PRESSED); + painter_.SetSeverity(AppMenuIconPainter::SEVERITY_HIGH, true); + painter_.Paint(&canvas, theme_provider_, rect, + AppMenuIconPainter::BEZEL_PRESSED); + + painter_.set_badge(*theme_provider_->GetImageSkiaNamed(IDR_PRODUCT_LOGO_16)); + painter_.Paint(&canvas, theme_provider_, rect, + AppMenuIconPainter::BEZEL_PRESSED); +} + +TEST_F(AppMenuIconPainterTest, PaintCallback) { + painter_.SetSeverity(AppMenuIconPainter::SEVERITY_LOW, true); + schedule_paint_count_ = 0; + painter_.AnimationProgressed(NULL); + EXPECT_EQ(1, schedule_paint_count_); +}
diff --git a/chrome/browser/ui/toolbar/wrench_menu_model_unittest.cc b/chrome/browser/ui/toolbar/app_menu_model_unittest.cc similarity index 99% rename from chrome/browser/ui/toolbar/wrench_menu_model_unittest.cc rename to chrome/browser/ui/toolbar/app_menu_model_unittest.cc index 2cdba638..80692db2 100644 --- a/chrome/browser/ui/toolbar/wrench_menu_model_unittest.cc +++ b/chrome/browser/ui/toolbar/app_menu_model_unittest.cc
@@ -171,7 +171,7 @@ EXPECT_EQ(model.enable_count_, 1); } -// Tests global error menu items in the wrench menu. +// Tests global error menu items in the app menu. TEST_F(AppMenuModelTest, GlobalError) { // Make sure services required for tests are initialized. GlobalErrorService* service =
diff --git a/chrome/browser/ui/toolbar/toolbar_actions_bar.cc b/chrome/browser/ui/toolbar/toolbar_actions_bar.cc index 1e0db3a..a7c651d 100644 --- a/chrome/browser/ui/toolbar/toolbar_actions_bar.cc +++ b/chrome/browser/ui/toolbar/toolbar_actions_bar.cc
@@ -287,7 +287,7 @@ DCHECK(!in_overflow_mode()); // We need an overflow view if either the end index is less than the number of // icons, or if a drag is in progress with the redesign turned on (since the - // user can drag an icon into the wrench menu). + // user can drag an icon into the app menu). return GetEndIndexInBounds() != toolbar_actions_.size() || (is_drag_in_progress_ && !platform_settings_.chevron_enabled); }
diff --git a/chrome/browser/ui/toolbar/toolbar_actions_bar.h b/chrome/browser/ui/toolbar/toolbar_actions_bar.h index 4b41699..b8757d6 100644 --- a/chrome/browser/ui/toolbar/toolbar_actions_bar.h +++ b/chrome/browser/ui/toolbar/toolbar_actions_bar.h
@@ -41,9 +41,9 @@ // // This can come in two flavors, main and "overflow". The main bar is visible // next to the omnibox, and the overflow bar is visible inside the chrome -// (fka wrench) menu. The main bar can have only a single row of icons with -// flexible width, whereas the overflow bar has multiple rows of icons with a -// fixed width (the width of the menu). +// app menu. The main bar can have only a single row of icons with flexible +// width, whereas the overflow bar has multiple rows of icons with a fixed +// width (the width of the menu). class ToolbarActionsBar : public ToolbarActionsModel::Observer { public: // A struct to contain the platform settings.
diff --git a/chrome/browser/ui/toolbar/wrench_icon_painter_unittest.cc b/chrome/browser/ui/toolbar/wrench_icon_painter_unittest.cc deleted file mode 100644 index 3c83f7c..0000000 --- a/chrome/browser/ui/toolbar/wrench_icon_painter_unittest.cc +++ /dev/null
@@ -1,69 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/toolbar/wrench_icon_painter.h" - -#include "chrome/browser/themes/theme_service.h" -#include "chrome/browser/themes/theme_service_factory.h" -#include "chrome/test/base/testing_profile.h" -#include "content/public/test/test_browser_thread_bundle.h" -#include "grit/theme_resources.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/geometry/rect.h" - -class WrenchIconPainterTest : public testing::Test, - public WrenchIconPainter::Delegate { - public: - WrenchIconPainterTest() : schedule_paint_count_(0), painter_(this) { - theme_provider_ = ThemeServiceFactory::GetForProfile(&profile_); - } - - void ScheduleWrenchIconPaint() override { ++schedule_paint_count_; } - - protected: - // Needed for gfx::Animation and the testing profile. - content::TestBrowserThreadBundle thread_bundle_; - TestingProfile profile_; - int schedule_paint_count_; - ui::ThemeProvider* theme_provider_; - WrenchIconPainter painter_; - - private: - DISALLOW_COPY_AND_ASSIGN(WrenchIconPainterTest); -}; - -// Nothing to test here. Just exercise the paint code to verify that nothing -// leaks or crashes. -TEST_F(WrenchIconPainterTest, Paint) { - gfx::Rect rect(0, 0, 29, 29); - gfx::Canvas canvas(rect.size(), 1.0f, true); - - painter_.Paint(&canvas, theme_provider_, rect, WrenchIconPainter::BEZEL_NONE); - painter_.Paint( - &canvas, theme_provider_, rect, WrenchIconPainter::BEZEL_HOVER); - painter_.Paint( - &canvas, theme_provider_, rect, WrenchIconPainter::BEZEL_PRESSED); - - painter_.SetSeverity(WrenchIconPainter::SEVERITY_LOW, true); - painter_.Paint( - &canvas, theme_provider_, rect, WrenchIconPainter::BEZEL_PRESSED); - painter_.SetSeverity(WrenchIconPainter::SEVERITY_MEDIUM, true); - painter_.Paint( - &canvas, theme_provider_, rect, WrenchIconPainter::BEZEL_PRESSED); - painter_.SetSeverity(WrenchIconPainter::SEVERITY_HIGH, true); - painter_.Paint( - &canvas, theme_provider_, rect, WrenchIconPainter::BEZEL_PRESSED); - - painter_.set_badge(*theme_provider_->GetImageSkiaNamed(IDR_PRODUCT_LOGO_16)); - painter_.Paint( - &canvas, theme_provider_, rect, WrenchIconPainter::BEZEL_PRESSED); -} - -TEST_F(WrenchIconPainterTest, PaintCallback) { - painter_.SetSeverity(WrenchIconPainter::SEVERITY_LOW, true); - schedule_paint_count_ = 0; - painter_.AnimationProgressed(NULL); - EXPECT_EQ(1, schedule_paint_count_); -}
diff --git a/chrome/browser/ui/views/bookmarks/bookmark_bar_view.cc b/chrome/browser/ui/views/bookmarks/bookmark_bar_view.cc index 872b500..ee8d786 100644 --- a/chrome/browser/ui/views/bookmarks/bookmark_bar_view.cc +++ b/chrome/browser/ui/views/bookmarks/bookmark_bar_view.cc
@@ -83,6 +83,7 @@ #include "ui/gfx/canvas.h" #include "ui/gfx/favicon_size.h" #include "ui/gfx/paint_vector_icon.h" +#include "ui/gfx/scoped_canvas.h" #include "ui/gfx/text_constants.h" #include "ui/gfx/text_elider.h" #include "ui/gfx/vector_icons_public.h" @@ -478,10 +479,11 @@ void OnPaint(gfx::Canvas* canvas) override { if (ui::MaterialDesignController::IsModeMaterial()) { + gfx::ScopedCanvas scoped_canvas(canvas); // 1px wide at all scale factors. If there is an uneven amount of padding // left over, place the extra pixel on the outside, i.e. away from the // "Other bookmarks" folder. - const float scale = canvas->SaveAndUnscale(); + const float scale = canvas->UndoDeviceScaleFactor(); const gfx::RectF scaled_bounds = gfx::ScaleRect(gfx::RectF(bounds()), scale); @@ -497,7 +499,6 @@ SkColorSetA(GetThemeProvider()->GetColor( ThemeProperties::COLOR_TOOLBAR_BUTTON_ICON), 0x4D)); - canvas->Restore(); } else { PaintVerticalDivider( canvas, kSeparatorStartX, height(), 1, kEdgeDividerColor,
diff --git a/chrome/browser/ui/views/bookmarks/bookmark_menu_delegate.h b/chrome/browser/ui/views/bookmarks/bookmark_menu_delegate.h index 9e4db91..d2bd95f 100644 --- a/chrome/browser/ui/views/bookmarks/bookmark_menu_delegate.h +++ b/chrome/browser/ui/views/bookmarks/bookmark_menu_delegate.h
@@ -43,7 +43,7 @@ // bookmarks in a MenuItemView. BookmarkMenuDelegate informally implements // MenuDelegate as its assumed another class is going to forward the appropriate // methods to this class. Doing so allows this class to be used for both menus -// on the bookmark bar and the bookmarks in the wrench menu. +// on the bookmark bar and the bookmarks in the app menu. class BookmarkMenuDelegate : public bookmarks::BaseBookmarkModelObserver, public BookmarkContextMenuObserver { public:
diff --git a/chrome/browser/ui/views/extensions/bookmark_override_browsertest.cc b/chrome/browser/ui/views/extensions/bookmark_override_browsertest.cc index aa3f4ae..871ff72 100644 --- a/chrome/browser/ui/views/extensions/bookmark_override_browsertest.cc +++ b/chrome/browser/ui/views/extensions/bookmark_override_browsertest.cc
@@ -65,7 +65,7 @@ EXPECT_TRUE(BookmarkBubbleView::bookmark_bubble()); } -// Test that invoking the IDC_BOOKMARK_PAGE command (as done by the wrench menu) +// Test that invoking the IDC_BOOKMARK_PAGE command (as done by the app menu) // brings up the bookmark UI, if no extension requests to override ctrl-D and // the user has assigned it to an extension. // Flaky on all platforms: https://crbug.com/448956.
diff --git a/chrome/browser/ui/views/extensions/extension_installed_bubble_view.h b/chrome/browser/ui/views/extensions/extension_installed_bubble_view.h index 6a143be..b0200bc 100644 --- a/chrome/browser/ui/views/extensions/extension_installed_bubble_view.h +++ b/chrome/browser/ui/views/extensions/extension_installed_bubble_view.h
@@ -23,8 +23,8 @@ // BROWSER_ACTION -> The browserAction icon in the toolbar. // PAGE_ACTION -> A preview of the pageAction icon in the location // bar which is shown while the Bubble is shown. -// GENERIC -> The wrench menu. This case includes pageActions that -// don't specify a default icon. +// GENERIC -> The app menu. This case includes pageActions that don't +// specify a default icon. class ExtensionInstalledBubbleView : public ExtensionInstalledBubble::ExtensionInstalledBubbleUi, public views::BubbleDelegateView {
diff --git a/chrome/browser/ui/views/frame/browser_view.cc b/chrome/browser/ui/views/frame/browser_view.cc index 0b6e909..e6665e7 100644 --- a/chrome/browser/ui/views/frame/browser_view.cc +++ b/chrome/browser/ui/views/frame/browser_view.cc
@@ -134,6 +134,7 @@ #include "ui/gfx/canvas.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/geometry/rect_conversions.h" +#include "ui/gfx/scoped_canvas.h" #include "ui/gfx/screen.h" #include "ui/strings/grit/ui_strings.h" #include "ui/views/controls/button/menu_button.h" @@ -551,13 +552,13 @@ void BrowserView::Paint1pxHorizontalLine(gfx::Canvas* canvas, SkColor color, const gfx::Rect& bounds) { - const float scale = canvas->SaveAndUnscale(); + gfx::ScopedCanvas scoped_canvas(canvas); + const float scale = canvas->UndoDeviceScaleFactor(); gfx::RectF rect(gfx::ScaleRect(gfx::RectF(bounds), scale)); rect.Inset(0, rect.height() - 1, 0, 0); SkPaint paint; paint.setColor(color); canvas->sk_canvas()->drawRect(gfx::RectFToSkRect(rect), paint); - canvas->Restore(); } void BrowserView::InitStatusBubble() {
diff --git a/chrome/browser/ui/views/location_bar/location_bar_view.cc b/chrome/browser/ui/views/location_bar/location_bar_view.cc index 53d680c..21d452b94 100644 --- a/chrome/browser/ui/views/location_bar/location_bar_view.cc +++ b/chrome/browser/ui/views/location_bar/location_bar_view.cc
@@ -1329,7 +1329,8 @@ if (ui::MaterialDesignController::IsModeMaterial()) { gfx::Canvas* canvas = recorder.canvas(); - const float scale = canvas->SaveAndUnscale(); + gfx::ScopedCanvas scoped_canvas(canvas); + const float scale = canvas->UndoDeviceScaleFactor(); SkPaint paint; paint.setStyle(SkPaint::Style::kStroke_Style); @@ -1346,7 +1347,6 @@ const SkScalar kCornerRadius = SkDoubleToScalar(2.5f * scale); canvas->sk_canvas()->drawRoundRect(gfx::RectFToSkRect(border_rect_f), kCornerRadius, kCornerRadius, paint); - recorder.canvas()->Restore(); } else { views::Painter::PaintPainterAt(recorder.canvas(), border_painter_.get(), border_rect);
diff --git a/chrome/browser/ui/views/sync/one_click_signin_bubble_view.h b/chrome/browser/ui/views/sync/one_click_signin_bubble_view.h index e22d014..5f8b619 100644 --- a/chrome/browser/ui/views/sync/one_click_signin_bubble_view.h +++ b/chrome/browser/ui/views/sync/one_click_signin_bubble_view.h
@@ -88,10 +88,10 @@ void WindowClosing() override; ui::ModalType GetModalType() const override; - // Builds a popup bubble anchored under the wrench menu + // Builds a popup bubble anchored under the app menu. void InitBubbleContent(views::GridLayout* layout); - // Builds a modal dialog aligned center top + // Builds a modal dialog aligned center top. void InitDialogContent(views::GridLayout* layout); // Initializes the OK/Undo buttons to be used at the bottom of the bubble.
diff --git a/chrome/browser/ui/views/toolbar/app_menu_button.cc b/chrome/browser/ui/views/toolbar/app_menu_button.cc index 2595631..fe81877 100644 --- a/chrome/browser/ui/views/toolbar/app_menu_button.cc +++ b/chrome/browser/ui/views/toolbar/app_menu_button.cc
@@ -36,7 +36,7 @@ AppMenuButton::AppMenuButton(ToolbarView* toolbar_view) : views::MenuButton(NULL, base::string16(), toolbar_view, false), - severity_(WrenchIconPainter::SEVERITY_NONE), + severity_(AppMenuIconPainter::SEVERITY_NONE), ink_drop_animation_controller_( views::InkDropAnimationControllerFactory:: CreateInkDropAnimationController(this)), @@ -47,7 +47,7 @@ destroyed_(nullptr), weak_factory_(this) { if (!ui::MaterialDesignController::IsModeMaterial()) - wrench_icon_painter_.reset(new WrenchIconPainter(this)); + icon_painter_.reset(new AppMenuIconPainter(this)); const int kInkDropLargeSize = 32; const int kInkDropLargeCornerRadius = 5; @@ -66,7 +66,7 @@ *destroyed_ = true; } -void AppMenuButton::SetSeverity(WrenchIconPainter::Severity severity, +void AppMenuButton::SetSeverity(AppMenuIconPainter::Severity severity, bool animate) { if (ui::MaterialDesignController::IsModeMaterial()) { severity_ = severity; @@ -74,7 +74,7 @@ return; } - wrench_icon_painter_->SetSeverity(severity, animate); + icon_painter_->SetSeverity(severity, animate); SchedulePaint(); } @@ -151,7 +151,7 @@ GetImageSkiaNamed(IDR_TOOLBAR_BEZEL_HOVER)->size(); } -void AppMenuButton::ScheduleWrenchIconPaint() { +void AppMenuButton::ScheduleAppMenuIconPaint() { SchedulePaint(); } @@ -159,17 +159,17 @@ DCHECK(ui::MaterialDesignController::IsModeMaterial()); SkColor color = SK_ColorRED; switch (severity_) { - case WrenchIconPainter::SEVERITY_NONE: + case AppMenuIconPainter::SEVERITY_NONE: color = GetThemeProvider()->GetColor( ThemeProperties::COLOR_TOOLBAR_BUTTON_ICON); break; - case WrenchIconPainter::SEVERITY_LOW: + case AppMenuIconPainter::SEVERITY_LOW: color = gfx::kGoogleGreen700; break; - case WrenchIconPainter::SEVERITY_MEDIUM: + case AppMenuIconPainter::SEVERITY_MEDIUM: color = gfx::kGoogleYellow700; break; - case WrenchIconPainter::SEVERITY_HIGH: + case AppMenuIconPainter::SEVERITY_HIGH: color = gfx::kGoogleRed700; break; } @@ -265,8 +265,6 @@ views::MenuButton::OnPaint(canvas); if (ui::MaterialDesignController::IsModeMaterial()) return; - wrench_icon_painter_->Paint(canvas, - GetThemeProvider(), - gfx::Rect(size()), - WrenchIconPainter::BEZEL_NONE); + icon_painter_->Paint(canvas, GetThemeProvider(), gfx::Rect(size()), + AppMenuIconPainter::BEZEL_NONE); }
diff --git a/chrome/browser/ui/views/toolbar/app_menu_button.h b/chrome/browser/ui/views/toolbar/app_menu_button.h index 5c41fd5..13fb2fa 100644 --- a/chrome/browser/ui/views/toolbar/app_menu_button.h +++ b/chrome/browser/ui/views/toolbar/app_menu_button.h
@@ -8,7 +8,7 @@ #include "base/macros.h" #include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" -#include "chrome/browser/ui/toolbar/wrench_icon_painter.h" +#include "chrome/browser/ui/toolbar/app_menu_icon_painter.h" #include "ui/views/animation/ink_drop_host.h" #include "ui/views/controls/button/menu_button.h" #include "ui/views/controls/button/menu_button_listener.h" @@ -27,12 +27,12 @@ class AppMenuButton : public views::InkDropHost, public views::MenuButton, - public WrenchIconPainter::Delegate { + public AppMenuIconPainter::Delegate { public: explicit AppMenuButton(ToolbarView* toolbar_view); ~AppMenuButton() override; - void SetSeverity(WrenchIconPainter::Severity severity, bool animate); + void SetSeverity(AppMenuIconPainter::Severity severity, bool animate); // Shows the app menu. |for_drop| indicates whether the menu is opened for a // drag-and-drop operation. @@ -55,8 +55,8 @@ // views::MenuButton: gfx::Size GetPreferredSize() const override; - // WrenchIconPainter::Delegate: - void ScheduleWrenchIconPaint() override; + // AppMenuIconPainter::Delegate: + void ScheduleAppMenuIconPaint() override; // Updates the presentation according to |severity_| and the theme provider. // Only used in MD. @@ -86,10 +86,10 @@ void OnPaint(gfx::Canvas* canvas) override; // Only used in pre-MD. - scoped_ptr<WrenchIconPainter> wrench_icon_painter_; + scoped_ptr<AppMenuIconPainter> icon_painter_; // Only used in MD. - WrenchIconPainter::Severity severity_; + AppMenuIconPainter::Severity severity_; // Animation controller for the ink drop ripple effect. scoped_ptr<views::InkDropAnimationController> ink_drop_animation_controller_;
diff --git a/chrome/browser/ui/views/toolbar/browser_actions_container.h b/chrome/browser/ui/views/toolbar/browser_actions_container.h index beaa1ab1..97ca4ee8 100644 --- a/chrome/browser/ui/views/toolbar/browser_actions_container.h +++ b/chrome/browser/ui/views/toolbar/browser_actions_container.h
@@ -63,7 +63,7 @@ // - The container is set to a width smaller than needed to show all icons. // - There is no other container in 'overflow' mode to handle the // non-visible icons for this container. -// s: ToolbarView::kStandardSpacing pixels of empty space (before the wrench +// s: ToolbarView::kStandardSpacing pixels of empty space (before the app // menu). // The reason the container contains the trailing space "s", rather than having // it be handled by the parent view, is so that when the chevron is invisible
diff --git a/chrome/browser/ui/views/toolbar/browser_actions_container_browsertest.cc b/chrome/browser/ui/views/toolbar/browser_actions_container_browsertest.cc index e449930..ab0e141 100644 --- a/chrome/browser/ui/views/toolbar/browser_actions_container_browsertest.cc +++ b/chrome/browser/ui/views/toolbar/browser_actions_container_browsertest.cc
@@ -272,7 +272,7 @@ scoped_ptr<views::View> overflow_parent_; // The overflow BrowserActionsContainer. We manufacture this so that we don't - // have to open the wrench menu. + // have to open the app menu. // Owned by the |overflow_parent_|. BrowserActionsContainer* overflow_bar_;
diff --git a/chrome/browser/ui/views/toolbar/toolbar_view.cc b/chrome/browser/ui/views/toolbar/toolbar_view.cc index 65502fc..106a799 100644 --- a/chrome/browser/ui/views/toolbar/toolbar_view.cc +++ b/chrome/browser/ui/views/toolbar/toolbar_view.cc
@@ -703,8 +703,8 @@ } void ToolbarView::UpdateBadgeSeverity(AppMenuBadgeController::BadgeType type, - WrenchIconPainter::Severity severity, - bool animate) { + AppMenuIconPainter::Severity severity, + bool animate) { // Showing the bubble requires |app_menu_button_| to be in a widget. See // comment in ConflictingModuleView for details. DCHECK(app_menu_button_->GetWidget());
diff --git a/chrome/browser/ui/views/toolbar/toolbar_view.h b/chrome/browser/ui/views/toolbar/toolbar_view.h index 62c67b3..08c3f99 100644 --- a/chrome/browser/ui/views/toolbar/toolbar_view.h +++ b/chrome/browser/ui/views/toolbar/toolbar_view.h
@@ -182,7 +182,7 @@ // AppMenuBadgeController::Delegate: void UpdateBadgeSeverity(AppMenuBadgeController::BadgeType type, - WrenchIconPainter::Severity severity, + AppMenuIconPainter::Severity severity, bool animate) override; // Returns the number of pixels above the location bar in non-normal display.
diff --git a/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc b/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc index bf2598e..1aa96e0 100644 --- a/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc +++ b/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc
@@ -436,35 +436,27 @@ UpdateState(error_reason); } -AccountId GaiaScreenHandler::GetAccountId( +std::string GaiaScreenHandler::GetCanonicalEmail( const std::string& authenticated_email, const std::string& gaia_id) const { + const std::string sanitized_email = gaia::SanitizeEmail(authenticated_email); + const std::string canonicalized_email = - gaia::CanonicalizeEmail(gaia::SanitizeEmail(authenticated_email)); - const AccountId authenticated_account_id( - AccountId::FromUserEmailGaiaId(canonicalized_email, gaia_id)); - - // If we don't have UserManager instance (i.e. we are in unit test), - // or a known user has authenticated, just log in. + gaia::CanonicalizeEmail(sanitized_email); user_manager::UserManager* user_manager = user_manager::UserManager::Get(); - if (!user_manager || user_manager->IsKnownUser(authenticated_account_id)) - return authenticated_account_id; - - // If [part of] user id has changed, update stored data and connect user - // to existing home directory. - AccountId old_account_id(EmptyAccountId()); - if (!user_manager->GetKnownUserAccountId(authenticated_account_id, - &old_account_id)) { - return authenticated_account_id; + if (user_manager && !user_manager->IsKnownUser(canonicalized_email)) { + std::string old_canonical_email; + if (user_manager->GetKnownUserCanonicalEmail(gaia_id, + &old_canonical_email)) { + if (old_canonical_email != canonicalized_email) { + LOG(WARNING) << "Existing user '" << old_canonical_email + << "' authenticated by alias '" << sanitized_email << "'."; + return old_canonical_email; + } + } } - - if (old_account_id.GetUserEmail() != canonicalized_email) { - LOG(WARNING) << "Existing user '" << old_account_id.GetUserEmail() - << "' authenticated by alias '" << canonicalized_email << "'."; - return old_account_id; - } - - return authenticated_account_id; + // For compatibility reasons, sanitized email is used. + return sanitized_email; } void GaiaScreenHandler::HandleCompleteAuthentication( @@ -482,7 +474,8 @@ const std::string sanitized_email = gaia::SanitizeEmail(email); Delegate()->SetDisplayEmail(sanitized_email); - UserContext user_context(GetAccountId(email, gaia_id)); + const std::string canonical_email = GetCanonicalEmail(email, gaia_id); + UserContext user_context(canonical_email); user_context.SetGaiaID(gaia_id); user_context.SetKey(Key(password)); user_context.SetAuthCode(auth_code); @@ -515,7 +508,7 @@ // Consumer management enrollment is in progress. const std::string owner_email = - user_manager::UserManager::Get()->GetOwnerAccountId().GetUserEmail(); + user_manager::UserManager::Get()->GetOwnerEmail(); if (typed_email != owner_email) { // Show Gaia sign-in screen again, since we only allow the owner to sign // in. @@ -602,7 +595,8 @@ DCHECK(!gaia_id.empty()); const std::string sanitized_email = gaia::SanitizeEmail(typed_email); Delegate()->SetDisplayEmail(sanitized_email); - UserContext user_context(GetAccountId(typed_email, gaia_id)); + const std::string canonical_email = GetCanonicalEmail(typed_email, gaia_id); + UserContext user_context(canonical_email); user_context.SetGaiaID(gaia_id); user_context.SetKey(Key(password)); user_context.SetAuthFlow(using_saml @@ -761,7 +755,7 @@ std::vector<std::string> input_methods = imm->GetInputMethodUtil()->GetHardwareLoginInputMethodIds(); const std::string owner_im = SigninScreenHandler::GetUserLRUInputMethod( - user_manager::UserManager::Get()->GetOwnerAccountId().GetUserEmail()); + user_manager::UserManager::Get()->GetOwnerEmail()); const std::string system_im = g_browser_process->local_state()->GetString( language_prefs::kPreferredKeyboardLayout); @@ -845,8 +839,7 @@ context.is_enrolling_consumer_management = is_enrolling_consumer_management_; std::string gaia_id; - if (user_manager::UserManager::Get()->FindGaiaID( - AccountId::FromUserEmail(context.email), &gaia_id)) + if (user_manager::UserManager::Get()->FindGaiaID(context.email, &gaia_id)) context.gaia_id = gaia_id; if (Delegate()) { @@ -856,7 +849,7 @@ if (!context.email.empty()) { context.gaps_cookie = user_manager::UserManager::Get()->GetKnownUserGAPSCookie( - AccountId::FromUserEmail(gaia::CanonicalizeEmail(context.email))); + gaia::CanonicalizeEmail(context.email)); } populated_email_.clear();
diff --git a/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.h b/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.h index d37fa1a..250d74c 100644 --- a/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.h +++ b/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.h
@@ -17,8 +17,6 @@ #include "chromeos/network/portal_detector/network_portal_detector.h" #include "net/base/net_errors.h" -class AccountId; - namespace policy { class ConsumerManagementService; } @@ -217,8 +215,8 @@ // Returns user canonical e-mail. Finds already used account alias, if // user has already signed in. - AccountId GetAccountId(const std::string& authenticated_email, - const std::string& gaia_id) const; + std::string GetCanonicalEmail(const std::string& authenticated_email, + const std::string& gaia_id) const; // Returns current visible screen. // TODO(jdufault): This definition exists in multiple locations. Refactor it
diff --git a/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc b/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc index 3e4f6e6..47f0628 100644 --- a/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc +++ b/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc
@@ -992,8 +992,7 @@ const std::string& password) { if (!delegate_) return; - UserContext user_context( - AccountId::FromUserEmail(gaia::SanitizeEmail(username))); + UserContext user_context(gaia::SanitizeEmail(username)); user_context.SetKey(Key(password)); delegate_->Login(user_context, SigninSpecifics()); } @@ -1073,7 +1072,7 @@ args->GetString(0, &email); gaia_screen_handler_->set_populated_email(email); if (!email.empty()) - SendReauthReason(AccountId::FromUserEmail(email)); + SendReauthReason(email); OnShowAddUser(); } @@ -1176,8 +1175,7 @@ void SigninScreenHandler::HandleCancelPasswordChangedFlow( const std::string& user_id) { if (!user_id.empty()) - RecordReauthReason(AccountId::FromUserEmail(user_id), - ReauthReason::PASSWORD_UPDATE_SKIPPED); + RecordReauthReason(user_id, ReauthReason::PASSWORD_UPDATE_SKIPPED); gaia_screen_handler_->StartClearingCookies( base::Bind(&SigninScreenHandler::CancelPasswordChangedFlowInternal, weak_factory_.GetWeakPtr())); @@ -1250,8 +1248,7 @@ bool use_24hour_clock = false; if (user_manager::UserManager::Get()->GetKnownUserBooleanPref( - AccountId::FromUserEmail(user_id), prefs::kUse24HourClock, - &use_24hour_clock)) { + user_id, prefs::kUse24HourClock, &use_24hour_clock)) { g_browser_process->platform_part() ->GetSystemClock() ->SetLastFocusedPodHourClockType(use_24hour_clock ? base::k24HourClock @@ -1323,8 +1320,7 @@ void SigninScreenHandler::HandleMaxIncorrectPasswordAttempts( const std::string& email) { - RecordReauthReason(AccountId::FromUserEmail(email), - ReauthReason::INCORRECT_PASSWORD_ENTERED); + RecordReauthReason(email, ReauthReason::INCORRECT_PASSWORD_ENTERED); } bool SigninScreenHandler::AllWhitelistedUsersPresent() { @@ -1345,8 +1341,7 @@ std::string whitelisted_user; // NB: Wildcards in the whitelist are also detected as not present here. if (!whitelist->GetString(i, &whitelisted_user) || - !user_manager->IsKnownUser( - AccountId::FromUserEmail(whitelisted_user))) { + !user_manager->IsKnownUser(whitelisted_user)) { return false; } }
diff --git a/chrome/browser/ui/webui/chromeos/login/signin_userlist_unittest.cc b/chrome/browser/ui/webui/chromeos/login/signin_userlist_unittest.cc index 952afcd..ed1d6f3 100644 --- a/chrome/browser/ui/webui/chromeos/login/signin_userlist_unittest.cc +++ b/chrome/browser/ui/webui/chromeos/login/signin_userlist_unittest.cc
@@ -49,13 +49,12 @@ fake_user_manager_->set_multi_profile_user_controller(controller_.get()); for (size_t i = 0; i < arraysize(kUsersPublic); ++i) - fake_user_manager_->AddPublicAccountUser( - AccountId::FromUserEmail(kUsersPublic[i])); + fake_user_manager_->AddPublicAccountUser(kUsersPublic[i]); for (size_t i = 0; i < arraysize(kUsers); ++i) - fake_user_manager_->AddUser(AccountId::FromUserEmail(kUsers[i])); + fake_user_manager_->AddUser(kUsers[i]); - fake_user_manager_->set_owner_id(AccountId::FromUserEmail(kOwner)); + fake_user_manager_->set_owner_email(kOwner); } void TearDown() override { @@ -85,10 +84,8 @@ EXPECT_EQ(kMaxUsers, users_to_send.size()); EXPECT_EQ(kOwner, users_to_send.back()->email()); - fake_user_manager_->RemoveUserFromList( - AccountId::FromUserEmail("a16@gmail.com")); - fake_user_manager_->RemoveUserFromList( - AccountId::FromUserEmail("a17@gmail.com")); + fake_user_manager_->RemoveUserFromList("a16@gmail.com"); + fake_user_manager_->RemoveUserFromList("a17@gmail.com"); users_to_send = UserSelectionScreen::PrepareUserListForSending( fake_user_manager_->GetUsers(), kOwner,
diff --git a/chrome/browser/ui/webui/chromeos/ui_account_tweaks.cc b/chrome/browser/ui/webui/chromeos/ui_account_tweaks.cc index 85a7c7cf1..3e1727b7 100644 --- a/chrome/browser/ui/webui/chromeos/ui_account_tweaks.cc +++ b/chrome/browser/ui/webui/chromeos/ui_account_tweaks.cc
@@ -23,8 +23,7 @@ CrosSettings::Get()->GetString(kDeviceOwner, &owner_email); // Translate owner's email to the display email. std::string display_email = - user_manager::UserManager::Get()->GetUserDisplayEmail( - AccountId::FromUserEmail(owner_email)); + user_manager::UserManager::Get()->GetUserDisplayEmail(owner_email); localized_strings->SetString("ownerUserId", display_email); localized_strings->SetBoolean("currentUserIsOwner",
diff --git a/chrome/browser/ui/webui/options/chromeos/accounts_options_browsertest.cc b/chrome/browser/ui/webui/options/chromeos/accounts_options_browsertest.cc index 3dcb20f..33c6c55 100644 --- a/chrome/browser/ui/webui/options/chromeos/accounts_options_browsertest.cc +++ b/chrome/browser/ui/webui/options/chromeos/accounts_options_browsertest.cc
@@ -37,9 +37,6 @@ : LoginManagerTest(false), device_settings_provider_(NULL) { stub_settings_provider_.Set(kDeviceOwner, base::StringValue(kTestUsers[0])); - for (size_t i = 0; i < arraysize(kTestUsers); ++i) { - test_users_.push_back(AccountId::FromUserEmail(kTestUsers[i])); - } } ~AccountsOptionsTest() override {} @@ -120,29 +117,28 @@ StubCrosSettingsProvider stub_settings_provider_; CrosSettingsProvider* device_settings_provider_; - std::vector<AccountId> test_users_; private: DISALLOW_COPY_AND_ASSIGN(AccountsOptionsTest); }; IN_PROC_BROWSER_TEST_F(AccountsOptionsTest, PRE_MultiProfilesAccountsOptions) { - RegisterUser(test_users_[0].GetUserEmail()); - RegisterUser(test_users_[1].GetUserEmail()); + RegisterUser(kTestUsers[0]); + RegisterUser(kTestUsers[1]); StartupUtils::MarkOobeCompleted(); } IN_PROC_BROWSER_TEST_F(AccountsOptionsTest, MultiProfilesAccountsOptions) { - LoginUser(test_users_[0].GetUserEmail()); + LoginUser(kTestUsers[0]); UserAddingScreen::Get()->Start(); content::RunAllPendingInMessageLoop(); - AddUser(test_users_[1].GetUserEmail()); + AddUser(kTestUsers[1]); user_manager::UserManager* manager = user_manager::UserManager::Get(); ASSERT_EQ(2u, manager->GetLoggedInUsers().size()); - CheckAccountsUI(manager->FindUser(test_users_[0]), true /* is_owner */); - CheckAccountsUI(manager->FindUser(test_users_[1]), false /* is_owner */); + CheckAccountsUI(manager->FindUser(kTestUsers[0]), true /* is_owner */); + CheckAccountsUI(manager->FindUser(kTestUsers[1]), false /* is_owner */); } } // namespace chromeos
diff --git a/chrome/browser/ui/webui/options/chromeos/accounts_options_handler.cc b/chrome/browser/ui/webui/options/chromeos/accounts_options_handler.cc index ada7049..40b639d 100644 --- a/chrome/browser/ui/webui/options/chromeos/accounts_options_handler.cc +++ b/chrome/browser/ui/webui/options/chromeos/accounts_options_handler.cc
@@ -129,8 +129,7 @@ OwnerSettingsServiceChromeOS::FromWebUI(web_ui())) { service->RemoveFromList(kAccountsPrefUsers, canonical_email); } - user_manager::UserManager::Get()->RemoveUser(AccountId::FromUserEmail(email), - nullptr); + user_manager::UserManager::Get()->RemoveUser(email, NULL); } void AccountsOptionsHandler::HandleUpdateWhitelist(
diff --git a/chrome/browser/ui/webui/options/chromeos/change_picture_options_handler.cc b/chrome/browser/ui/webui/options/chromeos/change_picture_options_handler.cc index 1ceeaa7..b6de55d1 100644 --- a/chrome/browser/ui/webui/options/chromeos/change_picture_options_handler.cc +++ b/chrome/browser/ui/webui/options/chromeos/change_picture_options_handler.cc
@@ -305,7 +305,7 @@ void ChangePictureOptionsHandler::UpdateProfileImage() { UserImageManager* user_image_manager = - ChromeUserManager::Get()->GetUserImageManager(GetUser()->GetAccountId()); + ChromeUserManager::Get()->GetUserImageManager(GetUser()->email()); // If we have a downloaded profile image and haven't sent it in // |SendSelectedImage|, send it now (without selecting). if (previous_image_index_ != user_manager::User::USER_IMAGE_PROFILE && @@ -336,7 +336,7 @@ DCHECK(!image_type.empty()); UserImageManager* user_image_manager = - ChromeUserManager::Get()->GetUserImageManager(GetUser()->GetAccountId()); + ChromeUserManager::Get()->GetUserImageManager(GetUser()->email()); int image_index = user_manager::User::USER_IMAGE_INVALID; bool waiting_for_camera_photo = false; @@ -396,7 +396,7 @@ int index, void* params) { ChromeUserManager::Get() - ->GetUserImageManager(GetUser()->GetAccountId()) + ->GetUserImageManager(GetUser()->email()) ->SaveUserImageFromFile(path); UMA_HISTOGRAM_ENUMERATION("UserImage.ChangeChoice", user_manager::kHistogramImageFromFile, @@ -407,7 +407,7 @@ void ChangePictureOptionsHandler::SetImageFromCamera( const gfx::ImageSkia& photo) { ChromeUserManager::Get() - ->GetUserImageManager(GetUser()->GetAccountId()) + ->GetUserImageManager(GetUser()->email()) ->SaveUserImage(user_manager::UserImage::CreateAndEncode(photo)); UMA_HISTOGRAM_ENUMERATION("UserImage.ChangeChoice", user_manager::kHistogramImageFromCamera,
diff --git a/chrome/browser/ui/webui/options/chromeos/core_chromeos_options_handler.cc b/chrome/browser/ui/webui/options/chromeos/core_chromeos_options_handler.cc index daed4a8..91f53821 100644 --- a/chrome/browser/ui/webui/options/chromeos/core_chromeos_options_handler.cc +++ b/chrome/browser/ui/webui/options/chromeos/core_chromeos_options_handler.cc
@@ -71,9 +71,7 @@ user_dict->SetString("name", display_email); user_dict->SetString("email", display_name); - const bool is_owner = - user_manager::UserManager::Get()->GetOwnerAccountId().GetUserEmail() == - username; + bool is_owner = user_manager::UserManager::Get()->GetOwnerEmail() == username; user_dict->SetBoolean("owner", is_owner); return user_dict; } @@ -91,8 +89,7 @@ std::string email; if ((*i)->GetAsString(&email)) { // Translate email to the display email. - const std::string display_email = - user_manager->GetUserDisplayEmail(AccountId::FromUserEmail(email)); + std::string display_email = user_manager->GetUserDisplayEmail(email); // TODO(ivankr): fetch display name for existing users. user_list->Append(CreateUserInfo(email, display_email, std::string())); } @@ -364,12 +361,10 @@ // Managed machines have no "owner". localized_strings->SetString("controlledSettingOwner", base::string16()); } else { - localized_strings->SetString( - "controlledSettingOwner", + localized_strings->SetString("controlledSettingOwner", l10n_util::GetStringFUTF16( IDS_OPTIONS_CONTROLLED_SETTING_OWNER, - base::ASCIIToUTF16( - user_manager->GetOwnerAccountId().GetUserEmail()))); + base::ASCIIToUTF16(user_manager->GetOwnerEmail()))); } }
diff --git a/chrome/browser/ui/webui/options/chromeos/shared_options_browsertest.cc b/chrome/browser/ui/webui/options/chromeos/shared_options_browsertest.cc index 1055a8d..9ec75fe5 100644 --- a/chrome/browser/ui/webui/options/chromeos/shared_options_browsertest.cc +++ b/chrome/browser/ui/webui/options/chromeos/shared_options_browsertest.cc
@@ -86,10 +86,8 @@ class SharedOptionsTest : public LoginManagerTest { public: SharedOptionsTest() - : LoginManagerTest(false), - device_settings_provider_(NULL), - test_owner_account_id_(AccountId::FromUserEmail(kTestOwner)), - test_non_owner_account_id_(AccountId::FromUserEmail(kTestNonOwner)) { + : LoginManagerTest(false), + device_settings_provider_(NULL) { stub_settings_provider_.Set(kDeviceOwner, base::StringValue(kTestOwner)); } @@ -268,43 +266,40 @@ StubAccountSettingsProvider stub_settings_provider_; CrosSettingsProvider* device_settings_provider_; - const AccountId test_owner_account_id_; - const AccountId test_non_owner_account_id_; - private: DISALLOW_COPY_AND_ASSIGN(SharedOptionsTest); }; IN_PROC_BROWSER_TEST_F(SharedOptionsTest, PRE_SharedOptions) { - RegisterUser(test_owner_account_id_.GetUserEmail()); - RegisterUser(test_non_owner_account_id_.GetUserEmail()); + RegisterUser(kTestOwner); + RegisterUser(kTestNonOwner); StartupUtils::MarkOobeCompleted(); } IN_PROC_BROWSER_TEST_F(SharedOptionsTest, SharedOptions) { // Log in the owner first, then add a secondary user. - LoginUser(test_owner_account_id_.GetUserEmail()); + LoginUser(kTestOwner); UserAddingScreen::Get()->Start(); content::RunAllPendingInMessageLoop(); - AddUser(test_non_owner_account_id_.GetUserEmail()); + AddUser(kTestNonOwner); user_manager::UserManager* manager = user_manager::UserManager::Get(); ASSERT_EQ(2u, manager->GetLoggedInUsers().size()); { SCOPED_TRACE("Checking settings for owner, primary user."); - CheckOptionsUI(manager->FindUser(manager->GetOwnerAccountId()), true, true); + CheckOptionsUI(manager->FindUser(manager->GetOwnerEmail()), true, true); } { SCOPED_TRACE("Checking settings for non-owner, secondary user."); - CheckOptionsUI(manager->FindUser(test_non_owner_account_id_), false, false); + CheckOptionsUI(manager->FindUser(kTestNonOwner), false, false); } // TODO(michaelpg): Add tests for non-primary owner and primary non-owner // when the owner-only multiprofile restriction is removed, probably M38. } IN_PROC_BROWSER_TEST_F(SharedOptionsTest, PRE_ScreenLockPreferencePrimary) { - RegisterUser(test_owner_account_id_.GetUserEmail()); - RegisterUser(test_non_owner_account_id_.GetUserEmail()); + RegisterUser(kTestOwner); + RegisterUser(kTestNonOwner); StartupUtils::MarkOobeCompleted(); } @@ -314,15 +309,14 @@ // other signed-in user has enabled this preference, the shared setting // indicator explains this.) IN_PROC_BROWSER_TEST_F(SharedOptionsTest, ScreenLockPreferencePrimary) { - LoginUser(test_owner_account_id_.GetUserEmail()); + LoginUser(kTestOwner); UserAddingScreen::Get()->Start(); content::RunAllPendingInMessageLoop(); - AddUser(test_non_owner_account_id_.GetUserEmail()); + AddUser(kTestNonOwner); user_manager::UserManager* manager = user_manager::UserManager::Get(); - const user_manager::User* user1 = manager->FindUser(test_owner_account_id_); - const user_manager::User* user2 = - manager->FindUser(test_non_owner_account_id_); + const user_manager::User* user1 = manager->FindUser(kTestOwner); + const user_manager::User* user2 = manager->FindUser(kTestNonOwner); PrefService* prefs1 = ProfileHelper::Get()->GetProfileByUserUnsafe(user1)->GetPrefs(); @@ -375,8 +369,8 @@ } IN_PROC_BROWSER_TEST_F(SharedOptionsTest, PRE_ScreenLockPreferenceSecondary) { - RegisterUser(test_owner_account_id_.GetUserEmail()); - RegisterUser(test_non_owner_account_id_.GetUserEmail()); + RegisterUser(kTestOwner); + RegisterUser(kTestNonOwner); StartupUtils::MarkOobeCompleted(); } @@ -386,15 +380,14 @@ // other signed-in user has enabled this preference, the shared setting // indicator explains this.) IN_PROC_BROWSER_TEST_F(SharedOptionsTest, ScreenLockPreferenceSecondary) { - LoginUser(test_owner_account_id_.GetUserEmail()); + LoginUser(kTestOwner); UserAddingScreen::Get()->Start(); content::RunAllPendingInMessageLoop(); - AddUser(test_non_owner_account_id_.GetUserEmail()); + AddUser(kTestNonOwner); user_manager::UserManager* manager = user_manager::UserManager::Get(); - const user_manager::User* user1 = manager->FindUser(test_owner_account_id_); - const user_manager::User* user2 = - manager->FindUser(test_non_owner_account_id_); + const user_manager::User* user1 = manager->FindUser(kTestOwner); + const user_manager::User* user2 = manager->FindUser(kTestNonOwner); PrefService* prefs1 = ProfileHelper::Get()->GetProfileByUserUnsafe(user1)->GetPrefs();
diff --git a/chrome/browser/ui/webui/options/chromeos/user_image_source.cc b/chrome/browser/ui/webui/options/chromeos/user_image_source.cc index 46572be..71a03b7 100644 --- a/chrome/browser/ui/webui/options/chromeos/user_image_source.cc +++ b/chrome/browser/ui/webui/options/chromeos/user_image_source.cc
@@ -8,7 +8,6 @@ #include "base/message_loop/message_loop.h" #include "base/strings/string_split.h" #include "chrome/common/url_constants.h" -#include "components/signin/core/account_id/account_id.h" #include "components/user_manager/user_image/default_user_images.h" #include "components/user_manager/user_manager.h" #include "grit/theme_resources.h" @@ -38,10 +37,10 @@ // Static. base::RefCountedMemory* UserImageSource::GetUserImage( - const AccountId& account_id, + const std::string& email, ui::ScaleFactor scale_factor) { const user_manager::User* user = - user_manager::UserManager::Get()->FindUser(account_id); + user_manager::UserManager::Get()->FindUser(email); if (user) { if (user->has_raw_image()) { return new base::RefCountedBytes(user->raw_image()); @@ -79,8 +78,7 @@ std::string email; GURL url(chrome::kChromeUIUserImageURL + path); ParseRequest(url, &email); - const AccountId account_id(AccountId::FromUserEmail(email)); - callback.Run(GetUserImage(account_id, ui::SCALE_FACTOR_100P)); + callback.Run(GetUserImage(email, ui::SCALE_FACTOR_100P)); } std::string UserImageSource::GetMimeType(const std::string& path) const {
diff --git a/chrome/browser/ui/webui/options/chromeos/user_image_source.h b/chrome/browser/ui/webui/options/chromeos/user_image_source.h index 87ffa12..ad11d6a 100644 --- a/chrome/browser/ui/webui/options/chromeos/user_image_source.h +++ b/chrome/browser/ui/webui/options/chromeos/user_image_source.h
@@ -13,8 +13,6 @@ #include "content/public/browser/url_data_source.h" #include "ui/base/layout.h" -class AccountId; - namespace base { class RefCountedMemory; } @@ -37,9 +35,9 @@ const content::URLDataSource::GotDataCallback& callback) override; std::string GetMimeType(const std::string& path) const override; - // Returns PNG encoded image for user with specified |account_id|. If there's - // no user with such an id, returns the first default image. - static base::RefCountedMemory* GetUserImage(const AccountId& account_id, + // Returns PNG encoded image for user with specified email. If there's + // no user with such email, returns the first default image. + static base::RefCountedMemory* GetUserImage(const std::string& email, ui::ScaleFactor scale_factor); private:
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 e7a9e67..a3b4ffc 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
@@ -38,6 +38,7 @@ html_source->AddLocalizedString("advancedPageTitle", IDS_SETTINGS_ADVANCED); html_source->AddLocalizedString("addLabel", IDS_ADD); html_source->AddLocalizedString("learnMore", IDS_LEARN_MORE); + html_source->AddLocalizedString("cancel", IDS_CANCEL); } #if defined(OS_CHROMEOS) @@ -224,6 +225,22 @@ "promptForDownload", IDS_SETTINGS_PROMPT_FOR_DOWNLOAD); } +void AddResetStrings(content::WebUIDataSource* html_source) { + html_source->AddLocalizedString( + "resetPageTitle", IDS_RESET_PROFILE_SETTINGS_SECTION_TITLE); + html_source->AddLocalizedString( + "resetPageDescription", IDS_RESET_PROFILE_SETTINGS_DESCRIPTION); + html_source->AddLocalizedString( + "resetPageExplanation", IDS_RESET_PROFILE_SETTINGS_EXPLANATION); + html_source->AddLocalizedString( + "resetPageCommit", IDS_RESET_PROFILE_SETTINGS_COMMIT_BUTTON); + html_source->AddLocalizedString( + "resetPageFeedback", IDS_RESET_PROFILE_SETTINGS_FEEDBACK); + html_source->AddString( + "resetPageLearnMoreUrl", + chrome::kResetProfileSettingsLearnMoreURL); +} + void AddDateTimeStrings(content::WebUIDataSource* html_source) { html_source->AddLocalizedString( "dateTimePageTitle", IDS_SETTINGS_DATE_TIME); @@ -528,6 +545,8 @@ IDS_SETTINGS_ENCRYPT_WITH_SYNC_PASSPHRASE_LEARN_MORE_LINK); html_source->AddLocalizedString("useDefaultSettingsButton", IDS_SETTINGS_USE_DEFAULT_SETTINGS_BUTTON); + // TODO(dpapad): Remove this string and use IDS_CANCEL (see AddCommonStrings + // at the top of this file). html_source->AddLocalizedString("cancelButton", IDS_SETTINGS_CANCEL_BUTTON); html_source->AddLocalizedString("okButton", @@ -628,6 +647,7 @@ #endif AddOnStartupStrings(html_source); AddPrivacyStrings(html_source); + AddResetStrings(html_source); AddSearchEnginesStrings(html_source); AddSearchStrings(html_source); #if !defined(OS_CHROMEOS)
diff --git a/chrome/browser/ui/webui/settings/md_settings_ui.cc b/chrome/browser/ui/webui/settings/md_settings_ui.cc index 909afe7c..39caf0a 100644 --- a/chrome/browser/ui/webui/settings/md_settings_ui.cc +++ b/chrome/browser/ui/webui/settings/md_settings_ui.cc
@@ -7,7 +7,6 @@ #include <string> #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/webui/options/sync_setup_handler.h" #include "chrome/browser/ui/webui/settings/appearance_handler.h" #include "chrome/browser/ui/webui/settings/downloads_handler.h" #include "chrome/browser/ui/webui/settings/font_handler.h" @@ -16,6 +15,7 @@ #include "chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.h" #include "chrome/browser/ui/webui/settings/settings_default_browser_handler.h" #include "chrome/browser/ui/webui/settings/settings_startup_pages_handler.h" +#include "chrome/browser/ui/webui/settings/sync_handler.h" #include "chrome/common/url_constants.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" @@ -40,7 +40,7 @@ AddSettingsPageUIHandler(new FontHandler(web_ui)); AddSettingsPageUIHandler(new LanguagesHandler(web_ui)); AddSettingsPageUIHandler(new StartupPagesHandler(web_ui)); - AddSettingsPageUIHandler(new SyncSetupHandler()); + AddSettingsPageUIHandler(new SyncHandler()); content::WebUIDataSource* html_source = content::WebUIDataSource::Create(chrome::kChromeUIMdSettingsHost);
diff --git a/chrome/browser/ui/webui/settings/sync_handler.cc b/chrome/browser/ui/webui/settings/sync_handler.cc new file mode 100644 index 0000000..702d649 --- /dev/null +++ b/chrome/browser/ui/webui/settings/sync_handler.cc
@@ -0,0 +1,814 @@ +// 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 "chrome/browser/ui/webui/settings/sync_handler.h" + +#include "base/basictypes.h" +#include "base/bind.h" +#include "base/bind_helpers.h" +#include "base/command_line.h" +#include "base/compiler_specific.h" +#include "base/i18n/time_formatting.h" +#include "base/json/json_reader.h" +#include "base/json/json_writer.h" +#include "base/metrics/histogram.h" +#include "base/prefs/pref_service.h" +#include "base/values.h" +#include "chrome/browser/lifetime/application_lifetime.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/profiles/profile_info_cache.h" +#include "chrome/browser/profiles/profile_metrics.h" +#include "chrome/browser/signin/chrome_signin_helper.h" +#include "chrome/browser/signin/signin_error_controller_factory.h" +#include "chrome/browser/signin/signin_manager_factory.h" +#include "chrome/browser/signin/signin_promo.h" +#include "chrome/browser/sync/profile_sync_service.h" +#include "chrome/browser/sync/profile_sync_service_factory.h" +#include "chrome/browser/ui/browser_finder.h" +#include "chrome/browser/ui/browser_window.h" +#include "chrome/browser/ui/singleton_tabs.h" +#include "chrome/browser/ui/webui/options/options_handlers_helper.h" +#include "chrome/browser/ui/webui/signin/login_ui_service.h" +#include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" +#include "chrome/common/chrome_switches.h" +#include "chrome/grit/generated_resources.h" +#include "components/signin/core/browser/signin_error_controller.h" +#include "components/signin/core/browser/signin_header_helper.h" +#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/core/common/profile_management_switches.h" +#include "components/sync_driver/sync_prefs.h" +#include "content/public/browser/render_view_host.h" +#include "content/public/browser/web_contents.h" +#include "content/public/browser/web_contents_delegate.h" +#include "google_apis/gaia/gaia_auth_util.h" +#include "google_apis/gaia/gaia_constants.h" +#include "net/base/url_util.h" +#include "ui/base/l10n/l10n_util.h" + +#if defined(OS_CHROMEOS) +#include "components/signin/core/browser/signin_manager_base.h" +#else +#include "components/signin/core/browser/signin_manager.h" +#endif + +using content::WebContents; +using l10n_util::GetStringFUTF16; +using l10n_util::GetStringUTF16; + +namespace { + +// A structure which contains all the configuration information for sync. +struct SyncConfigInfo { + SyncConfigInfo(); + ~SyncConfigInfo(); + + bool encrypt_all; + bool sync_everything; + bool sync_nothing; + syncer::ModelTypeSet data_types; + std::string passphrase; + bool passphrase_is_gaia; +}; + +SyncConfigInfo::SyncConfigInfo() + : encrypt_all(false), + sync_everything(false), + sync_nothing(false), + passphrase_is_gaia(false) { +} + +SyncConfigInfo::~SyncConfigInfo() {} + +bool GetConfiguration(const std::string& json, SyncConfigInfo* config) { + scoped_ptr<base::Value> parsed_value = base::JSONReader::Read(json); + base::DictionaryValue* result; + if (!parsed_value || !parsed_value->GetAsDictionary(&result)) { + DLOG(ERROR) << "GetConfiguration() not passed a Dictionary"; + return false; + } + + if (!result->GetBoolean("syncAllDataTypes", &config->sync_everything)) { + DLOG(ERROR) << "GetConfiguration() not passed a syncAllDataTypes value"; + return false; + } + + if (!result->GetBoolean("syncNothing", &config->sync_nothing)) { + DLOG(ERROR) << "GetConfiguration() not passed a syncNothing value"; + return false; + } + + DCHECK(!(config->sync_everything && config->sync_nothing)) + << "syncAllDataTypes and syncNothing cannot both be true"; + + syncer::ModelTypeNameMap type_names = syncer::GetUserSelectableTypeNameMap(); + + for (syncer::ModelTypeNameMap::const_iterator it = type_names.begin(); + it != type_names.end(); ++it) { + std::string key_name = it->second + std::string("Synced"); + bool sync_value; + if (!result->GetBoolean(key_name, &sync_value)) { + DLOG(ERROR) << "GetConfiguration() not passed a value for " << key_name; + return false; + } + if (sync_value) + config->data_types.Put(it->first); + } + + // Encryption settings. + if (!result->GetBoolean("encryptAllData", &config->encrypt_all)) { + DLOG(ERROR) << "GetConfiguration() not passed a value for encryptAllData"; + return false; + } + + // Passphrase settings. + bool have_passphrase; + if (!result->GetBoolean("usePassphrase", &have_passphrase)) { + DLOG(ERROR) << "GetConfiguration() not passed a usePassphrase value"; + return false; + } + + if (have_passphrase) { + if (!result->GetBoolean("isGooglePassphrase", + &config->passphrase_is_gaia)) { + DLOG(ERROR) << "GetConfiguration() not passed isGooglePassphrase value"; + return false; + } + if (!result->GetString("passphrase", &config->passphrase)) { + DLOG(ERROR) << "GetConfiguration() not passed a passphrase value"; + return false; + } + } + return true; +} + +} // namespace + +namespace settings { + +SyncHandler::SyncHandler() : configuring_sync_(false) { +} + +SyncHandler::~SyncHandler() { + // Just exit if running unit tests (no actual WebUI is attached). + if (!web_ui()) + return; + + // This case is hit when the user performs a back navigation. + CloseSyncSetup(); +} + +void SyncHandler::ConfigureSyncDone() { + base::StringValue page("done"); + web_ui()->CallJavascriptFunction( + "SyncSetupOverlay.showSyncSetupPage", page); + + // Suppress the sign in promo once the user starts sync. This way the user + // doesn't see the sign in promo even if they sign out later on. + signin::SetUserSkippedPromo(GetProfile()); + + ProfileSyncService* service = GetSyncService(); + DCHECK(service); + if (!service->HasSyncSetupCompleted()) { + // This is the first time configuring sync, so log it. + base::FilePath profile_file_path = GetProfile()->GetPath(); + ProfileMetrics::LogProfileSyncSignIn(profile_file_path); + + // We're done configuring, so notify ProfileSyncService that it is OK to + // start syncing. + service->SetSetupInProgress(false); + service->SetSyncSetupCompleted(); + } +} + +bool SyncHandler::IsActiveLogin() const { + // LoginUIService can be NULL if page is brought up in incognito mode + // (i.e. if the user is running in guest mode in cros and brings up settings). + LoginUIService* service = GetLoginUIService(); + return service && (service->current_login_ui() == this); +} + +void SyncHandler::RegisterMessages() { + web_ui()->RegisterMessageCallback( + "SyncSetupDidClosePage", + base::Bind(&SyncHandler::OnDidClosePage, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "SyncSetupConfigure", + base::Bind(&SyncHandler::HandleConfigure, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "SyncSetupShowSetupUI", + base::Bind(&SyncHandler::HandleShowSetupUI, + base::Unretained(this))); + web_ui()->RegisterMessageCallback("CloseTimeout", + base::Bind(&SyncHandler::HandleCloseTimeout, + base::Unretained(this))); +#if defined(OS_CHROMEOS) + web_ui()->RegisterMessageCallback( + "SyncSetupDoSignOutOnAuthError", + base::Bind(&SyncHandler::HandleDoSignOutOnAuthError, + base::Unretained(this))); +#else + web_ui()->RegisterMessageCallback("SyncSetupStopSyncing", + base::Bind(&SyncHandler::HandleStopSyncing, + base::Unretained(this))); + web_ui()->RegisterMessageCallback("SyncSetupStartSignIn", + base::Bind(&SyncHandler::HandleStartSignin, + base::Unretained(this))); +#endif +} + +#if !defined(OS_CHROMEOS) +void SyncHandler::DisplayGaiaLogin() { + DCHECK(!sync_startup_tracker_); + // Advanced options are no longer being configured if the login screen is + // visible. If the user exits the signin wizard after this without + // configuring sync, CloseSyncSetup() will ensure they are logged out. + configuring_sync_ = false; + DisplayGaiaLoginInNewTabOrWindow(); +} + +void SyncHandler::DisplayGaiaLoginInNewTabOrWindow() { + Browser* browser = chrome::FindBrowserWithWebContents( + web_ui()->GetWebContents()); + bool force_new_tab = false; + if (!browser) { + // Settings is not displayed in a browser window. Open a new window. + browser = new Browser(Browser::CreateParams( + Browser::TYPE_TABBED, GetProfile(), chrome::GetActiveDesktop())); + force_new_tab = true; + } + + // If the signin manager already has an authenticated username, this is a + // re-auth scenario, and we need to ensure that the user signs in with the + // same email address. + GURL url; + if (SigninManagerFactory::GetForProfile( + browser->profile())->IsAuthenticated()) { + UMA_HISTOGRAM_ENUMERATION("Signin.Reauth", + signin_metrics::HISTOGRAM_REAUTH_SHOWN, + signin_metrics::HISTOGRAM_REAUTH_MAX); + + SigninErrorController* error_controller = + SigninErrorControllerFactory::GetForProfile(browser->profile()); + DCHECK(error_controller->HasError()); + if (!force_new_tab) { + browser->window()->ShowAvatarBubbleFromAvatarButton( + BrowserWindow::AVATAR_BUBBLE_MODE_REAUTH, + signin::ManageAccountsParams()); + } else { + url = signin::GetReauthURL(browser->profile(), + error_controller->error_account_id()); + } + } else { + signin_metrics::LogSigninSource(signin_metrics::SOURCE_SETTINGS); + if (!force_new_tab) { + browser->window()->ShowAvatarBubbleFromAvatarButton( + BrowserWindow::AVATAR_BUBBLE_MODE_SIGNIN, + signin::ManageAccountsParams()); + } else { + url = signin::GetPromoURL(signin_metrics::SOURCE_SETTINGS, true); + } + } + + if (url.is_valid()) + chrome::ShowSingletonTab(browser, url); +} +#endif + +bool SyncHandler::PrepareSyncSetup() { + // If the wizard is already visible, just focus that one. + if (FocusExistingWizardIfPresent()) { + if (!IsActiveLogin()) + CloseSyncSetup(); + return false; + } + + // Notify services that login UI is now active. + GetLoginUIService()->SetLoginUI(this); + + ProfileSyncService* service = GetSyncService(); + if (service) + service->SetSetupInProgress(true); + + return true; +} + +void SyncHandler::DisplaySpinner() { + configuring_sync_ = true; + base::StringValue page("spinner"); + base::DictionaryValue args; + + const int kTimeoutSec = 30; + DCHECK(!backend_start_timer_); + backend_start_timer_.reset(new base::OneShotTimer()); + backend_start_timer_->Start(FROM_HERE, + base::TimeDelta::FromSeconds(kTimeoutSec), + this, &SyncHandler::DisplayTimeout); + + web_ui()->CallJavascriptFunction( + "SyncSetupOverlay.showSyncSetupPage", page, args); +} + +// TODO(kochi): Handle error conditions other than timeout. +// http://crbug.com/128692 +void SyncHandler::DisplayTimeout() { + // Stop a timer to handle timeout in waiting for checking network connection. + backend_start_timer_.reset(); + + // Do not listen to sync startup events. + sync_startup_tracker_.reset(); + + base::StringValue page("timeout"); + base::DictionaryValue args; + web_ui()->CallJavascriptFunction( + "SyncSetupOverlay.showSyncSetupPage", page, args); +} + +void SyncHandler::OnDidClosePage(const base::ListValue* args) { + CloseSyncSetup(); +} + +void SyncHandler::SyncStartupFailed() { + // Stop a timer to handle timeout in waiting for checking network connection. + backend_start_timer_.reset(); + + // Just close the sync overlay (the idea is that the base settings page will + // display the current error.) + CloseUI(); +} + +void SyncHandler::SyncStartupCompleted() { + ProfileSyncService* service = GetSyncService(); + DCHECK(service->IsBackendInitialized()); + + // Stop a timer to handle timeout in waiting for checking network connection. + backend_start_timer_.reset(); + + DisplayConfigureSync(false); +} + +Profile* SyncHandler::GetProfile() const { + return Profile::FromWebUI(web_ui()); +} + +ProfileSyncService* SyncHandler::GetSyncService() const { + return GetProfile()->IsSyncAllowed() ? + ProfileSyncServiceFactory::GetForProfile(GetProfile()) : NULL; +} + +void SyncHandler::HandleConfigure(const base::ListValue* args) { + DCHECK(!sync_startup_tracker_); + std::string json; + if (!args->GetString(0, &json)) { + NOTREACHED() << "Could not read JSON argument"; + return; + } + if (json.empty()) { + NOTREACHED(); + return; + } + + SyncConfigInfo configuration; + if (!GetConfiguration(json, &configuration)) { + // The page sent us something that we didn't understand. + // This probably indicates a programming error. + NOTREACHED(); + return; + } + + // Start configuring the ProfileSyncService using the configuration passed + // to us from the JS layer. + ProfileSyncService* service = GetSyncService(); + + // If the sync engine has shutdown for some reason, just close the sync + // dialog. + if (!service || !service->IsBackendInitialized()) { + CloseUI(); + return; + } + + // Disable sync, but remain signed in if the user selected "Sync nothing" in + // the advanced settings dialog. Note: In order to disable sync across + // restarts on Chrome OS, we must call RequestStop(CLEAR_DATA), which + // suppresses sync startup in addition to disabling it. + if (configuration.sync_nothing) { + ProfileSyncService::SyncEvent( + ProfileSyncService::STOP_FROM_ADVANCED_DIALOG); + CloseUI(); + service->RequestStop(ProfileSyncService::CLEAR_DATA); + service->SetSetupInProgress(false); + return; + } + + // Don't allow "encrypt all" if the ProfileSyncService doesn't allow it. + // The UI is hidden, but the user may have enabled it e.g. by fiddling with + // the web inspector. + if (!service->IsEncryptEverythingAllowed()) + configuration.encrypt_all = false; + + // Note: Data encryption will not occur until configuration is complete + // (when the PSS receives its CONFIGURE_DONE notification from the sync + // backend), so the user still has a chance to cancel out of the operation + // if (for example) some kind of passphrase error is encountered. + if (configuration.encrypt_all) + service->EnableEncryptEverything(); + + bool passphrase_failed = false; + if (!configuration.passphrase.empty()) { + // We call IsPassphraseRequired() here (instead of + // IsPassphraseRequiredForDecryption()) because the user may try to enter + // a passphrase even though no encrypted data types are enabled. + if (service->IsPassphraseRequired()) { + // If we have pending keys, try to decrypt them with the provided + // passphrase. We track if this succeeds or fails because a failed + // decryption should result in an error even if there aren't any encrypted + // data types. + passphrase_failed = + !service->SetDecryptionPassphrase(configuration.passphrase); + } else { + // OK, the user sent us a passphrase, but we don't have pending keys. So + // it either means that the pending keys were resolved somehow since the + // time the UI was displayed (re-encryption, pending passphrase change, + // etc) or the user wants to re-encrypt. + if (!configuration.passphrase_is_gaia && + !service->IsUsingSecondaryPassphrase()) { + // User passed us a secondary passphrase, and the data is encrypted + // with a GAIA passphrase so they must want to encrypt. + service->SetEncryptionPassphrase(configuration.passphrase, + ProfileSyncService::EXPLICIT); + } + } + } + + bool user_was_prompted_for_passphrase = + service->IsPassphraseRequiredForDecryption(); + service->OnUserChoseDatatypes(configuration.sync_everything, + configuration.data_types); + + // Need to call IsPassphraseRequiredForDecryption() *after* calling + // OnUserChoseDatatypes() because the user may have just disabled the + // encrypted datatypes (in which case we just want to exit, not prompt the + // user for a passphrase). + if (passphrase_failed || service->IsPassphraseRequiredForDecryption()) { + // We need a passphrase, or the user's attempt to set a passphrase failed - + // prompt them again. This covers a few subtle cases: + // 1) The user enters an incorrect passphrase *and* disabled the encrypted + // data types. In that case we want to notify the user that the + // passphrase was incorrect even though there are no longer any encrypted + // types enabled (IsPassphraseRequiredForDecryption() == false). + // 2) The user doesn't enter any passphrase. In this case, we won't call + // SetDecryptionPassphrase() (passphrase_failed == false), but we still + // want to display an error message to let the user know that their + // blank passphrase entry is not acceptable. + // 3) The user just enabled an encrypted data type - in this case we don't + // want to display an "invalid passphrase" error, since it's the first + // time the user is seeing the prompt. + DisplayConfigureSync(passphrase_failed || user_was_prompted_for_passphrase); + } else { + // No passphrase is required from the user so mark the configuration as + // complete and close the sync setup overlay. + ConfigureSyncDone(); + } + + ProfileMetrics::LogProfileSyncInfo(ProfileMetrics::SYNC_CUSTOMIZE); + if (configuration.encrypt_all) + ProfileMetrics::LogProfileSyncInfo(ProfileMetrics::SYNC_ENCRYPT); + if (configuration.passphrase_is_gaia && !configuration.passphrase.empty()) + ProfileMetrics::LogProfileSyncInfo(ProfileMetrics::SYNC_PASSPHRASE); + if (!configuration.sync_everything) + ProfileMetrics::LogProfileSyncInfo(ProfileMetrics::SYNC_CHOOSE); +} + +void SyncHandler::HandleShowSetupUI(const base::ListValue* args) { + if (!GetSyncService()) { + DLOG(WARNING) << "Cannot display sync UI when sync is disabled"; + CloseUI(); + return; + } + + SigninManagerBase* signin = + SigninManagerFactory::GetForProfile(GetProfile()); + if (!signin->IsAuthenticated()) { + // For web-based signin, the signin page is not displayed in an overlay + // on the settings page. So if we get here, it must be due to the user + // cancelling signin (by reloading the sync settings page during initial + // signin) or by directly navigating to settings/syncSetup + // (http://crbug.com/229836). So just exit and go back to the settings page. + DLOG(WARNING) << "Cannot display sync setup UI when not signed in"; + CloseUI(); + return; + } + + // If a setup wizard is already present, but not on this page, close the + // blank setup overlay on this page by showing the "done" page. This can + // happen if the user navigates to chrome://settings/syncSetup in more than + // one tab. See crbug.com/261566. + // Note: The following block will transfer focus to the existing wizard. + if (IsExistingWizardPresent() && !IsActiveLogin()) + CloseUI(); + + // If a setup wizard is present on this page or another, bring it to focus. + // Otherwise, display a new one on this page. + if (!FocusExistingWizardIfPresent()) + OpenSyncSetup(); +} + +#if defined(OS_CHROMEOS) +// On ChromeOS, we need to sign out the user session to fix an auth error, so +// the user goes through the real signin flow to generate a new auth token. +void SyncHandler::HandleDoSignOutOnAuthError(const base::ListValue* args) { + DVLOG(1) << "Signing out the user to fix a sync error."; + chrome::AttemptUserExit(); +} +#endif + +#if !defined(OS_CHROMEOS) +void SyncHandler::HandleStartSignin(const base::ListValue* args) { + // Should only be called if the user is not already signed in. + DCHECK(!SigninManagerFactory::GetForProfile(GetProfile())-> + IsAuthenticated()); + OpenSyncSetup(); +} + +void SyncHandler::HandleStopSyncing(const base::ListValue* args) { + if (GetSyncService()) + ProfileSyncService::SyncEvent(ProfileSyncService::STOP_FROM_OPTIONS); + SigninManagerFactory::GetForProfile(GetProfile())->SignOut( + signin_metrics::USER_CLICKED_SIGNOUT_SETTINGS); + + bool delete_profile = false; + if (args->GetBoolean(0, &delete_profile) && delete_profile) { + // Do as BrowserOptionsHandler::DeleteProfile(). + options::helper::DeleteProfileAtPath(GetProfile()->GetPath(), web_ui()); + } +} +#endif + +void SyncHandler::HandleCloseTimeout(const base::ListValue* args) { + CloseSyncSetup(); +} + +void SyncHandler::CloseSyncSetup() { + // Stop a timer to handle timeout in waiting for checking network connection. + backend_start_timer_.reset(); + + // Clear the sync startup tracker, since the setup wizard is being closed. + sync_startup_tracker_.reset(); + + ProfileSyncService* sync_service = GetSyncService(); + if (IsActiveLogin()) { + // Don't log a cancel event if the sync setup dialog is being + // automatically closed due to an auth error. + if (!sync_service || (!sync_service->HasSyncSetupCompleted() && + sync_service->GetAuthError().state() == GoogleServiceAuthError::NONE)) { + if (configuring_sync_) { + ProfileSyncService::SyncEvent( + ProfileSyncService::CANCEL_DURING_CONFIGURE); + + // If the user clicked "Cancel" while setting up sync, disable sync + // because we don't want the sync backend to remain in the + // first-setup-incomplete state. + // Note: In order to disable sync across restarts on Chrome OS, + // we must call RequestStop(CLEAR_DATA), which suppresses sync startup + // in addition to disabling it. + if (sync_service) { + DVLOG(1) << "Sync setup aborted by user action"; + sync_service->RequestStop(ProfileSyncService::CLEAR_DATA); + #if !defined(OS_CHROMEOS) + // Sign out the user on desktop Chrome if they click cancel during + // initial setup. + // TODO(rsimha): Revisit this for M30. See http://crbug.com/252049. + if (sync_service->IsFirstSetupInProgress()) { + SigninManagerFactory::GetForProfile(GetProfile())->SignOut( + signin_metrics::ABORT_SIGNIN); + } + #endif + } + } + } + + GetLoginUIService()->LoginUIClosed(this); + } + + // Alert the sync service anytime the sync setup dialog is closed. This can + // happen due to the user clicking the OK or Cancel button, or due to the + // dialog being closed by virtue of sync being disabled in the background. + if (sync_service) + sync_service->SetSetupInProgress(false); + + configuring_sync_ = false; +} + +void SyncHandler::OpenSyncSetup() { + if (!PrepareSyncSetup()) + return; + + // There are several different UI flows that can bring the user here: + // 1) Signin promo. + // 2) Normal signin through settings page (IsAuthenticated() is false). + // 3) Previously working credentials have expired. + // 4) User is signed in, but has stopped sync via the google dashboard, and + // signout is prohibited by policy so we need to force a re-auth. + // 5) User clicks [Advanced Settings] button on options page while already + // logged in. + // 6) One-click signin (credentials are already available, so should display + // sync configure UI, not login UI). + // 7) User re-enables sync after disabling it via advanced settings. +#if !defined(OS_CHROMEOS) + SigninManagerBase* signin = + SigninManagerFactory::GetForProfile(GetProfile()); + + if (!signin->IsAuthenticated() || + SigninErrorControllerFactory::GetForProfile(GetProfile())->HasError()) { + // User is not logged in (cases 1-2), or login has been specially requested + // because previously working credentials have expired (case 3). Close sync + // setup including any visible overlays, and display the gaia auth page. + // Control will be returned to the sync settings page once auth is complete. + CloseUI(); + DisplayGaiaLogin(); + return; + } +#endif + if (!GetSyncService()) { + // This can happen if the user directly navigates to /settings/syncSetup. + DLOG(WARNING) << "Cannot display sync UI when sync is disabled"; + CloseUI(); + return; + } + + // User is already logged in. They must have brought up the config wizard + // via the "Advanced..." button or through One-Click signin (cases 4-6), or + // they are re-enabling sync after having disabled it (case 7). + DisplayConfigureSync(false); +} + +void SyncHandler::OpenConfigureSync() { + if (!PrepareSyncSetup()) + return; + + DisplayConfigureSync(false); +} + +void SyncHandler::FocusUI() { + DCHECK(IsActiveLogin()); + WebContents* web_contents = web_ui()->GetWebContents(); + web_contents->GetDelegate()->ActivateContents(web_contents); +} + +void SyncHandler::CloseUI() { + CloseSyncSetup(); + base::StringValue page("done"); + web_ui()->CallJavascriptFunction( + "SyncSetupOverlay.showSyncSetupPage", page); +} + +bool SyncHandler::IsExistingWizardPresent() { + LoginUIService* service = GetLoginUIService(); + DCHECK(service); + return service->current_login_ui() != NULL; +} + +bool SyncHandler::FocusExistingWizardIfPresent() { + if (!IsExistingWizardPresent()) + return false; + + LoginUIService* service = GetLoginUIService(); + DCHECK(service); + service->current_login_ui()->FocusUI(); + return true; +} + +void SyncHandler::DisplayConfigureSync(bool passphrase_failed) { + // Should never call this when we are not signed in. + DCHECK(SigninManagerFactory::GetForProfile( + GetProfile())->IsAuthenticated()); + ProfileSyncService* service = GetSyncService(); + DCHECK(service); + if (!service->IsBackendInitialized()) { + service->RequestStart(); + + // See if it's even possible to bring up the sync backend - if not + // (unrecoverable error?), don't bother displaying a spinner that will be + // immediately closed because this leads to some ugly infinite UI loop (see + // http://crbug.com/244769). + if (SyncStartupTracker::GetSyncServiceState(GetProfile()) != + SyncStartupTracker::SYNC_STARTUP_ERROR) { + DisplaySpinner(); + } + + // Start SyncSetupTracker to wait for sync to initialize. + sync_startup_tracker_.reset( + new SyncStartupTracker(GetProfile(), this)); + return; + } + + // Should only get here if user is signed in and sync is initialized, so no + // longer need a SyncStartupTracker. + sync_startup_tracker_.reset(); + configuring_sync_ = true; + DCHECK(service->IsBackendInitialized()) + << "Cannot configure sync until the sync backend is initialized"; + + // Setup args for the sync configure screen: + // syncAllDataTypes: true if the user wants to sync everything + // syncNothing: true if the user wants to sync nothing + // <data_type>Registered: true if the associated data type is supported + // <data_type>Synced: true if the user wants to sync that specific data type + // encryptionEnabled: true if sync supports encryption + // encryptAllData: true if user wants to encrypt all data (not just + // passwords) + // usePassphrase: true if the data is encrypted with a secondary passphrase + // show_passphrase: true if a passphrase is needed to decrypt the sync data + base::DictionaryValue args; + + // Tell the UI layer which data types are registered/enabled by the user. + const syncer::ModelTypeSet registered_types = + service->GetRegisteredDataTypes(); + const syncer::ModelTypeSet preferred_types = service->GetPreferredDataTypes(); + const syncer::ModelTypeSet enforced_types = service->GetForcedDataTypes(); + syncer::ModelTypeNameMap type_names = syncer::GetUserSelectableTypeNameMap(); + for (syncer::ModelTypeNameMap::const_iterator it = type_names.begin(); + it != type_names.end(); ++it) { + syncer::ModelType sync_type = it->first; + const std::string key_name = it->second; + args.SetBoolean(key_name + "Registered", registered_types.Has(sync_type)); + args.SetBoolean(key_name + "Synced", preferred_types.Has(sync_type)); + args.SetBoolean(key_name + "Enforced", enforced_types.Has(sync_type)); + // TODO(treib): How do we want to handle pref groups, i.e. when only some of + // the sync types behind a checkbox are force-enabled? crbug.com/403326 + } + sync_driver::SyncPrefs sync_prefs(GetProfile()->GetPrefs()); + args.SetBoolean("passphraseFailed", passphrase_failed); + args.SetBoolean("syncAllDataTypes", sync_prefs.HasKeepEverythingSynced()); + args.SetBoolean("syncNothing", false); // Always false during initial setup. + args.SetBoolean("encryptAllData", service->IsEncryptEverythingEnabled()); + args.SetBoolean("encryptAllDataAllowed", + service->IsEncryptEverythingAllowed()); + + // We call IsPassphraseRequired() here, instead of calling + // IsPassphraseRequiredForDecryption(), because we want to show the passphrase + // UI even if no encrypted data types are enabled. + args.SetBoolean("showPassphrase", service->IsPassphraseRequired()); + + // To distinguish between FROZEN_IMPLICIT_PASSPHRASE and CUSTOM_PASSPHRASE + // we only set usePassphrase for CUSTOM_PASSPHRASE. + args.SetBoolean("usePassphrase", + service->GetPassphraseType() == syncer::CUSTOM_PASSPHRASE); + base::Time passphrase_time = service->GetExplicitPassphraseTime(); + syncer::PassphraseType passphrase_type = service->GetPassphraseType(); + if (!passphrase_time.is_null()) { + base::string16 passphrase_time_str = + base::TimeFormatShortDate(passphrase_time); + args.SetString( + "enterPassphraseBody", + GetStringFUTF16(IDS_SYNC_ENTER_PASSPHRASE_BODY_WITH_DATE, + passphrase_time_str)); + args.SetString( + "enterGooglePassphraseBody", + GetStringFUTF16(IDS_SYNC_ENTER_GOOGLE_PASSPHRASE_BODY_WITH_DATE, + passphrase_time_str)); + switch (passphrase_type) { + case syncer::FROZEN_IMPLICIT_PASSPHRASE: + args.SetString( + "fullEncryptionBody", + GetStringFUTF16(IDS_SYNC_FULL_ENCRYPTION_BODY_GOOGLE_WITH_DATE, + passphrase_time_str)); + break; + case syncer::CUSTOM_PASSPHRASE: + args.SetString( + "fullEncryptionBody", + GetStringFUTF16(IDS_SYNC_FULL_ENCRYPTION_BODY_CUSTOM_WITH_DATE, + passphrase_time_str)); + break; + default: + args.SetString( + "fullEncryptionBody", + GetStringUTF16(IDS_SYNC_FULL_ENCRYPTION_BODY_CUSTOM)); + break; + } + } else if (passphrase_type == syncer::CUSTOM_PASSPHRASE) { + args.SetString( + "fullEncryptionBody", + GetStringUTF16(IDS_SYNC_FULL_ENCRYPTION_BODY_CUSTOM)); + } else { + args.SetString( + "fullEncryptionBody", + GetStringUTF16(IDS_SYNC_FULL_ENCRYPTION_DATA)); + } + + base::StringValue page("configure"); + web_ui()->CallJavascriptFunction( + "SyncSetupOverlay.showSyncSetupPage", page, args); + + // Make sure the tab used for the Gaia sign in does not cover the settings + // tab. + FocusUI(); +} + +LoginUIService* SyncHandler::GetLoginUIService() const { + return LoginUIServiceFactory::GetForProfile(GetProfile()); +} + +} // namespace settings
diff --git a/chrome/browser/ui/webui/settings/sync_handler.h b/chrome/browser/ui/webui/settings/sync_handler.h new file mode 100644 index 0000000..8a30626 --- /dev/null +++ b/chrome/browser/ui/webui/settings/sync_handler.h
@@ -0,0 +1,161 @@ +// 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 CHROME_BROWSER_UI_WEBUI_SETTINGS_SYNC_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_SETTINGS_SYNC_HANDLER_H_ + +#include "base/gtest_prod_util.h" +#include "base/macros.h" +#include "base/memory/scoped_ptr.h" +#include "base/timer/timer.h" +#include "chrome/browser/sync/sync_startup_tracker.h" +#include "chrome/browser/ui/webui/signin/login_ui_service.h" +#include "content/public/browser/web_ui_message_handler.h" + +class LoginUIService; +class ProfileSyncService; +class SigninManagerBase; + +namespace content { +class WebContents; +class WebUI; +} + +namespace settings { + +class SyncHandler : public content::WebUIMessageHandler, + public SyncStartupTracker::Observer, + public LoginUIService::LoginUI { + public: + SyncHandler(); + ~SyncHandler() override; + + // content::WebUIMessageHandler implementation. + void RegisterMessages() override; + + // SyncStartupTracker::Observer implementation; + void SyncStartupCompleted() override; + void SyncStartupFailed() override; + + // LoginUIService::LoginUI implementation. + void FocusUI() override; + void CloseUI() override; + + // Initializes the sync setup flow and shows the setup UI. + void OpenSyncSetup(); + + // Shows advanced configuration dialog without going through sign in dialog. + // Kicks the sync backend if necessary with showing spinner dialog until it + // gets ready. + void OpenConfigureSync(); + + // Terminates the sync setup flow. + void CloseSyncSetup(); + + protected: + friend class SyncHandlerTest; + FRIEND_TEST_ALL_PREFIXES(SyncHandlerTest, + DisplayConfigureWithBackendDisabledAndCancel); + FRIEND_TEST_ALL_PREFIXES(SyncHandlerTest, HandleSetupUIWhenSyncDisabled); + FRIEND_TEST_ALL_PREFIXES(SyncHandlerTest, SelectCustomEncryption); + FRIEND_TEST_ALL_PREFIXES(SyncHandlerTest, ShowSyncSetupWhenNotSignedIn); + FRIEND_TEST_ALL_PREFIXES(SyncHandlerTest, SuccessfullySetPassphrase); + FRIEND_TEST_ALL_PREFIXES(SyncHandlerTest, TestSyncEverything); + FRIEND_TEST_ALL_PREFIXES(SyncHandlerTest, TestSyncNothing); + FRIEND_TEST_ALL_PREFIXES(SyncHandlerTest, TestSyncAllManually); + FRIEND_TEST_ALL_PREFIXES(SyncHandlerTest, TestPassphraseStillRequired); + FRIEND_TEST_ALL_PREFIXES(SyncHandlerTest, TestSyncIndividualTypes); + FRIEND_TEST_ALL_PREFIXES(SyncHandlerTest, TurnOnEncryptAll); + FRIEND_TEST_ALL_PREFIXES(SyncHandlerTest, TurnOnEncryptAllDisallowed); + FRIEND_TEST_ALL_PREFIXES(SyncHandlerTest, UnsuccessfullySetPassphrase); + FRIEND_TEST_ALL_PREFIXES(SyncHandlerNonCrosTest, + UnrecoverableErrorInitializingSync); + FRIEND_TEST_ALL_PREFIXES(SyncHandlerNonCrosTest, + GaiaErrorInitializingSync); + FRIEND_TEST_ALL_PREFIXES(SyncHandlerNonCrosTest, HandleCaptcha); + FRIEND_TEST_ALL_PREFIXES(SyncHandlerNonCrosTest, HandleGaiaAuthFailure); + FRIEND_TEST_ALL_PREFIXES(SyncHandlerNonCrosTest, + SubmitAuthWithInvalidUsername); + FRIEND_TEST_ALL_PREFIXES(SyncHandlerFirstSigninTest, DisplayBasicLogin); + + bool is_configuring_sync() const { return configuring_sync_; } + + // Called when configuring sync is done to close the dialog and start syncing. + void ConfigureSyncDone(); + + // Helper routine that gets the ProfileSyncService associated with the parent + // profile. + ProfileSyncService* GetSyncService() const; + + // Returns the LoginUIService for the parent profile. + LoginUIService* GetLoginUIService() const; + + private: + // Callbacks from the page. + void OnDidClosePage(const base::ListValue* args); + void HandleConfigure(const base::ListValue* args); + void HandlePassphraseEntry(const base::ListValue* args); + void HandlePassphraseCancel(const base::ListValue* args); + void HandleShowSetupUI(const base::ListValue* args); + void HandleDoSignOutOnAuthError(const base::ListValue* args); + void HandleStartSignin(const base::ListValue* args); + void HandleStopSyncing(const base::ListValue* args); + void HandleCloseTimeout(const base::ListValue* args); +#if !defined(OS_CHROMEOS) + // Displays the GAIA login form. + void DisplayGaiaLogin(); + + // When web-flow is enabled, displays the Gaia login form in a new tab. + // This function is virtual so that tests can override. + virtual void DisplayGaiaLoginInNewTabOrWindow(); +#endif + + // Helper routine that gets the Profile associated with this object (virtual + // so tests can override). + virtual Profile* GetProfile() const; + + // A utility function to call before actually showing setup dialog. Makes sure + // that a new dialog can be shown and sets flag that setup is in progress. + bool PrepareSyncSetup(); + + // Displays spinner-only UI indicating that something is going on in the + // background. + // TODO(kochi): better to show some message that the user can understand what + // is running in the background. + void DisplaySpinner(); + + // Displays an error dialog which shows timeout of starting the sync backend. + void DisplayTimeout(); + + // Returns true if this object is the active login object. + bool IsActiveLogin() const; + + // If a wizard already exists, return true. Otherwise, return false. + bool IsExistingWizardPresent(); + + // If a wizard already exists, focus it and return true. + bool FocusExistingWizardIfPresent(); + + // Display the configure sync UI. If |passphrase_failed| is true, the account + // requires a passphrase and one hasn't been provided or it was invalid. + void DisplayConfigureSync(bool passphrase_failed); + + // Helper object used to wait for the sync backend to startup. + scoped_ptr<SyncStartupTracker> sync_startup_tracker_; + + // Set to true whenever the sync configure UI is visible. This is used to tell + // what stage of the setup wizard the user was in and to update the UMA + // histograms in the case that the user cancels out. + bool configuring_sync_; + + // The OneShotTimer object used to timeout of starting the sync backend + // service. + scoped_ptr<base::OneShotTimer> backend_start_timer_; + + DISALLOW_COPY_AND_ASSIGN(SyncHandler); +}; + +} // namespace settings + +#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_SYNC_HANDLER_H_
diff --git a/chrome/browser/ui/webui/settings/sync_handler_unittest.cc b/chrome/browser/ui/webui/settings/sync_handler_unittest.cc new file mode 100644 index 0000000..8638d32 --- /dev/null +++ b/chrome/browser/ui/webui/settings/sync_handler_unittest.cc
@@ -0,0 +1,997 @@ +// 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 "chrome/browser/ui/webui/settings/sync_handler.h" + +#include <vector> + +#include "base/command_line.h" +#include "base/json/json_writer.h" +#include "base/memory/scoped_ptr.h" +#include "base/prefs/pref_service.h" +#include "base/stl_util.h" +#include "base/values.h" +#include "chrome/browser/signin/fake_signin_manager_builder.h" +#include "chrome/browser/signin/signin_error_controller_factory.h" +#include "chrome/browser/signin/signin_manager_factory.h" +#include "chrome/browser/sync/profile_sync_service_factory.h" +#include "chrome/browser/sync/profile_sync_service_mock.h" +#include "chrome/browser/ui/webui/signin/login_ui_service.h" +#include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" +#include "chrome/common/chrome_switches.h" +#include "chrome/common/pref_names.h" +#include "chrome/test/base/scoped_testing_local_state.h" +#include "chrome/test/base/testing_browser_process.h" +#include "chrome/test/base/testing_profile.h" +#include "components/signin/core/browser/fake_auth_status_provider.h" +#include "components/signin/core/browser/signin_manager.h" +#include "components/sync_driver/sync_prefs.h" +#include "content/public/browser/web_ui.h" +#include "content/public/test/test_browser_thread.h" +#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/test_web_ui.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "ui/base/layout.h" + +using ::testing::_; +using ::testing::Mock; +using ::testing::Return; +using ::testing::ReturnRef; +using ::testing::Values; + +typedef GoogleServiceAuthError AuthError; + +namespace { + +MATCHER_P(ModelTypeSetMatches, value, "") { return arg.Equals(value); } + +const char kTestUser[] = "chrome.p13n.test@gmail.com"; + +// Returns a ModelTypeSet with all user selectable types set. +syncer::ModelTypeSet GetAllTypes() { + return syncer::UserSelectableTypes(); +} + +enum SyncAllDataConfig { + SYNC_ALL_DATA, + CHOOSE_WHAT_TO_SYNC, + SYNC_NOTHING +}; + +enum EncryptAllConfig { + ENCRYPT_ALL_DATA, + ENCRYPT_PASSWORDS +}; + +// Create a json-format string with the key/value pairs appropriate for a call +// to HandleConfigure(). If |extra_values| is non-null, then the values from +// the passed dictionary are added to the json. +std::string GetConfiguration(const base::DictionaryValue* extra_values, + SyncAllDataConfig sync_all, + syncer::ModelTypeSet types, + const std::string& passphrase, + EncryptAllConfig encrypt_all) { + base::DictionaryValue result; + if (extra_values) + result.MergeDictionary(extra_values); + result.SetBoolean("syncAllDataTypes", sync_all == SYNC_ALL_DATA); + result.SetBoolean("syncNothing", sync_all == SYNC_NOTHING); + result.SetBoolean("encryptAllData", encrypt_all == ENCRYPT_ALL_DATA); + result.SetBoolean("usePassphrase", !passphrase.empty()); + if (!passphrase.empty()) + result.SetString("passphrase", passphrase); + // Add all of our data types. + result.SetBoolean("appsSynced", types.Has(syncer::APPS)); + result.SetBoolean("autofillSynced", types.Has(syncer::AUTOFILL)); + result.SetBoolean("bookmarksSynced", types.Has(syncer::BOOKMARKS)); + result.SetBoolean("extensionsSynced", types.Has(syncer::EXTENSIONS)); + result.SetBoolean("passwordsSynced", types.Has(syncer::PASSWORDS)); + result.SetBoolean("preferencesSynced", types.Has(syncer::PREFERENCES)); + result.SetBoolean("tabsSynced", types.Has(syncer::PROXY_TABS)); + result.SetBoolean("themesSynced", types.Has(syncer::THEMES)); + result.SetBoolean("typedUrlsSynced", types.Has(syncer::TYPED_URLS)); + result.SetBoolean("wifiCredentialsSynced", + types.Has(syncer::WIFI_CREDENTIALS)); + std::string args; + base::JSONWriter::Write(result, &args); + return args; +} + +// Checks whether the passed |dictionary| contains a |key| with the given +// |expected_value|. If |omit_if_false| is true, then the value should only +// be present if |expected_value| is true. +void CheckBool(const base::DictionaryValue* dictionary, + const std::string& key, + bool expected_value, + bool omit_if_false) { + if (omit_if_false && !expected_value) { + EXPECT_FALSE(dictionary->HasKey(key)) << + "Did not expect to find value for " << key; + } else { + bool actual_value; + EXPECT_TRUE(dictionary->GetBoolean(key, &actual_value)) << + "No value found for " << key; + EXPECT_EQ(expected_value, actual_value) << + "Mismatch found for " << key; + } +} + +void CheckBool(const base::DictionaryValue* dictionary, + const std::string& key, + bool expected_value) { + return CheckBool(dictionary, key, expected_value, false); +} + +// Checks to make sure that the values stored in |dictionary| match the values +// expected by the showSyncSetupPage() JS function for a given set of data +// types. +void CheckConfigDataTypeArguments(const base::DictionaryValue* dictionary, + SyncAllDataConfig config, + syncer::ModelTypeSet types) { + CheckBool(dictionary, "syncAllDataTypes", config == SYNC_ALL_DATA); + CheckBool(dictionary, "syncNothing", config == SYNC_NOTHING); + CheckBool(dictionary, "appsSynced", types.Has(syncer::APPS)); + CheckBool(dictionary, "autofillSynced", types.Has(syncer::AUTOFILL)); + CheckBool(dictionary, "bookmarksSynced", types.Has(syncer::BOOKMARKS)); + CheckBool(dictionary, "extensionsSynced", types.Has(syncer::EXTENSIONS)); + CheckBool(dictionary, "passwordsSynced", types.Has(syncer::PASSWORDS)); + CheckBool(dictionary, "preferencesSynced", types.Has(syncer::PREFERENCES)); + CheckBool(dictionary, "tabsSynced", types.Has(syncer::PROXY_TABS)); + CheckBool(dictionary, "themesSynced", types.Has(syncer::THEMES)); + CheckBool(dictionary, "typedUrlsSynced", types.Has(syncer::TYPED_URLS)); + CheckBool(dictionary, "wifiCredentialsSynced", + types.Has(syncer::WIFI_CREDENTIALS)); +} + +} // namespace + +namespace settings { + +class TestingSyncHandler : public SyncHandler { + public: + TestingSyncHandler(content::WebUI* web_ui, Profile* profile) + : profile_(profile) { + set_web_ui(web_ui); + } + ~TestingSyncHandler() override { set_web_ui(nullptr); } + + void FocusUI() override {} + + Profile* GetProfile() const override { return profile_; } + + using SyncHandler::is_configuring_sync; + + private: +#if !defined(OS_CHROMEOS) + void DisplayGaiaLoginInNewTabOrWindow() override {} +#endif + + // Weak pointer to parent profile. + Profile* profile_; + DISALLOW_COPY_AND_ASSIGN(TestingSyncHandler); +}; + +// The boolean parameter indicates whether the test is run with ClientOAuth +// or not. The test parameter is a bool: whether or not to test with/ +// /ClientLogin enabled or not. +class SyncHandlerTest : public testing::Test { + public: + SyncHandlerTest() : error_(GoogleServiceAuthError::NONE) {} + void SetUp() override { + error_ = GoogleServiceAuthError::AuthErrorNone(); + + TestingProfile::Builder builder; + builder.AddTestingFactory(SigninManagerFactory::GetInstance(), + BuildFakeSigninManagerBase); + profile_ = builder.Build(); + + // Sign in the user. + mock_signin_ = static_cast<SigninManagerBase*>( + SigninManagerFactory::GetForProfile(profile_.get())); + std::string username = GetTestUser(); + if (!username.empty()) + mock_signin_->SetAuthenticatedAccountInfo(username, username); + + mock_pss_ = static_cast<ProfileSyncServiceMock*>( + ProfileSyncServiceFactory::GetInstance()->SetTestingFactoryAndUse( + profile_.get(), + ProfileSyncServiceMock::BuildMockProfileSyncService)); + EXPECT_CALL(*mock_pss_, GetAuthError()).WillRepeatedly(ReturnRef(error_)); + ON_CALL(*mock_pss_, GetPassphraseType()).WillByDefault( + Return(syncer::IMPLICIT_PASSPHRASE)); + ON_CALL(*mock_pss_, GetPassphraseTime()).WillByDefault( + Return(base::Time())); + ON_CALL(*mock_pss_, GetExplicitPassphraseTime()).WillByDefault( + Return(base::Time())); + ON_CALL(*mock_pss_, GetRegisteredDataTypes()) + .WillByDefault(Return(syncer::ModelTypeSet())); + + mock_pss_->Initialize(); + + handler_.reset(new TestingSyncHandler(&web_ui_, profile_.get())); + } + + // Setup the expectations for calls made when displaying the config page. + void SetDefaultExpectationsForConfigPage() { + EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(true)); + EXPECT_CALL(*mock_pss_, GetRegisteredDataTypes()) + .WillRepeatedly(Return(GetAllTypes())); + EXPECT_CALL(*mock_pss_, GetPreferredDataTypes()) + .WillRepeatedly(Return(GetAllTypes())); + EXPECT_CALL(*mock_pss_, GetActiveDataTypes()) + .WillRepeatedly(Return(GetAllTypes())); + EXPECT_CALL(*mock_pss_, IsEncryptEverythingAllowed()) + .WillRepeatedly(Return(true)); + EXPECT_CALL(*mock_pss_, IsEncryptEverythingEnabled()) + .WillRepeatedly(Return(false)); + } + + void SetupInitializedProfileSyncService() { + // An initialized ProfileSyncService will have already completed sync setup + // and will have an initialized sync backend. + ASSERT_TRUE(mock_signin_->IsInitialized()); + EXPECT_CALL(*mock_pss_, IsBackendInitialized()) + .WillRepeatedly(Return(true)); + } + + void ExpectConfig() { + ASSERT_EQ(1U, web_ui_.call_data().size()); + const content::TestWebUI::CallData& data = *web_ui_.call_data()[0]; + EXPECT_EQ("SyncSetupOverlay.showSyncSetupPage", data.function_name()); + std::string page; + ASSERT_TRUE(data.arg1()->GetAsString(&page)); + EXPECT_EQ(page, "configure"); + } + + void ExpectDone() { + ASSERT_EQ(1U, web_ui_.call_data().size()); + const content::TestWebUI::CallData& data = *web_ui_.call_data()[0]; + EXPECT_EQ("SyncSetupOverlay.showSyncSetupPage", data.function_name()); + std::string page; + ASSERT_TRUE(data.arg1()->GetAsString(&page)); + EXPECT_EQ(page, "done"); + } + + void ExpectSpinnerAndClose() { + // We expect a call to SyncSetupOverlay.showSyncSetupPage. + EXPECT_EQ(1U, web_ui_.call_data().size()); + const content::TestWebUI::CallData& data = *web_ui_.call_data()[0]; + EXPECT_EQ("SyncSetupOverlay.showSyncSetupPage", data.function_name()); + + std::string page; + ASSERT_TRUE(data.arg1()->GetAsString(&page)); + EXPECT_EQ(page, "spinner"); + // Cancelling the spinner dialog will cause CloseSyncSetup(). + handler_->CloseSyncSetup(); + EXPECT_EQ(NULL, + LoginUIServiceFactory::GetForProfile( + profile_.get())->current_login_ui()); + } + + // It's difficult to notify sync listeners when using a ProfileSyncServiceMock + // so this helper routine dispatches an OnStateChanged() notification to the + // SyncStartupTracker. + void NotifySyncListeners() { + if (handler_->sync_startup_tracker_) + handler_->sync_startup_tracker_->OnStateChanged(); + } + + virtual std::string GetTestUser() { + return std::string(kTestUser); + } + + content::TestBrowserThreadBundle thread_bundle_; + scoped_ptr<Profile> profile_; + ProfileSyncServiceMock* mock_pss_; + GoogleServiceAuthError error_; + SigninManagerBase* mock_signin_; + content::TestWebUI web_ui_; + scoped_ptr<TestingSyncHandler> handler_; +}; + +class SyncHandlerFirstSigninTest : public SyncHandlerTest { + std::string GetTestUser() override { return std::string(); } +}; + +TEST_F(SyncHandlerTest, Basic) { +} + +#if !defined(OS_CHROMEOS) +TEST_F(SyncHandlerFirstSigninTest, DisplayBasicLogin) { + EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable()) + .WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted()) + .WillRepeatedly(Return(false)); + // Ensure that the user is not signed in before calling |HandleStartSignin()|. + SigninManager* manager = static_cast<SigninManager*>(mock_signin_); + manager->SignOut(signin_metrics::SIGNOUT_TEST); + handler_->HandleStartSignin(NULL); + + // Sync setup hands off control to the gaia login tab. + EXPECT_EQ(NULL, + LoginUIServiceFactory::GetForProfile( + profile_.get())->current_login_ui()); + + ASSERT_FALSE(handler_->is_configuring_sync()); + + handler_->CloseSyncSetup(); + EXPECT_EQ(NULL, + LoginUIServiceFactory::GetForProfile( + profile_.get())->current_login_ui()); +} + +TEST_F(SyncHandlerTest, ShowSyncSetupWhenNotSignedIn) { + EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable()) + .WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted()) + .WillRepeatedly(Return(false)); + handler_->HandleShowSetupUI(NULL); + + // We expect a call to SyncSetupOverlay.showSyncSetupPage. + ASSERT_EQ(1U, web_ui_.call_data().size()); + const content::TestWebUI::CallData& data = *web_ui_.call_data()[0]; + EXPECT_EQ("SyncSetupOverlay.showSyncSetupPage", data.function_name()); + + ASSERT_FALSE(handler_->is_configuring_sync()); + EXPECT_EQ(NULL, + LoginUIServiceFactory::GetForProfile( + profile_.get())->current_login_ui()); +} +#endif // !defined(OS_CHROMEOS) + +// Verifies that the sync setup is terminated correctly when the +// sync is disabled. +TEST_F(SyncHandlerTest, HandleSetupUIWhenSyncDisabled) { + EXPECT_CALL(*mock_pss_, IsManaged()).WillRepeatedly(Return(true)); + handler_->HandleShowSetupUI(NULL); + + // Sync setup is closed when sync is disabled. + EXPECT_EQ(NULL, + LoginUIServiceFactory::GetForProfile( + profile_.get())->current_login_ui()); + ASSERT_FALSE(handler_->is_configuring_sync()); +} + +// Verifies that the handler correctly handles a cancellation when +// it is displaying the spinner to the user. +TEST_F(SyncHandlerTest, DisplayConfigureWithBackendDisabledAndCancel) { + EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(true)); + EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable()) + .WillRepeatedly(Return(true)); + EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted()) + .WillRepeatedly(Return(false)); + error_ = GoogleServiceAuthError::AuthErrorNone(); + EXPECT_CALL(*mock_pss_, IsBackendInitialized()).WillRepeatedly(Return(false)); + + // We're simulating a user setting up sync, which would cause the backend to + // kick off initialization, but not download user data types. The sync + // backend will try to download control data types (e.g encryption info), but + // that won't finish for this test as we're simulating cancelling while the + // spinner is showing. + handler_->HandleShowSetupUI(NULL); + + EXPECT_EQ(handler_.get(), + LoginUIServiceFactory::GetForProfile( + profile_.get())->current_login_ui()); + + ExpectSpinnerAndClose(); +} + +// Verifies that the handler correctly transitions from showing the spinner +// to showing a configuration page when sync setup completes successfully. +TEST_F(SyncHandlerTest, + DisplayConfigureWithBackendDisabledAndSyncStartupCompleted) { + EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(true)); + EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable()) + .WillRepeatedly(Return(true)); + EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted()) + .WillRepeatedly(Return(false)); + error_ = GoogleServiceAuthError::AuthErrorNone(); + // Sync backend is stopped initially, and will start up. + EXPECT_CALL(*mock_pss_, IsBackendInitialized()).WillRepeatedly(Return(false)); + SetDefaultExpectationsForConfigPage(); + + handler_->OpenSyncSetup(); + + // We expect a call to SyncSetupOverlay.showSyncSetupPage. + EXPECT_EQ(1U, web_ui_.call_data().size()); + + const content::TestWebUI::CallData& data0 = *web_ui_.call_data()[0]; + EXPECT_EQ("SyncSetupOverlay.showSyncSetupPage", data0.function_name()); + std::string page; + ASSERT_TRUE(data0.arg1()->GetAsString(&page)); + EXPECT_EQ(page, "spinner"); + + Mock::VerifyAndClearExpectations(mock_pss_); + // Now, act as if the ProfileSyncService has started up. + SetDefaultExpectationsForConfigPage(); + EXPECT_CALL(*mock_pss_, IsBackendInitialized()).WillRepeatedly(Return(true)); + error_ = GoogleServiceAuthError::AuthErrorNone(); + EXPECT_CALL(*mock_pss_, GetAuthError()).WillRepeatedly(ReturnRef(error_)); + NotifySyncListeners(); + + // We expect a second call to SyncSetupOverlay.showSyncSetupPage. + EXPECT_EQ(2U, web_ui_.call_data().size()); + const content::TestWebUI::CallData& data1 = *web_ui_.call_data().back(); + EXPECT_EQ("SyncSetupOverlay.showSyncSetupPage", data1.function_name()); + ASSERT_TRUE(data1.arg1()->GetAsString(&page)); + EXPECT_EQ(page, "configure"); + const base::DictionaryValue* dictionary = nullptr; + ASSERT_TRUE(data1.arg2()->GetAsDictionary(&dictionary)); + CheckBool(dictionary, "passphraseFailed", false); + CheckBool(dictionary, "syncAllDataTypes", true); + CheckBool(dictionary, "encryptAllDataAllowed", true); + CheckBool(dictionary, "encryptAllData", false); + CheckBool(dictionary, "usePassphrase", false); +} + +// Verifies the case where the user cancels after the sync backend has +// initialized (meaning it already transitioned from the spinner to a proper +// configuration page, tested by +// DisplayConfigureWithBackendDisabledAndSigninSuccess), but before the user +// before the user has continued on. +TEST_F(SyncHandlerTest, + DisplayConfigureWithBackendDisabledAndCancelAfterSigninSuccess) { + EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(true)); + EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable()) + .WillRepeatedly(Return(true)); + EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted()) + .WillRepeatedly(Return(false)); + error_ = GoogleServiceAuthError::AuthErrorNone(); + EXPECT_CALL(*mock_pss_, IsBackendInitialized()) + .WillOnce(Return(false)) + .WillRepeatedly(Return(true)); + SetDefaultExpectationsForConfigPage(); + handler_->OpenSyncSetup(); + + // It's important to tell sync the user cancelled the setup flow before we + // tell it we're through with the setup progress. + testing::InSequence seq; + EXPECT_CALL(*mock_pss_, RequestStop(ProfileSyncService::CLEAR_DATA)); + EXPECT_CALL(*mock_pss_, SetSetupInProgress(false)); + + handler_->CloseSyncSetup(); + EXPECT_EQ(NULL, + LoginUIServiceFactory::GetForProfile( + profile_.get())->current_login_ui()); +} + +TEST_F(SyncHandlerTest, + DisplayConfigureWithBackendDisabledAndSigninFailed) { + EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(true)); + EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable()) + .WillRepeatedly(Return(true)); + EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted()) + .WillRepeatedly(Return(false)); + error_ = GoogleServiceAuthError::AuthErrorNone(); + EXPECT_CALL(*mock_pss_, IsBackendInitialized()).WillRepeatedly(Return(false)); + + handler_->OpenSyncSetup(); + const content::TestWebUI::CallData& data = *web_ui_.call_data()[0]; + EXPECT_EQ("SyncSetupOverlay.showSyncSetupPage", data.function_name()); + std::string page; + ASSERT_TRUE(data.arg1()->GetAsString(&page)); + EXPECT_EQ(page, "spinner"); + Mock::VerifyAndClearExpectations(mock_pss_); + error_ = GoogleServiceAuthError( + GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS); + EXPECT_CALL(*mock_pss_, GetAuthError()).WillRepeatedly(ReturnRef(error_)); + NotifySyncListeners(); + + // On failure, the dialog will be closed. + EXPECT_EQ(NULL, + LoginUIServiceFactory::GetForProfile( + profile_.get())->current_login_ui()); +} + +#if !defined(OS_CHROMEOS) + +class SyncHandlerNonCrosTest : public SyncHandlerTest { + public: + SyncHandlerNonCrosTest() {} +}; + +TEST_F(SyncHandlerNonCrosTest, HandleGaiaAuthFailure) { + EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable()) + .WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, HasUnrecoverableError()) + .WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted()) + .WillRepeatedly(Return(false)); + // Open the web UI. + handler_->OpenSyncSetup(); + + ASSERT_FALSE(handler_->is_configuring_sync()); +} + +// TODO(kochi): We need equivalent tests for ChromeOS. +TEST_F(SyncHandlerNonCrosTest, UnrecoverableErrorInitializingSync) { + EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable()) + .WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted()) + .WillRepeatedly(Return(false)); + // Open the web UI. + handler_->OpenSyncSetup(); + + ASSERT_FALSE(handler_->is_configuring_sync()); +} + +TEST_F(SyncHandlerNonCrosTest, GaiaErrorInitializingSync) { + EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable()) + .WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted()) + .WillRepeatedly(Return(false)); + // Open the web UI. + handler_->OpenSyncSetup(); + + ASSERT_FALSE(handler_->is_configuring_sync()); +} + +#endif // #if !defined(OS_CHROMEOS) + +TEST_F(SyncHandlerTest, TestSyncEverything) { + std::string args = GetConfiguration( + NULL, SYNC_ALL_DATA, GetAllTypes(), std::string(), ENCRYPT_PASSWORDS); + base::ListValue list_args; + list_args.Append(new base::StringValue(args)); + EXPECT_CALL(*mock_pss_, IsPassphraseRequiredForDecryption()) + .WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, IsPassphraseRequired()) + .WillRepeatedly(Return(false)); + SetupInitializedProfileSyncService(); + EXPECT_CALL(*mock_pss_, OnUserChoseDatatypes(true, _)); + handler_->HandleConfigure(&list_args); + + // Ensure that we navigated to the "done" state since we don't need a + // passphrase. + ExpectDone(); +} + +TEST_F(SyncHandlerTest, TestSyncNothing) { + std::string args = GetConfiguration( + NULL, SYNC_NOTHING, GetAllTypes(), std::string(), ENCRYPT_PASSWORDS); + base::ListValue list_args; + list_args.Append(new base::StringValue(args)); + EXPECT_CALL(*mock_pss_, RequestStop(ProfileSyncService::CLEAR_DATA)); + SetupInitializedProfileSyncService(); + handler_->HandleConfigure(&list_args); + + // We expect a call to SyncSetupOverlay.showSyncSetupPage. + ASSERT_EQ(1U, web_ui_.call_data().size()); + const content::TestWebUI::CallData& data = *web_ui_.call_data()[0]; + EXPECT_EQ("SyncSetupOverlay.showSyncSetupPage", data.function_name()); +} + +TEST_F(SyncHandlerTest, TurnOnEncryptAll) { + std::string args = GetConfiguration( + NULL, SYNC_ALL_DATA, GetAllTypes(), std::string(), ENCRYPT_ALL_DATA); + base::ListValue list_args; + list_args.Append(new base::StringValue(args)); + EXPECT_CALL(*mock_pss_, IsPassphraseRequiredForDecryption()) + .WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, IsPassphraseRequired()) + .WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, IsEncryptEverythingAllowed()) + .WillRepeatedly(Return(true)); + SetupInitializedProfileSyncService(); + EXPECT_CALL(*mock_pss_, EnableEncryptEverything()); + EXPECT_CALL(*mock_pss_, OnUserChoseDatatypes(true, _)); + handler_->HandleConfigure(&list_args); + + // Ensure that we navigated to the "done" state since we don't need a + // passphrase. + ExpectDone(); +} + +TEST_F(SyncHandlerTest, TestPassphraseStillRequired) { + std::string args = GetConfiguration( + NULL, SYNC_ALL_DATA, GetAllTypes(), std::string(), ENCRYPT_PASSWORDS); + base::ListValue list_args; + list_args.Append(new base::StringValue(args)); + EXPECT_CALL(*mock_pss_, IsPassphraseRequiredForDecryption()) + .WillRepeatedly(Return(true)); + EXPECT_CALL(*mock_pss_, IsPassphraseRequired()) + .WillRepeatedly(Return(true)); + EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase()) + .WillRepeatedly(Return(false)); + SetupInitializedProfileSyncService(); + EXPECT_CALL(*mock_pss_, OnUserChoseDatatypes(_, _)); + SetDefaultExpectationsForConfigPage(); + + // We should navigate back to the configure page since we need a passphrase. + handler_->HandleConfigure(&list_args); + + ExpectConfig(); +} + +TEST_F(SyncHandlerTest, SuccessfullySetPassphrase) { + base::DictionaryValue dict; + dict.SetBoolean("isGooglePassphrase", true); + std::string args = GetConfiguration(&dict, + SYNC_ALL_DATA, + GetAllTypes(), + "gaiaPassphrase", + ENCRYPT_PASSWORDS); + base::ListValue list_args; + list_args.Append(new base::StringValue(args)); + // Act as if an encryption passphrase is required the first time, then never + // again after that. + EXPECT_CALL(*mock_pss_, IsPassphraseRequired()).WillOnce(Return(true)); + EXPECT_CALL(*mock_pss_, IsPassphraseRequiredForDecryption()) + .WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase()) + .WillRepeatedly(Return(false)); + SetupInitializedProfileSyncService(); + EXPECT_CALL(*mock_pss_, OnUserChoseDatatypes(_, _)); + EXPECT_CALL(*mock_pss_, SetDecryptionPassphrase("gaiaPassphrase")). + WillOnce(Return(true)); + + handler_->HandleConfigure(&list_args); + // We should navigate to "done" page since we finished configuring. + ExpectDone(); +} + +TEST_F(SyncHandlerTest, SelectCustomEncryption) { + base::DictionaryValue dict; + dict.SetBoolean("isGooglePassphrase", false); + std::string args = GetConfiguration(&dict, + SYNC_ALL_DATA, + GetAllTypes(), + "custom_passphrase", + ENCRYPT_PASSWORDS); + base::ListValue list_args; + list_args.Append(new base::StringValue(args)); + EXPECT_CALL(*mock_pss_, IsPassphraseRequiredForDecryption()) + .WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, IsPassphraseRequired()) + .WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase()) + .WillRepeatedly(Return(false)); + SetupInitializedProfileSyncService(); + EXPECT_CALL(*mock_pss_, OnUserChoseDatatypes(_, _)); + EXPECT_CALL(*mock_pss_, + SetEncryptionPassphrase("custom_passphrase", + ProfileSyncService::EXPLICIT)); + + handler_->HandleConfigure(&list_args); + // We should navigate to "done" page since we finished configuring. + ExpectDone(); +} + +TEST_F(SyncHandlerTest, UnsuccessfullySetPassphrase) { + base::DictionaryValue dict; + dict.SetBoolean("isGooglePassphrase", true); + std::string args = GetConfiguration(&dict, + SYNC_ALL_DATA, + GetAllTypes(), + "invalid_passphrase", + ENCRYPT_PASSWORDS); + base::ListValue list_args; + list_args.Append(new base::StringValue(args)); + EXPECT_CALL(*mock_pss_, IsPassphraseRequiredForDecryption()) + .WillRepeatedly(Return(true)); + EXPECT_CALL(*mock_pss_, IsPassphraseRequired()) + .WillRepeatedly(Return(true)); + EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase()) + .WillRepeatedly(Return(false)); + SetupInitializedProfileSyncService(); + EXPECT_CALL(*mock_pss_, OnUserChoseDatatypes(_, _)); + EXPECT_CALL(*mock_pss_, SetDecryptionPassphrase("invalid_passphrase")). + WillOnce(Return(false)); + + SetDefaultExpectationsForConfigPage(); + // We should navigate back to the configure page since we need a passphrase. + handler_->HandleConfigure(&list_args); + + ExpectConfig(); + + // Make sure we display an error message to the user due to the failed + // passphrase. + const content::TestWebUI::CallData& data = *web_ui_.call_data()[0]; + const base::DictionaryValue* dictionary = nullptr; + ASSERT_TRUE(data.arg2()->GetAsDictionary(&dictionary)); + CheckBool(dictionary, "passphraseFailed", true); +} + +// Walks through each user selectable type, and tries to sync just that single +// data type. +TEST_F(SyncHandlerTest, TestSyncIndividualTypes) { + syncer::ModelTypeSet user_selectable_types = GetAllTypes(); + syncer::ModelTypeSet::Iterator it; + for (it = user_selectable_types.First(); it.Good(); it.Inc()) { + syncer::ModelTypeSet type_to_set; + type_to_set.Put(it.Get()); + std::string args = GetConfiguration(NULL, + CHOOSE_WHAT_TO_SYNC, + type_to_set, + std::string(), + ENCRYPT_PASSWORDS); + base::ListValue list_args; + list_args.Append(new base::StringValue(args)); + EXPECT_CALL(*mock_pss_, IsPassphraseRequiredForDecryption()) + .WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, IsPassphraseRequired()) + .WillRepeatedly(Return(false)); + SetupInitializedProfileSyncService(); + EXPECT_CALL(*mock_pss_, + OnUserChoseDatatypes(false, ModelTypeSetMatches(type_to_set))); + handler_->HandleConfigure(&list_args); + + ExpectDone(); + Mock::VerifyAndClearExpectations(mock_pss_); + web_ui_.ClearTrackedCalls(); + } +} + +TEST_F(SyncHandlerTest, TestSyncAllManually) { + std::string args = GetConfiguration(NULL, + CHOOSE_WHAT_TO_SYNC, + GetAllTypes(), + std::string(), + ENCRYPT_PASSWORDS); + base::ListValue list_args; + list_args.Append(new base::StringValue(args)); + EXPECT_CALL(*mock_pss_, IsPassphraseRequiredForDecryption()) + .WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, IsPassphraseRequired()) + .WillRepeatedly(Return(false)); + SetupInitializedProfileSyncService(); + EXPECT_CALL(*mock_pss_, + OnUserChoseDatatypes(false, ModelTypeSetMatches(GetAllTypes()))); + handler_->HandleConfigure(&list_args); + + ExpectDone(); +} + +TEST_F(SyncHandlerTest, ShowSyncSetup) { + EXPECT_CALL(*mock_pss_, IsPassphraseRequired()) + .WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase()) + .WillRepeatedly(Return(false)); + SetupInitializedProfileSyncService(); + // This should display the sync setup dialog (not login). + SetDefaultExpectationsForConfigPage(); + handler_->OpenSyncSetup(); + + ExpectConfig(); +} + +// We do not display signin on chromeos in the case of auth error. +TEST_F(SyncHandlerTest, ShowSigninOnAuthError) { + // Initialize the system to a signed in state, but with an auth error. + error_ = GoogleServiceAuthError( + GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS); + + SetupInitializedProfileSyncService(); + mock_signin_->SetAuthenticatedAccountInfo(kTestUser, kTestUser); + FakeAuthStatusProvider provider( + SigninErrorControllerFactory::GetForProfile(profile_.get())); + provider.SetAuthError(kTestUser, error_); + EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(true)); + EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable()) + .WillRepeatedly(Return(true)); + EXPECT_CALL(*mock_pss_, IsPassphraseRequired()) + .WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase()) + .WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, IsBackendInitialized()).WillRepeatedly(Return(false)); + +#if defined(OS_CHROMEOS) + // On ChromeOS, auth errors are ignored - instead we just try to start the + // sync backend (which will fail due to the auth error). This should only + // happen if the user manually navigates to chrome://settings/syncSetup - + // clicking on the button in the UI will sign the user out rather than + // displaying a spinner. Should be no visible UI on ChromeOS in this case. + EXPECT_EQ(NULL, LoginUIServiceFactory::GetForProfile( + profile_.get())->current_login_ui()); +#else + + // On ChromeOS, this should display the spinner while we try to startup the + // sync backend, and on desktop this displays the login dialog. + handler_->OpenSyncSetup(); + + // Sync setup is closed when re-auth is in progress. + EXPECT_EQ(NULL, + LoginUIServiceFactory::GetForProfile( + profile_.get())->current_login_ui()); + + ASSERT_FALSE(handler_->is_configuring_sync()); +#endif +} + +TEST_F(SyncHandlerTest, ShowSetupSyncEverything) { + EXPECT_CALL(*mock_pss_, IsPassphraseRequired()) + .WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase()) + .WillRepeatedly(Return(false)); + SetupInitializedProfileSyncService(); + SetDefaultExpectationsForConfigPage(); + // This should display the sync setup dialog (not login). + handler_->OpenSyncSetup(); + + ExpectConfig(); + const content::TestWebUI::CallData& data = *web_ui_.call_data()[0]; + const base::DictionaryValue* dictionary = nullptr; + ASSERT_TRUE(data.arg2()->GetAsDictionary(&dictionary)); + CheckBool(dictionary, "syncAllDataTypes", true); + CheckBool(dictionary, "appsRegistered", true); + CheckBool(dictionary, "autofillRegistered", true); + CheckBool(dictionary, "bookmarksRegistered", true); + CheckBool(dictionary, "extensionsRegistered", true); + CheckBool(dictionary, "passwordsRegistered", true); + CheckBool(dictionary, "preferencesRegistered", true); + CheckBool(dictionary, "wifiCredentialsRegistered", true); + CheckBool(dictionary, "tabsRegistered", true); + CheckBool(dictionary, "themesRegistered", true); + CheckBool(dictionary, "typedUrlsRegistered", true); + CheckBool(dictionary, "showPassphrase", false); + CheckBool(dictionary, "usePassphrase", false); + CheckBool(dictionary, "passphraseFailed", false); + CheckBool(dictionary, "encryptAllData", false); + CheckConfigDataTypeArguments(dictionary, SYNC_ALL_DATA, GetAllTypes()); +} + +TEST_F(SyncHandlerTest, ShowSetupManuallySyncAll) { + EXPECT_CALL(*mock_pss_, IsPassphraseRequired()) + .WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase()) + .WillRepeatedly(Return(false)); + SetupInitializedProfileSyncService(); + sync_driver::SyncPrefs sync_prefs(profile_->GetPrefs()); + sync_prefs.SetKeepEverythingSynced(false); + SetDefaultExpectationsForConfigPage(); + // This should display the sync setup dialog (not login). + handler_->OpenSyncSetup(); + + ExpectConfig(); + const content::TestWebUI::CallData& data = *web_ui_.call_data()[0]; + const base::DictionaryValue* dictionary = nullptr; + ASSERT_TRUE(data.arg2()->GetAsDictionary(&dictionary)); + CheckConfigDataTypeArguments(dictionary, CHOOSE_WHAT_TO_SYNC, GetAllTypes()); +} + +TEST_F(SyncHandlerTest, ShowSetupSyncForAllTypesIndividually) { + syncer::ModelTypeSet user_selectable_types = GetAllTypes(); + syncer::ModelTypeSet::Iterator it; + for (it = user_selectable_types.First(); it.Good(); it.Inc()) { + EXPECT_CALL(*mock_pss_, IsPassphraseRequired()) + .WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase()) + .WillRepeatedly(Return(false)); + SetupInitializedProfileSyncService(); + sync_driver::SyncPrefs sync_prefs(profile_->GetPrefs()); + sync_prefs.SetKeepEverythingSynced(false); + SetDefaultExpectationsForConfigPage(); + syncer::ModelTypeSet types; + types.Put(it.Get()); + EXPECT_CALL(*mock_pss_, GetPreferredDataTypes()). + WillRepeatedly(Return(types)); + + // This should display the sync setup dialog (not login). + handler_->OpenSyncSetup(); + + ExpectConfig(); + // Close the config overlay. + LoginUIServiceFactory::GetForProfile(profile_.get())->LoginUIClosed( + handler_.get()); + const content::TestWebUI::CallData& data = *web_ui_.call_data()[0]; + const base::DictionaryValue* dictionary = nullptr; + ASSERT_TRUE(data.arg2()->GetAsDictionary(&dictionary)); + CheckConfigDataTypeArguments(dictionary, CHOOSE_WHAT_TO_SYNC, types); + Mock::VerifyAndClearExpectations(mock_pss_); + // Clean up so we can loop back to display the dialog again. + web_ui_.ClearTrackedCalls(); + } +} + +TEST_F(SyncHandlerTest, ShowSetupGaiaPassphraseRequired) { + EXPECT_CALL(*mock_pss_, IsPassphraseRequired()) + .WillRepeatedly(Return(true)); + EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase()) + .WillRepeatedly(Return(false)); + SetupInitializedProfileSyncService(); + SetDefaultExpectationsForConfigPage(); + + // This should display the sync setup dialog (not login). + handler_->OpenSyncSetup(); + + ExpectConfig(); + const content::TestWebUI::CallData& data = *web_ui_.call_data()[0]; + const base::DictionaryValue* dictionary = nullptr; + ASSERT_TRUE(data.arg2()->GetAsDictionary(&dictionary)); + CheckBool(dictionary, "showPassphrase", true); + CheckBool(dictionary, "usePassphrase", false); + CheckBool(dictionary, "passphraseFailed", false); +} + +TEST_F(SyncHandlerTest, ShowSetupCustomPassphraseRequired) { + EXPECT_CALL(*mock_pss_, IsPassphraseRequired()) + .WillRepeatedly(Return(true)); + EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase()) + .WillRepeatedly(Return(true)); + EXPECT_CALL(*mock_pss_, GetPassphraseType()) + .WillRepeatedly(Return(syncer::CUSTOM_PASSPHRASE)); + SetupInitializedProfileSyncService(); + SetDefaultExpectationsForConfigPage(); + + // This should display the sync setup dialog (not login). + handler_->OpenSyncSetup(); + + ExpectConfig(); + const content::TestWebUI::CallData& data = *web_ui_.call_data()[0]; + const base::DictionaryValue* dictionary = nullptr; + ASSERT_TRUE(data.arg2()->GetAsDictionary(&dictionary)); + CheckBool(dictionary, "showPassphrase", true); + CheckBool(dictionary, "usePassphrase", true); + CheckBool(dictionary, "passphraseFailed", false); +} + +TEST_F(SyncHandlerTest, ShowSetupEncryptAll) { + EXPECT_CALL(*mock_pss_, IsPassphraseRequired()) + .WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase()) + .WillRepeatedly(Return(false)); + SetupInitializedProfileSyncService(); + SetDefaultExpectationsForConfigPage(); + EXPECT_CALL(*mock_pss_, IsEncryptEverythingEnabled()) + .WillRepeatedly(Return(true)); + + // This should display the sync setup dialog (not login). + handler_->OpenSyncSetup(); + + ExpectConfig(); + const content::TestWebUI::CallData& data = *web_ui_.call_data()[0]; + const base::DictionaryValue* dictionary = nullptr; + ASSERT_TRUE(data.arg2()->GetAsDictionary(&dictionary)); + CheckBool(dictionary, "encryptAllData", true); +} + +TEST_F(SyncHandlerTest, ShowSetupEncryptAllDisallowed) { + EXPECT_CALL(*mock_pss_, IsPassphraseRequired()) + .WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase()) + .WillRepeatedly(Return(false)); + SetupInitializedProfileSyncService(); + SetDefaultExpectationsForConfigPage(); + EXPECT_CALL(*mock_pss_, IsEncryptEverythingAllowed()) + .WillRepeatedly(Return(false)); + + // This should display the sync setup dialog (not login). + handler_->OpenSyncSetup(); + + ExpectConfig(); + const content::TestWebUI::CallData& data = *web_ui_.call_data()[0]; + const base::DictionaryValue* dictionary = nullptr; + ASSERT_TRUE(data.arg2()->GetAsDictionary(&dictionary)); + CheckBool(dictionary, "encryptAllData", false); + CheckBool(dictionary, "encryptAllDataAllowed", false); +} + +TEST_F(SyncHandlerTest, TurnOnEncryptAllDisallowed) { + std::string args = GetConfiguration( + NULL, SYNC_ALL_DATA, GetAllTypes(), std::string(), ENCRYPT_ALL_DATA); + base::ListValue list_args; + list_args.Append(new base::StringValue(args)); + EXPECT_CALL(*mock_pss_, IsPassphraseRequiredForDecryption()) + .WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, IsPassphraseRequired()) + .WillRepeatedly(Return(false)); + SetupInitializedProfileSyncService(); + EXPECT_CALL(*mock_pss_, IsEncryptEverythingAllowed()) + .WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, EnableEncryptEverything()).Times(0); + EXPECT_CALL(*mock_pss_, OnUserChoseDatatypes(true, _)); + handler_->HandleConfigure(&list_args); + + // Ensure that we navigated to the "done" state since we don't need a + // passphrase. + ExpectDone(); +} + +} // namespace settings
diff --git a/chrome/browser/upgrade_detector.h b/chrome/browser/upgrade_detector.h index 28dbdb6..75eff08 100644 --- a/chrome/browser/upgrade_detector.h +++ b/chrome/browser/upgrade_detector.h
@@ -71,7 +71,7 @@ // Retrieves the right icon ID based on the degree of severity (see // UpgradeNotificationAnnoyanceLevel, each level has an an accompanying icon - // to go with it) to display within the wrench menu. + // to go with it) to display within the app menu. int GetIconResourceID(); UpgradeNotificationAnnoyanceLevel upgrade_notification_stage() const {
diff --git a/chrome/chrome_browser_ui.gypi b/chrome/chrome_browser_ui.gypi index 2e86dd7..9fafe858 100644 --- a/chrome/chrome_browser_ui.gypi +++ b/chrome/chrome_browser_ui.gypi
@@ -1119,29 +1119,27 @@ 'browser/ui/cocoa/panels/panel_window_controller_cocoa.mm', 'browser/ui/cocoa/passwords/account_avatar_fetcher_manager.h', 'browser/ui/cocoa/passwords/account_avatar_fetcher_manager.mm', + 'browser/ui/cocoa/passwords/account_chooser_view_controller.h', + 'browser/ui/cocoa/passwords/account_chooser_view_controller.mm', + 'browser/ui/cocoa/passwords/auto_signin_view_controller.h', + 'browser/ui/cocoa/passwords/auto_signin_view_controller.mm', + 'browser/ui/cocoa/passwords/base_passwords_content_view_controller.h', + 'browser/ui/cocoa/passwords/base_passwords_content_view_controller.mm', + 'browser/ui/cocoa/passwords/confirmation_password_saved_view_controller.h', + 'browser/ui/cocoa/passwords/confirmation_password_saved_view_controller.mm', 'browser/ui/cocoa/passwords/credential_item_view.h', 'browser/ui/cocoa/passwords/credential_item_view.mm', - 'browser/ui/cocoa/passwords/manage_credential_item_view_controller.h', - 'browser/ui/cocoa/passwords/manage_credential_item_view_controller.mm', - 'browser/ui/cocoa/passwords/manage_password_item_view_controller.h', - 'browser/ui/cocoa/passwords/manage_password_item_view_controller.mm', - 'browser/ui/cocoa/passwords/manage_passwords_bubble_account_chooser_view_controller.h', - 'browser/ui/cocoa/passwords/manage_passwords_bubble_account_chooser_view_controller.mm', - 'browser/ui/cocoa/passwords/manage_passwords_bubble_auto_signin_view_controller.h', - 'browser/ui/cocoa/passwords/manage_passwords_bubble_auto_signin_view_controller.mm', - 'browser/ui/cocoa/passwords/manage_passwords_bubble_cocoa.h', - 'browser/ui/cocoa/passwords/manage_passwords_bubble_cocoa.mm', - 'browser/ui/cocoa/passwords/manage_passwords_bubble_confirmation_view_controller.h', - 'browser/ui/cocoa/passwords/manage_passwords_bubble_confirmation_view_controller.mm', - 'browser/ui/cocoa/passwords/manage_passwords_bubble_content_view_controller.h', - 'browser/ui/cocoa/passwords/manage_passwords_bubble_content_view_controller.mm', - 'browser/ui/cocoa/passwords/manage_passwords_bubble_controller.h', - 'browser/ui/cocoa/passwords/manage_passwords_bubble_controller.mm', - 'browser/ui/cocoa/passwords/manage_passwords_bubble_manage_view_controller.h', - 'browser/ui/cocoa/passwords/manage_passwords_bubble_manage_view_controller.mm', - 'browser/ui/cocoa/passwords/manage_passwords_bubble_pending_view_controller.h', - 'browser/ui/cocoa/passwords/manage_passwords_bubble_pending_view_controller.mm', + 'browser/ui/cocoa/passwords/manage_passwords_view_controller.h', + 'browser/ui/cocoa/passwords/manage_passwords_view_controller.mm', 'browser/ui/cocoa/passwords/password_item_views.h', + 'browser/ui/cocoa/passwords/passwords_bubble_cocoa.h', + 'browser/ui/cocoa/passwords/passwords_bubble_cocoa.mm', + 'browser/ui/cocoa/passwords/passwords_bubble_controller.h', + 'browser/ui/cocoa/passwords/passwords_bubble_controller.mm', + 'browser/ui/cocoa/passwords/passwords_list_view_controller.h', + 'browser/ui/cocoa/passwords/passwords_list_view_controller.mm', + 'browser/ui/cocoa/passwords/pending_password_view_controller.h', + 'browser/ui/cocoa/passwords/pending_password_view_controller.mm', 'browser/ui/cocoa/presentation_mode_controller.h', 'browser/ui/cocoa/presentation_mode_controller.mm', 'browser/ui/cocoa/profiles/avatar_base_controller.h', @@ -1716,6 +1714,8 @@ 'browser/ui/task_manager/task_manager_table_model.h', 'browser/ui/toolbar/app_menu_badge_controller.cc', 'browser/ui/toolbar/app_menu_badge_controller.h', + 'browser/ui/toolbar/app_menu_icon_painter.cc', + 'browser/ui/toolbar/app_menu_icon_painter.h', 'browser/ui/toolbar/app_menu_model.cc', 'browser/ui/toolbar/app_menu_model.h', 'browser/ui/toolbar/back_forward_menu_model.cc', @@ -1735,8 +1735,6 @@ 'browser/ui/toolbar/toolbar_actions_bar_bubble_delegate.h', 'browser/ui/toolbar/toolbar_actions_bar_delegate.h', 'browser/ui/toolbar/toolbar_actions_bar_observer.h', - 'browser/ui/toolbar/wrench_icon_painter.cc', - 'browser/ui/toolbar/wrench_icon_painter.h', 'browser/ui/translate/translate_bubble_factory.cc', 'browser/ui/translate/translate_bubble_factory.h', 'browser/ui/uma_browsing_activity_observer.cc', @@ -1953,6 +1951,8 @@ 'browser/ui/webui/settings/settings_default_browser_handler.h', 'browser/ui/webui/settings/settings_startup_pages_handler.cc', 'browser/ui/webui/settings/settings_startup_pages_handler.h', + 'browser/ui/webui/settings/sync_handler.cc', + 'browser/ui/webui/settings/sync_handler.h', 'browser/ui/webui/signin/inline_login_handler.cc', 'browser/ui/webui/signin/inline_login_handler.h', 'browser/ui/webui/signin/inline_login_ui.cc',
diff --git a/chrome/chrome_resources.gyp b/chrome/chrome_resources.gyp index 492536ca..6edb8194 100644 --- a/chrome/chrome_resources.gyp +++ b/chrome/chrome_resources.gyp
@@ -301,13 +301,24 @@ 'target_name': 'make_chrome_ui_string_overrider_factory', 'type': 'none', 'hard_dependency': 1, - 'dependencies': [ 'chrome_strings', ], + 'dependencies': [ + 'chrome_strings', + '../components/components_strings.gyp:components_strings', + ], 'actions': [ { 'action_name': 'generate_ui_string_overrider', 'inputs': [ '../components/variations/service/generate_ui_string_overrider.py', - '<(grit_out_dir)/grit/generated_resources.h' + '<(grit_out_dir)/grit/chromium_strings.h', + '<(grit_out_dir)/grit/generated_resources.h', + '<(grit_out_dir)/grit/google_chrome_strings.h', + '<(grit_out_dir)/grit/settings_chromium_strings.h', + '<(grit_out_dir)/grit/settings_google_chrome_strings.h', + '<(grit_out_dir)/grit/settings_strings.h', + '<(SHARED_INTERMEDIATE_DIR)/components/strings/grit/components_chromium_strings.h', + '<(SHARED_INTERMEDIATE_DIR)/components/strings/grit/components_google_chrome_strings.h', + '<(SHARED_INTERMEDIATE_DIR)/components/strings/grit/components_strings.h' ], 'outputs': [ '<(SHARED_INTERMEDIATE_DIR)/chrome/browser/metrics/variations/ui_string_overrider_factory.cc', @@ -320,7 +331,15 @@ '-o', '<(SHARED_INTERMEDIATE_DIR)', '-S', 'chrome/browser/metrics/variations/ui_string_overrider_factory.cc', '-H', 'chrome/browser/metrics/variations/ui_string_overrider_factory.h', - '<(grit_out_dir)/grit/generated_resources.h', + '<(grit_out_dir)/grit/chromium_strings.h', + '<(grit_out_dir)/grit/generated_resources.h', + '<(grit_out_dir)/grit/google_chrome_strings.h', + '<(grit_out_dir)/grit/settings_chromium_strings.h', + '<(grit_out_dir)/grit/settings_google_chrome_strings.h', + '<(grit_out_dir)/grit/settings_strings.h', + '<(SHARED_INTERMEDIATE_DIR)/components/strings/grit/components_chromium_strings.h', + '<(SHARED_INTERMEDIATE_DIR)/components/strings/grit/components_google_chrome_strings.h', + '<(SHARED_INTERMEDIATE_DIR)/components/strings/grit/components_strings.h' ], 'message': 'Generating generated resources map.', }
diff --git a/chrome/chrome_tests.gypi b/chrome/chrome_tests.gypi index 37f6b5c3..686876c 100644 --- a/chrome/chrome_tests.gypi +++ b/chrome/chrome_tests.gypi
@@ -486,7 +486,7 @@ 'browser/ui/cocoa/omnibox/omnibox_view_mac_browsertest.mm', 'browser/ui/cocoa/one_click_signin_bubble_controller_browsertest.mm', 'browser/ui/cocoa/one_click_signin_dialog_controller_browsertest.mm', - 'browser/ui/cocoa/passwords/manage_passwords_bubble_browsertest.mm', + 'browser/ui/cocoa/passwords/passwords_bubble_browsertest.mm', 'browser/ui/cocoa/profiles/profile_signin_confirmation_view_controller_browsertest.mm', 'browser/ui/cocoa/ssl_client_certificate_selector_cocoa_browsertest.mm', 'browser/ui/cocoa/view_id_util_browsertest.mm',
diff --git a/chrome/chrome_tests_unit.gypi b/chrome/chrome_tests_unit.gypi index d01399b..0219be77 100644 --- a/chrome/chrome_tests_unit.gypi +++ b/chrome/chrome_tests_unit.gypi
@@ -392,17 +392,16 @@ 'browser/ui/cocoa/omnibox/omnibox_view_mac_unittest.mm', 'browser/ui/cocoa/one_click_signin_bubble_controller_unittest.mm', 'browser/ui/cocoa/panels/panel_cocoa_unittest.mm', + 'browser/ui/cocoa/passwords/account_chooser_view_controller_unittest.mm', + 'browser/ui/cocoa/passwords/base_passwords_controller_test.h', + 'browser/ui/cocoa/passwords/base_passwords_controller_test.mm', + 'browser/ui/cocoa/passwords/confirmation_password_saved_view_controller_unittest.mm', 'browser/ui/cocoa/passwords/credential_item_view_unittest.mm', - 'browser/ui/cocoa/passwords/manage_credential_item_view_controller_unittest.mm', - 'browser/ui/cocoa/passwords/manage_password_item_view_controller_unittest.mm', - 'browser/ui/cocoa/passwords/manage_passwords_bubble_account_chooser_view_controller_unittest.mm', - 'browser/ui/cocoa/passwords/manage_passwords_bubble_cocoa_unittest.mm', - 'browser/ui/cocoa/passwords/manage_passwords_bubble_confirmation_view_controller_unittest.mm', - 'browser/ui/cocoa/passwords/manage_passwords_bubble_controller_unittest.mm', - 'browser/ui/cocoa/passwords/manage_passwords_bubble_manage_view_controller_unittest.mm', - 'browser/ui/cocoa/passwords/manage_passwords_bubble_pending_view_controller_unittest.mm', - 'browser/ui/cocoa/passwords/manage_passwords_controller_test.h', - 'browser/ui/cocoa/passwords/manage_passwords_controller_test.mm', + 'browser/ui/cocoa/passwords/manage_passwords_view_controller_unittest.mm', + 'browser/ui/cocoa/passwords/passwords_bubble_cocoa_unittest.mm', + 'browser/ui/cocoa/passwords/passwords_bubble_controller_unittest.mm', + 'browser/ui/cocoa/passwords/passwords_list_view_controller_unittest.mm', + 'browser/ui/cocoa/passwords/pending_password_view_controller_unittest.mm', 'browser/ui/cocoa/profiles/avatar_button_controller_unittest.mm', 'browser/ui/cocoa/profiles/avatar_button_unittest.mm', 'browser/ui/cocoa/profiles/avatar_icon_controller_unittest.mm', @@ -693,8 +692,11 @@ 'browser/extensions/extension_prefs_unittest.h', 'browser/extensions/extension_protocols_unittest.cc', 'browser/extensions/extension_reenabler_unittest.cc', + 'browser/extensions/extension_service_sync_unittest.cc', 'browser/extensions/extension_service_test_base.cc', 'browser/extensions/extension_service_test_base.h', + 'browser/extensions/extension_service_test_with_install.cc', + 'browser/extensions/extension_service_test_with_install.h', 'browser/extensions/extension_service_unittest.cc', 'browser/extensions/extension_special_storage_policy_unittest.cc', 'browser/extensions/extension_sync_data_unittest.cc', @@ -943,9 +945,9 @@ # Used by Full Safe Browsing (safe_browsing==1) and Mobile Safe # Browsing (==2) modes. 'chrome_unit_tests_shared_safe_browsing_sources': [ - 'browser/safe_browsing/threat_details_unittest.cc', 'browser/safe_browsing/ping_manager_unittest.cc', 'browser/safe_browsing/safe_browsing_blocking_page_unittest.cc', + 'browser/safe_browsing/threat_details_unittest.cc', 'browser/safe_browsing/ui_manager_unittest.cc', ], 'chrome_unit_tests_mobile_safe_browsing_sources': [ @@ -1218,8 +1220,8 @@ 'browser/chromeos/input_method/input_method_util_unittest.cc', 'browser/chromeos/locale_change_guard_unittest.cc', 'browser/chromeos/login/auth/cryptohome_authenticator_unittest.cc', - 'browser/chromeos/login/easy_unlock/easy_unlock_tpm_key_manager_unittest.cc', 'browser/chromeos/login/easy_unlock/easy_unlock_challenge_wrapper_unittest.cc', + 'browser/chromeos/login/easy_unlock/easy_unlock_tpm_key_manager_unittest.cc', 'browser/chromeos/login/error_screens_histogram_helper_unittest.cc', 'browser/chromeos/login/existing_user_controller_auto_login_unittest.cc', 'browser/chromeos/login/hwid_checker_unittest.cc', @@ -1548,6 +1550,8 @@ 'browser/ui/tabs/tab_strip_model_unittest.cc', 'browser/ui/tabs/test_tab_strip_model_delegate.cc', 'browser/ui/tabs/test_tab_strip_model_delegate.h', + 'browser/ui/toolbar/app_menu_icon_painter_unittest.cc', + 'browser/ui/toolbar/app_menu_model_unittest.cc', 'browser/ui/toolbar/back_forward_menu_model_unittest.cc', 'browser/ui/toolbar/encoding_menu_controller_unittest.cc', 'browser/ui/toolbar/mock_component_toolbar_actions_factory.cc', @@ -1563,8 +1567,6 @@ 'browser/ui/toolbar/toolbar_actions_bar_unittest.h', 'browser/ui/toolbar/toolbar_actions_model_unittest.cc', 'browser/ui/toolbar/toolbar_model_unittest.cc', - 'browser/ui/toolbar/wrench_icon_painter_unittest.cc', - 'browser/ui/toolbar/wrench_menu_model_unittest.cc', 'browser/ui/website_settings/permission_bubble_manager_unittest.cc', 'browser/ui/website_settings/permission_menu_model_unittest.cc', 'browser/ui/webui/downloads_util_unittest.cc', @@ -1574,6 +1576,7 @@ 'browser/ui/webui/options/language_options_handler_unittest.cc', 'browser/ui/webui/options/pepper_flash_content_settings_utils_unittest.cc', 'browser/ui/webui/options/sync_setup_handler_unittest.cc', + 'browser/ui/webui/settings/sync_handler_unittest.cc', 'browser/ui/webui/signin/login_ui_service_unittest.cc', 'browser/ui/webui/web_dialog_web_contents_delegate_unittest.cc', 'browser/ui/window_sizer/window_sizer_common_unittest.cc', @@ -2277,12 +2280,6 @@ 'dependencies!': [ '../third_party/libaddressinput/libaddressinput.gyp:libaddressinput', ], - 'sources!': [ - 'common/spellcheck_common_unittest.cc', - 'renderer/spellchecker/spellcheck_multilingual_unittest.cc', - 'renderer/spellchecker/spellcheck_provider_hunspell_unittest.cc', - 'renderer/spellchecker/spellcheck_unittest.cc', - ], 'ldflags': [ # Some android targets still depend on --gc-sections to link. # TODO: remove --gc-sections for Debug builds (crbug.com/159847). @@ -2314,6 +2311,14 @@ ['OS!="mac" and OS!="ios"', { 'dependencies': [ '../third_party/hunspell/hunspell.gyp:hunspell' ], }], + ['OS=="android"', { + 'sources!': [ + 'common/spellcheck_common_unittest.cc', + 'renderer/spellchecker/spellcheck_multilingual_unittest.cc', + 'renderer/spellchecker/spellcheck_provider_hunspell_unittest.cc', + 'renderer/spellchecker/spellcheck_unittest.cc', + ], + }] ], }], ['enable_one_click_signin==1', {
diff --git a/chrome/installer/util/installer_state.cc b/chrome/installer/util/installer_state.cc index 37e6abc..2ca6119d 100644 --- a/chrome/installer/util/installer_state.cc +++ b/chrome/installer/util/installer_state.cc
@@ -574,9 +574,8 @@ void InstallerState::AddComDllList( std::vector<base::FilePath>* com_dll_list) const { - std::for_each(products_.begin(), products_.end(), - std::bind2nd(std::mem_fun(&Product::AddComDllList), - com_dll_list)); + for (auto* product : products_) + product->AddComDllList(com_dll_list); } void InstallerState::UpdateStage(installer::InstallerStage stage) const {
diff --git a/chrome/renderer/loadtimes_extension_bindings.cc b/chrome/renderer/loadtimes_extension_bindings.cc index 036c980..692b8086 100644 --- a/chrome/renderer/loadtimes_extension_bindings.cc +++ b/chrome/renderer/loadtimes_extension_bindings.cc
@@ -99,71 +99,73 @@ static void GetLoadTimes(const v8::FunctionCallbackInfo<v8::Value>& args) { WebLocalFrame* frame = WebLocalFrame::frameForCurrentContext(); - if (frame) { - WebDataSource* data_source = frame->dataSource(); - if (data_source) { - DocumentState* document_state = - DocumentState::FromDataSource(data_source); - v8::Isolate* isolate = args.GetIsolate(); - v8::Local<v8::Object> load_times = v8::Object::New(isolate); - load_times->Set( - v8::String::NewFromUtf8(isolate, "requestTime"), - v8::Number::New(isolate, - document_state->request_time().ToDoubleT())); - load_times->Set( - v8::String::NewFromUtf8(isolate, "startLoadTime"), - v8::Number::New(isolate, - document_state->start_load_time().ToDoubleT())); - load_times->Set( - v8::String::NewFromUtf8(isolate, "commitLoadTime"), - v8::Number::New(isolate, - document_state->commit_load_time().ToDoubleT())); - load_times->Set( - v8::String::NewFromUtf8(isolate, "finishDocumentLoadTime"), - v8::Number::New( - isolate, - document_state->finish_document_load_time().ToDoubleT())); - load_times->Set( - v8::String::NewFromUtf8(isolate, "finishLoadTime"), - v8::Number::New(isolate, - document_state->finish_load_time().ToDoubleT())); - load_times->Set( - v8::String::NewFromUtf8(isolate, "firstPaintTime"), - v8::Number::New(isolate, - document_state->first_paint_time().ToDoubleT())); - load_times->Set( - v8::String::NewFromUtf8(isolate, "firstPaintAfterLoadTime"), - v8::Number::New( - isolate, - document_state->first_paint_after_load_time().ToDoubleT())); - load_times->Set( - v8::String::NewFromUtf8(isolate, "navigationType"), - v8::String::NewFromUtf8( - isolate, GetNavigationType(data_source->navigationType()))); - load_times->Set( - v8::String::NewFromUtf8(isolate, "wasFetchedViaSpdy"), - v8::Boolean::New(isolate, document_state->was_fetched_via_spdy())); - load_times->Set( - v8::String::NewFromUtf8(isolate, "wasNpnNegotiated"), - v8::Boolean::New(isolate, document_state->was_npn_negotiated())); - load_times->Set( - v8::String::NewFromUtf8(isolate, "npnNegotiatedProtocol"), - v8::String::NewFromUtf8( - isolate, document_state->npn_negotiated_protocol().c_str())); - load_times->Set( - v8::String::NewFromUtf8(isolate, "wasAlternateProtocolAvailable"), - v8::Boolean::New( - isolate, document_state->was_alternate_protocol_available())); - load_times->Set(v8::String::NewFromUtf8(isolate, "connectionInfo"), - v8::String::NewFromUtf8( - isolate, - net::HttpResponseInfo::ConnectionInfoToString( - document_state->connection_info()).c_str())); - args.GetReturnValue().Set(load_times); - return; - } + if (!frame) { + args.GetReturnValue().SetNull(); + return; } - args.GetReturnValue().SetNull(); + WebDataSource* data_source = frame->dataSource(); + if (!data_source) { + args.GetReturnValue().SetNull(); + return; + } + DocumentState* document_state = DocumentState::FromDataSource(data_source); + if (!document_state) { + args.GetReturnValue().SetNull(); + return; + } + double request_time = document_state->request_time().ToDoubleT(); + double start_load_time = document_state->start_load_time().ToDoubleT(); + double commit_load_time = document_state->commit_load_time().ToDoubleT(); + double finish_document_load_time = + document_state->finish_document_load_time().ToDoubleT(); + double finish_load_time = document_state->finish_load_time().ToDoubleT(); + double first_paint_time = document_state->first_paint_time().ToDoubleT(); + double first_paint_after_load_time = + document_state->first_paint_after_load_time().ToDoubleT(); + std::string navigation_type = + GetNavigationType(data_source->navigationType()); + bool was_fetched_via_spdy = document_state->was_fetched_via_spdy(); + bool was_npn_negotiated = document_state->was_npn_negotiated(); + std::string npn_negotiated_protocol = + document_state->npn_negotiated_protocol(); + bool was_alternate_protocol_available = + document_state->was_alternate_protocol_available(); + std::string connection_info = net::HttpResponseInfo::ConnectionInfoToString( + document_state->connection_info()); + // Important: |frame|, |data_source| and |document_state| should not be + // referred to below this line, as JS setters below can invalidate these + // pointers. + v8::Isolate* isolate = args.GetIsolate(); + v8::Local<v8::Object> load_times = v8::Object::New(isolate); + load_times->Set(v8::String::NewFromUtf8(isolate, "requestTime"), + v8::Number::New(isolate, request_time)); + load_times->Set(v8::String::NewFromUtf8(isolate, "startLoadTime"), + v8::Number::New(isolate, start_load_time)); + load_times->Set(v8::String::NewFromUtf8(isolate, "commitLoadTime"), + v8::Number::New(isolate, commit_load_time)); + load_times->Set(v8::String::NewFromUtf8(isolate, "finishDocumentLoadTime"), + v8::Number::New(isolate, finish_document_load_time)); + load_times->Set(v8::String::NewFromUtf8(isolate, "finishLoadTime"), + v8::Number::New(isolate, finish_load_time)); + load_times->Set(v8::String::NewFromUtf8(isolate, "firstPaintTime"), + v8::Number::New(isolate, first_paint_time)); + load_times->Set(v8::String::NewFromUtf8(isolate, "firstPaintAfterLoadTime"), + v8::Number::New(isolate, first_paint_after_load_time)); + load_times->Set(v8::String::NewFromUtf8(isolate, "navigationType"), + v8::String::NewFromUtf8(isolate, navigation_type.c_str())); + load_times->Set(v8::String::NewFromUtf8(isolate, "wasFetchedViaSpdy"), + v8::Boolean::New(isolate, was_fetched_via_spdy)); + load_times->Set(v8::String::NewFromUtf8(isolate, "wasNpnNegotiated"), + v8::Boolean::New(isolate, was_npn_negotiated)); + load_times->Set( + v8::String::NewFromUtf8(isolate, "npnNegotiatedProtocol"), + v8::String::NewFromUtf8(isolate, npn_negotiated_protocol.c_str())); + load_times->Set( + v8::String::NewFromUtf8(isolate, "wasAlternateProtocolAvailable"), + v8::Boolean::New(isolate, was_alternate_protocol_available)); + load_times->Set(v8::String::NewFromUtf8(isolate, "connectionInfo"), + v8::String::NewFromUtf8(isolate, connection_info.c_str())); + args.GetReturnValue().Set(load_times); } static void GetCSI(const v8::FunctionCallbackInfo<v8::Value>& args) {
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index ba1b137..6c98f0b 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -1455,696 +1455,704 @@ ] } } +} - js2gtest("unit_tests_js") { - test_type = "unit" - sources = rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_gtestjs_sources, +js2gtest("unit_tests_js") { + test_type = "unit" + sources = rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_gtestjs_sources, + ".", + "//chrome") + extra_js_files = + rebase_path(chrome_tests_unit_gypi_values.chrome_unit_tests_js_sources, + ".", + "//chrome") + if (is_chromeos) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_chromeos_gtestjs_sources, ".", "//chrome") - extra_js_files = - rebase_path(chrome_tests_unit_gypi_values.chrome_unit_tests_js_sources, - ".", - "//chrome") - if (is_chromeos) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_chromeos_gtestjs_sources, - ".", - "//chrome") - extra_js_files += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_chromeos_js_sources, - ".", - "//chrome") - } + extra_js_files += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_chromeos_js_sources, + ".", + "//chrome") + } +} + +# TODO(GYP): Delete this after we've converted everything to GN. +# The _run targets exist only for compatibility w/ GYP. +group("unit_tests_run") { + testonly = true + deps = [ + ":unit_tests", + ] +} + +test("unit_tests") { + sources = rebase_path(chrome_tests_unit_gypi_values.chrome_unit_tests_sources, + ".", + "//chrome") + + configs += [ "//build/config:precompiled_headers" ] + + data = [ + "data/", + "//base/test/data/", + "//chrome/third_party/mock4js/", + "//components/test/data/", + "//extensions/test/data/", + "//google_apis/test/data/", + "//net/data/", + "//net/tools/testserver/", + "//third_party/accessibility-audit/axs_testing.js", + "//third_party/hunspell_dictionaries/", + "//third_party/pyftpdlib/", + "//third_party/pywebsocket/", + "//third_party/tlslite/", + "//third_party/zlib/google/test/data/", + "//tools/metrics/histograms/histograms.xml", + "$root_out_dir/pyproto/google/", + "$root_out_dir/test_data/chrome/browser/resources/google_now/", + "$root_out_dir/test_data/chrome/browser/resources/print_preview/", + "$root_out_dir/test_data/chrome/renderer/resources/extensions/", + "$root_out_dir/test_data/ui/webui/", + "$root_out_dir/resources.pak", + ] + if (is_android || is_linux || is_win) { + data += [ + "$root_out_dir/chrome_100_percent.pak", + "$root_out_dir/locales/en-US.pak", + ] + } + if (is_linux || is_win) { + data += [ "$root_out_dir/chrome_material_100_percent.pak" ] } - # TODO(GYP): Delete this after we've converted everything to GN. - # The _run targets exist only for compatibility w/ GYP. - group("unit_tests_run") { - testonly = true - deps = [ - ":unit_tests", + defines = [] + + deps = [ + # NOTE: New depndencies should generally be added in the OS!="ios" + # dependencies block below, rather than here. + # Unit tests should only depend on: + # 1) everything that the chrome binaries depend on: + "//chrome:browser_dependencies", + "//chrome:child_dependencies", + + # 2) test-specific support libraries: + ":test_support_unit", + "//base/test:test_support", + "//chrome/test:test_support", + "//components/resources", + "//components/content_settings/core/test:test_support", + "//content/test:test_support", + "//content/public/app:both", + "//crypto:platform", + "//crypto:test_support", + "//net", + "//net:test_support", + "//sync:test_support_sync_api", + "//sync:test_support_sync_core", + "//sync:test_support_sync_internal_api", + "//testing/gmock", + "//testing/gtest", + + # 3) anything tests directly depend on + "//base/allocator", + "//chrome:resources", + "//chrome:strings", + "//courgette:courgette_lib", + "//google_apis", + "//skia", + "//third_party/cacheinvalidation", + "//third_party/icu", + "//third_party/libxml", + "//ui/base:test_support", + "//ui/gfx:test_support", + "//ui/resources", + ] + data_deps = [] + + # TODO(GYP) Windows stuff + # ['incremental_chrome_dll==1', { + # 'UseLibraryDependencyInputs': "true", + + if (!is_ios) { + deps += [ + ":unit_tests_js", + "//components/autofill/content/browser/wallet:test_support", + "//components/autofill/content/renderer:test_support", + "//components/data_reduction_proxy/core/browser:test_support", + "//components/data_use_measurement/core", + "//components/metrics/proto", + "//components/safe_browsing_db", + "//components/safe_json:test_support", + "//components/webdata_services:test_support", + "//components/strings", + "//device/bluetooth:mocks", + "//content/app/resources", + "//gpu:test_support", + "//media:test_support", + + #'../ppapi/ppapi_internal.gyp:ppapi_unittest_shared', TODO(GYP) + "//third_party/leveldatabase", + "//third_party/libaddressinput", + "//third_party/libjingle", + "//third_party/libphonenumber", + "//third_party/webrtc/modules/desktop_capture", + "//tools/json_schema_compiler/test", + "//ui/gl", + "//v8", ] } - test("unit_tests") { - sources = - rebase_path(chrome_tests_unit_gypi_values.chrome_unit_tests_sources, - ".", - "//chrome") + if (is_android) { + deps -= [ "//third_party/libaddressinput" ] - configs += [ "//build/config:precompiled_headers" ] + # Some android targets still depend on --gc-sections to link. + # TODO: remove --gc-sections for Debug builds (crbug.com/159847). + ldflags = [ "-Wl,--gc-sections" ] + deps += [ "//testing/android/native_test:native_test_native_code" ] + isolate_file = "../unit_tests.isolate" + } else { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_non_android_sources, + ".", + "//chrome") + sources -= + [ "../browser/download/download_request_infobar_delegate_unittest.cc" ] + } - data = [ - "data/", - "//base/test/data/", - "//chrome/third_party/mock4js/", - "//components/test/data/", - "//extensions/test/data/", - "//google_apis/test/data/", - "//net/data/", - "//net/tools/testserver/", - "//third_party/accessibility-audit/axs_testing.js", - "//third_party/hunspell_dictionaries/", - "//third_party/pyftpdlib/", - "//third_party/pywebsocket/", - "//third_party/tlslite/", - "//third_party/zlib/google/test/data/", - "//tools/metrics/histograms/histograms.xml", - "$root_out_dir/pyproto/google/", - "$root_out_dir/test_data/chrome/browser/resources/google_now/", - "$root_out_dir/test_data/chrome/browser/resources/print_preview/", - "$root_out_dir/test_data/chrome/renderer/resources/extensions/", - "$root_out_dir/test_data/ui/webui/", - "$root_out_dir/resources.pak", - ] - if (is_android || is_linux || is_win) { - data += [ - "$root_out_dir/chrome_100_percent.pak", - "$root_out_dir/locales/en-US.pak", - ] - } - if (is_linux || is_win) { - data += [ "$root_out_dir/chrome_material_100_percent.pak" ] - } + if (!is_android && !is_ios) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_non_mobile_sources, + ".", + "//chrome") + } - defines = [] - - deps = [ - # NOTE: New depndencies should generally be added in the OS!="ios" - # dependencies block below, rather than here. - # Unit tests should only depend on: - # 1) everything that the chrome binaries depend on: - "//chrome:browser_dependencies", - "//chrome:child_dependencies", - - # 2) test-specific support libraries: - ":test_support_unit", - "//base/test:test_support", - "//chrome/test:test_support", - "//components/resources", - "//components/content_settings/core/test:test_support", - "//content/test:test_support", - "//content/public/app:both", - "//crypto:platform", - "//crypto:test_support", - "//net", - "//net:test_support", - "//sync:test_support_sync_api", - "//sync:test_support_sync_core", - "//sync:test_support_sync_internal_api", - "//testing/gmock", - "//testing/gtest", - - # 3) anything tests directly depend on - "//base/allocator", - "//chrome:resources", - "//chrome:strings", - "//courgette:courgette_lib", - "//google_apis", - "//skia", - "//third_party/cacheinvalidation", - "//third_party/icu", - "//third_party/libxml", - "//ui/base:test_support", - "//ui/gfx:test_support", - "//ui/resources", - ] - data_deps = [] - - # TODO(GYP) Windows stuff - # ['incremental_chrome_dll==1', { - # 'UseLibraryDependencyInputs': "true", - - if (!is_ios) { - deps += [ - ":unit_tests_js", - "//components/audio_modem:test_support", - "//components/autofill/content/browser/wallet:test_support", - "//components/autofill/content/renderer:test_support", - "//components/data_reduction_proxy/core/browser:test_support", - "//components/data_use_measurement/core", - "//components/metrics/proto", - "//components/safe_browsing_db", - "//components/safe_json:test_support", - "//components/webdata_services:test_support", - "//components/strings", - "//device/bluetooth:mocks", - "//content/app/resources", - "//gpu:test_support", - "//media:test_support", - - #'../ppapi/ppapi_internal.gyp:ppapi_unittest_shared', TODO(GYP) - "//third_party/leveldatabase", - "//third_party/libaddressinput", - "//third_party/libjingle", - "//third_party/libphonenumber", - "//third_party/webrtc/modules/desktop_capture", - "//tools/json_schema_compiler/test", - "//ui/gl", - "//v8", - ] + if (is_ios || is_chromeos) { + sources -= [ "../browser/signin/chrome_signin_status_metrics_provider_delegate_unittest.cc" ] + } + if (enable_background) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_background_sources, + ".", + "//chrome") + } + if (enable_spellcheck) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_spellchecker_sources, + ".", + "//chrome") + if (is_mac && !is_ios) { + deps += [ "//third_party/hunspell" ] } if (is_android) { - deps -= [ "//third_party/libaddressinput" ] - - # Some android targets still depend on --gc-sections to link. - # TODO: remove --gc-sections for Debug builds (crbug.com/159847). - ldflags = [ "-Wl,--gc-sections" ] - deps += [ "//testing/android/native_test:native_test_native_code" ] - isolate_file = "../unit_tests.isolate" - } else { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_non_android_sources, - ".", - "//chrome") - sources -= [ "../browser/download/download_request_infobar_delegate_unittest.cc" ] - } - - if (!is_android && !is_ios) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_non_mobile_sources, - ".", - "//chrome") - } - - if (is_ios || is_chromeos) { - sources -= [ "../browser/signin/chrome_signin_status_metrics_provider_delegate_unittest.cc" ] - } - if (enable_background) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_background_sources, - ".", - "//chrome") - } - if (enable_spellcheck) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_spellchecker_sources, - ".", - "//chrome") - if (is_mac && !is_ios) { - deps += [ "//third_party/hunspell" ] - } - } - - if (enable_one_click_signin) { - sources += [ - "../browser/ui/sync/one_click_signin_sync_observer_unittest.cc", - "../browser/ui/sync/one_click_signin_sync_starter_unittest.cc", - ] - } - - if (enable_extensions) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_extensions_sources, - ".", - "//chrome") - deps += [ - "//chrome/common/extensions/api", - "//device/usb:mocks", - "//extensions:extensions_resources", - "//extensions/strings", - ] - if (enable_configuration_policy) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_extensions_policy_sources, - ".", - "//chrome") - } - if (!is_chromeos) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_extensions_non_chromeos_sources, - ".", - "//chrome") - } - } - if (use_ash) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_ash_sources, - ".", - "//chrome") - deps += [ - "//ash:test_support", - "//ash/resources", - "//ash/strings", - ] - - # We eventually want to compile both in Win Aura builds, see - # http://crbug.com/155545. - if (!is_win) { - sources -= [ "../browser/ui/window_sizer/window_sizer_unittest.cc" ] - } - } - if (use_aura) { - sources += [ "//ui/views/controls/webview/webview_unittest.cc" ] - deps += [ - "//ui/wm", - "//ui/aura:test_support", - "//ui/views:test_support", - ] - } - if (!is_chromeos && is_linux) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_desktop_linux_sources, - ".", - "//chrome") - } - if (!is_chromeos && !use_ozone && is_linux) { - deps += [ - "//chrome/browser/ui/libgtk2ui", - "//build/linux:gio", - ] - } - - if (enable_task_manager) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_task_manager_sources, - ".", - "//chrome") - } - if (enable_mdns) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_mdns_sources, - ".", - "//chrome") - } - if (enable_service_discovery) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_service_discovery_sources, - ".", - "//chrome") - } - if (enable_configuration_policy) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_configuration_policy_sources, - ".", - "//chrome") - if (is_chromeos) { - sources -= - [ "../browser/policy/cloud/user_policy_signin_service_unittest.cc" ] - } else if (is_android) { - sources -= [ "../browser/policy/policy_path_parser_unittest.cc" ] - } - if (!is_android && !is_ios && !is_chromeos) { - sources += - [ "../browser/net/disk_cache_dir_policy_handler_unittest.cc" ] - } - if (!is_android && !is_ios) { - sources += - [ "../browser/download/download_dir_policy_handler_unittest.cc" ] - - deps += [ "//components/bubble:test_support" ] - } - } - if (enable_web_speech) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_speech_sources, - ".", - "//chrome") - } - if (enable_notifications) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_notifications_sources, - ".", - "//chrome") - if (is_android) { - sources -= [ - # Android does not use the Message Center notification system. - "../browser/notifications/message_center_notifications_unittest.cc", - "../browser/notifications/message_center_settings_controller_unittest.cc", - ] - } - } - if (safe_browsing_mode == 1) { - # TODO(sgurun): enable tests for safe_browsing==2. - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_full_safe_browsing_sources + chrome_tests_unit_gypi_values.chrome_unit_tests_shared_safe_browsing_sources, - ".", - "//chrome") - deps += [ ":test_proto" ] - } else if (safe_browsing_mode == 2) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_mobile_safe_browsing_sources + chrome_tests_unit_gypi_values.chrome_unit_tests_shared_safe_browsing_sources, - ".", - "//chrome") - } - if (enable_autofill_dialog && !is_android) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_autofill_dialog_sources, - ".", - "//chrome") - } - if (enable_plugins) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_plugins_sources, - ".", - "//chrome") - } - if (enable_print_preview) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_print_preview_sources, - ".", - "//chrome") - } - if (enable_media_router) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_media_router_sources, - ".", - "//chrome") - deps += [ "//chrome/browser/media/router:test_support" ] - if (!is_android) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_media_router_non_android_sources, - ".", - "//chrome") - } - } - if (enable_captive_portal_detection) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_captive_portal_sources, - ".", - "//chrome") - } - if (enable_session_service) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_session_service_sources, - ".", - "//chrome") - } - if (enable_webrtc) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_webrtc_sources, - ".", - "//chrome") - } - if (is_chromeos) { - deps += [ "//chrome/browser/chromeos:unit_tests" ] - sources -= [ "../browser/signin/signin_manager_unittest.cc" ] - } - if (use_x11) { - deps += [ "//ui/events/devices" ] - data_deps += [ "//tools/xdisplaycheck" ] - } else { - sources -= [ "../browser/password_manager/password_store_x_unittest.cc" ] - } - if (cld_version == 2) { - # Unit tests should be independent of the CLD2 access mechanism, just use - # static for simplicity. - deps += [ "//third_party/cld_2:cld2_static" ] - } - if (is_desktop_linux && current_cpu == "x64") { - # Only add this test for 64 bit builds because otherwise we need the 32 - # bit library on 64 bit systems when running this test. - sources += - [ "../browser/password_manager/native_backend_gnome_x_unittest.cc" ] - configs += [ - "//chrome/browser:gnome_keyring", - "//chrome/browser:gnome_keyring_direct", - ] - } - if (is_linux && !is_chromeos) { - sources += - [ "../browser/password_manager/native_backend_libsecret_unittest.cc" ] - } - if (is_linux && use_aura) { - deps += [ - "//dbus", - "//dbus:test_support", - "//ui/aura:test_support", - ] - } - if (is_linux && is_chrome_branded && current_cpu == "x86") { - ldflags = [ "-Wl,--strip-debug" ] - } - if (is_mac) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_mac_sources, - ".", - "//chrome") sources -= [ - # This tests the function GetSpellCheckLanguages which is not used on - # Mac. - "../browser/spellchecker/spellcheck_service_unittest.cc", - "../browser/ui/tests/ui_gfx_image_unittest.cc", - - # This tests Chrome's spellchecker which Mac doesn't use. + "../common/spellcheck_common_unittest.cc", "../renderer/spellchecker/spellcheck_multilingual_unittest.cc", "../renderer/spellchecker/spellcheck_provider_hunspell_unittest.cc", - "../tools/convert_dict/convert_dict_unittest.cc", + "../renderer/spellchecker/spellcheck_unittest.cc", ] - - # The test fetches resources which means Mac need the app bundle to exist - # on disk so it can pull from it. - deps += [ - "//third_party/google_toolbox_for_mac", - "//third_party/ocmock", - ] - - # TODO(mark): We really want this for all non-static library targets, - # but when we tried to pull it up to the common.gypi level, it broke - # other things like the ui and startup tests. *shrug* - ldflags = [ "-Wl,-ObjC" ] - } - if (is_mac || is_android) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_mac_android_sources, - ".", - "//chrome") - } - if (is_android) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_android_sources, - ".", - "//chrome") - } - if (!is_mac && !is_ios) { - deps += [ - "//chrome/tools/convert_dict:lib", - "//chrome:packed_extra_resources", - "//chrome:packed_resources", - "//third_party/hunspell", - ] - } - if (is_win || is_mac) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_win_mac_sources, - ".", - "//chrome") - } - if (is_win || is_mac || is_chromeos) { - sources += [ "../common/extensions/api/networking_private/networking_private_crypto_unittest.cc" ] - } - if (enable_rlz_support) { - sources += [ "../browser/rlz/chrome_rlz_tracker_delegate_unittest.cc" ] - deps += [ - "//chrome/browser:rlz", - "//components/rlz", - "//rlz:test_support", - ] - } - if (is_win) { - # The PDB gets too large for incremental linking. - configs -= [ "//build/config/win:default_incremental_linking" ] - configs += [ "//build/config/win:no_incremental_linking" ] - - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_win_sources, - ".", - "//chrome") - deps += [ - "//chrome:other_version", - "//chrome_elf:blacklist_test_dll_1", - "//chrome/installer/util:strings", - "//third_party/iaccessible2", - "//third_party/isimpledom", - "//third_party/wtl", - "//ui/resources", - ] - data_deps += [ - "//chrome/browser/safe_browsing/incident_reporting/verifier_test:verifier_test_dll_1", - "//chrome/browser/safe_browsing/incident_reporting/verifier_test:verifier_test_dll_2", - ] - - libs = [ - "comsupp.lib", - "oleacc.lib", - "rpcrt4.lib", - "urlmon.lib", - "winmm.lib", - ] - if (!is_chrome_branded) { - sources -= [ "../browser/google/google_update_win_unittest.cc" ] - } - } - if (is_android || is_ios) { - sources -= [ - "../browser/devtools/device/webrtc/devtools_bridge_instances_request_unittest.cc", - "../browser/ui/bookmarks/bookmark_ui_utils_desktop_unittest.cc", - "../browser/ui/sync/sync_promo_ui_unittest.cc", - ] - } else { - deps += [ "//chrome/tools/profile_reset:jtl_compiler_lib" ] - } - if (!is_android && !is_chromeos) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_non_android_or_chromeos_sources, - ".", - "//chrome") - } - if (enable_themes) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_themes_sources, - ".", - "//chrome") - } - if (toolkit_views) { - deps += [ - "//components/web_modal:test_support", - "//ui/views", - "//ui/views:test_support", - ] - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_views_sources, - ".", - "//chrome") - if (!is_chromeos && (!is_mac || mac_views_browser)) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_views_non_chromeos_sources, - ".", - "//chrome") - } - if (!is_mac) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_views_non_mac_sources, - ".", - "//chrome") - } - } - if (!is_android && (use_nss_certs || use_openssl_certs)) { - sources += [ "../common/net/x509_certificate_model_unittest.cc" ] - } - if (enable_supervised_users) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_supervised_user_sources, - ".", - "//chrome") - } - if (enable_supervised_users && !is_android && !is_ios) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_supervised_user_legacy_sources, - ".", - "//chrome") - } - if (safe_browsing_mode == 1 && enable_extensions) { - sources += [ "../browser/extensions/blacklist_unittest.cc" ] - } - if (cld_version == 1) { - sources += [ "//third_party/cld/encodings/compact_lang_det/compact_lang_det_unittest_small.cc" ] - defines += [ "CLD_WINDOWS" ] - deps += [ "//third_party/cld" ] - } - if (enable_app_list) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_app_list_sources, - ".", - "//chrome") - deps += [ "//ui/app_list:test_support" ] - } - if (enable_app_list && is_chromeos) { - sources += rebase_path( - chrome_tests_unit_gypi_values.chrome_unit_tests_app_list_chromeos_sources, - ".", - "//chrome") - } - if (enable_plugins && !enable_plugin_installation) { - sources -= [ "../browser/plugins/plugin_installer_unittest.cc" ] } } - if (is_win || (is_linux && !is_chromeos)) { - # TODO(GYP): Figure out which of these work and are needed on other - # platforms. - test("chrome_app_unittests") { - sources = [ - "../app/chrome_watcher_client_unittest_win.cc", - "../app/chrome_watcher_client_win.cc", - "../app/chrome_watcher_command_line_unittest_win.cc", - "../app/chrome_watcher_command_line_win.cc", - "../app/delay_load_hook_unittest_win.cc", - "../app/delay_load_hook_win.cc", - "../app/delay_load_hook_win.h", - "../app/resources/resources_unittest.cc", - "../app/signature_validator_win.cc", - "../app/signature_validator_win.h", - "../app/signature_validator_win_unittest.cc", - "../common/crash_keys.cc", - "../common/crash_keys.h", - ] + if (enable_one_click_signin) { + sources += [ + "../browser/ui/sync/one_click_signin_sync_observer_unittest.cc", + "../browser/ui/sync/one_click_signin_sync_starter_unittest.cc", + ] + } - deps = [ - ":test_support", - "//breakpad:client", - "//chrome/browser", - "//chrome/child", - "//components/crash/core/common", - "//base/test:run_all_unittests", - "//base/test:test_support", - ] - if (cld_version == 2) { - # Use whatever CLD2 data access mode that the - # application embedder is using. - deps += [ "//third_party/cld_2:cld2_platform_impl" ] - } - } - - test("performance_browser_tests") { - sources = rebase_path( - chrome_tests_gypi_values.performance_browser_tests_sources, + if (enable_extensions) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_extensions_sources, + ".", + "//chrome") + deps += [ + "//chrome/common/extensions/api", + "//components/audio_modem:test_support", + "//device/usb:mocks", + "//extensions:extensions_resources", + "//extensions/strings", + ] + if (enable_configuration_policy) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_extensions_policy_sources, ".", "//chrome") + } + if (!is_chromeos) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_extensions_non_chromeos_sources, + ".", + "//chrome") + } + } + if (use_ash) { + sources += + rebase_path(chrome_tests_unit_gypi_values.chrome_unit_tests_ash_sources, + ".", + "//chrome") + deps += [ + "//ash:test_support", + "//ash/resources", + "//ash/strings", + ] - defines = [ "HAS_OUT_OF_PROC_TEST_RUNNER" ] + # We eventually want to compile both in Win Aura builds, see + # http://crbug.com/155545. + if (!is_win) { + sources -= [ "../browser/ui/window_sizer/window_sizer_unittest.cc" ] + } + } + if (use_aura) { + sources += [ "//ui/views/controls/webview/webview_unittest.cc" ] + deps += [ + "//ui/wm", + "//ui/aura:test_support", + "//ui/views:test_support", + ] + } + if (!is_chromeos && is_linux) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_desktop_linux_sources, + ".", + "//chrome") + } + if (!is_chromeos && !use_ozone && is_linux) { + deps += [ + "//chrome/browser/ui/libgtk2ui", + "//build/linux:gio", + ] + } - deps = [ - ":test_support", - ":test_support_ui", - "//base", - "//base:i18n", - "//base/test:test_support", - "//chrome/browser", - "//chrome/renderer", - "//components/about_handler", - "//components/autofill/content/browser/wallet:test_support", - "//components/autofill/content/renderer:test_support", - "//media/cast:test_support", - "//testing/gmock", - "//testing/gtest", - "//testing/perf", + if (enable_task_manager) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_task_manager_sources, + ".", + "//chrome") + } + if (enable_mdns) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_mdns_sources, + ".", + "//chrome") + } + if (enable_service_discovery) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_service_discovery_sources, + ".", + "//chrome") + } + if (enable_configuration_policy) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_configuration_policy_sources, + ".", + "//chrome") + if (is_chromeos) { + sources -= + [ "../browser/policy/cloud/user_policy_signin_service_unittest.cc" ] + } else if (is_android) { + sources -= [ "../browser/policy/policy_path_parser_unittest.cc" ] + } + if (!is_android && !is_ios && !is_chromeos) { + sources += [ "../browser/net/disk_cache_dir_policy_handler_unittest.cc" ] + } + if (!is_android && !is_ios) { + sources += + [ "../browser/download/download_dir_policy_handler_unittest.cc" ] + + deps += [ "//components/bubble:test_support" ] + } + } + if (enable_web_speech) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_speech_sources, + ".", + "//chrome") + } + if (enable_notifications) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_notifications_sources, + ".", + "//chrome") + if (is_android) { + sources -= [ + # Android does not use the Message Center notification system. + "../browser/notifications/message_center_notifications_unittest.cc", + "../browser/notifications/message_center_settings_controller_unittest.cc", ] + } + } + if (safe_browsing_mode == 1) { + # TODO(sgurun): enable tests for safe_browsing==2. + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_full_safe_browsing_sources + chrome_tests_unit_gypi_values.chrome_unit_tests_shared_safe_browsing_sources, + ".", + "//chrome") + deps += [ ":test_proto" ] + } else if (safe_browsing_mode == 2) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_mobile_safe_browsing_sources + chrome_tests_unit_gypi_values.chrome_unit_tests_shared_safe_browsing_sources, + ".", + "//chrome") + } + if (enable_autofill_dialog && !is_android) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_autofill_dialog_sources, + ".", + "//chrome") + } + if (enable_plugins) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_plugins_sources, + ".", + "//chrome") + } + if (enable_print_preview) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_print_preview_sources, + ".", + "//chrome") + } + if (enable_media_router) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_media_router_sources, + ".", + "//chrome") + deps += [ "//chrome/browser/media/router:test_support" ] + if (!is_android) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_media_router_non_android_sources, + ".", + "//chrome") + } + } + if (enable_captive_portal_detection) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_captive_portal_sources, + ".", + "//chrome") + } + if (enable_session_service) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_session_service_sources, + ".", + "//chrome") + } + if (enable_webrtc) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_webrtc_sources, + ".", + "//chrome") + } + if (is_chromeos) { + deps += [ "//chrome/browser/chromeos:unit_tests" ] + sources -= [ "../browser/signin/signin_manager_unittest.cc" ] + } + if (use_x11) { + deps += [ "//ui/events/devices" ] + data_deps += [ "//tools/xdisplaycheck" ] + } else { + sources -= [ "../browser/password_manager/password_store_x_unittest.cc" ] + } + if (cld_version == 2) { + # Unit tests should be independent of the CLD2 access mechanism, just use + # static for simplicity. + deps += [ "//third_party/cld_2:cld2_static" ] + } + if (is_desktop_linux && current_cpu == "x64") { + # Only add this test for 64 bit builds because otherwise we need the 32 + # bit library on 64 bit systems when running this test. + sources += + [ "../browser/password_manager/native_backend_gnome_x_unittest.cc" ] + configs += [ + "//chrome/browser:gnome_keyring", + "//chrome/browser:gnome_keyring_direct", + ] + } + if (is_linux && !is_chromeos) { + sources += + [ "../browser/password_manager/native_backend_libsecret_unittest.cc" ] + } + if (is_linux && use_aura) { + deps += [ + "//dbus", + "//dbus:test_support", + "//ui/aura:test_support", + ] + } + if (is_linux && is_chrome_branded && current_cpu == "x86") { + ldflags = [ "-Wl,--strip-debug" ] + } + if (is_mac) { + sources += + rebase_path(chrome_tests_unit_gypi_values.chrome_unit_tests_mac_sources, + ".", + "//chrome") + sources -= [ + # This tests the function GetSpellCheckLanguages which is not used on + # Mac. + "../browser/spellchecker/spellcheck_service_unittest.cc", + "../browser/ui/tests/ui_gfx_image_unittest.cc", - if (is_win) { - configs -= [ "//build/config/win:default_incremental_linking" ] - configs += - [ "//build/config/win:default_large_module_incremental_linking" ] - } else { - sources -= [ - "../app/chrome_command_ids.h", + # This tests Chrome's spellchecker which Mac doesn't use. + "../renderer/spellchecker/spellcheck_multilingual_unittest.cc", + "../renderer/spellchecker/spellcheck_provider_hunspell_unittest.cc", + "../tools/convert_dict/convert_dict_unittest.cc", + ] - #"../app/chrome_dll.rc", - #"../app/chrome_dll_resource.h", - "../app/chrome_version.rc.version", - ] - } - if (!is_mac) { - sources -= [ "perf/mach_ports_performancetest.cc" ] - } + # The test fetches resources which means Mac need the app bundle to exist + # on disk so it can pull from it. + deps += [ + "//third_party/google_toolbox_for_mac", + "//third_party/ocmock", + ] - if (cld_version == 2) { - # Use whatever CLD2 data access mode that the - # application embedder is using. - deps += [ "//third_party/cld_2:cld2_platform_impl" ] - } + # TODO(mark): We really want this for all non-static library targets, + # but when we tried to pull it up to the common.gypi level, it broke + # other things like the ui and startup tests. *shrug* + ldflags = [ "-Wl,-ObjC" ] + } + if (is_mac || is_android) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_mac_android_sources, + ".", + "//chrome") + } + if (is_android) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_android_sources, + ".", + "//chrome") + } + if (!is_mac && !is_ios) { + deps += [ + "//chrome/tools/convert_dict:lib", + "//chrome:packed_extra_resources", + "//chrome:packed_resources", + "//third_party/hunspell", + ] + } + if (is_win || is_mac) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_win_mac_sources, + ".", + "//chrome") + } + if (is_win || is_mac || is_chromeos) { + sources += [ "../common/extensions/api/networking_private/networking_private_crypto_unittest.cc" ] + } + if (enable_rlz_support) { + sources += [ "../browser/rlz/chrome_rlz_tracker_delegate_unittest.cc" ] + deps += [ + "//chrome/browser:rlz", + "//components/rlz", + "//rlz:test_support", + ] + } + if (is_win) { + # The PDB gets too large for incremental linking. + configs -= [ "//build/config/win:default_incremental_linking" ] + configs += [ "//build/config/win:no_incremental_linking" ] + + sources += + rebase_path(chrome_tests_unit_gypi_values.chrome_unit_tests_win_sources, + ".", + "//chrome") + deps += [ + "//chrome:other_version", + "//chrome_elf:blacklist_test_dll_1", + "//chrome/installer/util:strings", + "//third_party/iaccessible2", + "//third_party/isimpledom", + "//third_party/wtl", + "//ui/resources", + ] + data_deps += [ + "//chrome/browser/safe_browsing/incident_reporting/verifier_test:verifier_test_dll_1", + "//chrome/browser/safe_browsing/incident_reporting/verifier_test:verifier_test_dll_2", + ] + + libs = [ + "comsupp.lib", + "oleacc.lib", + "rpcrt4.lib", + "urlmon.lib", + "winmm.lib", + ] + if (!is_chrome_branded) { + sources -= [ "../browser/google/google_update_win_unittest.cc" ] + } + } + if (is_android || is_ios) { + sources -= [ + "../browser/devtools/device/webrtc/devtools_bridge_instances_request_unittest.cc", + "../browser/ui/bookmarks/bookmark_ui_utils_desktop_unittest.cc", + "../browser/ui/sync/sync_promo_ui_unittest.cc", + ] + } else { + deps += [ "//chrome/tools/profile_reset:jtl_compiler_lib" ] + } + if (!is_android && !is_chromeos) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_non_android_or_chromeos_sources, + ".", + "//chrome") + } + if (enable_themes) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_themes_sources, + ".", + "//chrome") + } + if (toolkit_views) { + deps += [ + "//components/web_modal:test_support", + "//ui/views", + "//ui/views:test_support", + ] + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_views_sources, + ".", + "//chrome") + if (!is_chromeos && (!is_mac || mac_views_browser)) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_views_non_chromeos_sources, + ".", + "//chrome") + } + if (!is_mac) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_views_non_mac_sources, + ".", + "//chrome") + } + } + if (!is_android && (use_nss_certs || use_openssl_certs)) { + sources += [ "../common/net/x509_certificate_model_unittest.cc" ] + } + if (enable_supervised_users) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_supervised_user_sources, + ".", + "//chrome") + } + if (enable_supervised_users && !is_android && !is_ios) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_supervised_user_legacy_sources, + ".", + "//chrome") + } + if (safe_browsing_mode == 1 && enable_extensions) { + sources += [ "../browser/extensions/blacklist_unittest.cc" ] + } + if (cld_version == 1) { + sources += [ "//third_party/cld/encodings/compact_lang_det/compact_lang_det_unittest_small.cc" ] + defines += [ "CLD_WINDOWS" ] + deps += [ "//third_party/cld" ] + } + if (enable_app_list) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_app_list_sources, + ".", + "//chrome") + deps += [ "//ui/app_list:test_support" ] + } + if (enable_app_list && is_chromeos) { + sources += rebase_path( + chrome_tests_unit_gypi_values.chrome_unit_tests_app_list_chromeos_sources, + ".", + "//chrome") + } + if (enable_plugins && !enable_plugin_installation) { + sources -= [ "../browser/plugins/plugin_installer_unittest.cc" ] + } +} + +if (is_win || (is_linux && !is_chromeos)) { + # TODO(GYP): Figure out which of these work and are needed on other + # platforms. + test("chrome_app_unittests") { + sources = [ + "../app/chrome_watcher_client_unittest_win.cc", + "../app/chrome_watcher_client_win.cc", + "../app/chrome_watcher_command_line_unittest_win.cc", + "../app/chrome_watcher_command_line_win.cc", + "../app/delay_load_hook_unittest_win.cc", + "../app/delay_load_hook_win.cc", + "../app/delay_load_hook_win.h", + "../app/resources/resources_unittest.cc", + "../app/signature_validator_win.cc", + "../app/signature_validator_win.h", + "../app/signature_validator_win_unittest.cc", + "../common/crash_keys.cc", + "../common/crash_keys.h", + ] + + deps = [ + ":test_support", + "//breakpad:client", + "//chrome/browser", + "//chrome/child", + "//components/crash/core/common", + "//base/test:run_all_unittests", + "//base/test:test_support", + ] + if (cld_version == 2) { + # Use whatever CLD2 data access mode that the + # application embedder is using. + deps += [ "//third_party/cld_2:cld2_platform_impl" ] + } + } + + test("performance_browser_tests") { + sources = + rebase_path(chrome_tests_gypi_values.performance_browser_tests_sources, + ".", + "//chrome") + + defines = [ "HAS_OUT_OF_PROC_TEST_RUNNER" ] + + deps = [ + ":test_support", + ":test_support_ui", + "//base", + "//base:i18n", + "//base/test:test_support", + "//chrome/browser", + "//chrome/renderer", + "//components/about_handler", + "//components/autofill/content/browser/wallet:test_support", + "//components/autofill/content/renderer:test_support", + "//media/cast:test_support", + "//testing/gmock", + "//testing/gtest", + "//testing/perf", + ] + + if (is_win) { + configs -= [ "//build/config/win:default_incremental_linking" ] + configs += + [ "//build/config/win:default_large_module_incremental_linking" ] + } else { + sources -= [ + "../app/chrome_command_ids.h", + + #"../app/chrome_dll.rc", + #"../app/chrome_dll_resource.h", + "../app/chrome_version.rc.version", + ] + } + if (!is_mac) { + sources -= [ "perf/mach_ports_performancetest.cc" ] + } + + if (cld_version == 2) { + # Use whatever CLD2 data access mode that the + # application embedder is using. + deps += [ "//third_party/cld_2:cld2_platform_impl" ] } } }
diff --git a/chrome/test/data/android/contextualsearch/tap_test.html b/chrome/test/data/android/contextualsearch/tap_test.html index 2f7cd90..4a10e80 100644 --- a/chrome/test/data/android/contextualsearch/tap_test.html +++ b/chrome/test/data/android/contextualsearch/tap_test.html
@@ -22,6 +22,9 @@ <div>United States <span id="intelligence">Intelligence</span></div> <div>United <span id="states">States</span> Intelligence</div> <div>United <span id="states-near">StatesNear</span> Intelligence</div> + <!-- These three spans should be close to each other so that taps from one to + to the next are within our "near" threshold. --> + <div><span id="search">Search</span> <span id="term">Term</span> <span id="resolution">Resolution</span></div> <form action="demo_form.asp"> <label for="male">Male</label> <input type="radio" name="sex" id="male" value="male"><br>
diff --git a/chrome/test/data/extensions/api_test/webnavigation/failures/test_failures.js b/chrome/test/data/extensions/api_test/webnavigation/failures/test_failures.js index c32ec513..f057288 100644 --- a/chrome/test/data/extensions/api_test/webnavigation/failures/test_failures.js +++ b/chrome/test/data/extensions/api_test/webnavigation/failures/test_failures.js
@@ -173,13 +173,6 @@ transitionQualifiers: [], transitionType: "link", url: getURL('e.html') }}, - { label: "onDOMContentLoaded", - event: "onDOMContentLoaded", - details: { frameId: 0, - processId: 0, - tabId: 0, - timeStamp: 0, - url: getURL('e.html') }}, { label: "onErrorOccurred", event: "onErrorOccurred", details: { error: "net::ERR_ABORTED", @@ -188,7 +181,7 @@ tabId: 0, timeStamp: 0, url: getURL('e.html') }}], - [["onBeforeNavigate", "onCommitted", "onDOMContentLoaded", + [["onBeforeNavigate", "onCommitted", "onErrorOccurred"]]); chrome.tabs.update(tabId, { url: getURL('e.html') }); },
diff --git a/chromecast/base/cast_sys_info_dummy.h b/chromecast/base/cast_sys_info_dummy.h index 89a8b8be..ec6c0eab 100644 --- a/chromecast/base/cast_sys_info_dummy.h +++ b/chromecast/base/cast_sys_info_dummy.h
@@ -5,7 +5,9 @@ #ifndef CHROMECAST_BASE_CAST_SYS_INFO_DUMMY_H_ #define CHROMECAST_BASE_CAST_SYS_INFO_DUMMY_H_ -#include "base/macros.h" +// Note(slan): This file is needed by internal targets which cannot depend on +// "//base". Amend this include with a comment so gn check ignores it. +#include "base/macros.h" // nogncheck #include "chromecast/public/cast_sys_info.h" namespace chromecast {
diff --git a/chromecast/browser/BUILD.gn b/chromecast/browser/BUILD.gn index 4453f8a6e..1223add 100644 --- a/chromecast/browser/BUILD.gn +++ b/chromecast/browser/BUILD.gn
@@ -91,6 +91,7 @@ "//content/public/browser", "//content/public/common", "//content/public/utility", + "//gpu", "//media", "//ipc", "//net",
diff --git a/chromecast/media/BUILD.gn b/chromecast/media/BUILD.gn index f12385b..5144799 100644 --- a/chromecast/media/BUILD.gn +++ b/chromecast/media/BUILD.gn
@@ -6,7 +6,7 @@ import("//testing/test.gni") group("media") { - deps = [ + public_deps = [ "//chromecast/media/audio", "//chromecast/media/base", "//chromecast/media/cdm", @@ -40,7 +40,7 @@ deps = [ ":media", - "//chromecast/media/audio:test_support", + "//chromecast/media/audio", "//chromecast/media/base:message_loop", "//chromecast/media/cma/backend", "//chromecast/media/cma/base",
diff --git a/chromecast/media/audio/BUILD.gn b/chromecast/media/audio/BUILD.gn index 5d87fa3..3066fa4 100644 --- a/chromecast/media/audio/BUILD.gn +++ b/chromecast/media/audio/BUILD.gn
@@ -14,25 +14,13 @@ configs += [ "//chromecast:config" ] - public_deps = [ + deps = [ + "//base", + "//chromecast/base", + "//chromecast/media/base", + "//chromecast/media/cma/base", "//chromecast/public/media", - ] - - deps = [ "//media", - ] -} - -source_set("test_support") { - testonly = true - - configs += [ "//chromecast:config" ] - - public_deps = [ - ":audio", - ] - - deps = [ - "//testing/gtest", + "//media:shared_memory_support", ] }
diff --git a/chromecast/media/cma/BUILD.gn b/chromecast/media/cma/BUILD.gn index b4b1f6d..5c76f12 100644 --- a/chromecast/media/cma/BUILD.gn +++ b/chromecast/media/cma/BUILD.gn
@@ -2,8 +2,9 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +# Targets may depend on this to bring in every CMA component. group("cma") { - deps = [ + public_deps = [ "//chromecast/media/cma/backend", "//chromecast/media/cma/base", "//chromecast/media/cma/ipc",
diff --git a/chromecast/renderer/media/BUILD.gn b/chromecast/renderer/media/BUILD.gn index 38efe6a..0e127f3 100644 --- a/chromecast/renderer/media/BUILD.gn +++ b/chromecast/renderer/media/BUILD.gn
@@ -33,8 +33,11 @@ "//chromecast/common/media", "//chromecast/media", "//content/public/renderer", + "//gpu/command_buffer/client:gles2_interface", + "//gpu/command_buffer/common", "//ipc", "//media", + "//ui/gfx/geometry", ] }
diff --git a/chromeos/login/auth/cryptohome_authenticator.cc b/chromeos/login/auth/cryptohome_authenticator.cc index e9e10174..156a66d 100644 --- a/chromeos/login/auth/cryptohome_authenticator.cc +++ b/chromeos/login/auth/cryptohome_authenticator.cc
@@ -148,9 +148,9 @@ } cryptohome::HomedirMethods::GetInstance()->MountEx( - cryptohome::Identification( - attempt->user_context.GetAccountId().GetUserEmail()), - cryptohome::Authorization(auth_key), mount, + cryptohome::Identification(attempt->user_context.GetUserID()), + cryptohome::Authorization(auth_key), + mount, base::Bind(&OnMount, attempt, resolver)); } @@ -266,10 +266,13 @@ } cryptohome::HomedirMethods::GetInstance()->GetKeyDataEx( - cryptohome::Identification( - attempt->user_context.GetAccountId().GetUserEmail()), - kCryptohomeGAIAKeyLabel, base::Bind(&OnGetKeyDataEx, attempt, resolver, - ephemeral, create_if_nonexistent)); + cryptohome::Identification(attempt->user_context.GetUserID()), + kCryptohomeGAIAKeyLabel, + base::Bind(&OnGetKeyDataEx, + attempt, + resolver, + ephemeral, + create_if_nonexistent)); } // Calls cryptohome's mount method for guest and also get the user hash from @@ -283,7 +286,7 @@ attempt, resolver)); cryptohome::AsyncMethodCaller::GetInstance()->AsyncGetSanitizedUsername( - attempt->user_context.GetAccountId().GetUserEmail(), + attempt->user_context.GetUserID(), base::Bind(&TriggerResolveHash, attempt, resolver)); } @@ -292,11 +295,14 @@ scoped_refptr<CryptohomeAuthenticator> resolver, int flags) { cryptohome::AsyncMethodCaller::GetInstance()->AsyncMountPublic( - attempt->user_context.GetAccountId().GetUserEmail(), flags, + attempt->user_context.GetUserID(), + flags, base::Bind(&TriggerResolveWithLoginTimeMarker, - "CryptohomeMountPublic-End", attempt, resolver)); + "CryptohomeMountPublic-End", + attempt, + resolver)); cryptohome::AsyncMethodCaller::GetInstance()->AsyncGetSanitizedUsername( - attempt->user_context.GetAccountId().GetUserEmail(), + attempt->user_context.GetUserID(), base::Bind(&TriggerResolveHash, attempt, resolver)); } @@ -318,17 +324,21 @@ scoped_ptr<Key> new_key = TransformKeyIfNeeded(*attempt->user_context.GetKey(), system_salt); if (passing_old_hash) { - caller->AsyncMigrateKey( - attempt->user_context.GetAccountId().GetUserEmail(), - old_key->GetSecret(), new_key->GetSecret(), - base::Bind(&TriggerResolveWithLoginTimeMarker, "CryptohomeMount-End", - attempt, resolver)); + caller->AsyncMigrateKey(attempt->user_context.GetUserID(), + old_key->GetSecret(), + new_key->GetSecret(), + base::Bind(&TriggerResolveWithLoginTimeMarker, + "CryptohomeMount-End", + attempt, + resolver)); } else { - caller->AsyncMigrateKey( - attempt->user_context.GetAccountId().GetUserEmail(), - new_key->GetSecret(), old_key->GetSecret(), - base::Bind(&TriggerResolveWithLoginTimeMarker, "CryptohomeMount-End", - attempt, resolver)); + caller->AsyncMigrateKey(attempt->user_context.GetUserID(), + new_key->GetSecret(), + old_key->GetSecret(), + base::Bind(&TriggerResolveWithLoginTimeMarker, + "CryptohomeMount-End", + attempt, + resolver)); } } @@ -338,9 +348,11 @@ chromeos::LoginEventRecorder::Get()->AddLoginTimeMarker( "CryptohomeRemove-Start", false); cryptohome::AsyncMethodCaller::GetInstance()->AsyncRemove( - attempt->user_context.GetAccountId().GetUserEmail(), - base::Bind(&TriggerResolveWithLoginTimeMarker, "CryptohomeRemove-End", - attempt, resolver)); + attempt->user_context.GetUserID(), + base::Bind(&TriggerResolveWithLoginTimeMarker, + "CryptohomeRemove-End", + attempt, + resolver)); } // Calls cryptohome's key check method. @@ -350,7 +362,8 @@ scoped_ptr<Key> key = TransformKeyIfNeeded(*attempt->user_context.GetKey(), system_salt); cryptohome::AsyncMethodCaller::GetInstance()->AsyncCheckKey( - attempt->user_context.GetAccountId().GetUserEmail(), key->GetSecret(), + attempt->user_context.GetUserID(), + key->GetSecret(), base::Bind(&TriggerResolve, attempt, resolver)); }
diff --git a/chromeos/login/auth/extended_authenticator_impl.cc b/chromeos/login/auth/extended_authenticator_impl.cc index 88ec3cf..0aa10e5 100644 --- a/chromeos/login/auth/extended_authenticator_impl.cc +++ b/chromeos/login/auth/extended_authenticator_impl.cc
@@ -17,7 +17,6 @@ #include "chromeos/login/auth/key.h" #include "chromeos/login/auth/user_context.h" #include "chromeos/login_event_recorder.h" -#include "components/signin/core/account_id/account_id.h" #include "crypto/sha2.h" #include "google_apis/gaia/gaia_auth_util.h" @@ -92,7 +91,7 @@ for (size_t i = 0; i < keys.size(); i++) { mount.create_keys.push_back(keys[i]); } - UserContext context(AccountId::FromUserEmail(user_id)); + UserContext context(user_id); Key key(keys.front().secret); key.SetLabel(keys.front().label); context.SetKey(key); @@ -187,8 +186,7 @@ const UserContext& user_context) { RecordStartMarker("MountEx"); - const std::string canonicalized = - gaia::CanonicalizeEmail(user_context.GetAccountId().GetUserEmail()); + std::string canonicalized = gaia::CanonicalizeEmail(user_context.GetUserID()); cryptohome::Identification id(canonicalized); const Key* const key = user_context.GetKey(); cryptohome::Authorization auth(key->GetSecret(), key->GetLabel()); @@ -210,8 +208,7 @@ const UserContext& user_context) { RecordStartMarker("CheckKeyEx"); - const std::string canonicalized = - gaia::CanonicalizeEmail(user_context.GetAccountId().GetUserEmail()); + std::string canonicalized = gaia::CanonicalizeEmail(user_context.GetUserID()); cryptohome::Identification id(canonicalized); const Key* const key = user_context.GetKey(); cryptohome::Authorization auth(key->GetSecret(), key->GetLabel()); @@ -232,8 +229,7 @@ const UserContext& user_context) { RecordStartMarker("AddKeyEx"); - const std::string canonicalized = - gaia::CanonicalizeEmail(user_context.GetAccountId().GetUserEmail()); + std::string canonicalized = gaia::CanonicalizeEmail(user_context.GetUserID()); cryptohome::Identification id(canonicalized); const Key* const auth_key = user_context.GetKey(); cryptohome::Authorization auth(auth_key->GetSecret(), auth_key->GetLabel()); @@ -257,8 +253,7 @@ const UserContext& user_context) { RecordStartMarker("UpdateKeyAuthorized"); - const std::string canonicalized = - gaia::CanonicalizeEmail(user_context.GetAccountId().GetUserEmail()); + std::string canonicalized = gaia::CanonicalizeEmail(user_context.GetUserID()); cryptohome::Identification id(canonicalized); const Key* const auth_key = user_context.GetKey(); cryptohome::Authorization auth(auth_key->GetSecret(), auth_key->GetLabel()); @@ -280,8 +275,7 @@ const UserContext& user_context) { RecordStartMarker("RemoveKeyEx"); - const std::string canonicalized = - gaia::CanonicalizeEmail(user_context.GetAccountId().GetUserEmail()); + std::string canonicalized = gaia::CanonicalizeEmail(user_context.GetUserID()); cryptohome::Identification id(canonicalized); const Key* const auth_key = user_context.GetKey(); cryptohome::Authorization auth(auth_key->GetSecret(), auth_key->GetLabel());
diff --git a/chromeos/login/auth/fake_extended_authenticator.cc b/chromeos/login/auth/fake_extended_authenticator.cc index e57755b9..90b569b 100644 --- a/chromeos/login/auth/fake_extended_authenticator.cc +++ b/chromeos/login/auth/fake_extended_authenticator.cc
@@ -6,7 +6,6 @@ #include "base/logging.h" #include "chromeos/login/auth/auth_status_consumer.h" -#include "components/signin/core/account_id/account_id.h" namespace chromeos { @@ -38,8 +37,7 @@ const ResultCallback& success_callback) { if (expected_user_context_ == context) { UserContext reported_user_context(context); - const std::string mount_hash = - reported_user_context.GetAccountId().GetUserEmail() + "-hash"; + const std::string mount_hash = reported_user_context.GetUserID() + "-hash"; reported_user_context.SetUserIDHash(mount_hash); if (!success_callback.is_null()) success_callback.Run(mount_hash);
diff --git a/chromeos/login/auth/login_performer.cc b/chromeos/login/auth/login_performer.cc index b988f1d..ba4e82b 100644 --- a/chromeos/login/auth/login_performer.cc +++ b/chromeos/login/auth/login_performer.cc
@@ -18,7 +18,6 @@ #include "chromeos/login/user_names.h" #include "chromeos/login_event_recorder.h" #include "chromeos/settings/cros_settings_names.h" -#include "components/signin/core/account_id/account_id.h" #include "google_apis/gaia/gaia_auth_util.h" #include "net/cookies/cookie_monster.h" #include "net/cookies/cookie_store.h" @@ -108,8 +107,7 @@ void LoginPerformer::NotifyWhitelistCheckFailure() { if (delegate_) - delegate_->WhiteListCheckFailed( - user_context_.GetAccountId().GetUserEmail()); + delegate_->WhiteListCheckFailed(user_context_.GetUserID()); else NOTREACHED(); } @@ -130,8 +128,7 @@ void LoginPerformer::DoPerformLogin(const UserContext& user_context, AuthorizationMode auth_mode) { - const std::string email = - gaia::CanonicalizeEmail(user_context.GetAccountId().GetUserEmail()); + std::string email = gaia::CanonicalizeEmail(user_context.GetUserID()); bool wildcard_match = false; if (!IsUserWhitelisted(email, &wildcard_match)) { @@ -140,7 +137,7 @@ } if (user_context.GetAuthFlow() == UserContext::AUTH_FLOW_EASY_UNLOCK) - SetupEasyUnlockUserFlow(user_context.GetAccountId().GetUserEmail()); + SetupEasyUnlockUserFlow(user_context.GetUserID()); switch (auth_mode_) { case AUTH_MODE_EXTENSION: { @@ -159,9 +156,8 @@ } void LoginPerformer::LoginAsSupervisedUser(const UserContext& user_context) { - DCHECK_EQ( - chromeos::login::kSupervisedUserDomain, - gaia::ExtractDomainName(user_context.GetAccountId().GetUserEmail())); + DCHECK_EQ(chromeos::login::kSupervisedUserDomain, + gaia::ExtractDomainName(user_context.GetUserID())); user_context_ = user_context; user_context_.SetUserType(user_manager::USER_TYPE_SUPERVISED); @@ -178,11 +174,11 @@ const UserContext& user_context) { if (!AreSupervisedUsersAllowed()) { LOG(ERROR) << "Login attempt of supervised user detected."; - delegate_->WhiteListCheckFailed(user_context.GetAccountId().GetUserEmail()); + delegate_->WhiteListCheckFailed(user_context.GetUserID()); return; } - SetupSupervisedUserFlow(user_context.GetAccountId().GetUserEmail()); + SetupSupervisedUserFlow(user_context.GetUserID()); UserContext user_context_copy = TransformSupervisedKey(user_context); if (UseExtendedAuthenticatorForSupervisedUser(user_context)) { @@ -206,7 +202,7 @@ } void LoginPerformer::LoginAsPublicSession(const UserContext& user_context) { - if (!CheckPolicyForUser(user_context.GetAccountId().GetUserEmail())) { + if (!CheckPolicyForUser(user_context.GetUserID())) { DCHECK(delegate_); if (delegate_) delegate_->PolicyLoadFailed();
diff --git a/chromeos/login/auth/stub_authenticator.cc b/chromeos/login/auth/stub_authenticator.cc index 371453d8..6a183a4 100644 --- a/chromeos/login/auth/stub_authenticator.cc +++ b/chromeos/login/auth/stub_authenticator.cc
@@ -38,7 +38,7 @@ authentication_context_ = context; // Don't compare the entire |expected_user_context_| to |user_context| because // during non-online re-auth |user_context| does not have a gaia id. - if (expected_user_context_.GetAccountId() == user_context.GetAccountId() && + if (expected_user_context_.GetUserID() == user_context.GetUserID() && *expected_user_context_.GetKey() == *user_context.GetKey()) { task_runner_->PostTask(FROM_HERE, base::Bind(&StubAuthenticator::OnAuthSuccess, this)); @@ -57,8 +57,7 @@ void StubAuthenticator::LoginAsSupervisedUser(const UserContext& user_context) { UserContext new_user_context = user_context; - new_user_context.SetUserIDHash(user_context.GetAccountId().GetUserEmail() + - kUserIdHashSuffix); + new_user_context.SetUserIDHash(user_context.GetUserID() + kUserIdHashSuffix); consumer_->OnAuthSuccess(new_user_context); } @@ -69,18 +68,17 @@ void StubAuthenticator::LoginAsPublicSession(const UserContext& user_context) { UserContext logged_in_user_context = user_context; logged_in_user_context.SetIsUsingOAuth(false); - logged_in_user_context.SetUserIDHash( - logged_in_user_context.GetAccountId().GetUserEmail() + kUserIdHashSuffix); + logged_in_user_context.SetUserIDHash(logged_in_user_context.GetUserID() + + kUserIdHashSuffix); consumer_->OnAuthSuccess(logged_in_user_context); } -void StubAuthenticator::LoginAsKioskAccount( - const std::string& /* app_user_id */, - bool use_guest_mount) { - UserContext user_context(expected_user_context_.GetAccountId()); +void StubAuthenticator::LoginAsKioskAccount(const std::string& app_user_id, + bool use_guest_mount) { + UserContext user_context(expected_user_context_.GetUserID()); user_context.SetIsUsingOAuth(false); - user_context.SetUserIDHash( - expected_user_context_.GetAccountId().GetUserEmail() + kUserIdHashSuffix); + user_context.SetUserIDHash(expected_user_context_.GetUserID() + + kUserIdHashSuffix); consumer_->OnAuthSuccess(user_context); } @@ -88,8 +86,8 @@ // If we want to be more like the real thing, we could save the user ID // in AuthenticateToLogin, but there's not much of a point. UserContext user_context(expected_user_context_); - user_context.SetUserIDHash( - expected_user_context_.GetAccountId().GetUserEmail() + kUserIdHashSuffix); + user_context.SetUserIDHash(expected_user_context_.GetUserID() + + kUserIdHashSuffix); consumer_->OnAuthSuccess(user_context); }
diff --git a/chromeos/login/auth/user_context.cc b/chromeos/login/auth/user_context.cc index 0060e3c4..1f630c2 100644 --- a/chromeos/login/auth/user_context.cc +++ b/chromeos/login/auth/user_context.cc
@@ -7,10 +7,14 @@ namespace chromeos { -UserContext::UserContext() : account_id_(EmptyAccountId()) {} +UserContext::UserContext() + : is_using_oauth_(true), + auth_flow_(AUTH_FLOW_OFFLINE), + user_type_(user_manager::USER_TYPE_REGULAR) { +} UserContext::UserContext(const UserContext& other) - : account_id_(other.account_id_), + : user_id_(other.user_id_), gaia_id_(other.gaia_id_), key_(other.key_), auth_code_(other.auth_code_), @@ -23,28 +27,32 @@ public_session_locale_(other.public_session_locale_), public_session_input_method_(other.public_session_input_method_), device_id_(other.device_id_), - gaps_cookie_(other.gaps_cookie_) {} + gaps_cookie_(other.gaps_cookie_) { +} -UserContext::UserContext(const AccountId& account_id) - : account_id_(account_id) { - account_id_.SetUserEmail( - login::CanonicalizeUserID(account_id.GetUserEmail())); +UserContext::UserContext(const std::string& user_id) + : user_id_(login::CanonicalizeUserID(user_id)), + is_using_oauth_(true), + auth_flow_(AUTH_FLOW_OFFLINE), + user_type_(user_manager::USER_TYPE_REGULAR) { } UserContext::UserContext(user_manager::UserType user_type, const std::string& user_id) - : account_id_(EmptyAccountId()), user_type_(user_type) { + : is_using_oauth_(true), + auth_flow_(AUTH_FLOW_OFFLINE), + user_type_(user_type) { if (user_type_ == user_manager::USER_TYPE_REGULAR) - account_id_ = AccountId::FromUserEmail(login::CanonicalizeUserID(user_id)); + user_id_ = login::CanonicalizeUserID(user_id); else - account_id_ = AccountId::FromUserEmail(user_id); + user_id_ = user_id; } UserContext::~UserContext() { } bool UserContext::operator==(const UserContext& context) const { - return context.account_id_ == account_id_ && context.gaia_id_ == gaia_id_ && + return context.user_id_ == user_id_ && context.gaia_id_ == gaia_id_ && context.key_ == key_ && context.auth_code_ == auth_code_ && context.refresh_token_ == refresh_token_ && context.access_token_ == access_token_ && @@ -59,8 +67,8 @@ return !(*this == context); } -const AccountId& UserContext::GetAccountId() const { - return account_id_; +const std::string& UserContext::GetUserID() const { + return user_id_; } const std::string& UserContext::GetGaiaID() const { @@ -120,12 +128,12 @@ } bool UserContext::HasCredentials() const { - return (account_id_.is_valid() && !key_.GetSecret().empty()) || + return (!user_id_.empty() && !key_.GetSecret().empty()) || !auth_code_.empty(); } void UserContext::SetUserID(const std::string& user_id) { - account_id_ = AccountId::FromUserEmail(login::CanonicalizeUserID(user_id)); + user_id_ = login::CanonicalizeUserID(user_id); } void UserContext::SetGaiaID(const std::string& gaia_id) {
diff --git a/chromeos/login/auth/user_context.h b/chromeos/login/auth/user_context.h index a4440cc..4dbd71b 100644 --- a/chromeos/login/auth/user_context.h +++ b/chromeos/login/auth/user_context.h
@@ -9,16 +9,12 @@ #include "chromeos/chromeos_export.h" #include "chromeos/login/auth/key.h" -#include "components/signin/core/account_id/account_id.h" #include "components/user_manager/user_type.h" -class AccountId; - namespace chromeos { // Information that is passed around while authentication is in progress. The -// credentials may consist of a |account_id_|, |key_| pair or a GAIA -// |auth_code_|. +// credentials may consist of a |user_id_|, |key_| pair or a GAIA |auth_code_|. // The |user_id_hash_| is used to locate the user's home directory // mount point for the user. It is set when the mount has been completed. class CHROMEOS_EXPORT UserContext { @@ -39,14 +35,14 @@ UserContext(); UserContext(const UserContext& other); - explicit UserContext(const AccountId& account_id); + explicit UserContext(const std::string& user_id); UserContext(user_manager::UserType user_type, const std::string& user_id); ~UserContext(); bool operator==(const UserContext& context) const; bool operator!=(const UserContext& context) const; - const AccountId& GetAccountId() const; + const std::string& GetUserID() const; const std::string& GetGaiaID() const; const Key* GetKey() const; Key* GetKey(); @@ -82,16 +78,16 @@ void ClearSecrets(); private: - AccountId account_id_; + std::string user_id_; std::string gaia_id_; Key key_; std::string auth_code_; std::string refresh_token_; std::string access_token_; // OAuthLogin scoped access token. std::string user_id_hash_; - bool is_using_oauth_ = true; - AuthFlow auth_flow_ = AUTH_FLOW_OFFLINE; - user_manager::UserType user_type_ = user_manager::USER_TYPE_REGULAR; + bool is_using_oauth_; + AuthFlow auth_flow_; + user_manager::UserType user_type_; std::string public_session_locale_; std::string public_session_input_method_; std::string device_id_;
diff --git a/components/devtools_service/BUILD.gn b/components/devtools_service/BUILD.gn index 44ea6e403..26ca66eb 100644 --- a/components/devtools_service/BUILD.gn +++ b/components/devtools_service/BUILD.gn
@@ -41,6 +41,8 @@ "main.cc", ] + avoid_runner_cycle = true + deps = [ ":lib", "//mojo/application/public/cpp",
diff --git a/components/test_runner/test_runner.cc b/components/test_runner/test_runner.cc index b35d7bf..6106761 100644 --- a/components/test_runner/test_runner.cc +++ b/components/test_runner/test_runner.cc
@@ -36,7 +36,6 @@ #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebFindOptions.h" #include "third_party/WebKit/public/web/WebFrame.h" -#include "third_party/WebKit/public/web/WebGraphicsContext.h" #include "third_party/WebKit/public/web/WebInputElement.h" #include "third_party/WebKit/public/web/WebKit.h" #include "third_party/WebKit/public/web/WebLocalFrame.h"
diff --git a/components/update_client/background_downloader_win.cc b/components/update_client/background_downloader_win.cc index 1c67a55..0b9814e 100644 --- a/components/update_client/background_downloader_win.cc +++ b/components/update_client/background_downloader_win.cc
@@ -310,19 +310,22 @@ // Compares the job creation time and returns true if the job creation time // is older than |num_days|. -struct JobCreationOlderThanDays - : public std::binary_function<IBackgroundCopyJob*, int, bool> { - bool operator()(IBackgroundCopyJob* job, int num_days) const; +class JobCreationOlderThanDays { + public: + JobCreationOlderThanDays(int num_days) : num_days_(num_days) {} + bool operator()(IBackgroundCopyJob* job) const; + + private: + int num_days_; }; -bool JobCreationOlderThanDays::operator()(IBackgroundCopyJob* job, - int num_days) const { +bool JobCreationOlderThanDays::operator()(IBackgroundCopyJob* job) const { BG_JOB_TIMES times = {}; HRESULT hr = job->GetTimes(×); if (FAILED(hr)) return false; - const base::TimeDelta time_delta(base::TimeDelta::FromDays(num_days)); + const base::TimeDelta time_delta(base::TimeDelta::FromDays(num_days_)); const base::Time creation_time(base::Time::FromFileTime(times.CreationTime)); return creation_time + time_delta < base::Time::Now(); @@ -330,15 +333,17 @@ // Compares the url of a file in a job and returns true if the remote name // of any file in a job matches the argument. -struct JobFileUrlEqual : public std::binary_function<IBackgroundCopyJob*, - const base::string16&, - bool> { - bool operator()(IBackgroundCopyJob* job, - const base::string16& remote_name) const; +class JobFileUrlEqual { + public: + JobFileUrlEqual(const base::string16& remote_name) + : remote_name_(remote_name) {} + bool operator()(IBackgroundCopyJob* job) const; + + private: + base::string16 remote_name_; }; -bool JobFileUrlEqual::operator()(IBackgroundCopyJob* job, - const base::string16& remote_name) const { +bool JobFileUrlEqual::operator()(IBackgroundCopyJob* job) const { std::vector<ScopedComPtr<IBackgroundCopyFile>> files; HRESULT hr = GetFilesInJob(job, &files); if (FAILED(hr)) @@ -347,7 +352,7 @@ for (size_t i = 0; i != files.size(); ++i) { ScopedCoMem<base::char16> name; if (SUCCEEDED(files[i]->GetRemoteName(&name)) && - remote_name.compare(name) == 0) + remote_name_.compare(name) == 0) return true; } @@ -395,7 +400,7 @@ std::vector<ScopedComPtr<IBackgroundCopyJob>> jobs; HRESULT hr = FindBitsJobIf( - std::bind2nd(JobCreationOlderThanDays(), kPurgeStaleJobsAfterDays), + JobCreationOlderThanDays(kPurgeStaleJobsAfterDays), bits_manager.get(), &jobs); if (FAILED(hr)) return hr; @@ -730,7 +735,7 @@ IBackgroundCopyJob** job) { std::vector<ScopedComPtr<IBackgroundCopyJob>> jobs; HRESULT hr = FindBitsJobIf( - std::bind2nd(JobFileUrlEqual(), base::SysUTF8ToWide(url.spec())), + JobFileUrlEqual(base::SysUTF8ToWide(url.spec())), bits_manager_.get(), &jobs); if (SUCCEEDED(hr) && !jobs.empty()) { *job = jobs.front().Detach();
diff --git a/components/update_client/update_client.cc b/components/update_client/update_client.cc index 8b8e598..03c77db 100644 --- a/components/update_client/update_client.cc +++ b/components/update_client/update_client.cc
@@ -81,6 +81,12 @@ UpdateClientImpl::~UpdateClientImpl() { DCHECK(thread_checker_.CalledOnValidThread()); + + while (!task_queue_.empty()) { + delete task_queue_.front(); + task_queue_.pop(); + } + config_ = nullptr; } @@ -105,8 +111,7 @@ crx_data_callback, callback)); // Install tasks are run concurrently and never queued up. - auto it = tasks_.insert(task.release()).first; - RunTask(*it); + RunTask(task.Pass()); } void UpdateClientImpl::Update(const std::vector<std::string>& ids, @@ -122,17 +127,17 @@ // If no other tasks are running at the moment, run this update task. // Otherwise, queue the task up. if (tasks_.empty()) { - auto it = tasks_.insert(task.release()).first; - RunTask(*it); + RunTask(task.Pass()); } else { task_queue_.push(task.release()); } } -void UpdateClientImpl::RunTask(Task* task) { +void UpdateClientImpl::RunTask(scoped_ptr<Task> task) { DCHECK(thread_checker_.CalledOnValidThread()); base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&Task::Run, base::Unretained(task))); + FROM_HERE, base::Bind(&Task::Run, base::Unretained(task.get()))); + tasks_.insert(task.release()); } void UpdateClientImpl::OnTaskComplete( @@ -151,7 +156,7 @@ // Pick up a task from the queue if the queue has pending tasks and no other // task is running. if (tasks_.empty() && !task_queue_.empty()) { - RunTask(task_queue_.front()); + RunTask(scoped_ptr<Task>(task_queue_.front()).Pass()); task_queue_.pop(); } }
diff --git a/components/update_client/update_client_internal.h b/components/update_client/update_client_internal.h index b74c696..0dc98be 100644 --- a/components/update_client/update_client_internal.h +++ b/components/update_client/update_client_internal.h
@@ -13,6 +13,8 @@ #include <vector> #include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" #include "base/observer_list.h" #include "base/threading/thread_checker.h" #include "components/update_client/crx_downloader.h" @@ -54,7 +56,7 @@ private: ~UpdateClientImpl() override; - void RunTask(Task* task); + void RunTask(scoped_ptr<Task> task); void OnTaskComplete(const CompletionCallback& completion_callback, Task* task, int error);
diff --git a/components/user_manager.gypi b/components/user_manager.gypi index 67f090d..de4297c 100644 --- a/components/user_manager.gypi +++ b/components/user_manager.gypi
@@ -8,6 +8,7 @@ 'user_manager_shared_sources': [ 'user_manager/empty_user_info.cc', 'user_manager/empty_user_info.h', + 'user_manager/user_id.h', 'user_manager/user_info.cc', 'user_manager/user_info.h', 'user_manager/user_info_impl.cc', @@ -35,7 +36,6 @@ 'type': '<(component)', 'dependencies': [ '<(DEPTH)/base/base.gyp:base', - '<(DEPTH)/components/components.gyp:signin_core_account_id', '<(DEPTH)/skia/skia.gyp:skia', '<(DEPTH)/ui/gfx/gfx.gyp:gfx', ],
diff --git a/components/user_manager/BUILD.gn b/components/user_manager/BUILD.gn index 55ab2a2..0dfc852 100644 --- a/components/user_manager/BUILD.gn +++ b/components/user_manager/BUILD.gn
@@ -6,6 +6,7 @@ sources = [ "empty_user_info.cc", "empty_user_info.h", + "user_id.h", "user_info.cc", "user_info.h", "user_info_impl.cc", @@ -15,7 +16,6 @@ deps = [ "//base", - "//components/signin/core/account_id", "//skia", "//ui/gfx", ] @@ -60,7 +60,6 @@ deps = [ ":user_manager", "//base", - "//components/signin/core/account_id", "//skia", "//ui/base", ]
diff --git a/components/user_manager/DEPS b/components/user_manager/DEPS index 5c77f80..c21fe3c 100644 --- a/components/user_manager/DEPS +++ b/components/user_manager/DEPS
@@ -4,7 +4,6 @@ "+chromeos/login/login_state.h", "+chromeos/login/user_names.h", "+components/session_manager/core/session_manager.h", -"+components/signin/core/account_id/account_id.h", "+google_apis/gaia/gaia_auth_util.h", "+third_party/skia/include", "+ui/base/l10n",
diff --git a/components/user_manager/empty_user_info.cc b/components/user_manager/empty_user_info.cc index 08d4a19f..ab886f1 100644 --- a/components/user_manager/empty_user_info.cc +++ b/components/user_manager/empty_user_info.cc
@@ -6,7 +6,6 @@ #include "base/logging.h" #include "base/strings/utf_string_conversions.h" -#include "components/signin/core/account_id/account_id.h" namespace user_manager { @@ -31,9 +30,9 @@ return std::string(); } -AccountId EmptyUserInfo::GetAccountId() const { +std::string EmptyUserInfo::GetUserID() const { NOTIMPLEMENTED(); - return EmptyAccountId(); + return std::string(); } const gfx::ImageSkia& EmptyUserInfo::GetImage() const {
diff --git a/components/user_manager/empty_user_info.h b/components/user_manager/empty_user_info.h index 76c0d16..52d677c 100644 --- a/components/user_manager/empty_user_info.h +++ b/components/user_manager/empty_user_info.h
@@ -25,7 +25,7 @@ base::string16 GetDisplayName() const override; base::string16 GetGivenName() const override; std::string GetEmail() const override; - AccountId GetAccountId() const override; + std::string GetUserID() const override; const gfx::ImageSkia& GetImage() const override; private:
diff --git a/components/user_manager/fake_user_manager.cc b/components/user_manager/fake_user_manager.cc index 4caa1b3..39f63f1 100644 --- a/components/user_manager/fake_user_manager.cc +++ b/components/user_manager/fake_user_manager.cc
@@ -31,30 +31,28 @@ FakeUserManager::FakeUserManager() : UserManagerBase(new FakeTaskRunner(), new FakeTaskRunner()), - primary_user_(nullptr) {} + primary_user_(NULL), + owner_email_(std::string()) { +} FakeUserManager::~FakeUserManager() { } -const user_manager::User* FakeUserManager::AddUser( - const AccountId& account_id) { - return AddUserWithAffiliation(account_id, false); +const user_manager::User* FakeUserManager::AddUser(const std::string& email) { + return AddUserWithAffiliation(email, false); } const user_manager::User* FakeUserManager::AddUserWithAffiliation( - const AccountId& account_id, - bool is_affiliated) { - user_manager::User* user = user_manager::User::CreateRegularUser(account_id); + const std::string& email, bool is_affiliated) { + user_manager::User* user = user_manager::User::CreateRegularUser(email); user->set_affiliation(is_affiliated); users_.push_back(user); return user; } -void FakeUserManager::RemoveUserFromList(const AccountId& account_id) { +void FakeUserManager::RemoveUserFromList(const std::string& email) { user_manager::UserList::iterator it = users_.begin(); - // TODO (alemate): Chenge this to GetAccountId(), once a real AccountId is - // passed. crbug.com/546876 - while (it != users_.end() && (*it)->GetEmail() != account_id.GetUserEmail()) + while (it != users_.end() && (*it)->email() != email) ++it; if (it != users_.end()) { delete *it; @@ -81,7 +79,7 @@ return logged_in_users_; } -void FakeUserManager::UserLoggedIn(const AccountId& account_id, +void FakeUserManager::UserLoggedIn(const std::string& email, const std::string& username_hash, bool browser_restart) { for (user_manager::UserList::const_iterator it = users_.begin(); @@ -99,20 +97,17 @@ } user_manager::User* FakeUserManager::GetActiveUserInternal() const { - if (!users_.empty()) { - if (active_account_id_.is_valid()) { + if (users_.size()) { + if (!active_user_id_.empty()) { for (user_manager::UserList::const_iterator it = users_.begin(); it != users_.end(); ++it) { - // TODO (alemate): Chenge this to GetAccountId(), once a real AccountId - // is - // passed. crbug.com/546876 - if ((*it)->GetEmail() == active_account_id_.GetUserEmail()) + if ((*it)->email() == active_user_id_) return *it; } } return users_[0]; } - return nullptr; + return NULL; } const user_manager::User* FakeUserManager::GetActiveUser() const { @@ -123,15 +118,14 @@ return GetActiveUserInternal(); } -void FakeUserManager::SwitchActiveUser(const AccountId& account_id) {} +void FakeUserManager::SwitchActiveUser(const std::string& email) { +} -void FakeUserManager::SaveUserDisplayName(const AccountId& account_id, +void FakeUserManager::SaveUserDisplayName(const std::string& username, const base::string16& display_name) { for (user_manager::UserList::iterator it = users_.begin(); it != users_.end(); ++it) { - // TODO (alemate): Chenge this to GetAccountId(), once a real AccountId is - // passed. crbug.com/546876 - if ((*it)->GetEmail() == account_id.GetUserEmail()) { + if ((*it)->email() == username) { (*it)->set_display_name(display_name); return; } @@ -146,38 +140,36 @@ return users_; } -const AccountId& FakeUserManager::GetOwnerAccountId() const { - return owner_account_id_; +const std::string& FakeUserManager::GetOwnerEmail() const { + return owner_email_; } -bool FakeUserManager::IsKnownUser(const AccountId& account_id) const { +bool FakeUserManager::IsKnownUser(const std::string& email) const { return true; } const user_manager::User* FakeUserManager::FindUser( - const AccountId& account_id) const { + const std::string& email) const { const user_manager::UserList& users = GetUsers(); for (user_manager::UserList::const_iterator it = users.begin(); it != users.end(); ++it) { - // TODO (alemate): Chenge this to GetAccountId(), once a real AccountId is - // passed. crbug.com/546876 - if ((*it)->GetEmail() == account_id.GetUserEmail()) + if ((*it)->email() == email) return *it; } - return nullptr; + return NULL; } user_manager::User* FakeUserManager::FindUserAndModify( - const AccountId& account_id) { - return nullptr; + const std::string& email) { + return NULL; } const user_manager::User* FakeUserManager::GetLoggedInUser() const { - return nullptr; + return NULL; } user_manager::User* FakeUserManager::GetLoggedInUser() { - return nullptr; + return NULL; } const user_manager::User* FakeUserManager::GetPrimaryUser() const { @@ -185,12 +177,12 @@ } base::string16 FakeUserManager::GetUserDisplayName( - const AccountId& account_id) const { + const std::string& username) const { return base::string16(); } std::string FakeUserManager::GetUserDisplayEmail( - const AccountId& account_id) const { + const std::string& username) const { return std::string(); } @@ -246,7 +238,7 @@ } bool FakeUserManager::IsUserNonCryptohomeDataEphemeral( - const AccountId& account_id) const { + const std::string& email) const { return false; } @@ -264,23 +256,23 @@ } PrefService* FakeUserManager::GetLocalState() const { - return nullptr; + return NULL; } bool FakeUserManager::IsEnterpriseManaged() const { return false; } -bool FakeUserManager::IsDemoApp(const AccountId& account_id) const { +bool FakeUserManager::IsDemoApp(const std::string& user_id) const { return false; } -bool FakeUserManager::IsKioskApp(const AccountId& account_id) const { +bool FakeUserManager::IsKioskApp(const std::string& user_id) const { return false; } bool FakeUserManager::IsPublicAccountMarkedForRemoval( - const AccountId& account_id) const { + const std::string& user_id) const { return false; }
diff --git a/components/user_manager/fake_user_manager.h b/components/user_manager/fake_user_manager.h index 77f1649..a40eed6e 100644 --- a/components/user_manager/fake_user_manager.h +++ b/components/user_manager/fake_user_manager.h
@@ -9,7 +9,6 @@ #include <string> #include "base/memory/scoped_ptr.h" -#include "components/signin/core/account_id/account_id.h" #include "components/user_manager/user.h" #include "components/user_manager/user_manager_base.h" @@ -24,16 +23,15 @@ // Create and add a new user. Created user is not affiliated with the domain, // that owns the device. - virtual const user_manager::User* AddUser(const AccountId& account_id); + virtual const user_manager::User* AddUser(const std::string& email); // The same as AddUser() but allows to specify user affiliation with the // domain, that owns the device. virtual const user_manager::User* AddUserWithAffiliation( - const AccountId& account_id, - bool is_affiliated); + const std::string& email, bool is_affiliated); // Calculates the user name hash and calls UserLoggedIn to login a user. - void LoginUser(const AccountId& account_id); + void LoginUser(const std::string& email); // UserManager overrides. const user_manager::UserList& GetUsers() const override; @@ -41,43 +39,42 @@ const user_manager::UserList& GetLoggedInUsers() const override; // Set the user as logged in. - void UserLoggedIn(const AccountId& account_id, + void UserLoggedIn(const std::string& email, const std::string& username_hash, bool browser_restart) override; const user_manager::User* GetActiveUser() const override; user_manager::User* GetActiveUser() override; - void SwitchActiveUser(const AccountId& account_id) override; - void SaveUserDisplayName(const AccountId& account_id, + void SwitchActiveUser(const std::string& email) override; + void SaveUserDisplayName(const std::string& username, const base::string16& display_name) override; // Not implemented. - void UpdateUserAccountData(const AccountId& account_id, + void UpdateUserAccountData(const std::string& user_id, const UserAccountData& account_data) override {} void Shutdown() override {} const user_manager::UserList& GetLRULoggedInUsers() const override; user_manager::UserList GetUnlockUsers() const override; - const AccountId& GetOwnerAccountId() const override; + const std::string& GetOwnerEmail() const override; void SessionStarted() override {} - void RemoveUser(const AccountId& account_id, + void RemoveUser(const std::string& email, user_manager::RemoveUserDelegate* delegate) override {} - void RemoveUserFromList(const AccountId& account_id) override; - bool IsKnownUser(const AccountId& account_id) const override; - const user_manager::User* FindUser( - const AccountId& account_id) const override; - user_manager::User* FindUserAndModify(const AccountId& account_id) override; + void RemoveUserFromList(const std::string& email) override; + bool IsKnownUser(const std::string& email) const override; + const user_manager::User* FindUser(const std::string& email) const override; + user_manager::User* FindUserAndModify(const std::string& email) override; const user_manager::User* GetLoggedInUser() const override; user_manager::User* GetLoggedInUser() override; const user_manager::User* GetPrimaryUser() const override; void SaveUserOAuthStatus( - const AccountId& account_id, + const std::string& username, user_manager::User::OAuthTokenStatus oauth_token_status) override {} - void SaveForceOnlineSignin(const AccountId& account_id, + void SaveForceOnlineSignin(const std::string& user_id, bool force_online_signin) override {} - base::string16 GetUserDisplayName(const AccountId& account_id) const override; - void SaveUserDisplayEmail(const AccountId& account_id, + base::string16 GetUserDisplayName(const std::string& username) const override; + void SaveUserDisplayEmail(const std::string& username, const std::string& display_email) override {} - std::string GetUserDisplayEmail(const AccountId& account_id) const override; + std::string GetUserDisplayEmail(const std::string& username) const override; bool IsCurrentUserOwner() const override; bool IsCurrentUserNew() const override; bool IsCurrentUserNonCryptohomeDataEphemeral() const override; @@ -91,7 +88,7 @@ bool IsLoggedInAsStub() const override; bool IsSessionStarted() const override; bool IsUserNonCryptohomeDataEphemeral( - const AccountId& account_id) const override; + const std::string& email) const override; void AddObserver(Observer* obs) override {} void RemoveObserver(Observer* obs) override {} void AddSessionStateObserver(UserSessionStateObserver* obs) override {} @@ -104,36 +101,37 @@ const std::string& GetApplicationLocale() const override; PrefService* GetLocalState() const override; void HandleUserOAuthTokenStatusChange( - const AccountId& account_id, + const std::string& user_id, user_manager::User::OAuthTokenStatus status) const override {} bool IsEnterpriseManaged() const override; - void LoadPublicAccounts(std::set<AccountId>* public_sessions_set) override {} + void LoadPublicAccounts(std::set<std::string>* public_sessions_set) override { + } void PerformPreUserListLoadingActions() override {} void PerformPostUserListLoadingActions() override {} void PerformPostUserLoggedInActions(bool browser_restart) override {} - bool IsDemoApp(const AccountId& account_id) const override; - bool IsKioskApp(const AccountId& account_id) const override; + bool IsDemoApp(const std::string& user_id) const override; + bool IsKioskApp(const std::string& user_id) const override; bool IsPublicAccountMarkedForRemoval( - const AccountId& account_id) const override; + const std::string& user_id) const override; void DemoAccountLoggedIn() override {} - void KioskAppLoggedIn(const AccountId& kiosk_app_account_id) override {} + void KioskAppLoggedIn(const std::string& app_id) override {} void PublicAccountUserLoggedIn(user_manager::User* user) override {} - void SupervisedUserLoggedIn(const AccountId& account_id) override {} - void OnUserRemoved(const AccountId& account_id) override {} + void SupervisedUserLoggedIn(const std::string& user_id) override {} + void OnUserRemoved(const std::string& user_id) override {} protected: user_manager::User* primary_user_; // If set this is the active user. If empty, the first created user is the // active user. - AccountId active_account_id_ = EmptyAccountId(); + std::string active_user_id_; private: // We use this internal function for const-correctness. user_manager::User* GetActiveUserInternal() const; - // stub, always empty. - AccountId owner_account_id_ = EmptyAccountId(); + // stub, always empty string. + std::string owner_email_; DISALLOW_COPY_AND_ASSIGN(FakeUserManager); };
diff --git a/components/user_manager/user.cc b/components/user_manager/user.cc index 39ef430d5..defc1173 100644 --- a/components/user_manager/user.cc +++ b/components/user_manager/user.cc
@@ -9,7 +9,6 @@ #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_restrictions.h" #include "chromeos/login/user_names.h" -#include "components/signin/core/account_id/account_id.h" #include "components/user_manager/user_image/default_user_images.h" #include "google_apis/gaia/gaia_auth_util.h" #include "ui/base/resource/resource_bundle.h" @@ -35,14 +34,10 @@ user_type == USER_TYPE_CHILD; } -const std::string& User::email() const { - return account_id_.GetUserEmail(); -} - // Also used for regular supervised users. class RegularUser : public User { public: - explicit RegularUser(const AccountId& account_id); + explicit RegularUser(const std::string& email); ~RegularUser() override; // Overridden from User: @@ -51,7 +46,7 @@ void SetIsChild(bool is_child) override; private: - bool is_child_ = false; + bool is_child_; DISALLOW_COPY_AND_ASSIGN(RegularUser); }; @@ -70,7 +65,7 @@ class KioskAppUser : public User { public: - explicit KioskAppUser(const AccountId& kiosk_app_account_id); + explicit KioskAppUser(const std::string& app_id); ~KioskAppUser() override; // Overridden from User: @@ -82,7 +77,7 @@ class SupervisedUser : public User { public: - explicit SupervisedUser(const AccountId& account_id); + explicit SupervisedUser(const std::string& username); ~SupervisedUser() override; // Overridden from User: @@ -95,7 +90,7 @@ class PublicAccountUser : public User { public: - explicit PublicAccountUser(const AccountId& account_id); + explicit PublicAccountUser(const std::string& email); ~PublicAccountUser() override; // Overridden from User: @@ -123,9 +118,8 @@ return user_image_.image(); } -AccountId User::GetAccountId() const { - return AccountId::FromUserEmail( - gaia::CanonicalizeEmail(gaia::SanitizeEmail(email()))); +UserID User::GetUserID() const { + return gaia::CanonicalizeEmail(gaia::SanitizeEmail(email())); } void User::SetIsChild(bool is_child) { @@ -150,7 +144,7 @@ if (use_display_email && !display_email_.empty()) return GetUserName(display_email_); else - return GetUserName(account_id_.GetUserEmail()); + return GetUserName(email_); } bool User::HasDefaultImage() const { @@ -181,27 +175,39 @@ return is_active_; } -User* User::CreateRegularUser(const AccountId& account_id) { - return new RegularUser(account_id); +User* User::CreateRegularUser(const std::string& email) { + return new RegularUser(email); } User* User::CreateGuestUser() { return new GuestUser; } -User* User::CreateKioskAppUser(const AccountId& kiosk_app_account_id) { - return new KioskAppUser(kiosk_app_account_id); +User* User::CreateKioskAppUser(const std::string& kiosk_app_username) { + return new KioskAppUser(kiosk_app_username); } -User* User::CreateSupervisedUser(const AccountId& account_id) { - return new SupervisedUser(account_id); +User* User::CreateSupervisedUser(const std::string& username) { + return new SupervisedUser(username); } -User* User::CreatePublicAccountUser(const AccountId& account_id) { - return new PublicAccountUser(account_id); +User* User::CreatePublicAccountUser(const std::string& email) { + return new PublicAccountUser(email); } -User::User(const AccountId& account_id) : account_id_(account_id) {} +User::User(const std::string& email) + : email_(email), + oauth_token_status_(OAUTH_TOKEN_STATUS_UNKNOWN), + force_online_signin_(false), + image_index_(USER_IMAGE_INVALID), + image_is_stub_(false), + image_is_loading_(false), + can_lock_(false), + is_logged_in_(false), + is_active_(false), + profile_is_created_(false), + is_affiliated_(false){ +} User::~User() { } @@ -231,9 +237,10 @@ image_is_loading_ = is_loading; } -RegularUser::RegularUser(const AccountId& account_id) : User(account_id) { +RegularUser::RegularUser(const std::string& email) + : User(email), is_child_(false) { set_can_lock(true); - set_display_email(account_id.GetUserEmail()); + set_display_email(email); } RegularUser::~RegularUser() { @@ -253,7 +260,7 @@ is_child_ = is_child; } -GuestUser::GuestUser() : User(chromeos::login::GuestAccountId()) { +GuestUser::GuestUser() : User(chromeos::login::kGuestUserName) { set_display_email(std::string()); } @@ -264,9 +271,9 @@ return user_manager::USER_TYPE_GUEST; } -KioskAppUser::KioskAppUser(const AccountId& kiosk_app_account_id) - : User(kiosk_app_account_id) { - set_display_email(kiosk_app_account_id.GetUserEmail()); +KioskAppUser::KioskAppUser(const std::string& kiosk_app_username) + : User(kiosk_app_username) { + set_display_email(kiosk_app_username); } KioskAppUser::~KioskAppUser() { @@ -276,7 +283,7 @@ return user_manager::USER_TYPE_KIOSK_APP; } -SupervisedUser::SupervisedUser(const AccountId& account_id) : User(account_id) { +SupervisedUser::SupervisedUser(const std::string& username) : User(username) { set_can_lock(true); } @@ -291,8 +298,8 @@ return base::UTF16ToUTF8(display_name()); } -PublicAccountUser::PublicAccountUser(const AccountId& account_id) - : User(account_id) {} +PublicAccountUser::PublicAccountUser(const std::string& email) : User(email) { +} PublicAccountUser::~PublicAccountUser() { }
diff --git a/components/user_manager/user.h b/components/user_manager/user.h index fe0899ef1..d961acf 100644 --- a/components/user_manager/user.h +++ b/components/user_manager/user.h
@@ -10,7 +10,7 @@ #include "base/basictypes.h" #include "base/strings/string16.h" -#include "components/signin/core/account_id/account_id.h" +#include "components/user_manager/user_id.h" #include "components/user_manager/user_image/user_image.h" #include "components/user_manager/user_info.h" #include "components/user_manager/user_manager_export.h" @@ -83,8 +83,7 @@ virtual UserType GetType() const = 0; // The email the user used to log in. - // TODO(alemate): rename this to GetUserEmail() (see crbug.com/548923) - const std::string& email() const; + const std::string& email() const { return email_; } // The displayed user name. base::string16 display_name() const { return display_name_; } @@ -97,7 +96,7 @@ base::string16 GetDisplayName() const override; base::string16 GetGivenName() const override; const gfx::ImageSkia& GetImage() const override; - AccountId GetAccountId() const override; + UserID GetUserID() const override; // Allows managing child status of the user. Used for RegularUser. virtual void SetIsChild(bool is_child); @@ -183,13 +182,13 @@ friend class chromeos::UserAddingScreenTest; // Do not allow anyone else to create new User instances. - static User* CreateRegularUser(const AccountId& account_id); + static User* CreateRegularUser(const UserID& email); static User* CreateGuestUser(); - static User* CreateKioskAppUser(const AccountId& kiosk_app_account_id); - static User* CreateSupervisedUser(const AccountId& account_id); - static User* CreatePublicAccountUser(const AccountId& account_id); + static User* CreateKioskAppUser(const UserID& kiosk_app_username); + static User* CreateSupervisedUser(const UserID& username); + static User* CreatePublicAccountUser(const UserID& email); - explicit User(const AccountId& account_id); + explicit User(const std::string& email); ~User() override; const std::string* GetAccountLocale() const { return account_locale_.get(); } @@ -252,15 +251,15 @@ } private: - AccountId account_id_; + std::string email_; base::string16 display_name_; base::string16 given_name_; // The displayed user email, defaults to |email_|. std::string display_email_; - bool using_saml_ = false; + bool using_saml_; UserImage user_image_; - OAuthTokenStatus oauth_token_status_ = OAUTH_TOKEN_STATUS_UNKNOWN; - bool force_online_signin_ = false; + OAuthTokenStatus oauth_token_status_; + bool force_online_signin_; // This is set to chromeos locale if account data has been downloaded. // (Or failed to download, but at least one download attempt finished). @@ -273,34 +272,34 @@ // Either index of a default image for the user, |USER_IMAGE_EXTERNAL| or // |USER_IMAGE_PROFILE|. - int image_index_ = USER_IMAGE_INVALID; + int image_index_; // True if current user image is a stub set by a |SetStubImage| call. - bool image_is_stub_ = false; + bool image_is_stub_; // True if current user image is being loaded from file. - bool image_is_loading_ = false; + bool image_is_loading_; // True if user is able to lock screen. - bool can_lock_ = false; + bool can_lock_; // True if user is currently logged in in current session. - bool is_logged_in_ = false; + bool is_logged_in_; // True if user is currently logged in and active in current session. - bool is_active_ = false; + bool is_active_; // True if user Profile is created - bool profile_is_created_ = false; + bool profile_is_created_; // True if the user is affiliated to the device. - bool is_affiliated_ = false; + bool is_affiliated_; DISALLOW_COPY_AND_ASSIGN(User); }; // List of known users. -using UserList = std::vector<User*>; +typedef std::vector<User*> UserList; } // namespace user_manager
diff --git a/components/user_manager/user_id.h b/components/user_manager/user_id.h new file mode 100644 index 0000000..bf8730a --- /dev/null +++ b/components/user_manager/user_id.h
@@ -0,0 +1,17 @@ +// 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 COMPONENTS_USER_MANAGER_USER_ID_H_ +#define COMPONENTS_USER_MANAGER_USER_ID_H_ + +#include <string> + +namespace user_manager { + +// Type that contains enough information to identify user on ChromeOS. +typedef std::string UserID; + +} // namespace user_manager + +#endif // COMPONENTS_USER_MANAGER_USER_ID_H_
diff --git a/components/user_manager/user_info.h b/components/user_manager/user_info.h index 2f0cf19..cc613c1 100644 --- a/components/user_manager/user_info.h +++ b/components/user_manager/user_info.h
@@ -8,10 +8,9 @@ #include <string> #include "base/strings/string16.h" +#include "components/user_manager/user_id.h" #include "components/user_manager/user_manager_export.h" -class AccountId; - namespace gfx { class ImageSkia; } @@ -35,8 +34,9 @@ // as well as capitalized letters. For example: "Foo.Bar@mock.com". virtual std::string GetEmail() const = 0; - // Returns AccountId for the user. - virtual AccountId GetAccountId() const = 0; + // Gets the user id (sanitized email address) for the user. + // The function would return something like "foobar@mock.com". + virtual UserID GetUserID() const = 0; // Gets the avatar image for the user. virtual const gfx::ImageSkia& GetImage() const = 0;
diff --git a/components/user_manager/user_info_impl.cc b/components/user_manager/user_info_impl.cc index cf6d2ad3..6aa21a8 100644 --- a/components/user_manager/user_info_impl.cc +++ b/components/user_manager/user_info_impl.cc
@@ -6,7 +6,6 @@ #include "base/logging.h" #include "base/strings/utf_string_conversions.h" -#include "components/signin/core/account_id/account_id.h" namespace user_manager { @@ -28,8 +27,8 @@ return "stub-user@domain.com"; } -AccountId UserInfoImpl::GetAccountId() const { - return AccountId::FromUserEmail(GetEmail()); +std::string UserInfoImpl::GetUserID() const { + return GetEmail(); } const gfx::ImageSkia& UserInfoImpl::GetImage() const {
diff --git a/components/user_manager/user_info_impl.h b/components/user_manager/user_info_impl.h index 4922e36..d23ca0c 100644 --- a/components/user_manager/user_info_impl.h +++ b/components/user_manager/user_info_impl.h
@@ -24,7 +24,7 @@ base::string16 GetDisplayName() const override; base::string16 GetGivenName() const override; std::string GetEmail() const override; - AccountId GetAccountId() const override; + std::string GetUserID() const override; const gfx::ImageSkia& GetImage() const override; private:
diff --git a/components/user_manager/user_manager.h b/components/user_manager/user_manager.h index 03a08d75..24b8c9a 100644 --- a/components/user_manager/user_manager.h +++ b/components/user_manager/user_manager.h
@@ -8,11 +8,10 @@ #include <string> #include "components/user_manager/user.h" +#include "components/user_manager/user_id.h" #include "components/user_manager/user_manager_export.h" #include "components/user_manager/user_type.h" -class AccountId; - namespace base { class DictionaryValue; } @@ -55,7 +54,7 @@ virtual void UserAddedToSession(const User* added_user); // Called right before notifying on user change so that those who rely - // on account_id hash would be accessing up-to-date value. + // on user_id hash would be accessing up-to-date value. virtual void ActiveUserHashChanged(const std::string& hash); // Called when child status has changed. @@ -139,22 +138,21 @@ // All users that are unable to perform unlock are excluded from this list. virtual UserList GetUnlockUsers() const = 0; - // Returns account Id of the owner user. Returns an empty Id if there is + // Returns the email of the owner user. Returns an empty string if there is // no owner for the device. - virtual const AccountId& GetOwnerAccountId() const = 0; + virtual const std::string& GetOwnerEmail() const = 0; - // Indicates that a user with the given |account_id| has just logged in. The + // Indicates that a user with the given |user_id| has just logged in. The // persistent list is updated accordingly if the user is not ephemeral. // |browser_restart| is true when reloading Chrome after crash to distinguish // from normal sign in flow. // |username_hash| is used to identify homedir mount point. - virtual void UserLoggedIn(const AccountId& account_id, + virtual void UserLoggedIn(const std::string& user_id, const std::string& username_hash, bool browser_restart) = 0; - // Switches to active user identified by |account_id|. User has to be logged - // in. - virtual void SwitchActiveUser(const AccountId& account_id) = 0; + // Switches to active user identified by |user_id|. User has to be logged in. + virtual void SwitchActiveUser(const std::string& user_id) = 0; // Switches to the last active user (called after crash happens and session // restore has completed). @@ -172,25 +170,25 @@ // Removes the user from the device. Note, it will verify that the given user // isn't the owner, so calling this method for the owner will take no effect. // Note, |delegate| can be NULL. - virtual void RemoveUser(const AccountId& account_id, + virtual void RemoveUser(const std::string& user_id, RemoveUserDelegate* delegate) = 0; // Removes the user from the persistent list only. Also removes the user's // picture. - virtual void RemoveUserFromList(const AccountId& account_id) = 0; + virtual void RemoveUserFromList(const std::string& user_id) = 0; - // Returns true if a user with the given account id is found in the persistent + // Returns true if a user with the given user id is found in the persistent // list or currently logged in as ephemeral. - virtual bool IsKnownUser(const AccountId& account_id) const = 0; + virtual bool IsKnownUser(const std::string& user_id) const = 0; - // Returns the user with the given account id if found in the persistent + // Returns the user with the given user id if found in the persistent // list or currently logged in as ephemeral. Returns |NULL| otherwise. - virtual const User* FindUser(const AccountId& account_id) const = 0; + virtual const User* FindUser(const std::string& user_id) const = 0; - // Returns the user with the given account id if found in the persistent + // Returns the user with the given user id if found in the persistent // list or currently logged in as ephemeral. Returns |NULL| otherwise. // Same as FindUser but returns non-const pointer to User object. - virtual User* FindUserAndModify(const AccountId& account_id) = 0; + virtual User* FindUserAndModify(const std::string& user_id) = 0; // Returns the logged-in user. // TODO(nkostylev): Deprecate this call, move clients to GetActiveUser(). @@ -210,43 +208,42 @@ // Saves user's oauth token status in local state preferences. virtual void SaveUserOAuthStatus( - const AccountId& account_id, + const std::string& user_id, User::OAuthTokenStatus oauth_token_status) = 0; // Saves a flag indicating whether online authentication against GAIA should // be enforced during the user's next sign-in. - virtual void SaveForceOnlineSignin(const AccountId& account_id, + virtual void SaveForceOnlineSignin(const std::string& user_id, bool force_online_signin) = 0; // Saves user's displayed name in local state preferences. // Ignored If there is no such user. - virtual void SaveUserDisplayName(const AccountId& account_id, + virtual void SaveUserDisplayName(const std::string& user_id, const base::string16& display_name) = 0; // Updates data upon User Account download. - virtual void UpdateUserAccountData(const AccountId& account_id, + virtual void UpdateUserAccountData(const std::string& user_id, const UserAccountData& account_data) = 0; - // Returns the display name for user |account_id| if it is known (was + // Returns the display name for user |user_id| if it is known (was // previously set by a |SaveUserDisplayName| call). // Otherwise, returns an empty string. virtual base::string16 GetUserDisplayName( - const AccountId& account_id) const = 0; + const std::string& user_id) const = 0; // Saves user's displayed (non-canonical) email in local state preferences. // Ignored If there is no such user. - virtual void SaveUserDisplayEmail(const AccountId& account_id, + virtual void SaveUserDisplayEmail(const std::string& user_id, const std::string& display_email) = 0; - // Returns the display email for user |account_id| if it is known (was + // Returns the display email for user |user_id| if it is known (was // previously set by a |SaveUserDisplayEmail| call). - // Otherwise, returns |account_id| itself. - virtual std::string GetUserDisplayEmail( - const AccountId& account_id) const = 0; + // Otherwise, returns |user_id| itself. + virtual std::string GetUserDisplayEmail(const std::string& user_id) const = 0; - // Saves user's type for user |account_id| into local state preferences. + // Saves user's type for user |user_id| into local state preferences. // Ignored If there is no such user. - virtual void SaveUserType(const AccountId& account_id, + virtual void SaveUserType(const std::string& user_id, const UserType& user_type) = 0; // Returns true if current user is an owner. @@ -293,12 +290,11 @@ // or restart after crash. virtual bool IsSessionStarted() const = 0; - // Returns true if data stored or cached for the user with the given - // |account_id| + // Returns true if data stored or cached for the user with the given user id // address outside that user's cryptohome (wallpaper, avatar, OAuth token // status, display name, display email) is to be treated as ephemeral. virtual bool IsUserNonCryptohomeDataEphemeral( - const AccountId& account_id) const = 0; + const std::string& user_id) const = 0; virtual void AddObserver(Observer* obs) = 0; virtual void RemoveObserver(Observer* obs) = 0; @@ -317,101 +313,95 @@ // Methods for storage/retrieval of per-user properties in Local State. - // Performs a lookup of properties associated with |account_id|. If found, + // Performs a lookup of properties associated with |user_id|. If found, // returns |true| and fills |out_value|. |out_value| can be NULL, if // only existence check is required. - virtual bool FindKnownUserPrefs(const AccountId& account_id, + virtual bool FindKnownUserPrefs(const UserID& user_id, const base::DictionaryValue** out_value) = 0; - // Updates (or creates) properties associated with |account_id| based + // Updates (or creates) properties associated with |user_id| based // on |values|. |clear| defines if existing properties are cleared (|true|) // or if it is just a incremental update (|false|). - virtual void UpdateKnownUserPrefs(const AccountId& account_id, + virtual void UpdateKnownUserPrefs(const UserID& user_id, const base::DictionaryValue& values, bool clear) = 0; - // Returns true if |account_id| preference by |path| does exist, + // Returns true if |user_id| preference by |path| does exist, // fills in |out_value|. Otherwise returns false. - virtual bool GetKnownUserStringPref(const AccountId& account_id, + virtual bool GetKnownUserStringPref(const UserID& user_id, const std::string& path, std::string* out_value) = 0; - // Updates user's identified by |account_id| string preference |path|. - virtual void SetKnownUserStringPref(const AccountId& account_id, + // Updates user's identified by |user_id| string preference |path|. + virtual void SetKnownUserStringPref(const UserID& user_id, const std::string& path, const std::string& in_value) = 0; - // Returns true if |account_id| preference by |path| does exist, + // Returns true if |user_id| preference by |path| does exist, // fills in |out_value|. Otherwise returns false. - virtual bool GetKnownUserBooleanPref(const AccountId& account_id, + virtual bool GetKnownUserBooleanPref(const UserID& user_id, const std::string& path, bool* out_value) = 0; - // Updates user's identified by |account_id| boolean preference |path|. - virtual void SetKnownUserBooleanPref(const AccountId& account_id, + // Updates user's identified by |user_id| boolean preference |path|. + virtual void SetKnownUserBooleanPref(const UserID& user_id, const std::string& path, const bool in_value) = 0; - // Returns true if |account_id| preference by |path| does exist, + // Returns true if |user_id| preference by |path| does exist, // fills in |out_value|. Otherwise returns false. - virtual bool GetKnownUserIntegerPref(const AccountId& account_id, + virtual bool GetKnownUserIntegerPref(const UserID& user_id, const std::string& path, int* out_value) = 0; - // Updates user's identified by |account_id| integer preference |path|. - virtual void SetKnownUserIntegerPref(const AccountId& account_id, + // Updates user's identified by |user_id| integer preference |path|. + virtual void SetKnownUserIntegerPref(const UserID& user_id, const std::string& path, const int in_value) = 0; - // Returns true if user's AccountId was found. - // Returns it in |out_account_id|. - virtual bool GetKnownUserAccountId(const AccountId& authenticated_account_id, - AccountId* out_account_id) = 0; + // Returns true if user's canonical email was found. + // Returns it in |out_email|. + virtual bool GetKnownUserCanonicalEmail(const UserID& user_id, + std::string* out_email) = 0; - // Updates |gaia_id| for user with |account_id|. - // TODO(alemate): Update this once AccountId contains GAIA ID - // (crbug.com/548926). - virtual void UpdateGaiaID(const AccountId& account_id, + // Updates |gaia_id| for user with |user_id|. + // TODO(antrim): Update this once UserID contains GAIA ID. + virtual void UpdateGaiaID(const UserID& user_id, const std::string& gaia_id) = 0; - // Find GAIA ID for user with |account_id|, fill in |out_value| and return - // true + // Find GAIA ID for user with |user_id|, fill in |out_value| and return true // if GAIA ID was found or false otherwise. - // TODO(antrim): Update this once AccountId contains GAIA ID - // (crbug.com/548926). - virtual bool FindGaiaID(const AccountId& account_id, - std::string* out_value) = 0; + // TODO(antrim): Update this once UserID contains GAIA ID. + virtual bool FindGaiaID(const UserID& user_id, std::string* out_value) = 0; // Saves whether the user authenticates using SAML. - virtual void UpdateUsingSAML(const AccountId& account_id, + virtual void UpdateUsingSAML(const UserID& user_id, const bool using_saml) = 0; // Returns if SAML needs to be used for authentication of the user with - // |account_id|, if it is known (was set by a |UpdateUsingSaml| call). - // Otherwise + // |user_id|, if it is known (was set by a |UpdateUsingSaml| call). Otherwise // returns false. - virtual bool FindUsingSAML(const AccountId& account_id) = 0; + virtual bool FindUsingSAML(const UserID& user_id) = 0; // Setter and getter for DeviceId known user string preference. - virtual void SetKnownUserDeviceId(const AccountId& account_id, + virtual void SetKnownUserDeviceId(const UserID& user_id, const std::string& device_id) = 0; - virtual std::string GetKnownUserDeviceId(const AccountId& account_id) = 0; + virtual std::string GetKnownUserDeviceId(const UserID& user_id) = 0; // Setter and getter for GAPSCookie known user string preference. - virtual void SetKnownUserGAPSCookie(const AccountId& account_id, + virtual void SetKnownUserGAPSCookie(const UserID& user_id, const std::string& gaps_cookie) = 0; - virtual std::string GetKnownUserGAPSCookie(const AccountId& account_id) = 0; + virtual std::string GetKnownUserGAPSCookie(const UserID& user_id) = 0; // Saves why the user has to go through re-auth flow. - virtual void UpdateReauthReason(const AccountId& account_id, + virtual void UpdateReauthReason(const UserID& user_id, const int reauth_reason) = 0; - // Returns the reason why the user with |account_id| has to go through the + // Returns the reason why the user with |user_id| has to go through the // re-auth flow. Returns true if such a reason was recorded or false // otherwise. - virtual bool FindReauthReason(const AccountId& account_id, - int* out_value) = 0; + virtual bool FindReauthReason(const UserID& user_id, int* out_value) = 0; protected: // Sets UserManager instance.
diff --git a/components/user_manager/user_manager_base.cc b/components/user_manager/user_manager_base.cc index 81a68ffa2..3bcb61c2 100644 --- a/components/user_manager/user_manager_base.cc +++ b/components/user_manager/user_manager_base.cc
@@ -115,26 +115,25 @@ ignore_result(l10n_util::CheckAndResolveLocale(raw_locale, resolved_locale)); } -// Checks if values in |dict| correspond with |account_id| identity. -bool UserMatches(const AccountId& account_id, - const base::DictionaryValue& dict) { +// Checks if values in |dict| correspond with |user_id| identity. +bool UserMatches(const UserID& user_id, const base::DictionaryValue& dict) { std::string value; bool has_email = dict.GetString(kCanonicalEmail, &value); - if (has_email && account_id.GetUserEmail() == value) + if (has_email && user_id == value) return true; // TODO(antrim): update code once user id is really a struct. bool has_gaia_id = dict.GetString(kGAIAIdKey, &value); - if (has_gaia_id && account_id.GetUserEmail() == value) + if (has_gaia_id && user_id == value) return true; return false; } -// Fills relevant |dict| values based on |account_id|. -void UpdateIdentity(const AccountId& account_id, base::DictionaryValue& dict) { - dict.SetString(kCanonicalEmail, account_id.GetUserEmail()); +// Fills relevant |dict| values based on |user_id|. +void UpdateIdentity(const UserID& user_id, base::DictionaryValue& dict) { + dict.SetString(kCanonicalEmail, user_id); } } // namespace @@ -156,7 +155,17 @@ UserManagerBase::UserManagerBase( scoped_refptr<base::TaskRunner> task_runner, scoped_refptr<base::TaskRunner> blocking_task_runner) - : task_runner_(task_runner), + : active_user_(NULL), + primary_user_(NULL), + user_loading_stage_(STAGE_NOT_LOADED), + session_started_(false), + is_current_user_owner_(false), + is_current_user_new_(false), + is_current_user_ephemeral_regular_user_(false), + ephemeral_users_enabled_(false), + manager_creation_time_(base::TimeTicks::Now()), + last_session_active_user_initialized_(false), + task_runner_(task_runner), blocking_task_runner_(blocking_task_runner), weak_factory_(this) { UpdateLoginState(); @@ -192,22 +201,21 @@ return lru_logged_in_users_; } -const AccountId& UserManagerBase::GetOwnerAccountId() const { - return owner_account_id_; +const std::string& UserManagerBase::GetOwnerEmail() const { + return owner_email_; } -void UserManagerBase::UserLoggedIn(const AccountId& account_id, +void UserManagerBase::UserLoggedIn(const std::string& user_id, const std::string& username_hash, bool browser_restart) { DCHECK(task_runner_->RunsTasksOnCurrentThread()); - if (!last_session_active_account_id_initialized_) { - last_session_active_account_id_ = - AccountId::FromUserEmail(GetLocalState()->GetString(kLastActiveUser)); - last_session_active_account_id_initialized_ = true; + if (!last_session_active_user_initialized_) { + last_session_active_user_ = GetLocalState()->GetString(kLastActiveUser); + last_session_active_user_initialized_ = true; } - User* user = FindUserInListAndModify(account_id); + User* user = FindUserInListAndModify(user_id); if (active_user_ && user) { user->set_is_logged_in(true); user->set_username_hash(username_hash); @@ -221,11 +229,11 @@ return; } - if (account_id == chromeos::login::GuestAccountId()) { + if (user_id == chromeos::login::kGuestUserName) { GuestUserLoggedIn(); - } else if (IsKioskApp(account_id)) { - KioskAppLoggedIn(account_id); - } else if (IsDemoApp(account_id)) { + } else if (IsKioskApp(user_id)) { + KioskAppLoggedIn(user_id); + } else if (IsDemoApp(user_id)) { DemoAccountLoggedIn(); } else { EnsureUsersLoaded(); @@ -234,16 +242,16 @@ PublicAccountUserLoggedIn(user); } else if ((user && user->GetType() == USER_TYPE_SUPERVISED) || (!user && - gaia::ExtractDomainName(account_id.GetUserEmail()) == + gaia::ExtractDomainName(user_id) == chromeos::login::kSupervisedUserDomain)) { - SupervisedUserLoggedIn(account_id); - } else if (browser_restart && IsPublicAccountMarkedForRemoval(account_id)) { - PublicAccountUserLoggedIn(User::CreatePublicAccountUser(account_id)); - } else if (account_id != GetOwnerAccountId() && !user && + SupervisedUserLoggedIn(user_id); + } else if (browser_restart && IsPublicAccountMarkedForRemoval(user_id)) { + PublicAccountUserLoggedIn(User::CreatePublicAccountUser(user_id)); + } else if (user_id != GetOwnerEmail() && !user && (AreEphemeralUsersEnabled() || browser_restart)) { - RegularUserLoggedInAsEphemeral(account_id); + RegularUserLoggedInAsEphemeral(user_id); } else { - RegularUserLoggedIn(account_id); + RegularUserLoggedIn(user_id); } } @@ -259,22 +267,21 @@ if (!primary_user_) { primary_user_ = active_user_; if (primary_user_->HasGaiaAccount()) - SendGaiaUserLoginMetrics(account_id); + SendGaiaUserLoginMetrics(user_id); } UMA_HISTOGRAM_ENUMERATION( "UserManager.LoginUserType", active_user_->GetType(), NUM_USER_TYPES); GetLocalState()->SetString( - kLastLoggedInGaiaUser, - active_user_->HasGaiaAccount() ? account_id.GetUserEmail() : ""); + kLastLoggedInGaiaUser, active_user_->HasGaiaAccount() ? user_id : ""); NotifyOnLogin(); PerformPostUserLoggedInActions(browser_restart); } -void UserManagerBase::SwitchActiveUser(const AccountId& account_id) { - User* user = FindUserAndModify(account_id); +void UserManagerBase::SwitchActiveUser(const std::string& user_id) { + User* user = FindUserAndModify(user_id); if (!user) { NOTREACHED() << "Switching to a non-existing user"; return; @@ -310,15 +317,14 @@ } void UserManagerBase::SwitchToLastActiveUser() { - if (!last_session_active_account_id_.is_valid()) + if (last_session_active_user_.empty()) return; - if (AccountId::FromUserEmail(GetActiveUser()->email()) != - last_session_active_account_id_) - SwitchActiveUser(last_session_active_account_id_); + if (GetActiveUser()->email() != last_session_active_user_) + SwitchActiveUser(last_session_active_user_); // Make sure that this function gets run only once. - last_session_active_account_id_.clear(); + last_session_active_user_.clear(); } void UserManagerBase::SessionStarted() { @@ -335,48 +341,47 @@ } } -void UserManagerBase::RemoveUser(const AccountId& account_id, +void UserManagerBase::RemoveUser(const std::string& user_id, RemoveUserDelegate* delegate) { DCHECK(task_runner_->RunsTasksOnCurrentThread()); - if (!CanUserBeRemoved(FindUser(account_id))) + if (!CanUserBeRemoved(FindUser(user_id))) return; - RemoveUserInternal(account_id, delegate); + RemoveUserInternal(user_id, delegate); } -void UserManagerBase::RemoveUserInternal(const AccountId& account_id, +void UserManagerBase::RemoveUserInternal(const std::string& user_email, RemoveUserDelegate* delegate) { - RemoveNonOwnerUserInternal(account_id, delegate); + RemoveNonOwnerUserInternal(user_email, delegate); } -void UserManagerBase::RemoveNonOwnerUserInternal(const AccountId& account_id, +void UserManagerBase::RemoveNonOwnerUserInternal(const std::string& user_email, RemoveUserDelegate* delegate) { if (delegate) - delegate->OnBeforeUserRemoved(account_id.GetUserEmail()); - RemoveUserFromList(account_id); + delegate->OnBeforeUserRemoved(user_email); + RemoveUserFromList(user_email); cryptohome::AsyncMethodCaller::GetInstance()->AsyncRemove( - account_id.GetUserEmail(), - base::Bind(&OnRemoveUserComplete, account_id.GetUserEmail())); + user_email, base::Bind(&OnRemoveUserComplete, user_email)); if (delegate) - delegate->OnUserRemoved(account_id.GetUserEmail()); + delegate->OnUserRemoved(user_email); } -void UserManagerBase::RemoveUserFromList(const AccountId& account_id) { +void UserManagerBase::RemoveUserFromList(const std::string& user_id) { DCHECK(task_runner_->RunsTasksOnCurrentThread()); - RemoveNonCryptohomeData(account_id); + RemoveNonCryptohomeData(user_id); if (user_loading_stage_ == STAGE_LOADED) { - DeleteUser(RemoveRegularOrSupervisedUserFromList(account_id)); + DeleteUser(RemoveRegularOrSupervisedUserFromList(user_id)); } else if (user_loading_stage_ == STAGE_LOADING) { - DCHECK(gaia::ExtractDomainName(account_id.GetUserEmail()) == + DCHECK(gaia::ExtractDomainName(user_id) == chromeos::login::kSupervisedUserDomain || - HasPendingBootstrap(account_id)); + HasPendingBootstrap(user_id)); // Special case, removing partially-constructed supervised user or // boostrapping user during user list loading. ListPrefUpdate users_update(GetLocalState(), kRegularUsers); - users_update->Remove(base::StringValue(account_id.GetUserEmail()), nullptr); - OnUserRemoved(account_id); + users_update->Remove(base::StringValue(user_id), NULL); + OnUserRemoved(user_id); } else { NOTREACHED() << "Users are not loaded yet."; return; @@ -386,22 +391,22 @@ GetLocalState()->CommitPendingWrite(); } -bool UserManagerBase::IsKnownUser(const AccountId& account_id) const { - return FindUser(account_id) != nullptr; +bool UserManagerBase::IsKnownUser(const std::string& user_id) const { + return FindUser(user_id) != NULL; } -const User* UserManagerBase::FindUser(const AccountId& account_id) const { +const User* UserManagerBase::FindUser(const std::string& user_id) const { DCHECK(task_runner_->RunsTasksOnCurrentThread()); - if (active_user_ && active_user_->GetAccountId() == account_id) + if (active_user_ && active_user_->email() == user_id) return active_user_; - return FindUserInList(account_id); + return FindUserInList(user_id); } -User* UserManagerBase::FindUserAndModify(const AccountId& account_id) { +User* UserManagerBase::FindUserAndModify(const std::string& user_id) { DCHECK(task_runner_->RunsTasksOnCurrentThread()); - if (active_user_ && active_user_->GetAccountId() == account_id) + if (active_user_ && active_user_->email() == user_id) return active_user_; - return FindUserInListAndModify(account_id); + return FindUserInListAndModify(user_id); } const User* UserManagerBase::GetLoggedInUser() const { @@ -430,73 +435,73 @@ } void UserManagerBase::SaveUserOAuthStatus( - const AccountId& account_id, + const std::string& user_id, User::OAuthTokenStatus oauth_token_status) { DCHECK(task_runner_->RunsTasksOnCurrentThread()); DVLOG(1) << "Saving user OAuth token status in Local State"; - User* user = FindUserAndModify(account_id); + User* user = FindUserAndModify(user_id); if (user) user->set_oauth_token_status(oauth_token_status); // Do not update local state if data stored or cached outside the user's // cryptohome is to be treated as ephemeral. - if (IsUserNonCryptohomeDataEphemeral(account_id)) + if (IsUserNonCryptohomeDataEphemeral(user_id)) return; DictionaryPrefUpdate oauth_status_update(GetLocalState(), kUserOAuthTokenStatus); oauth_status_update->SetWithoutPathExpansion( - account_id.GetUserEmail(), + user_id, new base::FundamentalValue(static_cast<int>(oauth_token_status))); } -void UserManagerBase::SaveForceOnlineSignin(const AccountId& account_id, +void UserManagerBase::SaveForceOnlineSignin(const std::string& user_id, bool force_online_signin) { DCHECK(task_runner_->RunsTasksOnCurrentThread()); // Do not update local state if data stored or cached outside the user's // cryptohome is to be treated as ephemeral. - if (IsUserNonCryptohomeDataEphemeral(account_id)) + if (IsUserNonCryptohomeDataEphemeral(user_id)) return; DictionaryPrefUpdate force_online_update(GetLocalState(), kUserForceOnlineSignin); - force_online_update->SetBooleanWithoutPathExpansion(account_id.GetUserEmail(), + force_online_update->SetBooleanWithoutPathExpansion(user_id, force_online_signin); } -void UserManagerBase::SaveUserDisplayName(const AccountId& account_id, +void UserManagerBase::SaveUserDisplayName(const std::string& user_id, const base::string16& display_name) { DCHECK(task_runner_->RunsTasksOnCurrentThread()); - if (User* user = FindUserAndModify(account_id)) { + if (User* user = FindUserAndModify(user_id)) { user->set_display_name(display_name); // Do not update local state if data stored or cached outside the user's // cryptohome is to be treated as ephemeral. - if (!IsUserNonCryptohomeDataEphemeral(account_id)) { + if (!IsUserNonCryptohomeDataEphemeral(user_id)) { DictionaryPrefUpdate display_name_update(GetLocalState(), kUserDisplayName); display_name_update->SetWithoutPathExpansion( - account_id.GetUserEmail(), new base::StringValue(display_name)); + user_id, new base::StringValue(display_name)); } } } base::string16 UserManagerBase::GetUserDisplayName( - const AccountId& account_id) const { - const User* user = FindUser(account_id); + const std::string& user_id) const { + const User* user = FindUser(user_id); return user ? user->display_name() : base::string16(); } -void UserManagerBase::SaveUserDisplayEmail(const AccountId& account_id, +void UserManagerBase::SaveUserDisplayEmail(const std::string& user_id, const std::string& display_email) { DCHECK(task_runner_->RunsTasksOnCurrentThread()); - User* user = FindUserAndModify(account_id); + User* user = FindUserAndModify(user_id); if (!user) { - LOG(ERROR) << "User not found: " << account_id.GetUserEmail(); + LOG(ERROR) << "User not found: " << user_id; return; // Ignore if there is no such user. } @@ -504,89 +509,88 @@ // Do not update local state if data stored or cached outside the user's // cryptohome is to be treated as ephemeral. - if (IsUserNonCryptohomeDataEphemeral(account_id)) + if (IsUserNonCryptohomeDataEphemeral(user_id)) return; DictionaryPrefUpdate display_email_update(GetLocalState(), kUserDisplayEmail); display_email_update->SetWithoutPathExpansion( - account_id.GetUserEmail(), new base::StringValue(display_email)); + user_id, new base::StringValue(display_email)); } std::string UserManagerBase::GetUserDisplayEmail( - const AccountId& account_id) const { - const User* user = FindUser(account_id); - return user ? user->display_email() : account_id.GetUserEmail(); + const std::string& user_id) const { + const User* user = FindUser(user_id); + return user ? user->display_email() : user_id; } -void UserManagerBase::SaveUserType(const AccountId& account_id, +void UserManagerBase::SaveUserType(const std::string& user_id, const UserType& user_type) { DCHECK(task_runner_->RunsTasksOnCurrentThread()); - User* user = FindUserAndModify(account_id); + User* user = FindUserAndModify(user_id); if (!user) { - LOG(ERROR) << "User not found: " << account_id.GetUserEmail(); + LOG(ERROR) << "User not found: " << user_id; return; // Ignore if there is no such user. } // Do not update local state if data stored or cached outside the user's // cryptohome is to be treated as ephemeral. - if (IsUserNonCryptohomeDataEphemeral(account_id)) + if (IsUserNonCryptohomeDataEphemeral(user_id)) return; DictionaryPrefUpdate user_type_update(GetLocalState(), kUserType); user_type_update->SetWithoutPathExpansion( - account_id.GetUserEmail(), - new base::FundamentalValue(static_cast<int>(user_type))); + user_id, new base::FundamentalValue(static_cast<int>(user_type))); GetLocalState()->CommitPendingWrite(); } -void UserManagerBase::UpdateUsingSAML(const AccountId& account_id, +void UserManagerBase::UpdateUsingSAML(const std::string& user_id, const bool using_saml) { - SetKnownUserBooleanPref(account_id, kUsingSAMLKey, using_saml); + SetKnownUserBooleanPref(user_id, kUsingSAMLKey, using_saml); } -bool UserManagerBase::FindUsingSAML(const AccountId& account_id) { +bool UserManagerBase::FindUsingSAML(const std::string& user_id) { bool using_saml; - if (GetKnownUserBooleanPref(account_id, kUsingSAMLKey, &using_saml)) + if (GetKnownUserBooleanPref(user_id, kUsingSAMLKey, &using_saml)) return using_saml; return false; } -void UserManagerBase::UpdateReauthReason(const AccountId& account_id, +void UserManagerBase::UpdateReauthReason(const std::string& user_id, const int reauth_reason) { - SetKnownUserIntegerPref(account_id, kReauthReasonKey, reauth_reason); + SetKnownUserIntegerPref(user_id, kReauthReasonKey, reauth_reason); } -bool UserManagerBase::FindReauthReason(const AccountId& account_id, +bool UserManagerBase::FindReauthReason(const std::string& user_id, int* out_value) { - return GetKnownUserIntegerPref(account_id, kReauthReasonKey, out_value); + return GetKnownUserIntegerPref(user_id, kReauthReasonKey, out_value); } void UserManagerBase::UpdateUserAccountData( - const AccountId& account_id, + const std::string& user_id, const UserAccountData& account_data) { DCHECK(task_runner_->RunsTasksOnCurrentThread()); - SaveUserDisplayName(account_id, account_data.display_name()); + SaveUserDisplayName(user_id, account_data.display_name()); - if (User* user = FindUserAndModify(account_id)) { + if (User* user = FindUserAndModify(user_id)) { base::string16 given_name = account_data.given_name(); user->set_given_name(given_name); - if (!IsUserNonCryptohomeDataEphemeral(account_id)) { + if (!IsUserNonCryptohomeDataEphemeral(user_id)) { DictionaryPrefUpdate given_name_update(GetLocalState(), kUserGivenName); given_name_update->SetWithoutPathExpansion( - account_id.GetUserEmail(), new base::StringValue(given_name)); + user_id, new base::StringValue(given_name)); } } - UpdateUserAccountLocale(account_id, account_data.locale()); + UpdateUserAccountLocale(user_id, account_data.locale()); } // static void UserManagerBase::ParseUserList(const base::ListValue& users_list, - const std::set<AccountId>& existing_users, - std::vector<AccountId>* users_vector, - std::set<AccountId>* users_set) { + const std::set<std::string>& existing_users, + std::vector<std::string>* users_vector, + std::set<std::string>* users_set) { users_vector->clear(); users_set->clear(); for (size_t i = 0; i < users_list.GetSize(); ++i) { @@ -595,13 +599,12 @@ LOG(ERROR) << "Corrupt entry in user list at index " << i << "."; continue; } - const AccountId account_id(AccountId::FromUserEmail(email)); - if (existing_users.find(account_id) != existing_users.end() || - !users_set->insert(account_id).second) { + if (existing_users.find(email) != existing_users.end() || + !users_set->insert(email).second) { LOG(ERROR) << "Duplicate user: " << email; continue; } - users_vector->push_back(account_id); + users_vector->push_back(email); } } @@ -628,7 +631,7 @@ bool UserManagerBase::IsCurrentUserNonCryptohomeDataEphemeral() const { DCHECK(task_runner_->RunsTasksOnCurrentThread()); return IsUserLoggedIn() && - IsUserNonCryptohomeDataEphemeral(GetLoggedInUser()->GetAccountId()); + IsUserNonCryptohomeDataEphemeral(GetLoggedInUser()->email()); } bool UserManagerBase::CanCurrentUserLock() const { @@ -684,17 +687,17 @@ } bool UserManagerBase::IsUserNonCryptohomeDataEphemeral( - const AccountId& account_id) const { + const std::string& user_id) const { // Data belonging to the guest and stub users is always ephemeral. - if (account_id == chromeos::login::GuestAccountId() || - account_id == chromeos::login::StubAccountId()) { + if (user_id == chromeos::login::kGuestUserName || + user_id == chromeos::login::kStubUser) { return true; } // Data belonging to the owner, anyone found on the user list and obsolete // public accounts whose data has not been removed yet is not ephemeral. - if (account_id == GetOwnerAccountId() || UserExistsInList(account_id) || - IsPublicAccountMarkedForRemoval(account_id)) { + if (user_id == GetOwnerEmail() || UserExistsInList(user_id) || + IsPublicAccountMarkedForRemoval(user_id)) { return false; } @@ -703,7 +706,7 @@ // policy was enabled. // - or - // b) The user logged into any other account type. - if (IsUserLoggedIn() && (account_id == GetLoggedInUser()->GetAccountId()) && + if (IsUserLoggedIn() && (user_id == GetLoggedInUser()->email()) && (is_current_user_ephemeral_regular_user_ || !IsLoggedInAsUserWithGaiaAccount())) { return true; @@ -783,20 +786,20 @@ is_current_user_new_ = is_new; } -bool UserManagerBase::HasPendingBootstrap(const AccountId& account_id) const { +bool UserManagerBase::HasPendingBootstrap(const std::string& user_id) const { return false; } -void UserManagerBase::SetOwnerId(const AccountId& owner_account_id) { - owner_account_id_ = owner_account_id; +void UserManagerBase::SetOwnerEmail(const std::string& owner_user_id) { + owner_email_ = owner_user_id; } -const AccountId& UserManagerBase::GetPendingUserSwitchID() const { +const std::string& UserManagerBase::GetPendingUserSwitchID() const { return pending_user_switch_; } -void UserManagerBase::SetPendingUserSwitchId(const AccountId& account_id) { - pending_user_switch_ = account_id; +void UserManagerBase::SetPendingUserSwitchID(const std::string& user_id) { + pending_user_switch_ = user_id; } void UserManagerBase::EnsureUsersLoaded() { @@ -824,27 +827,27 @@ local_state->GetDictionary(kUserType); // Load public sessions first. - std::set<AccountId> public_sessions_set; + std::set<std::string> public_sessions_set; LoadPublicAccounts(&public_sessions_set); // Load regular users and supervised users. - std::vector<AccountId> regular_users; - std::set<AccountId> regular_users_set; + std::vector<std::string> regular_users; + std::set<std::string> regular_users_set; ParseUserList(*prefs_regular_users, public_sessions_set, ®ular_users, ®ular_users_set); - for (std::vector<AccountId>::const_iterator it = regular_users.begin(); - it != regular_users.end(); ++it) { - User* user = nullptr; - const std::string domain = gaia::ExtractDomainName(it->GetUserEmail()); + for (std::vector<std::string>::const_iterator it = regular_users.begin(); + it != regular_users.end(); + ++it) { + User* user = NULL; + const std::string domain = gaia::ExtractDomainName(*it); if (domain == chromeos::login::kSupervisedUserDomain) { user = User::CreateSupervisedUser(*it); } else { user = User::CreateRegularUser(*it); int user_type; - if (prefs_user_types->GetIntegerWithoutPathExpansion(it->GetUserEmail(), - &user_type) && + if (prefs_user_types->GetIntegerWithoutPathExpansion(*it, &user_type) && user_type == USER_TYPE_CHILD) { ChangeUserChildStatus(user, true /* is child */); } @@ -855,19 +858,18 @@ users_.push_back(user); base::string16 display_name; - if (prefs_display_names->GetStringWithoutPathExpansion(it->GetUserEmail(), + if (prefs_display_names->GetStringWithoutPathExpansion(*it, &display_name)) { user->set_display_name(display_name); } base::string16 given_name; - if (prefs_given_names->GetStringWithoutPathExpansion(it->GetUserEmail(), - &given_name)) { + if (prefs_given_names->GetStringWithoutPathExpansion(*it, &given_name)) { user->set_given_name(given_name); } std::string display_email; - if (prefs_display_emails->GetStringWithoutPathExpansion(it->GetUserEmail(), + if (prefs_display_emails->GetStringWithoutPathExpansion(*it, &display_email)) { user->set_display_email(display_email); } @@ -883,32 +885,32 @@ return users_; } -const User* UserManagerBase::FindUserInList(const AccountId& account_id) const { +const User* UserManagerBase::FindUserInList(const std::string& user_id) const { const UserList& users = GetUsers(); for (UserList::const_iterator it = users.begin(); it != users.end(); ++it) { - if ((*it)->GetAccountId() == account_id) + if ((*it)->email() == user_id) return *it; } - return nullptr; + return NULL; } -bool UserManagerBase::UserExistsInList(const AccountId& account_id) const { +bool UserManagerBase::UserExistsInList(const std::string& user_id) const { const base::ListValue* user_list = GetLocalState()->GetList(kRegularUsers); for (size_t i = 0; i < user_list->GetSize(); ++i) { std::string email; - if (user_list->GetString(i, &email) && (account_id.GetUserEmail() == email)) + if (user_list->GetString(i, &email) && (user_id == email)) return true; } return false; } -User* UserManagerBase::FindUserInListAndModify(const AccountId& account_id) { +User* UserManagerBase::FindUserInListAndModify(const std::string& user_id) { UserList& users = GetUsersAndModify(); for (UserList::iterator it = users.begin(); it != users.end(); ++it) { - if ((*it)->GetAccountId() == account_id) + if ((*it)->email() == user_id) return *it; } - return nullptr; + return NULL; } void UserManagerBase::GuestUserLoggedIn() { @@ -923,16 +925,16 @@ users_.insert(users_.begin(), user); } -void UserManagerBase::RegularUserLoggedIn(const AccountId& account_id) { +void UserManagerBase::RegularUserLoggedIn(const std::string& user_id) { // Remove the user from the user list. - active_user_ = RemoveRegularOrSupervisedUserFromList(account_id); + active_user_ = RemoveRegularOrSupervisedUserFromList(user_id); // If the user was not found on the user list, create a new user. SetIsCurrentUserNew(!active_user_); if (IsCurrentUserNew()) { - active_user_ = User::CreateRegularUser(account_id); - active_user_->set_oauth_token_status(LoadUserOAuthStatus(account_id)); - SaveUserDisplayName(active_user_->GetAccountId(), + active_user_ = User::CreateRegularUser(user_id); + active_user_->set_oauth_token_status(LoadUserOAuthStatus(user_id)); + SaveUserDisplayName(active_user_->email(), base::UTF8ToUTF16(active_user_->GetAccountName(true))); } @@ -943,11 +945,11 @@ } void UserManagerBase::RegularUserLoggedInAsEphemeral( - const AccountId& account_id) { + const std::string& user_id) { DCHECK(task_runner_->RunsTasksOnCurrentThread()); SetIsCurrentUserNew(true); is_current_user_ephemeral_regular_user_ = true; - active_user_ = User::CreateRegularUser(account_id); + active_user_ = User::CreateRegularUser(user_id); } void UserManagerBase::NotifyOnLogin() { @@ -959,83 +961,77 @@ } User::OAuthTokenStatus UserManagerBase::LoadUserOAuthStatus( - const AccountId& account_id) const { + const std::string& user_id) const { DCHECK(task_runner_->RunsTasksOnCurrentThread()); const base::DictionaryValue* prefs_oauth_status = GetLocalState()->GetDictionary(kUserOAuthTokenStatus); int oauth_token_status = User::OAUTH_TOKEN_STATUS_UNKNOWN; if (prefs_oauth_status && - prefs_oauth_status->GetIntegerWithoutPathExpansion( - account_id.GetUserEmail(), &oauth_token_status)) { + prefs_oauth_status->GetIntegerWithoutPathExpansion(user_id, + &oauth_token_status)) { User::OAuthTokenStatus status = static_cast<User::OAuthTokenStatus>(oauth_token_status); - HandleUserOAuthTokenStatusChange(account_id, status); + HandleUserOAuthTokenStatusChange(user_id, status); return status; } return User::OAUTH_TOKEN_STATUS_UNKNOWN; } -bool UserManagerBase::LoadForceOnlineSignin(const AccountId& account_id) const { +bool UserManagerBase::LoadForceOnlineSignin(const std::string& user_id) const { DCHECK(task_runner_->RunsTasksOnCurrentThread()); const base::DictionaryValue* prefs_force_online = GetLocalState()->GetDictionary(kUserForceOnlineSignin); bool force_online_signin = false; if (prefs_force_online) { - prefs_force_online->GetBooleanWithoutPathExpansion( - account_id.GetUserEmail(), &force_online_signin); + prefs_force_online->GetBooleanWithoutPathExpansion(user_id, + &force_online_signin); } return force_online_signin; } -void UserManagerBase::RemoveNonCryptohomeData(const AccountId& account_id) { +void UserManagerBase::RemoveNonCryptohomeData(const std::string& user_id) { PrefService* prefs = GetLocalState(); DictionaryPrefUpdate prefs_display_name_update(prefs, kUserDisplayName); - prefs_display_name_update->RemoveWithoutPathExpansion( - account_id.GetUserEmail(), nullptr); + prefs_display_name_update->RemoveWithoutPathExpansion(user_id, NULL); DictionaryPrefUpdate prefs_given_name_update(prefs, kUserGivenName); - prefs_given_name_update->RemoveWithoutPathExpansion(account_id.GetUserEmail(), - nullptr); + prefs_given_name_update->RemoveWithoutPathExpansion(user_id, NULL); DictionaryPrefUpdate prefs_display_email_update(prefs, kUserDisplayEmail); - prefs_display_email_update->RemoveWithoutPathExpansion( - account_id.GetUserEmail(), nullptr); + prefs_display_email_update->RemoveWithoutPathExpansion(user_id, NULL); DictionaryPrefUpdate prefs_oauth_update(prefs, kUserOAuthTokenStatus); - prefs_oauth_update->RemoveWithoutPathExpansion(account_id.GetUserEmail(), - nullptr); + prefs_oauth_update->RemoveWithoutPathExpansion(user_id, NULL); DictionaryPrefUpdate prefs_force_online_update(prefs, kUserForceOnlineSignin); - prefs_force_online_update->RemoveWithoutPathExpansion( - account_id.GetUserEmail(), nullptr); + prefs_force_online_update->RemoveWithoutPathExpansion(user_id, NULL); - RemoveKnownUserPrefs(account_id); + RemoveKnownUserPrefs(user_id); - const AccountId last_active_user = - AccountId::FromUserEmail(GetLocalState()->GetString(kLastActiveUser)); - if (account_id == last_active_user) + std::string last_active_user = GetLocalState()->GetString(kLastActiveUser); + if (user_id == last_active_user) GetLocalState()->SetString(kLastActiveUser, std::string()); } bool UserManagerBase::FindKnownUserPrefs( - const AccountId& account_id, + const UserID& user_id, const base::DictionaryValue** out_value) { PrefService* local_state = GetLocalState(); // Local State may not be initialized in tests. if (!local_state) return false; - if (IsUserNonCryptohomeDataEphemeral(account_id)) + if (IsUserNonCryptohomeDataEphemeral(user_id)) return false; const base::ListValue* known_users = local_state->GetList(kKnownUsers); for (size_t i = 0; i < known_users->GetSize(); ++i) { const base::DictionaryValue* element = nullptr; if (known_users->GetDictionary(i, &element)) { - if (UserMatches(account_id, *element)) { + if (UserMatches(user_id, *element)) { known_users->GetDictionary(i, out_value); return true; } @@ -1044,7 +1040,7 @@ return false; } -void UserManagerBase::UpdateKnownUserPrefs(const AccountId& account_id, +void UserManagerBase::UpdateKnownUserPrefs(const UserID& user_id, const base::DictionaryValue& values, bool clear) { PrefService* local_state = GetLocalState(); @@ -1053,39 +1049,39 @@ if (!local_state) return; - if (IsUserNonCryptohomeDataEphemeral(account_id)) + if (IsUserNonCryptohomeDataEphemeral(user_id)) return; ListPrefUpdate update(local_state, kKnownUsers); for (size_t i = 0; i < update->GetSize(); ++i) { base::DictionaryValue* element = nullptr; if (update->GetDictionary(i, &element)) { - if (UserMatches(account_id, *element)) { + if (UserMatches(user_id, *element)) { if (clear) element->Clear(); element->MergeDictionary(&values); - UpdateIdentity(account_id, *element); + UpdateIdentity(user_id, *element); return; } } } scoped_ptr<base::DictionaryValue> new_value(new base::DictionaryValue()); new_value->MergeDictionary(&values); - UpdateIdentity(account_id, *new_value); + UpdateIdentity(user_id, *new_value); update->Append(new_value.release()); } -bool UserManagerBase::GetKnownUserStringPref(const AccountId& account_id, +bool UserManagerBase::GetKnownUserStringPref(const UserID& user_id, const std::string& path, std::string* out_value) { const base::DictionaryValue* user_pref_dict = nullptr; - if (!FindKnownUserPrefs(account_id, &user_pref_dict)) + if (!FindKnownUserPrefs(user_id, &user_pref_dict)) return false; return user_pref_dict->GetString(path, out_value); } -void UserManagerBase::SetKnownUserStringPref(const AccountId& account_id, +void UserManagerBase::SetKnownUserStringPref(const UserID& user_id, const std::string& path, const std::string& in_value) { PrefService* local_state = GetLocalState(); @@ -1097,20 +1093,20 @@ ListPrefUpdate update(local_state, kKnownUsers); base::DictionaryValue dict; dict.SetString(path, in_value); - UpdateKnownUserPrefs(account_id, dict, false); + UpdateKnownUserPrefs(user_id, dict, false); } -bool UserManagerBase::GetKnownUserBooleanPref(const AccountId& account_id, +bool UserManagerBase::GetKnownUserBooleanPref(const UserID& user_id, const std::string& path, bool* out_value) { const base::DictionaryValue* user_pref_dict = nullptr; - if (!FindKnownUserPrefs(account_id, &user_pref_dict)) + if (!FindKnownUserPrefs(user_id, &user_pref_dict)) return false; return user_pref_dict->GetBoolean(path, out_value); } -void UserManagerBase::SetKnownUserBooleanPref(const AccountId& account_id, +void UserManagerBase::SetKnownUserBooleanPref(const UserID& user_id, const std::string& path, const bool in_value) { PrefService* local_state = GetLocalState(); @@ -1122,19 +1118,19 @@ ListPrefUpdate update(local_state, kKnownUsers); base::DictionaryValue dict; dict.SetBoolean(path, in_value); - UpdateKnownUserPrefs(account_id, dict, false); + UpdateKnownUserPrefs(user_id, dict, false); } -bool UserManagerBase::GetKnownUserIntegerPref(const AccountId& account_id, +bool UserManagerBase::GetKnownUserIntegerPref(const UserID& user_id, const std::string& path, int* out_value) { const base::DictionaryValue* user_pref_dict = nullptr; - if (!FindKnownUserPrefs(account_id, &user_pref_dict)) + if (!FindKnownUserPrefs(user_id, &user_pref_dict)) return false; return user_pref_dict->GetInteger(path, out_value); } -void UserManagerBase::SetKnownUserIntegerPref(const AccountId& account_id, +void UserManagerBase::SetKnownUserIntegerPref(const UserID& user_id, const std::string& path, const int in_value) { PrefService* local_state = GetLocalState(); @@ -1146,92 +1142,80 @@ ListPrefUpdate update(local_state, kKnownUsers); base::DictionaryValue dict; dict.SetInteger(path, in_value); - UpdateKnownUserPrefs(account_id, dict, false); + UpdateKnownUserPrefs(user_id, dict, false); } -bool UserManagerBase::GetKnownUserAccountId( - const AccountId& authenticated_account_id, - AccountId* out_account_id) { - DCHECK(!authenticated_account_id.GetGaiaId().empty()); - std::string canonical_email; - if (!GetKnownUserStringPref( - AccountId::FromGaiaId(authenticated_account_id.GetGaiaId()), - kCanonicalEmail, &canonical_email)) - return false; - - *out_account_id = authenticated_account_id; - out_account_id->SetUserEmail(canonical_email); - return true; +bool UserManagerBase::GetKnownUserCanonicalEmail(const UserID& user_id, + std::string* out_email) { + return GetKnownUserStringPref(user_id, kCanonicalEmail, out_email); } -void UserManagerBase::UpdateGaiaID(const AccountId& account_id, +void UserManagerBase::UpdateGaiaID(const UserID& user_id, const std::string& gaia_id) { - SetKnownUserStringPref(account_id, kGAIAIdKey, gaia_id); + SetKnownUserStringPref(user_id, kGAIAIdKey, gaia_id); } -bool UserManagerBase::FindGaiaID(const AccountId& account_id, +bool UserManagerBase::FindGaiaID(const UserID& user_id, std::string* out_value) { - return GetKnownUserStringPref(account_id, kGAIAIdKey, out_value); + return GetKnownUserStringPref(user_id, kGAIAIdKey, out_value); } -void UserManagerBase::SetKnownUserDeviceId(const AccountId& account_id, +void UserManagerBase::SetKnownUserDeviceId(const UserID& user_id, const std::string& device_id) { - const std::string known_device_id = GetKnownUserDeviceId(account_id); + const std::string known_device_id = GetKnownUserDeviceId(user_id); if (!known_device_id.empty() && device_id != known_device_id) { NOTREACHED() << "Trying to change device ID for known user."; } - SetKnownUserStringPref(account_id, kDeviceId, device_id); + SetKnownUserStringPref(user_id, kDeviceId, device_id); } -std::string UserManagerBase::GetKnownUserDeviceId(const AccountId& account_id) { +std::string UserManagerBase::GetKnownUserDeviceId(const UserID& user_id) { std::string device_id; - if (GetKnownUserStringPref(account_id, kDeviceId, &device_id)) { + if (GetKnownUserStringPref(user_id, kDeviceId, &device_id)) { return device_id; } return std::string(); } -void UserManagerBase::SetKnownUserGAPSCookie(const AccountId& account_id, +void UserManagerBase::SetKnownUserGAPSCookie(const UserID& user_id, const std::string& gaps_cookie) { - SetKnownUserStringPref(account_id, kGAPSCookie, gaps_cookie); + SetKnownUserStringPref(user_id, kGAPSCookie, gaps_cookie); } -std::string UserManagerBase::GetKnownUserGAPSCookie( - const AccountId& account_id) { +std::string UserManagerBase::GetKnownUserGAPSCookie(const UserID& user_id) { std::string gaps_cookie; - if (GetKnownUserStringPref(account_id, kGAPSCookie, &gaps_cookie)) { + if (GetKnownUserStringPref(user_id, kGAPSCookie, &gaps_cookie)) { return gaps_cookie; } return std::string(); } User* UserManagerBase::RemoveRegularOrSupervisedUserFromList( - const AccountId& account_id) { + const std::string& user_id) { ListPrefUpdate prefs_users_update(GetLocalState(), kRegularUsers); prefs_users_update->Clear(); - User* user = nullptr; + User* user = NULL; for (UserList::iterator it = users_.begin(); it != users_.end();) { - if ((*it)->GetAccountId() == account_id) { + const std::string user_email = (*it)->email(); + if (user_email == user_id) { user = *it; it = users_.erase(it); } else { - if ((*it)->HasGaiaAccount() || (*it)->IsSupervised()) { - const std::string user_email = (*it)->email(); + if ((*it)->HasGaiaAccount() || (*it)->IsSupervised()) prefs_users_update->Append(new base::StringValue(user_email)); - } ++it; } } - OnUserRemoved(account_id); + OnUserRemoved(user_id); return user; } -void UserManagerBase::RemoveKnownUserPrefs(const AccountId& account_id) { +void UserManagerBase::RemoveKnownUserPrefs(const UserID& user_id) { ListPrefUpdate update(GetLocalState(), kKnownUsers); for (size_t i = 0; i < update->GetSize(); ++i) { base::DictionaryValue* element = nullptr; if (update->GetDictionary(i, &element)) { - if (UserMatches(account_id, *element)) { + if (UserMatches(user_id, *element)) { update->Remove(i, nullptr); break; } @@ -1266,9 +1250,8 @@ if (user->IsSupervised() == is_child) return; user->SetIsChild(is_child); - SaveUserType(user->GetAccountId(), is_child - ? user_manager::USER_TYPE_CHILD - : user_manager::USER_TYPE_REGULAR); + SaveUserType(user->email(), is_child ? user_manager::USER_TYPE_CHILD + : user_manager::USER_TYPE_REGULAR); FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver, session_state_observer_list_, UserChangedChildStatus(user)); @@ -1318,7 +1301,7 @@ lru_logged_in_users_.insert(lru_logged_in_users_.begin(), user); } -void UserManagerBase::SendGaiaUserLoginMetrics(const AccountId& account_id) { +void UserManagerBase::SendGaiaUserLoginMetrics(const std::string& user_id) { // If this isn't the first time Chrome was run after the system booted, // assume that Chrome was restarted because a previous session ended. if (!base::CommandLine::ForCurrentProcess()->HasSwitch( @@ -1327,8 +1310,7 @@ GetLocalState()->GetString(kLastLoggedInGaiaUser); const base::TimeDelta time_to_login = base::TimeTicks::Now() - manager_creation_time_; - if (!last_email.empty() && - account_id != AccountId::FromUserEmail(last_email) && + if (!last_email.empty() && user_id != last_email && time_to_login.InSeconds() <= kLogoutToLoginDelayMaxSec) { UMA_HISTOGRAM_CUSTOM_COUNTS("UserManager.LogoutToLoginDelay", time_to_login.InSeconds(), @@ -1339,29 +1321,31 @@ } } -void UserManagerBase::UpdateUserAccountLocale(const AccountId& account_id, +void UserManagerBase::UpdateUserAccountLocale(const std::string& user_id, const std::string& locale) { scoped_ptr<std::string> resolved_locale(new std::string()); if (!locale.empty() && locale != GetApplicationLocale()) { - // base::Pased will nullptr out |resolved_locale|, so cache the underlying - // ptr. + // base::Pased will NULL out |resolved_locale|, so cache the underlying ptr. std::string* raw_resolved_locale = resolved_locale.get(); blocking_task_runner_->PostTaskAndReply( - FROM_HERE, base::Bind(ResolveLocale, locale, - base::Unretained(raw_resolved_locale)), + FROM_HERE, + base::Bind(ResolveLocale, + locale, + base::Unretained(raw_resolved_locale)), base::Bind(&UserManagerBase::DoUpdateAccountLocale, - weak_factory_.GetWeakPtr(), account_id, + weak_factory_.GetWeakPtr(), + user_id, base::Passed(&resolved_locale))); } else { resolved_locale.reset(new std::string(locale)); - DoUpdateAccountLocale(account_id, resolved_locale.Pass()); + DoUpdateAccountLocale(user_id, resolved_locale.Pass()); } } void UserManagerBase::DoUpdateAccountLocale( - const AccountId& account_id, + const std::string& user_id, scoped_ptr<std::string> resolved_locale) { - User* user = FindUserAndModify(account_id); + User* user = FindUserAndModify(user_id); if (user && resolved_locale) user->SetAccountLocale(*resolved_locale); } @@ -1370,7 +1354,7 @@ const bool is_active_user = (user == active_user_); delete user; if (is_active_user) - active_user_ = nullptr; + active_user_ = NULL; } } // namespace user_manager
diff --git a/components/user_manager/user_manager_base.h b/components/user_manager/user_manager_base.h index ead7d449..a5f5f8f 100644 --- a/components/user_manager/user_manager_base.h +++ b/components/user_manager/user_manager_base.h
@@ -15,8 +15,8 @@ #include "base/observer_list.h" #include "base/synchronization/lock.h" #include "base/time/time.h" -#include "components/signin/core/account_id/account_id.h" #include "components/user_manager/user.h" +#include "components/user_manager/user_id.h" #include "components/user_manager/user_manager.h" #include "components/user_manager/user_manager_export.h" #include "components/user_manager/user_type.h" @@ -51,37 +51,37 @@ const UserList& GetUsers() const override; const UserList& GetLoggedInUsers() const override; const UserList& GetLRULoggedInUsers() const override; - const AccountId& GetOwnerAccountId() const override; - void UserLoggedIn(const AccountId& account_id, + const std::string& GetOwnerEmail() const override; + void UserLoggedIn(const std::string& user_id, const std::string& user_id_hash, bool browser_restart) override; - void SwitchActiveUser(const AccountId& account_id) override; + void SwitchActiveUser(const std::string& user_id) override; void SwitchToLastActiveUser() override; void SessionStarted() override; - void RemoveUser(const AccountId& account_id, + void RemoveUser(const std::string& user_id, RemoveUserDelegate* delegate) override; - void RemoveUserFromList(const AccountId& account_id) override; - bool IsKnownUser(const AccountId& account_id) const override; - const User* FindUser(const AccountId& account_id) const override; - User* FindUserAndModify(const AccountId& account_id) override; + void RemoveUserFromList(const std::string& user_id) override; + bool IsKnownUser(const std::string& user_id) const override; + const User* FindUser(const std::string& user_id) const override; + User* FindUserAndModify(const std::string& user_id) override; const User* GetLoggedInUser() const override; User* GetLoggedInUser() override; const User* GetActiveUser() const override; User* GetActiveUser() override; const User* GetPrimaryUser() const override; - void SaveUserOAuthStatus(const AccountId& account_id, + void SaveUserOAuthStatus(const std::string& user_id, User::OAuthTokenStatus oauth_token_status) override; - void SaveForceOnlineSignin(const AccountId& account_id, + void SaveForceOnlineSignin(const std::string& user_id, bool force_online_signin) override; - void SaveUserDisplayName(const AccountId& account_id, + void SaveUserDisplayName(const std::string& user_id, const base::string16& display_name) override; - base::string16 GetUserDisplayName(const AccountId& account_id) const override; - void SaveUserDisplayEmail(const AccountId& account_id, + base::string16 GetUserDisplayName(const std::string& user_id) const override; + void SaveUserDisplayEmail(const std::string& user_id, const std::string& display_email) override; - std::string GetUserDisplayEmail(const AccountId& account_id) const override; - void SaveUserType(const AccountId& account_id, + std::string GetUserDisplayEmail(const std::string& user_id) const override; + void SaveUserType(const std::string& user_id, const UserType& user_type) override; - void UpdateUserAccountData(const AccountId& account_id, + void UpdateUserAccountData(const std::string& user_id, const UserAccountData& account_data) override; bool IsCurrentUserOwner() const override; bool IsCurrentUserNew() const override; @@ -97,7 +97,7 @@ bool IsLoggedInAsStub() const override; bool IsSessionStarted() const override; bool IsUserNonCryptohomeDataEphemeral( - const AccountId& account_id) const override; + const std::string& user_id) const override; void AddObserver(UserManager::Observer* obs) override; void RemoveObserver(UserManager::Observer* obs) override; void AddSessionStateObserver( @@ -106,61 +106,58 @@ UserManager::UserSessionStateObserver* obs) override; void NotifyLocalStateChanged() override; void ChangeUserChildStatus(User* user, bool is_child) override; - bool FindKnownUserPrefs(const AccountId& account_id, + bool FindKnownUserPrefs(const UserID& user_id, const base::DictionaryValue** out_value) override; - void UpdateKnownUserPrefs(const AccountId& account_id, + void UpdateKnownUserPrefs(const UserID& user_id, const base::DictionaryValue& values, bool clear) override; - bool GetKnownUserStringPref(const AccountId& account_id, + bool GetKnownUserStringPref(const UserID& user_id, const std::string& path, std::string* out_value) override; - void SetKnownUserStringPref(const AccountId& account_id, + void SetKnownUserStringPref(const UserID& user_id, const std::string& path, const std::string& in_value) override; - bool GetKnownUserBooleanPref(const AccountId& account_id, + bool GetKnownUserBooleanPref(const UserID& user_id, const std::string& path, bool* out_value) override; - void SetKnownUserBooleanPref(const AccountId& account_id, + void SetKnownUserBooleanPref(const UserID& user_id, const std::string& path, const bool in_value) override; - bool GetKnownUserIntegerPref(const AccountId& account_id, + bool GetKnownUserIntegerPref(const UserID& user_id, const std::string& path, int* out_value) override; - void SetKnownUserIntegerPref(const AccountId& account_id, + void SetKnownUserIntegerPref(const UserID& user_id, const std::string& path, - int in_value) override; - bool GetKnownUserAccountId(const AccountId& authenticated_account_id, - AccountId* out_account_id) override; - void UpdateGaiaID(const AccountId& account_id, - const std::string& gaia_id) override; - bool FindGaiaID(const AccountId& account_id, std::string* out_value) override; - void UpdateUsingSAML(const AccountId& account_id, + const int in_value) override; + bool GetKnownUserCanonicalEmail(const UserID& user_id, + std::string* out_email) override; + void UpdateGaiaID(const UserID& user_id, const std::string& gaia_id) override; + bool FindGaiaID(const UserID& user_id, std::string* out_value) override; + void UpdateUsingSAML(const std::string& user_id, const bool using_saml) override; - bool FindUsingSAML(const AccountId& account_id) override; - void SetKnownUserDeviceId(const AccountId& account_id, + bool FindUsingSAML(const std::string& user_id) override; + void SetKnownUserDeviceId(const UserID& user_id, const std::string& device_id) override; - std::string GetKnownUserDeviceId(const AccountId& account_id) override; - void SetKnownUserGAPSCookie(const AccountId& account_id, + std::string GetKnownUserDeviceId(const UserID& user_id) override; + void SetKnownUserGAPSCookie(const UserID& user_id, const std::string& gaps_cookie) override; - std::string GetKnownUserGAPSCookie(const AccountId& account_id) override; - void UpdateReauthReason(const AccountId& account_id, - int reauth_reason) override; - bool FindReauthReason(const AccountId& account_id, int* out_value) override; + std::string GetKnownUserGAPSCookie(const UserID& user_id) override; + void UpdateReauthReason(const std::string& user_id, + const int reauth_reason) override; + bool FindReauthReason(const std::string& user_id, int* out_value) override; - // This method updates "User was added to the device in this session nad is - // not full initialized yet" flag. virtual void SetIsCurrentUserNew(bool is_new); // TODO(xiyuan): Figure out a better way to expose this info. - virtual bool HasPendingBootstrap(const AccountId& account_id) const; + virtual bool HasPendingBootstrap(const std::string& user_id) const; // Helper function that copies users from |users_list| to |users_vector| and // |users_set|. Duplicates and users already present in |existing_users| are // skipped. static void ParseUserList(const base::ListValue& users_list, - const std::set<AccountId>& existing_users, - std::vector<AccountId>* users_vector, - std::set<AccountId>* users_set); + const std::set<std::string>& existing_users, + std::vector<std::string>* users_vector, + std::set<std::string>* users_set); // Returns true if trusted device policies have successfully been retrieved // and ephemeral users are enabled. @@ -188,9 +185,9 @@ // Subsequent calls have no effect. Must be called on the UI thread. virtual void EnsureUsersLoaded(); - // Handle OAuth token |status| change for |account_id|. + // Handle OAuth token |status| change for |user_id|. virtual void HandleUserOAuthTokenStatusChange( - const AccountId& account_id, + const std::string& user_id, User::OAuthTokenStatus status) const = 0; // Returns true if device is enterprise managed. @@ -201,7 +198,8 @@ // skipped. // Loads public accounts from the Local state and fills in // |public_sessions_set|. - virtual void LoadPublicAccounts(std::set<AccountId>* public_sessions_set) = 0; + virtual void LoadPublicAccounts( + std::set<std::string>* public_sessions_set) = 0; // Notifies that user has logged in. virtual void NotifyOnLogin(); @@ -226,36 +224,36 @@ // Implementation for RemoveUser method. It is synchronous. It is called from // RemoveUserInternal after owner check. - virtual void RemoveNonOwnerUserInternal(const AccountId& account_id, + virtual void RemoveNonOwnerUserInternal(const std::string& user_email, RemoveUserDelegate* delegate); // Removes a regular or supervised user from the user list. // Returns the user if found or NULL otherwise. // Also removes the user from the persistent user list. - User* RemoveRegularOrSupervisedUserFromList(const AccountId& account_id); + User* RemoveRegularOrSupervisedUserFromList(const std::string& user_id); // Implementation for RemoveUser method. This is an asynchronous part of the // method, that verifies that owner will not get deleted, and calls // |RemoveNonOwnerUserInternal|. - virtual void RemoveUserInternal(const AccountId& account_id, + virtual void RemoveUserInternal(const std::string& user_email, RemoveUserDelegate* delegate); // Removes data stored or cached outside the user's cryptohome (wallpaper, // avatar, OAuth token status, display name, display email). - virtual void RemoveNonCryptohomeData(const AccountId& account_id); + virtual void RemoveNonCryptohomeData(const std::string& user_id); // Check for a particular user type. - // Returns true if |account_id| represents demo app. - virtual bool IsDemoApp(const AccountId& account_id) const = 0; + // Returns true if |user_id| represents demo app. + virtual bool IsDemoApp(const std::string& user_id) const = 0; - // Returns true if |account_id| represents kiosk app. - virtual bool IsKioskApp(const AccountId& account_id) const = 0; + // Returns true if |user_id| represents kiosk app. + virtual bool IsKioskApp(const std::string& user_id) const = 0; - // Returns true if |account_id| represents public account that has been marked + // Returns true if |user_id| represents public account that has been marked // for deletion. virtual bool IsPublicAccountMarkedForRemoval( - const AccountId& account_id) const = 0; + const std::string& user_id) const = 0; // These methods are called when corresponding user type has signed in. @@ -266,22 +264,22 @@ virtual void GuestUserLoggedIn(); // Indicates that a kiosk app robot just logged in. - virtual void KioskAppLoggedIn(const AccountId& kiosk_app_account_id) = 0; + virtual void KioskAppLoggedIn(const std::string& app_id) = 0; // Indicates that a user just logged into a public session. virtual void PublicAccountUserLoggedIn(User* user) = 0; // Indicates that a regular user just logged in. - virtual void RegularUserLoggedIn(const AccountId& account_id); + virtual void RegularUserLoggedIn(const std::string& user_id); // Indicates that a regular user just logged in as ephemeral. - virtual void RegularUserLoggedInAsEphemeral(const AccountId& account_id); + virtual void RegularUserLoggedInAsEphemeral(const std::string& user_id); // Indicates that a supervised user just logged in. - virtual void SupervisedUserLoggedIn(const AccountId& account_id) = 0; + virtual void SupervisedUserLoggedIn(const std::string& user_id) = 0; // Should be called when regular user was removed. - virtual void OnUserRemoved(const AccountId& account_id) = 0; + virtual void OnUserRemoved(const std::string& user_id) = 0; // Getters/setters for private members. @@ -290,20 +288,20 @@ virtual bool GetEphemeralUsersEnabled() const; virtual void SetEphemeralUsersEnabled(bool enabled); - virtual void SetOwnerId(const AccountId& owner_account_id); + virtual void SetOwnerEmail(const std::string& owner_user_id); - virtual const AccountId& GetPendingUserSwitchID() const; - virtual void SetPendingUserSwitchId(const AccountId& account_id); + virtual const std::string& GetPendingUserSwitchID() const; + virtual void SetPendingUserSwitchID(const std::string& user_id); // The logged-in user that is currently active in current session. // NULL until a user has logged in, then points to one // of the User instances in |users_|, the |guest_user_| instance or an // ephemeral user instance. - User* active_user_ = nullptr; + User* active_user_; // The primary user of the current session. It is recorded for the first // signed-in user and does not change thereafter. - User* primary_user_ = nullptr; + User* primary_user_; // List of all known users. User instances are owned by |this|. Regular users // are removed by |RemoveUserFromList|, public accounts by @@ -330,21 +328,21 @@ // Returns the user with the given email address if found in the persistent // list. Returns |NULL| otherwise. - const User* FindUserInList(const AccountId& account_id) const; + const User* FindUserInList(const std::string& user_id) const; // Returns |true| if user with the given id is found in the persistent list. // Returns |false| otherwise. Does not trigger user loading. - bool UserExistsInList(const AccountId& account_id) const; + bool UserExistsInList(const std::string& user_id) const; // Same as FindUserInList but returns non-const pointer to User object. - User* FindUserInListAndModify(const AccountId& account_id); + User* FindUserInListAndModify(const std::string& user_id); // Reads user's oauth token status from local state preferences. - User::OAuthTokenStatus LoadUserOAuthStatus(const AccountId& account_id) const; + User::OAuthTokenStatus LoadUserOAuthStatus(const std::string& user_id) const; // Read a flag indicating whether online authentication against GAIA should // be enforced during the user's next sign-in from local state preferences. - bool LoadForceOnlineSignin(const AccountId& account_id) const; + bool LoadForceOnlineSignin(const std::string& user_id) const; // Notifies observers that merge session state had changed. void NotifyMergeSessionStateChanged(); @@ -352,7 +350,7 @@ // Notifies observers that active user has changed. void NotifyActiveUserChanged(const User* active_user); - // Notifies observers that active account_id hash has changed. + // Notifies observers that active user_id hash has changed. void NotifyActiveUserHashChanged(const std::string& hash); // Update the global LoginState. @@ -362,49 +360,49 @@ void SetLRUUser(User* user); // Sends metrics in response to a user with gaia account (regular) logging in. - void SendGaiaUserLoginMetrics(const AccountId& account_id); + void SendGaiaUserLoginMetrics(const std::string& user_id); - // Sets account locale for user with id |account_id|. - virtual void UpdateUserAccountLocale(const AccountId& account_id, + // Sets account locale for user with id |user_id|. + virtual void UpdateUserAccountLocale(const std::string& user_id, const std::string& locale); // Updates user account after locale was resolved. - void DoUpdateAccountLocale(const AccountId& account_id, + void DoUpdateAccountLocale(const std::string& user_id, scoped_ptr<std::string> resolved_locale); - // Removes all user preferences associated with |account_id|. - void RemoveKnownUserPrefs(const AccountId& account_id); + // Removes all user preferences associated with |user_id|. + void RemoveKnownUserPrefs(const UserID& user_id); // Indicates stage of loading user from prefs. - UserLoadStage user_loading_stage_ = STAGE_NOT_LOADED; + UserLoadStage user_loading_stage_; // True if SessionStarted() has been called. - bool session_started_ = false; + bool session_started_; // Cached flag of whether currently logged-in user is owner or not. // May be accessed on different threads, requires locking. - bool is_current_user_owner_ = false; + bool is_current_user_owner_; mutable base::Lock is_current_user_owner_lock_; // Cached flag of whether the currently logged-in user existed before this // login. - bool is_current_user_new_ = false; + bool is_current_user_new_; // Cached flag of whether the currently logged-in user is a regular user who // logged in as ephemeral. Storage of persistent information is avoided for // such users by not adding them to the persistent user list, not downloading // their custom avatars and mounting their cryptohomes using tmpfs. Defaults // to |false|. - bool is_current_user_ephemeral_regular_user_ = false; + bool is_current_user_ephemeral_regular_user_; // Cached flag indicating whether the ephemeral user policy is enabled. // Defaults to |false| if the value has not been read from trusted device // policy yet. - bool ephemeral_users_enabled_ = false; + bool ephemeral_users_enabled_; - // Cached name of device owner. Defaults to empty if the value has not + // Cached name of device owner. Defaults to empty string if the value has not // been read from trusted device policy yet. - AccountId owner_account_id_ = EmptyAccountId(); + std::string owner_email_; base::ObserverList<UserManager::Observer> observer_list_; @@ -413,17 +411,17 @@ session_state_observer_list_; // Time at which this object was created. - base::TimeTicks manager_creation_time_ = base::TimeTicks::Now(); + base::TimeTicks manager_creation_time_; // ID of the user just added to the session that needs to be activated // as soon as user's profile is loaded. - AccountId pending_user_switch_ = EmptyAccountId(); + std::string pending_user_switch_; // ID of the user that was active in the previous session. // Preference value is stored here before first user signs in // because pref will be overidden once session restore starts. - AccountId last_session_active_account_id_ = EmptyAccountId(); - bool last_session_active_account_id_initialized_ = false; + std::string last_session_active_user_; + bool last_session_active_user_initialized_; // TaskRunner for UI thread. scoped_refptr<base::TaskRunner> task_runner_;
diff --git a/components/variations/service/generate_ui_string_overrider.py b/components/variations/service/generate_ui_string_overrider.py index 288272c..6e43559 100755 --- a/components/variations/service/generate_ui_string_overrider.py +++ b/components/variations/service/generate_ui_string_overrider.py
@@ -71,6 +71,11 @@ resources = [Resource(_HashName(name), name, index) for name, index in _GetNameIndexPairsIter(resources_content)] + # Deduplicate resources. Some name-index pairs appear in both chromium_ and + # google_chrome_ header files. Unless deduplicated here, collisions will be + # raised in _CheckForHashCollisions. + resources = list(set(resources)) + # The default |Resource| order makes |resources| sorted by the hash, then # name, then index. resources.sort() @@ -160,7 +165,7 @@ collisions = _CheckForHashCollisions(hashed_tuples) if collisions: error_message = "\n".join( - ["hash: %i, name: %s" % (i[0], i[1]) for i in sorted(collisions)]) + ["hash: %i, name: %s" % (i.hash, i.name) for i in sorted(collisions)]) error_message = ("\nThe following names had hash collisions " "(sorted by the hash value):\n%s\n" %(error_message)) raise HashCollisionError(error_message)
diff --git a/components/wallpaper/wallpaper_manager_base.cc b/components/wallpaper/wallpaper_manager_base.cc index cd0bf89..8afdc1c 100644 --- a/components/wallpaper/wallpaper_manager_base.cc +++ b/components/wallpaper/wallpaper_manager_base.cc
@@ -501,8 +501,8 @@ void WallpaperManagerBase::SetPolicyControlledWallpaper( const std::string& user_id, const user_manager::UserImage& user_image) { - const user_manager::User* user = user_manager::UserManager::Get()->FindUser( - AccountId::FromUserEmail(user_id)); + const user_manager::User* user = + user_manager::UserManager::Get()->FindUser(user_id); if (!user) { NOTREACHED() << "Unknown user."; return; @@ -886,7 +886,7 @@ info.location = base::FilePath(user_id_hash).Append(info.location).value(); bool is_persistent = !user_manager::UserManager::Get()->IsUserNonCryptohomeDataEphemeral( - AccountId::FromUserEmail(user_id)); + user_id); SetUserWallpaperInfo(user_id, info, is_persistent); } }
diff --git a/content/browser/background_sync/background_sync_browsertest.cc b/content/browser/background_sync/background_sync_browsertest.cc index 8fc9da1..3026345 100644 --- a/content/browser/background_sync/background_sync_browsertest.cc +++ b/content/browser/background_sync/background_sync_browsertest.cc
@@ -109,10 +109,14 @@ shell_ = incognito ? CreateOffTheRecordBrowser() : shell(); } - BackgroundSyncContext* GetSyncContextFromShell(Shell* shell) { - StoragePartition* storage = BrowserContext::GetDefaultStoragePartition( - shell_->web_contents()->GetBrowserContext()); - return storage->GetBackgroundSyncContext(); + StoragePartition* GetStorage() { + WebContents* web_contents = shell_->web_contents(); + return BrowserContext::GetStoragePartition( + web_contents->GetBrowserContext(), web_contents->GetSiteInstance()); + } + + BackgroundSyncContext* GetSyncContext() { + return GetStorage()->GetBackgroundSyncContext(); } void SetUpCommandLine(base::CommandLine* command_line) override { @@ -162,6 +166,8 @@ // (assertion failure) if the tag isn't registered. bool OneShotPending(const std::string& tag); + void ClearStoragePartitionData(); + std::string PopConsoleString(); bool PopConsole(const std::string& expected_msg); bool RegisterServiceWorker(); @@ -194,8 +200,8 @@ BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&BackgroundSyncBrowserTest::SetOnlineOnIOThread, - base::Unretained(this), - base::Unretained(GetSyncContextFromShell(shell_)), online)); + base::Unretained(this), base::Unretained(GetSyncContext()), + online)); base::RunLoop().RunUntilIdle(); } @@ -206,10 +212,10 @@ BackgroundSyncNetworkObserver* network_observer = sync_manager->GetNetworkObserverForTesting(); if (online) { - network_observer->NotifyManagerIfNetworkChanged( + network_observer->NotifyManagerIfNetworkChangedForTesting( NetworkChangeNotifier::CONNECTION_WIFI); } else { - network_observer->NotifyManagerIfNetworkChanged( + network_observer->NotifyManagerIfNetworkChangedForTesting( NetworkChangeNotifier::CONNECTION_NONE); } } @@ -218,8 +224,7 @@ bool is_pending; base::RunLoop run_loop; - StoragePartition* storage = BrowserContext::GetDefaultStoragePartition( - shell_->web_contents()->GetBrowserContext()); + StoragePartition* storage = GetStorage(); BackgroundSyncContext* sync_context = storage->GetBackgroundSyncContext(); ServiceWorkerContextWrapper* service_worker_context = static_cast<ServiceWorkerContextWrapper*>( @@ -240,6 +245,27 @@ return is_pending; } +void BackgroundSyncBrowserTest::ClearStoragePartitionData() { + // Clear data from the storage partition. Parameters are set to clear data + // for service workers, for all origins, for an unbounded time range. + StoragePartition* storage = GetStorage(); + + uint32 storage_partition_mask = + StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS; + uint32 quota_storage_mask = StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL; + const GURL& delete_origin = GURL(); + const base::Time delete_begin = base::Time(); + base::Time delete_end = base::Time::Max(); + + base::RunLoop run_loop; + + storage->ClearData(storage_partition_mask, quota_storage_mask, delete_origin, + StoragePartition::OriginMatcherFunction(), delete_begin, + delete_end, run_loop.QuitClosure()); + + run_loop.Run(); +} + std::string BackgroundSyncBrowserTest::PopConsoleString() { std::string script_result; EXPECT_TRUE(RunScript("resultQueue.pop()", &script_result)); @@ -597,7 +623,7 @@ } IN_PROC_BROWSER_TEST_F(BackgroundSyncBrowserTest, - CallFinishedAfterSyncSuceeds) { + CallFinishedAfterSyncSucceeds) { EXPECT_TRUE(RegisterServiceWorker()); EXPECT_TRUE(LoadTestPage(kDefaultTestURL)); // Control the page. @@ -638,4 +664,99 @@ EXPECT_TRUE(NotifyWhenFinishedImmediateOneShot("ok - delay result: false")); } +// Verify that a background sync registration is deleted when site data is +// cleared. +IN_PROC_BROWSER_TEST_F(BackgroundSyncBrowserTest, + SyncRegistrationDeletedWhenClearingSiteData) { + EXPECT_TRUE(RegisterServiceWorker()); + EXPECT_TRUE(LoadTestPage(kDefaultTestURL)); // Control the page. + + // Prevent firing by going offline. + SetOnline(false); + EXPECT_TRUE(RegisterOneShot("foo")); + EXPECT_TRUE(GetRegistrationOneShot("foo")); + EXPECT_TRUE(OneShotPending("foo")); + + // Simulate a user clearing site data (including Service Workers, crucially), + // by clearing data from the storage partition. + ClearStoragePartitionData(); + + EXPECT_FALSE(GetRegistrationOneShot("foo")); +} + +// Verify that a background sync registration, from a service worker, is deleted +// when site data is cleared. +IN_PROC_BROWSER_TEST_F(BackgroundSyncBrowserTest, + SyncRegistrationFromSWDeletedWhenClearingSiteData) { + EXPECT_TRUE(RegisterServiceWorker()); + EXPECT_TRUE(LoadTestPage(kDefaultTestURL)); // Control the page. + + std::vector<std::string> registered_tags; + EXPECT_TRUE(GetRegistrationsOneShot(registered_tags)); + + SetOnline(false); + + EXPECT_TRUE(RegisterOneShotFromServiceWorker("foo_sw")); + EXPECT_TRUE(PopConsole("ok - foo_sw registered in SW")); + EXPECT_TRUE(GetRegistrationOneShotFromServiceWorker("foo_sw")); + + // Simulate a user clearing site data (including Service Workers, crucially), + // by clearing data from the storage partition. + ClearStoragePartitionData(); + + EXPECT_FALSE(GetRegistrationOneShotFromServiceWorker("foo")); +} + +// Verify that multiple background sync registrations are deleted when site +// data is cleared. +IN_PROC_BROWSER_TEST_F(BackgroundSyncBrowserTest, + SyncRegistrationsDeletedWhenClearingSiteData) { + EXPECT_TRUE(RegisterServiceWorker()); + EXPECT_TRUE(LoadTestPage(kDefaultTestURL)); // Control the page. + + std::vector<std::string> registered_tags; + EXPECT_TRUE(GetRegistrationsOneShot(registered_tags)); + + SetOnline(false); + registered_tags.push_back("foo"); + registered_tags.push_back("bar"); + + for (const std::string& tag : registered_tags) + EXPECT_TRUE(RegisterOneShot(tag)); + + EXPECT_TRUE(GetRegistrationsOneShot(registered_tags)); + + for (const std::string& tag : registered_tags) + EXPECT_TRUE(OneShotPending(tag)); + + // Simulate a user clearing site data (including Service Workers, crucially), + // by clearing data from the storage partition. + ClearStoragePartitionData(); + + for (const std::string& tag : registered_tags) + EXPECT_FALSE(GetRegistrationOneShot(tag)); +} + +// Verify that a sync event that is currently firing is deleted when site +// data is cleared. +IN_PROC_BROWSER_TEST_F(BackgroundSyncBrowserTest, + FiringSyncEventDeletedWhenClearingSiteData) { + EXPECT_TRUE(RegisterServiceWorker()); + EXPECT_TRUE(LoadTestPage(kDefaultTestURL)); // Control the page. + + SetOnline(true); + EXPECT_TRUE(RegisterOneShot("delay")); + + // Verify that it is firing. + EXPECT_TRUE(GetRegistrationOneShot("delay")); + EXPECT_FALSE(OneShotPending("delay")); + + // Simulate a user clearing site data (including Service Workers, crucially), + // by clearing data from the storage partition. + ClearStoragePartitionData(); + + // Verify that it was deleted. + EXPECT_FALSE(GetRegistrationOneShot("delay")); +} + } // namespace content
diff --git a/content/browser/background_sync/background_sync_manager_unittest.cc b/content/browser/background_sync/background_sync_manager_unittest.cc index b5077140..de8a37c 100644 --- a/content/browser/background_sync/background_sync_manager_unittest.cc +++ b/content/browser/background_sync/background_sync_manager_unittest.cc
@@ -320,7 +320,8 @@ if (test_background_sync_manager_) { BackgroundSyncNetworkObserver* network_observer = test_background_sync_manager_->GetNetworkObserverForTesting(); - network_observer->NotifyManagerIfNetworkChanged(connection_type); + network_observer->NotifyManagerIfNetworkChangedForTesting( + connection_type); base::RunLoop().RunUntilIdle(); } }
diff --git a/content/browser/background_sync/background_sync_network_observer.cc b/content/browser/background_sync/background_sync_network_observer.cc index a08e7d8..f8a0e08 100644 --- a/content/browser/background_sync/background_sync_network_observer.cc +++ b/content/browser/background_sync/background_sync_network_observer.cc
@@ -65,6 +65,11 @@ NotifyManagerIfNetworkChanged(connection_type); } +void BackgroundSyncNetworkObserver::NotifyManagerIfNetworkChangedForTesting( + net::NetworkChangeNotifier::ConnectionType connection_type) { + NotifyManagerIfNetworkChanged(connection_type); +} + void BackgroundSyncNetworkObserver::NotifyManagerIfNetworkChanged( net::NetworkChangeNotifier::ConnectionType connection_type) { DCHECK_CURRENTLY_ON(BrowserThread::IO);
diff --git a/content/browser/background_sync/background_sync_network_observer.h b/content/browser/background_sync/background_sync_network_observer.h index f00727c8..26700db4 100644 --- a/content/browser/background_sync/background_sync_network_observer.h +++ b/content/browser/background_sync/background_sync_network_observer.h
@@ -33,11 +33,11 @@ void OnNetworkChanged( net::NetworkChangeNotifier::ConnectionType connection_type) override; - private: - friend class BackgroundSyncBrowserTest; - friend class BackgroundSyncManagerTest; - friend class BackgroundSyncServiceImplTest; + // Allow tests to call NotifyManagerIfNetworkChanged. + void NotifyManagerIfNetworkChangedForTesting( + net::NetworkChangeNotifier::ConnectionType connection_type); + private: // Calls NotifyNetworkChanged if the connection type has changed. void NotifyManagerIfNetworkChanged( net::NetworkChangeNotifier::ConnectionType connection_type);
diff --git a/content/browser/background_sync/background_sync_service_impl_unittest.cc b/content/browser/background_sync/background_sync_service_impl_unittest.cc index a688968..8ffded0 100644 --- a/content/browser/background_sync/background_sync_service_impl_unittest.cc +++ b/content/browser/background_sync/background_sync_service_impl_unittest.cc
@@ -153,7 +153,7 @@ BackgroundSyncNetworkObserver* network_observer = background_sync_context_->background_sync_manager() ->GetNetworkObserverForTesting(); - network_observer->NotifyManagerIfNetworkChanged( + network_observer->NotifyManagerIfNetworkChangedForTesting( net::NetworkChangeNotifier::CONNECTION_NONE); base::RunLoop().RunUntilIdle(); }
diff --git a/content/browser/devtools/devtools_frontend_host_impl.cc b/content/browser/devtools/devtools_frontend_host_impl.cc index 67981c59..8302a41 100644 --- a/content/browser/devtools/devtools_frontend_host_impl.cc +++ b/content/browser/devtools/devtools_frontend_host_impl.cc
@@ -21,8 +21,9 @@ // static DevToolsFrontendHost* DevToolsFrontendHost::Create( RenderFrameHost* frontend_main_frame, - DevToolsFrontendHost::Delegate* delegate) { - return new DevToolsFrontendHostImpl(frontend_main_frame, delegate); + const HandleMessageCallback& handle_message_callback) { + return new DevToolsFrontendHostImpl(frontend_main_frame, + handle_message_callback); } // static @@ -39,10 +40,10 @@ DevToolsFrontendHostImpl::DevToolsFrontendHostImpl( RenderFrameHost* frontend_main_frame, - DevToolsFrontendHost::Delegate* delegate) + const HandleMessageCallback& handle_message_callback) : WebContentsObserver( WebContents::FromRenderFrameHost(frontend_main_frame)), - delegate_(delegate) { + handle_message_callback_(handle_message_callback) { frontend_main_frame->Send(new DevToolsMsg_SetupDevToolsClient( frontend_main_frame->GetRoutingID(), DevToolsFrontendHost::GetFrontendResource( @@ -64,8 +65,6 @@ return false; bool handled = true; IPC_BEGIN_MESSAGE_MAP(DevToolsFrontendHostImpl, message) - IPC_MESSAGE_HANDLER(DevToolsAgentMsg_DispatchOnInspectorBackend, - OnDispatchOnInspectorBackend) IPC_MESSAGE_HANDLER(DevToolsHostMsg_DispatchOnEmbedder, OnDispatchOnEmbedder) IPC_MESSAGE_UNHANDLED(handled = false) @@ -73,14 +72,9 @@ return handled; } -void DevToolsFrontendHostImpl::OnDispatchOnInspectorBackend( - const std::string& message) { - delegate_->HandleMessageFromDevToolsFrontendToBackend(message); -} - void DevToolsFrontendHostImpl::OnDispatchOnEmbedder( const std::string& message) { - delegate_->HandleMessageFromDevToolsFrontend(message); + handle_message_callback_.Run(message); } } // namespace content
diff --git a/content/browser/devtools/devtools_frontend_host_impl.h b/content/browser/devtools/devtools_frontend_host_impl.h index 148bc2f6..b2d6e3c85 100644 --- a/content/browser/devtools/devtools_frontend_host_impl.h +++ b/content/browser/devtools/devtools_frontend_host_impl.h
@@ -13,8 +13,9 @@ class DevToolsFrontendHostImpl : public DevToolsFrontendHost, public WebContentsObserver { public: - DevToolsFrontendHostImpl(RenderFrameHost* frontend_main_frame, - DevToolsFrontendHost::Delegate* delegate); + DevToolsFrontendHostImpl( + RenderFrameHost* frontend_main_frame, + const HandleMessageCallback& handle_message_callback); ~DevToolsFrontendHostImpl() override; void BadMessageRecieved() override; @@ -24,10 +25,9 @@ bool OnMessageReceived(const IPC::Message& message, RenderFrameHost* render_frame_host) override; - void OnDispatchOnInspectorBackend(const std::string& message); void OnDispatchOnEmbedder(const std::string& message); - DevToolsFrontendHost::Delegate* delegate_; + HandleMessageCallback handle_message_callback_; DISALLOW_COPY_AND_ASSIGN(DevToolsFrontendHostImpl); };
diff --git a/content/browser/loader/async_resource_handler_browsertest.cc b/content/browser/loader/async_resource_handler_browsertest.cc index cb48a23..4276ce2b 100644 --- a/content/browser/loader/async_resource_handler_browsertest.cc +++ b/content/browser/loader/async_resource_handler_browsertest.cc
@@ -28,8 +28,10 @@ // ThreadSanitizer is too slow to perform the full upload, so tests // using that build get an easier test which might not show two distinct -// progress events. See crbug.com/526985. -#if defined(THREAD_SANITIZER) +// progress events. See crbug.com/526985. In addition, OSX buildbots have +// experienced slowdowns on this test (crbug.com/548819), give them the easier +// test too. +#if defined(THREAD_SANITIZER) || defined(OS_MACOSX) const size_t kPayloadSize = 1062882; // 2*3^12 #else const size_t kPayloadSize = 28697814; // 2*3^15
diff --git a/content/browser/loader/resource_buffer.cc b/content/browser/loader/resource_buffer.cc index 58839db..9dc63d6 100644 --- a/content/browser/loader/resource_buffer.cc +++ b/content/browser/loader/resource_buffer.cc
@@ -54,11 +54,7 @@ min_alloc_size_ = min_allocation_size; max_alloc_size_ = max_allocation_size; -#if defined(OS_MACOSX) && !defined(OS_IOS) - return shared_mem_.CreateAndMapAnonymousMach(buf_size_); -#else return shared_mem_.CreateAndMapAnonymous(buf_size_); -#endif // defined(OS_MACOSX) && !defined(OS_IOS) } bool ResourceBuffer::IsInitialized() const {
diff --git a/content/browser/loader/upload_data_stream_builder.cc b/content/browser/loader/upload_data_stream_builder.cc index 12b4b80..a79299c 100644 --- a/content/browser/loader/upload_data_stream_builder.cc +++ b/content/browser/loader/upload_data_stream_builder.cc
@@ -111,6 +111,7 @@ break; } case ResourceRequestBody::Element::TYPE_DISK_CACHE_ENTRY: + case ResourceRequestBody::Element::TYPE_BYTES_DESCRIPTION: case ResourceRequestBody::Element::TYPE_UNKNOWN: NOTREACHED(); break;
diff --git a/content/browser/media/capture/aura_window_capture_machine.cc b/content/browser/media/capture/aura_window_capture_machine.cc index e5019f7..11150ea 100644 --- a/content/browser/media/capture/aura_window_capture_machine.cc +++ b/content/browser/media/capture/aura_window_capture_machine.cc
@@ -485,7 +485,7 @@ InternalStop(base::Bind(&base::DoNothing)); - oracle_proxy_->ReportError("OnWindowDestroying()"); + oracle_proxy_->ReportError(FROM_HERE, "OnWindowDestroying()"); } void AuraWindowCaptureMachine::OnWindowAddedToRootWindow(
diff --git a/content/browser/media/capture/desktop_capture_device.cc b/content/browser/media/capture/desktop_capture_device.cc index 6cc4839..bc16454 100644 --- a/content/browser/media/capture/desktop_capture_device.cc +++ b/content/browser/media/capture/desktop_capture_device.cc
@@ -206,9 +206,7 @@ capture_in_progress_ = false; if (!frame) { - std::string log("Failed to capture a frame."); - LOG(ERROR) << log; - client_->OnError(log); + client_->OnError(FROM_HERE, "Failed to capture a frame."); return; }
diff --git a/content/browser/media/capture/desktop_capture_device_aura_unittest.cc b/content/browser/media/capture/desktop_capture_device_aura_unittest.cc index 790334e..dd12640c 100644 --- a/content/browser/media/capture/desktop_capture_device_aura_unittest.cc +++ b/content/browser/media/capture/desktop_capture_device_aura_unittest.cc
@@ -4,6 +4,7 @@ #include "content/browser/media/capture/desktop_capture_device_aura.h" +#include "base/location.h" #include "base/synchronization/waitable_event.h" #include "content/browser/browser_thread_impl.h" #include "content/public/browser/desktop_media_id.h" @@ -54,7 +55,9 @@ MOCK_METHOD0(DoReserveOutputBuffer, void(void)); MOCK_METHOD0(DoOnIncomingCapturedBuffer, void(void)); MOCK_METHOD0(DoOnIncomingCapturedVideoFrame, void(void)); - MOCK_METHOD1(OnError, void(const std::string& reason)); + MOCK_METHOD2(OnError, + void(const tracked_objects::Location& from_here, + const std::string& reason)); // Trampoline methods to workaround GMOCK problems with scoped_ptr<>. scoped_ptr<Buffer> ReserveOutputBuffer( @@ -142,7 +145,7 @@ ASSERT_TRUE(capture_device.get()); scoped_ptr<MockDeviceClient> client(new MockDeviceClient()); - EXPECT_CALL(*client, OnError(_)).Times(0); + EXPECT_CALL(*client, OnError(_, _)).Times(0); media::VideoCaptureParams capture_params; capture_params.requested_format.frame_size.SetSize(640, 480);
diff --git a/content/browser/media/capture/desktop_capture_device_unittest.cc b/content/browser/media/capture/desktop_capture_device_unittest.cc index afaac445..a754ff7 100644 --- a/content/browser/media/capture/desktop_capture_device_unittest.cc +++ b/content/browser/media/capture/desktop_capture_device_unittest.cc
@@ -75,7 +75,9 @@ MOCK_METHOD0(DoReserveOutputBuffer, void(void)); MOCK_METHOD0(DoOnIncomingCapturedBuffer, void(void)); MOCK_METHOD0(DoOnIncomingCapturedVideoFrame, void(void)); - MOCK_METHOD1(OnError, void(const std::string& reason)); + MOCK_METHOD2(OnError, + void(const tracked_objects::Location& from_here, + const std::string& reason)); // Trampoline methods to workaround GMOCK problems with scoped_ptr<>. scoped_ptr<Buffer> ReserveOutputBuffer( @@ -283,7 +285,7 @@ int frame_size; scoped_ptr<MockDeviceClient> client(new MockDeviceClient()); - EXPECT_CALL(*client, OnError(_)).Times(0); + EXPECT_CALL(*client, OnError(_, _)).Times(0); EXPECT_CALL(*client, OnIncomingCapturedData(_, _, _, _, _)).WillRepeatedly( DoAll(SaveArg<1>(&frame_size), SaveArg<2>(&format), @@ -317,7 +319,7 @@ base::WaitableEvent done_event(false, false); scoped_ptr<MockDeviceClient> client(new MockDeviceClient()); - EXPECT_CALL(*client, OnError(_)).Times(0); + EXPECT_CALL(*client, OnError(_, _)).Times(0); EXPECT_CALL(*client, OnIncomingCapturedData(_, _, _, _, _)).WillRepeatedly( DoAll(WithArg<2>(Invoke(&format_checker, &FormatChecker::ExpectAcceptableSize)), @@ -357,7 +359,7 @@ base::WaitableEvent done_event(false, false); scoped_ptr<MockDeviceClient> client(new MockDeviceClient()); - EXPECT_CALL(*client, OnError(_)).Times(0); + EXPECT_CALL(*client, OnError(_,_)).Times(0); EXPECT_CALL(*client, OnIncomingCapturedData(_, _, _, _, _)).WillRepeatedly( DoAll(WithArg<2>(Invoke(&format_checker, &FormatChecker::ExpectAcceptableSize)), @@ -402,7 +404,7 @@ base::WaitableEvent done_event(false, false); scoped_ptr<MockDeviceClient> client(new MockDeviceClient()); - EXPECT_CALL(*client, OnError(_)).Times(0); + EXPECT_CALL(*client, OnError(_,_)).Times(0); EXPECT_CALL(*client, OnIncomingCapturedData(_, _, _, _, _)).WillRepeatedly( DoAll(WithArg<2>(Invoke(&format_checker, &FormatChecker::ExpectAcceptableSize)), @@ -449,7 +451,7 @@ webrtc::DesktopSize(kTestFrameWidth1, kTestFrameHeight1))); scoped_ptr<MockDeviceClient> client(new MockDeviceClient()); - EXPECT_CALL(*client, OnError(_)).Times(0); + EXPECT_CALL(*client, OnError(_,_)).Times(0); EXPECT_CALL(*client, OnIncomingCapturedData(_, _, _, _, _)).WillRepeatedly( DoAll(Invoke(this, &DesktopCaptureDeviceTest::CopyFrame), SaveArg<1>(&frame_size), @@ -492,7 +494,7 @@ webrtc::DesktopSize(kTestFrameWidth1, kTestFrameHeight1))); scoped_ptr<MockDeviceClient> client(new MockDeviceClient()); - EXPECT_CALL(*client, OnError(_)).Times(0); + EXPECT_CALL(*client, OnError(_,_)).Times(0); EXPECT_CALL(*client, OnIncomingCapturedData(_, _, _, _, _)).WillRepeatedly( DoAll(Invoke(this, &DesktopCaptureDeviceTest::CopyFrame), SaveArg<1>(&frame_size),
diff --git a/content/browser/media/capture/web_contents_video_capture_device.cc b/content/browser/media/capture/web_contents_video_capture_device.cc index 64312d9a..e8e55ad 100644 --- a/content/browser/media/capture/web_contents_video_capture_device.cc +++ b/content/browser/media/capture/web_contents_video_capture_device.cc
@@ -762,7 +762,8 @@ if (IsStarted()) { // Tracking of WebContents and/or its main frame has failed before Stop() // was called, so report this as an error: - oracle_proxy_->ReportError("WebContents and/or main frame are gone."); + oracle_proxy_->ReportError(FROM_HERE, + "WebContents and/or main frame are gone."); } return; }
diff --git a/content/browser/media/capture/web_contents_video_capture_device_unittest.cc b/content/browser/media/capture/web_contents_video_capture_device_unittest.cc index c8ea3db7..7a6463a4 100644 --- a/content/browser/media/capture/web_contents_video_capture_device_unittest.cc +++ b/content/browser/media/capture/web_contents_video_capture_device_unittest.cc
@@ -407,7 +407,10 @@ frame->visible_rect().size()); } - void OnError(const std::string& reason) override { error_callback_.Run(); } + void OnError(const tracked_objects::Location& from_here, + const std::string& reason) override { + error_callback_.Run(); + } double GetBufferPoolUtilization() const override { return 0.0; }
diff --git a/content/browser/memory/memory_message_filter.cc b/content/browser/memory/memory_message_filter.cc index 8f6fe48..9a792d8 100644 --- a/content/browser/memory/memory_message_filter.cc +++ b/content/browser/memory/memory_message_filter.cc
@@ -36,4 +36,9 @@ Send(new MemoryMsg_SimulatePressureNotification(level)); } +void MemoryMessageFilter::SendPressureNotification( + base::MemoryPressureListener::MemoryPressureLevel level) { + Send(new MemoryMsg_PressureNotification(level)); +} + } // namespace content
diff --git a/content/browser/memory/memory_message_filter.h b/content/browser/memory/memory_message_filter.h index d489c25..c3fd30f 100644 --- a/content/browser/memory/memory_message_filter.h +++ b/content/browser/memory/memory_message_filter.h
@@ -25,6 +25,8 @@ void SendSetPressureNotificationsSuppressed(bool suppressed); void SendSimulatePressureNotification( base::MemoryPressureListener::MemoryPressureLevel level); + void SendPressureNotification( + base::MemoryPressureListener::MemoryPressureLevel level); protected: ~MemoryMessageFilter() override;
diff --git a/content/browser/renderer_host/media/video_capture_controller_unittest.cc b/content/browser/renderer_host/media/video_capture_controller_unittest.cc index dc82a26..a030323 100644 --- a/content/browser/renderer_host/media/video_capture_controller_unittest.cc +++ b/content/browser/renderer_host/media/video_capture_controller_unittest.cc
@@ -594,7 +594,7 @@ // Start with one client. controller_->AddClient( route_id, client_a_.get(), base::kNullProcessHandle, 100, session_100); - device_->OnError("Test Error"); + device_->OnError(FROM_HERE, "Test Error"); EXPECT_CALL(*client_a_, DoError(route_id)).Times(1); base::RunLoop().RunUntilIdle(); Mock::VerifyAndClearExpectations(client_a_.get()); @@ -651,7 +651,7 @@ scoped_refptr<media::VideoFrame> video_frame = WrapI420Buffer(dims, static_cast<uint8*>(buffer->data())); - device_->OnError("Test Error"); + device_->OnError(FROM_HERE, "Test Error"); device_->OnIncomingCapturedVideoFrame(buffer.Pass(), video_frame, base::TimeTicks());
diff --git a/content/browser/renderer_host/media/video_capture_device_client.cc b/content/browser/renderer_host/media/video_capture_device_client.cc index 7ba7761..0cd2d4f91 100644 --- a/content/browser/renderer_host/media/video_capture_device_client.cc +++ b/content/browser/renderer_host/media/video_capture_device_client.cc
@@ -8,6 +8,7 @@ #include "base/bind.h" #include "base/command_line.h" +#include "base/location.h" #include "base/strings/stringprintf.h" #include "base/trace_event/trace_event.h" #include "content/browser/compositor/image_transport_factory.h" @@ -393,12 +394,13 @@ } void VideoCaptureDeviceClient::OnError( + const tracked_objects::Location& from_here, const std::string& reason) { const std::string log_message = base::StringPrintf( - "Error on video capture: %s, OS message: %s", - reason.c_str(), - logging::SystemErrorCodeToString( - logging::GetLastSystemErrorCode()).c_str()); + "Error on %s:%d: %s, OS message: %s", from_here.file_name(), + from_here.line_number(), reason.c_str(), + logging::SystemErrorCodeToString(logging::GetLastSystemErrorCode()) + .c_str()); DLOG(ERROR) << log_message; OnLog(log_message); BrowserThread::PostTask(BrowserThread::IO,
diff --git a/content/browser/renderer_host/media/video_capture_device_client.h b/content/browser/renderer_host/media/video_capture_device_client.h index 844c611a..111839c 100644 --- a/content/browser/renderer_host/media/video_capture_device_client.h +++ b/content/browser/renderer_host/media/video_capture_device_client.h
@@ -65,7 +65,8 @@ scoped_ptr<Buffer> buffer, const scoped_refptr<media::VideoFrame>& frame, const base::TimeTicks& timestamp) override; - void OnError(const std::string& reason) override; + void OnError(const tracked_objects::Location& from_here, + const std::string& reason) override; void OnLog(const std::string& message) override; double GetBufferPoolUtilization() const override;
diff --git a/content/browser/renderer_host/media/video_capture_manager.cc b/content/browser/renderer_host/media/video_capture_manager.cc index 003c2897..43788fb 100644 --- a/content/browser/renderer_host/media/video_capture_manager.cc +++ b/content/browser/renderer_host/media/video_capture_manager.cc
@@ -431,7 +431,7 @@ } if (!video_capture_device) { - device_client->OnError("Could not create capture device"); + device_client->OnError(FROM_HERE, "Could not create capture device"); return nullptr; }
diff --git a/content/browser/renderer_host/render_process_host_impl.cc b/content/browser/renderer_host/render_process_host_impl.cc index daab2692..e4b11092 100644 --- a/content/browser/renderer_host/render_process_host_impl.cc +++ b/content/browser/renderer_host/render_process_host_impl.cc
@@ -1358,6 +1358,7 @@ switches::kEnableThreadedCompositing, switches::kEnableTouchDragDrop, switches::kEnableUnsafeES3APIs, + switches::kEnableUseZoomForDSF, switches::kEnableViewport, switches::kEnableVtune, switches::kEnableWebBluetooth,
diff --git a/content/browser/tracing/background_tracing_config_unittest.cc b/content/browser/tracing/background_tracing_config_unittest.cc index a6a5ebf..2b95069 100644 --- a/content/browser/tracing/background_tracing_config_unittest.cc +++ b/content/browser/tracing/background_tracing_config_unittest.cc
@@ -295,6 +295,20 @@ "{\"category\":\"BENCHMARK_DEEP\"," "\"rule\":\"TRACE_ON_NAVIGATION_UNTIL_TRIGGER_OR_FULL\"," "\"trigger_name\":\"foo\"}"); + + config = ReadFromJSONString( + "{\"mode\":\"REACTIVE_TRACING_MODE\",\"configs\": [{\"rule\": " + "\"TRACE_ON_NAVIGATION_UNTIL_TRIGGER_OR_FULL\", " + "\"category\": \"BENCHMARK_DEEP\", \"trigger_name\": \"foo\", " + "\"trigger_chance\": 0.5}]}"); + EXPECT_TRUE(config); + EXPECT_EQ(config->tracing_mode(), BackgroundTracingConfig::REACTIVE); + EXPECT_EQ(config->rules().size(), 1u); + EXPECT_EQ(RuleToString(config->rules()[0]), + "{\"category\":\"BENCHMARK_DEEP\"," + "\"rule\":\"TRACE_ON_NAVIGATION_UNTIL_TRIGGER_OR_FULL\"," + "\"trigger_chance\":0.5,\"trigger_name\":\"foo\"}"); + config = ReadFromJSONString( "{\"mode\":\"REACTIVE_TRACING_MODE\",\"configs\": [{\"rule\": " "\"TRACE_ON_NAVIGATION_UNTIL_TRIGGER_OR_FULL\", " @@ -363,6 +377,24 @@ scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->SetString("rule", "MONITOR_AND_DUMP_WHEN_TRIGGER_NAMED"); + dict->SetString("trigger_name", "foo"); + dict->SetDouble("trigger_chance", 0.5); + config->AddPreemptiveRule(dict.get()); + + EXPECT_EQ( + ConfigToString(config.get()), + "{\"category\":\"BENCHMARK_DEEP\",\"configs\":[{\"rule\":" + "\"MONITOR_AND_DUMP_WHEN_TRIGGER_NAMED\",\"trigger_chance\":0.5," + "\"trigger_name\":\"foo\"}],\"mode\":\"PREEMPTIVE_TRACING_MODE\"}"); + } + + { + config.reset( + new BackgroundTracingConfigImpl(BackgroundTracingConfig::PREEMPTIVE)); + config->set_category_preset(BackgroundTracingConfigImpl::BENCHMARK_DEEP); + + scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + dict->SetString("rule", "MONITOR_AND_DUMP_WHEN_TRIGGER_NAMED"); dict->SetString("trigger_name", "foo1"); config->AddPreemptiveRule(dict.get());
diff --git a/content/browser/tracing/background_tracing_manager_browsertest.cc b/content/browser/tracing/background_tracing_manager_browsertest.cc index b52850d..63aceff 100644 --- a/content/browser/tracing/background_tracing_manager_browsertest.cc +++ b/content/browser/tracing/background_tracing_manager_browsertest.cc
@@ -668,6 +668,110 @@ } } +// This tests that no preemptive trace is triggered with 0 chance set. +IN_PROC_BROWSER_TEST_F(BackgroundTracingManagerBrowserTest, + PreemptiveNotTriggerWithZeroChance) { + { + SetupBackgroundTracingManager(); + + base::RunLoop run_loop; + BackgroundTracingManagerUploadConfigWrapper upload_config_wrapper( + (base::Closure())); + + base::DictionaryValue dict; + + dict.SetString("mode", "PREEMPTIVE_TRACING_MODE"); + dict.SetString("category", "BENCHMARK"); + + scoped_ptr<base::ListValue> rules_list(new base::ListValue()); + { + scoped_ptr<base::DictionaryValue> rules_dict(new base::DictionaryValue()); + rules_dict->SetString("rule", "MONITOR_AND_DUMP_WHEN_TRIGGER_NAMED"); + rules_dict->SetString("trigger_name", "preemptive_test"); + rules_dict->SetDouble("trigger_chance", 0.0); + rules_list->Append(rules_dict.Pass()); + } + dict.Set("configs", rules_list.Pass()); + + scoped_ptr<BackgroundTracingConfig> config( + BackgroundTracingConfigImpl::FromDict(&dict)); + + EXPECT_TRUE(config); + + content::BackgroundTracingManager::TriggerHandle handle = + content::BackgroundTracingManager::GetInstance()->RegisterTriggerType( + "preemptive_test"); + + BackgroundTracingManager::GetInstance()->SetActiveScenario( + config.Pass(), upload_config_wrapper.get_receive_callback(), + BackgroundTracingManager::NO_DATA_FILTERING); + + BackgroundTracingManager::GetInstance()->WhenIdle( + base::Bind(&DisableScenarioWhenIdle)); + + BackgroundTracingManager::GetInstance()->TriggerNamedEvent( + handle, + base::Bind(&StartedFinalizingCallback, run_loop.QuitClosure(), false)); + + run_loop.Run(); + + EXPECT_TRUE(upload_config_wrapper.get_receive_count() == 0); + } +} + +// This tests that no reactive trace is triggered with 0 chance set. +IN_PROC_BROWSER_TEST_F(BackgroundTracingManagerBrowserTest, + ReactiveNotTriggerWithZeroChance) { + { + SetupBackgroundTracingManager(); + + base::RunLoop run_loop; + BackgroundTracingManagerUploadConfigWrapper upload_config_wrapper( + (base::Closure())); + + base::DictionaryValue dict; + + dict.SetString("mode", "REACTIVE_TRACING_MODE"); + + scoped_ptr<base::ListValue> rules_list(new base::ListValue()); + { + scoped_ptr<base::DictionaryValue> rules_dict(new base::DictionaryValue()); + rules_dict->SetString("rule", + "TRACE_ON_NAVIGATION_UNTIL_TRIGGER_OR_FULL"); + rules_dict->SetString("trigger_name", "reactive_test1"); + rules_dict->SetString("category", "BENCHMARK"); + rules_dict->SetDouble("trigger_chance", 0.0); + + rules_list->Append(rules_dict.Pass()); + } + dict.Set("configs", rules_list.Pass()); + + scoped_ptr<BackgroundTracingConfig> config( + BackgroundTracingConfigImpl::FromDict(&dict)); + + EXPECT_TRUE(config); + + content::BackgroundTracingManager::TriggerHandle handle = + content::BackgroundTracingManager::GetInstance()->RegisterTriggerType( + "preemptive_test"); + + BackgroundTracingManager::GetInstance()->SetActiveScenario( + config.Pass(), upload_config_wrapper.get_receive_callback(), + BackgroundTracingManager::NO_DATA_FILTERING); + + BackgroundTracingManager::GetInstance()->WhenIdle( + base::Bind(&DisableScenarioWhenIdle)); + + BackgroundTracingManager::GetInstance()->TriggerNamedEvent( + handle, + base::Bind(&StartedFinalizingCallback, run_loop.QuitClosure(), false)); + + run_loop.Run(); + + EXPECT_TRUE(upload_config_wrapper.get_receive_count() == 0); + } +} + // This tests that histogram triggers for preemptive mode configs. IN_PROC_BROWSER_TEST_F(BackgroundTracingManagerBrowserTest, ReceiveTraceSucceedsOnHigherHistogramSample) {
diff --git a/content/browser/tracing/background_tracing_manager_impl.cc b/content/browser/tracing/background_tracing_manager_impl.cc index 21d6125b..45da890 100644 --- a/content/browser/tracing/background_tracing_manager_impl.cc +++ b/content/browser/tracing/background_tracing_manager_impl.cc
@@ -9,6 +9,7 @@ #include "base/json/json_writer.h" #include "base/macros.h" #include "base/metrics/histogram_macros.h" +#include "base/rand_util.h" #include "base/sys_info.h" #include "base/time/time.h" #include "content/browser/tracing/background_tracing_rule.h" @@ -39,6 +40,7 @@ FINALIZATION_DISALLOWED = 6, FINALIZATION_STARTED = 7, FINALIZATION_COMPLETE = 8, + SCENARIO_ACTION_FAILED_LOWRES_CLOCK = 9, NUMBER_OF_BACKGROUND_TRACING_METRICS, }; @@ -134,6 +136,13 @@ if (is_tracing_) return false; + // If we don't have a high resolution timer available, traces will be + // too inaccurate to be useful. + if (!base::TimeTicks::IsHighResolution()) { + RecordBackgroundTracingMetric(SCENARIO_ACTION_FAILED_LOWRES_CLOCK); + return false; + } + bool requires_anonymized_data = (data_filtering == ANONYMIZE_DATA); // If the I/O thread isn't running, this is a startup scenario and @@ -314,6 +323,13 @@ StartedFinalizingCallback callback) { CHECK(config_); + double trigger_chance = triggered_rule->trigger_chance(); + if (trigger_chance < 1.0 && base::RandDouble() > trigger_chance) { + if (!callback.is_null()) + callback.Run(false); + return; + } + int trace_timeout = triggered_rule->GetTraceTimeout(); if (config_->tracing_mode() == BackgroundTracingConfigImpl::REACTIVE) {
diff --git a/content/browser/tracing/background_tracing_rule.cc b/content/browser/tracing/background_tracing_rule.cc index cd78b1b..f09608a 100644 --- a/content/browser/tracing/background_tracing_rule.cc +++ b/content/browser/tracing/background_tracing_rule.cc
@@ -22,6 +22,7 @@ const char kConfigCategoryKey[] = "category"; const char kConfigRuleTriggerNameKey[] = "trigger_name"; const char kConfigRuleTriggerDelay[] = "trigger_delay"; +const char kConfigRuleTriggerChance[] = "trigger_chance"; const char kConfigRuleHistogramNameKey[] = "histogram_name"; const char kConfigRuleHistogramValueOldKey[] = "histogram_value"; @@ -55,7 +56,7 @@ namespace content { -BackgroundTracingRule::BackgroundTracingRule() {} +BackgroundTracingRule::BackgroundTracingRule() : trigger_chance_(1.0) {} BackgroundTracingRule::~BackgroundTracingRule() {} @@ -73,6 +74,16 @@ return -1; } +void BackgroundTracingRule::IntoDict(base::DictionaryValue* dict) const { + DCHECK(dict); + if (trigger_chance_ < 1.0) + dict->SetDouble(kConfigRuleTriggerChance, trigger_chance_); +} + +void BackgroundTracingRule::Setup(const base::DictionaryValue* dict) { + dict->GetDouble(kConfigRuleTriggerChance, &trigger_chance_); +} + namespace { class NamedTriggerRule : public BackgroundTracingRule { @@ -93,6 +104,7 @@ void IntoDict(base::DictionaryValue* dict) const override { DCHECK(dict); + BackgroundTracingRule::IntoDict(dict); dict->SetString(kConfigRuleKey, kPreemptiveConfigRuleMonitorNamed); dict->SetString(kConfigRuleTriggerNameKey, named_event_.c_str()); } @@ -173,6 +185,7 @@ void IntoDict(base::DictionaryValue* dict) const override { DCHECK(dict); + BackgroundTracingRule::IntoDict(dict); dict->SetString(kConfigRuleKey, kPreemptiveConfigRuleMonitorHistogram); dict->SetString(kConfigRuleHistogramNameKey, histogram_name_.c_str()); dict->SetInteger(kConfigRuleHistogramValue1Key, histogram_lower_value_); @@ -265,6 +278,7 @@ // BackgroundTracingRule implementation void IntoDict(base::DictionaryValue* dict) const override { DCHECK(dict); + BackgroundTracingRule::IntoDict(dict); dict->SetString( kConfigCategoryKey, BackgroundTracingConfigImpl::CategoryPresetToString(category_preset_)); @@ -326,6 +340,7 @@ void IntoDict(base::DictionaryValue* dict) const override { DCHECK(dict); + BackgroundTracingRule::IntoDict(dict); dict->SetString( kConfigCategoryKey, BackgroundTracingConfigImpl::CategoryPresetToString(category_preset_)); @@ -404,13 +419,16 @@ if (!dict->GetString(kConfigRuleKey, &type)) return nullptr; + scoped_ptr<BackgroundTracingRule> tracing_rule; if (type == kPreemptiveConfigRuleMonitorNamed) - return NamedTriggerRule::Create(dict); + tracing_rule = NamedTriggerRule::Create(dict); + else if (type == kPreemptiveConfigRuleMonitorHistogram) + tracing_rule = HistogramRule::Create(dict); - if (type == kPreemptiveConfigRuleMonitorHistogram) - return HistogramRule::Create(dict); + if (tracing_rule) + tracing_rule->Setup(dict); - return nullptr; + return tracing_rule; } scoped_ptr<BackgroundTracingRule> BackgroundTracingRule::ReactiveRuleFromDict( @@ -422,13 +440,20 @@ if (!dict->GetString(kConfigRuleKey, &type)) return nullptr; - if (type == kReactiveConfigRuleTraceOnNavigationUntilTriggerOrFull) - return ReactiveTraceForNSOrTriggerOrFullRule::Create(dict, category_preset); + scoped_ptr<BackgroundTracingRule> tracing_rule; - if (type == kReactiveConfigRuleTraceAtRandomIntervals) - return ReactiveTraceAtRandomIntervalsRule::Create(dict, category_preset); + if (type == kReactiveConfigRuleTraceOnNavigationUntilTriggerOrFull) { + tracing_rule = + ReactiveTraceForNSOrTriggerOrFullRule::Create(dict, category_preset); + } else if (type == kReactiveConfigRuleTraceAtRandomIntervals) { + tracing_rule = + ReactiveTraceAtRandomIntervalsRule::Create(dict, category_preset); + } - return nullptr; + if (tracing_rule) + tracing_rule->Setup(dict); + + return tracing_rule; } } // namespace content
diff --git a/content/browser/tracing/background_tracing_rule.h b/content/browser/tracing/background_tracing_rule.h index c5407ba..6e85836c 100644 --- a/content/browser/tracing/background_tracing_rule.h +++ b/content/browser/tracing/background_tracing_rule.h
@@ -20,7 +20,8 @@ virtual ~BackgroundTracingRule(); virtual void Install() {} - virtual void IntoDict(base::DictionaryValue* dict) const = 0; + virtual void IntoDict(base::DictionaryValue* dict) const; + void Setup(const base::DictionaryValue* dict); virtual bool ShouldTriggerNamedEvent(const std::string& named_event) const; virtual BackgroundTracingConfigImpl::CategoryPreset GetCategoryPreset() const; virtual void OnHistogramTrigger(const std::string& histogram_name) const {} @@ -28,6 +29,9 @@ // Seconds from the rule is triggered to finalization should start. virtual int GetTraceTimeout() const; + // Probability that we should allow a tigger to happen. + double trigger_chance() const { return trigger_chance_; } + static scoped_ptr<BackgroundTracingRule> PreemptiveRuleFromDict( const base::DictionaryValue* dict); @@ -37,6 +41,8 @@ private: DISALLOW_COPY_AND_ASSIGN(BackgroundTracingRule); + + double trigger_chance_; }; } // namespace content
diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc index e01a4d5..fdf40d3 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc
@@ -168,22 +168,6 @@ cache->OnExternalCacheHit(url, http_method); } -// Helper function for retrieving all the sites in a frame tree. -bool CollectSites(BrowserContext* context, - std::set<GURL>* sites, - FrameTreeNode* node) { - // Record about:blank as a real (process-having) site only if the SiteInstance - // is unassigned. Do not otherwise depend on the siteinstance's site URL, - // since its value reflects the current process model, and this function - // should behave identically across all process models. - if (node->current_url() == GURL(url::kAboutBlankURL) && - node->current_frame_host()->GetSiteInstance()->HasSite()) { - return true; - } - sites->insert(SiteInstance::GetSiteForURL(context, node->current_url())); - return true; -} - bool FindMatchingProcess(int render_process_id, bool* did_match_process, FrameTreeNode* node) { @@ -1038,14 +1022,6 @@ return upload_position_; } -std::set<GURL> WebContentsImpl::GetSitesInTab() const { - std::set<GURL> sites; - frame_tree_.ForEach(base::Bind(&CollectSites, - base::Unretained(GetBrowserContext()), - base::Unretained(&sites))); - return sites; -} - const std::string& WebContentsImpl::GetEncoding() const { return canonical_encoding_; }
diff --git a/content/browser/web_contents/web_contents_impl.h b/content/browser/web_contents/web_contents_impl.h index 60cde3c9..73a3a2a 100644 --- a/content/browser/web_contents/web_contents_impl.h +++ b/content/browser/web_contents/web_contents_impl.h
@@ -271,7 +271,6 @@ const base::string16& GetLoadStateHost() const override; uint64 GetUploadSize() const override; uint64 GetUploadPosition() const override; - std::set<GURL> GetSitesInTab() const override; const std::string& GetEncoding() const override; bool DisplayedInsecureContent() const override; void IncrementCapturerCount(const gfx::Size& capture_size) override;
diff --git a/content/browser/web_contents/web_contents_view_mac.h b/content/browser/web_contents/web_contents_view_mac.h index d116d7d..46427c5 100644 --- a/content/browser/web_contents/web_contents_view_mac.h +++ b/content/browser/web_contents/web_contents_view_mac.h
@@ -38,7 +38,10 @@ CONTENT_EXPORT @interface WebContentsViewCocoa : BaseView { @private - content::WebContentsViewMac* webContentsView_; // WEAK; owns us + // Instances of this class are owned by both webContentsView_ and AppKit. It + // is possible for an instance to outlive its webContentsView_. The + // webContentsView_ must call -clearWebContentsView in its destructor. + content::WebContentsViewMac* webContentsView_; base::scoped_nsobject<WebDragSource> dragSource_; base::scoped_nsobject<WebDragDest> dragDest_; BOOL mouseDownCanMoveWindow_; @@ -46,10 +49,6 @@ - (void)setMouseDownCanMoveWindow:(BOOL)canMove; - (void)setOpaque:(BOOL)opaque; - -// Expose this, since sometimes one needs both the NSView and the -// WebContentsImpl. -- (content::WebContentsImpl*)webContents; @end namespace content {
diff --git a/content/browser/web_contents/web_contents_view_mac.mm b/content/browser/web_contents/web_contents_view_mac.mm index 5588f1f..33d5ae30 100644 --- a/content/browser/web_contents/web_contents_view_mac.mm +++ b/content/browser/web_contents/web_contents_view_mac.mm
@@ -67,6 +67,7 @@ - (void)clearWebContentsView; - (void)closeTabAfterEvent; - (void)viewDidBecomeFirstResponder:(NSNotification*)notification; +- (content::WebContentsImpl*)webContents; @end namespace content { @@ -455,8 +456,8 @@ } - (WebContentsImpl*)webContents { - if (webContentsView_ == NULL) - return NULL; + if (!webContentsView_) + return nullptr; return webContentsView_->web_contents(); } @@ -488,8 +489,11 @@ } - (void)setOpaque:(BOOL)opaque { + WebContentsImpl* webContents = [self webContents]; + if (!webContents) + return; RenderWidgetHostViewMac* view = static_cast<RenderWidgetHostViewMac*>( - webContentsView_->web_contents()->GetRenderWidgetHostView()); + webContents->GetRenderWidgetHostView()); DCHECK(view); [view->cocoa_view() setOpaque:opaque]; } @@ -503,6 +507,8 @@ dragOperationMask:(NSDragOperation)operationMask image:(NSImage*)image offset:(NSPoint)offset { + if (![self webContents]) + return; dragSource_.reset([[WebDragSource alloc] initWithContents:[self webContents] view:self @@ -580,15 +586,19 @@ } - (void)clearWebContentsView { - webContentsView_ = NULL; + webContentsView_ = nullptr; [dragSource_ clearWebContentsView]; } - (void)closeTabAfterEvent { - webContentsView_->CloseTab(); + if (webContentsView_) + webContentsView_->CloseTab(); } - (void)viewDidBecomeFirstResponder:(NSNotification*)notification { + if (![self webContents]) + return; + NSView* view = [notification object]; if (![[self subviews] containsObject:view]) return;
diff --git a/content/browser/web_contents/web_drag_source_mac.h b/content/browser/web_contents/web_drag_source_mac.h index f1ccc4df..49dad89cc 100644 --- a/content/browser/web_contents/web_drag_source_mac.h +++ b/content/browser/web_contents/web_drag_source_mac.h
@@ -22,9 +22,13 @@ @interface WebDragSource : NSObject { @private // Our contents. Weak reference (owns or co-owns us). + // An instance of this class may outlive |contents_|. The destructor of + // |contents_| must set this ivar to |nullptr|. content::WebContentsImpl* contents_; // The view from which the drag was initiated. Weak reference. + // An instance of this class may outlive |contentsView_|. The destructor of + // |contentsView_| must set this ivar to |nullptr|. NSView* contentsView_; // Our drop data. Should only be initialized once.
diff --git a/content/browser/web_contents/web_drag_source_mac.mm b/content/browser/web_contents/web_drag_source_mac.mm index ff3a881e..9e6443be 100644 --- a/content/browser/web_contents/web_drag_source_mac.mm +++ b/content/browser/web_contents/web_drag_source_mac.mm
@@ -225,6 +225,9 @@ } - (void)startDrag { + if (!contentsView_) + return; + NSEvent* currentEvent = [NSApp currentEvent]; // Synthesize an event for dragging, since we can't be sure that @@ -260,7 +263,7 @@ - (void)endDragAt:(NSPoint)screenPoint operation:(NSDragOperation)operation { - if (!contents_) + if (!contents_ || !contentsView_) return; contents_->SystemDragEnded(); @@ -309,7 +312,7 @@ if (!file.IsValid()) return nil; - if (downloadURL_.is_valid()) { + if (downloadURL_.is_valid() && contents_) { scoped_refptr<DragDownloadFile> dragFileDownloader(new DragDownloadFile( filePath, file.Pass(), @@ -342,6 +345,9 @@ @implementation WebDragSource (Private) - (void)fillPasteboard { + if (!contentsView_) + return; + DCHECK(pasteboard_.get()); [pasteboard_ declareTypes:@[ ui::kChromeDragDummyPboardType ]
diff --git a/content/child/memory/child_memory_message_filter.cc b/content/child/memory/child_memory_message_filter.cc index 9306e7c..c824c5a 100644 --- a/content/child/memory/child_memory_message_filter.cc +++ b/content/child/memory/child_memory_message_filter.cc
@@ -32,7 +32,16 @@ void ChildMemoryMessageFilter::OnSimulatePressureNotification( base::MemoryPressureListener::MemoryPressureLevel level) { + // Pass the message to SimulatePressureNotification. This will emit the + // message to all listeners even if notifications are suppressed. base::MemoryPressureListener::SimulatePressureNotification(level); } +void ChildMemoryMessageFilter::OnPressureNotification( + base::MemoryPressureListener::MemoryPressureLevel level) { + // Forward the message along the normal notification path. If notifications + // are suppressed then the notification will be swallowed. + base::MemoryPressureListener::NotifyMemoryPressure(level); +} + } // namespace content
diff --git a/content/child/memory/child_memory_message_filter.h b/content/child/memory/child_memory_message_filter.h index bc1e665..07ce55e1 100644 --- a/content/child/memory/child_memory_message_filter.h +++ b/content/child/memory/child_memory_message_filter.h
@@ -26,6 +26,8 @@ void OnSetPressureNotificationsSuppressed(bool suppressed); void OnSimulatePressureNotification( base::MemoryPressureListener::MemoryPressureLevel level); + void OnPressureNotification( + base::MemoryPressureListener::MemoryPressureLevel level); DISALLOW_COPY_AND_ASSIGN(ChildMemoryMessageFilter); };
diff --git a/content/common/gpu/image_transport_surface_overlay_mac.mm b/content/common/gpu/image_transport_surface_overlay_mac.mm index 298baa3..c7639cb 100644 --- a/content/common/gpu/image_transport_surface_overlay_mac.mm +++ b/content/common/gpu/image_transport_surface_overlay_mac.mm
@@ -374,6 +374,8 @@ swap->scale_factor, swap->pixel_damage_rect); std::sort(swap->overlay_planes.begin(), swap->overlay_planes.end(), OverlayPlane::Compare); + for (auto& plane : swap->overlay_planes) + dip_damage_rect.Subtract(plane->dip_frame_rect); ScopedCAActionDisabler disabler; UpdateRootAndPartialDamagePlanes(swap->root_plane, dip_damage_rect);
diff --git a/content/common/memory_messages.h b/content/common/memory_messages.h index 6ae158a..42f0d47e 100644 --- a/content/common/memory_messages.h +++ b/content/common/memory_messages.h
@@ -31,3 +31,9 @@ IPC_MESSAGE_CONTROL1( MemoryMsg_SimulatePressureNotification, base::MemoryPressureListener::MemoryPressureLevel /* level */) + +// Sent by the browser to all child processes to indicate an actual memory +// pressure notification. +IPC_MESSAGE_CONTROL1( + MemoryMsg_PressureNotification, + base::MemoryPressureListener::MemoryPressureLevel /* level */)
diff --git a/content/common/resource_messages.cc b/content/common/resource_messages.cc index 9cadbff..ba92207 100644 --- a/content/common/resource_messages.cc +++ b/content/common/resource_messages.cc
@@ -42,6 +42,10 @@ m->WriteData(p.bytes(), static_cast<int>(p.length())); break; } + case storage::DataElement::TYPE_BYTES_DESCRIPTION: { + WriteParam(m, p.length()); + break; + } case storage::DataElement::TYPE_FILE: { WriteParam(m, p.path()); WriteParam(m, p.offset()); @@ -88,6 +92,13 @@ r->SetToBytes(data, len); break; } + case storage::DataElement::TYPE_BYTES_DESCRIPTION: { + uint64 length; + if (!ReadParam(m, iter, &length)) + return false; + r->SetToBytesDescription(length); + break; + } case storage::DataElement::TYPE_FILE: { base::FilePath file_path; uint64 offset, length;
diff --git a/content/common/sandbox_win.cc b/content/common/sandbox_win.cc index d1a1886..d8689bc 100644 --- a/content/common/sandbox_win.cc +++ b/content/common/sandbox_win.cc
@@ -566,8 +566,7 @@ } void AddAppContainerPolicy(sandbox::TargetPolicy* policy, const wchar_t* sid) { - if (base::win::GetVersion() == base::win::VERSION_WIN8 || - base::win::GetVersion() == base::win::VERSION_WIN8_1) { + if (base::win::GetVersion() >= base::win::VERSION_WIN8) { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kEnableAppContainer)) {
diff --git a/content/content_shell.gypi b/content/content_shell.gypi index da23661..4a77d2b6 100644 --- a/content/content_shell.gypi +++ b/content/content_shell.gypi
@@ -86,6 +86,7 @@ ], 'sources': [ # Note: sources list duplicated in GN build. + 'shell/android/shell_descriptors.h', 'shell/android/shell_jni_registrar.cc', 'shell/android/shell_jni_registrar.h', 'shell/android/shell_manager.cc',
diff --git a/content/public/android/java/src/org/chromium/content/browser/MediaThrottler.java b/content/public/android/java/src/org/chromium/content/browser/MediaThrottler.java index 1895d6e..9992704 100644 --- a/content/public/android/java/src/org/chromium/content/browser/MediaThrottler.java +++ b/content/public/android/java/src/org/chromium/content/browser/MediaThrottler.java
@@ -103,7 +103,11 @@ protected Void doInBackground(Void... voids) { synchronized (mLock) { if (mPlayer != null || mRequestCount == 0) return null; - mPlayer = MediaPlayer.create(mContext, R.raw.empty); + try { + mPlayer = MediaPlayer.create(mContext, R.raw.empty); + } catch (IllegalStateException e) { + Log.e(TAG, "Exception happens while creating the watch dog player.", e); + } if (mPlayer == null) { Log.e(TAG, "Unable to create watch dog player, treat it as server crash."); onMediaServerCrash(); @@ -131,7 +135,7 @@ return false; } mRequestCount++; - if (mRequestCount == 1) { + if (mRequestCount == 1 || mPlayer == null) { mHandler.removeCallbacks(mDelayedReleaseRunnable); mHandler.post(new Runnable() { @Override
diff --git a/content/public/android/java/src/org/chromium/content/browser/input/OWNERS b/content/public/android/java/src/org/chromium/content/browser/input/OWNERS index 812e8d9..28400a3 100644 --- a/content/public/android/java/src/org/chromium/content/browser/input/OWNERS +++ b/content/public/android/java/src/org/chromium/content/browser/input/OWNERS
@@ -1 +1,3 @@ +aelias@chromium.org aurimas@chromium.org +changwan@chromium.org
diff --git a/content/public/android/javatests/src/org/chromium/content/browser/input/OWNERS b/content/public/android/javatests/src/org/chromium/content/browser/input/OWNERS index 812e8d9..28400a3 100644 --- a/content/public/android/javatests/src/org/chromium/content/browser/input/OWNERS +++ b/content/public/android/javatests/src/org/chromium/content/browser/input/OWNERS
@@ -1 +1,3 @@ +aelias@chromium.org aurimas@chromium.org +changwan@chromium.org
diff --git a/content/public/browser/devtools_frontend_host.h b/content/public/browser/devtools_frontend_host.h index 05d6ab1..c7acf6a 100644 --- a/content/public/browser/devtools_frontend_host.h +++ b/content/public/browser/devtools_frontend_host.h
@@ -7,6 +7,7 @@ #include <string> +#include "base/callback.h" #include "base/strings/string_piece.h" #include "content/common/content_export.h" @@ -20,27 +21,13 @@ // the content public API. class DevToolsFrontendHost { public: - // Delegate actually handles messages from frontend. - class Delegate { - public: - virtual ~Delegate() {} - - // Message is coming from frontend to the embedder. - virtual void HandleMessageFromDevToolsFrontend( - const std::string& message) = 0; - - // Message is coming from frontend to the backend. - // TODO(dgozman): remove this by making one of the possible messages - // passed via the method above. - virtual void HandleMessageFromDevToolsFrontendToBackend( - const std::string& message) = 0; - }; + using HandleMessageCallback = base::Callback<void(const std::string&)>; // Creates a new DevToolsFrontendHost for RenderFrameHost where DevTools // frontend is loaded. CONTENT_EXPORT static DevToolsFrontendHost* Create( RenderFrameHost* frontend_main_frame, - Delegate* delegate); + const HandleMessageCallback& handle_message_callback); CONTENT_EXPORT virtual ~DevToolsFrontendHost() {}
diff --git a/content/public/browser/web_contents.h b/content/public/browser/web_contents.h index a991d907..cda64874 100644 --- a/content/public/browser/web_contents.h +++ b/content/public/browser/web_contents.h
@@ -327,9 +327,6 @@ virtual uint64 GetUploadSize() const = 0; virtual uint64 GetUploadPosition() const = 0; - // Returns a set of the site URLs currently committed in this tab. - virtual std::set<GURL> GetSitesInTab() const = 0; - // Returns the character encoding of the page. virtual const std::string& GetEncoding() const = 0;
diff --git a/content/public/common/content_switches.h b/content/public/common/content_switches.h index 68d6b44..66b4cc5 100644 --- a/content/public/common/content_switches.h +++ b/content/public/common/content_switches.h
@@ -136,7 +136,7 @@ CONTENT_EXPORT extern const char kEnableTracing[]; CONTENT_EXPORT extern const char kEnableTracingOutput[]; CONTENT_EXPORT extern const char kEnableUserMediaScreenCapturing[]; -extern const char kEnableUseZoomForDSF[]; +CONTENT_EXPORT extern const char kEnableUseZoomForDSF[]; CONTENT_EXPORT extern const char kEnableViewport[]; CONTENT_EXPORT extern const char kEnableVtune[]; CONTENT_EXPORT extern const char kEnableWebGLDraftExtensions[];
diff --git a/content/public/test/test_launcher.cc b/content/public/test/test_launcher.cc index 4a28891..597818dd 100644 --- a/content/public/test/test_launcher.cc +++ b/content/public/test/test_launcher.cc
@@ -130,8 +130,8 @@ const std::vector<std::string>& test_names) override; private: - void DoRunTest(base::TestLauncher* test_launcher, - const std::string& test_name); + void DoRunTests(base::TestLauncher* test_launcher, + const std::vector<std::string>& test_names); // Launches test named |test_name| using parallel launcher, // given result of PRE_ test |pre_test_result|. @@ -142,6 +142,7 @@ // Callback to receive result of a test. void GTestCallback( base::TestLauncher* test_launcher, + const std::vector<std::string>& test_names, const std::string& test_name, int exit_code, const base::TimeDelta& elapsed_time, @@ -254,7 +255,9 @@ while (ContainsKey(reverse_dependent_test_map_, full_name)) full_name = GetPreTestName(full_name); - DoRunTest(test_launcher, full_name); + std::vector<std::string> test_list; + test_list.push_back(full_name); + DoRunTests(test_launcher, test_list); } return test_names.size() + additional_tests_to_run_count; @@ -316,14 +319,21 @@ tests_to_run_now.push_back(full_name); } - for (size_t i = 0; i < tests_to_run_now.size(); i++) - DoRunTest(test_launcher, tests_to_run_now[i]); + DoRunTests(test_launcher, tests_to_run_now); return test_names_set.size(); } -void WrapperTestLauncherDelegate::DoRunTest(base::TestLauncher* test_launcher, - const std::string& test_name) { +void WrapperTestLauncherDelegate::DoRunTests( + base::TestLauncher* test_launcher, + const std::vector<std::string>& test_names) { + if (test_names.empty()) + return; + + std::string test_name(test_names.front()); + std::vector<std::string> test_names_copy( + test_names.begin() + 1, test_names.end()); + std::string test_name_no_pre(RemoveAnyPrePrefixes(test_name)); base::CommandLine cmd_line(*base::CommandLine::ForCurrentProcess()); @@ -359,6 +369,7 @@ base::Bind(&WrapperTestLauncherDelegate::GTestCallback, base::Unretained(this), test_launcher, + test_names_copy, test_name)); } @@ -368,7 +379,9 @@ const base::TestResult& pre_test_result) { if (pre_test_result.status == base::TestResult::TEST_SUCCESS) { // Only run the dependent test if PRE_ test succeeded. - DoRunTest(test_launcher, test_name); + std::vector<std::string> test_list; + test_list.push_back(test_name); + DoRunTests(test_launcher, test_list); } else { // Otherwise skip the test. base::TestResult test_result; @@ -386,6 +399,7 @@ void WrapperTestLauncherDelegate::GTestCallback( base::TestLauncher* test_launcher, + const std::vector<std::string>& test_names, const std::string& test_name, int exit_code, const base::TimeDelta& elapsed_time, @@ -422,6 +436,8 @@ } test_launcher->OnTestFinished(result); + + DoRunTests(test_launcher, test_names); } } // namespace
diff --git a/content/renderer/devtools/devtools_client.cc b/content/renderer/devtools/devtools_client.cc index 92dcc1773..b19516b3 100644 --- a/content/renderer/devtools/devtools_client.cc +++ b/content/renderer/devtools/devtools_client.cc
@@ -42,11 +42,6 @@ render_frame()->ExecuteJavaScript(base::UTF8ToUTF16(compatibility_script_)); } -void DevToolsClient::sendMessageToBackend(const WebString& message) { - Send(new DevToolsAgentMsg_DispatchOnInspectorBackend(routing_id(), - message.utf8())); -} - void DevToolsClient::sendMessageToEmbedder(const WebString& message) { Send(new DevToolsHostMsg_DispatchOnEmbedder(routing_id(), message.utf8()));
diff --git a/content/renderer/devtools/devtools_client.h b/content/renderer/devtools/devtools_client.h index 205ae1a0..a751a31 100644 --- a/content/renderer/devtools/devtools_client.h +++ b/content/renderer/devtools/devtools_client.h
@@ -38,7 +38,6 @@ void DidClearWindowObject() override; // WebDevToolsFrontendClient implementation. - void sendMessageToBackend(const blink::WebString&) override; void sendMessageToEmbedder(const blink::WebString&) override; bool isUnderTest() override;
diff --git a/content/renderer/gpu/render_widget_compositor.cc b/content/renderer/gpu/render_widget_compositor.cc index c684a37..62c97cc 100644 --- a/content/renderer/gpu/render_widget_compositor.cc +++ b/content/renderer/gpu/render_widget_compositor.cc
@@ -605,12 +605,6 @@ } void RenderWidgetCompositor::setViewportSize( - const WebSize&, - const WebSize& device_viewport_size) { - layer_tree_host_->SetViewportSize(device_viewport_size); -} - -void RenderWidgetCompositor::setViewportSize( const WebSize& device_viewport_size) { layer_tree_host_->SetViewportSize(device_viewport_size); } @@ -1086,4 +1080,9 @@ return actual; } +void RenderWidgetCompositor::SetPaintedDeviceScaleFactor( + float device_scale) { + layer_tree_host_->SetPaintedDeviceScaleFactor(device_scale); +} + } // namespace content
diff --git a/content/renderer/gpu/render_widget_compositor.h b/content/renderer/gpu/render_widget_compositor.h index ee101bb..c2c3c2c 100644 --- a/content/renderer/gpu/render_widget_compositor.h +++ b/content/renderer/gpu/render_widget_compositor.h
@@ -81,6 +81,7 @@ void SetSurfaceIdNamespace(uint32_t surface_id_namespace); cc::ManagedMemoryPolicy GetGpuMemoryPolicy( const cc::ManagedMemoryPolicy& policy); + void SetPaintedDeviceScaleFactor(float device_scale); // WebLayerTreeView implementation. void setRootLayer(const blink::WebLayer& layer) override; @@ -89,9 +90,6 @@ blink::WebCompositorAnimationTimeline* compositor_timeline) override; void detachCompositorAnimationTimeline( blink::WebCompositorAnimationTimeline* compositor_timeline) override; - virtual void setViewportSize( - const blink::WebSize& unused_deprecated, - const blink::WebSize& device_viewport_size); void setViewportSize(const blink::WebSize& device_viewport_size) override; virtual blink::WebFloatPoint adjustEventPointForPinchZoom( const blink::WebFloatPoint& point) const;
diff --git a/content/renderer/media/android/webmediaplayer_android.cc b/content/renderer/media/android/webmediaplayer_android.cc index 69ec1a7..4e6db86 100644 --- a/content/renderer/media/android/webmediaplayer_android.cc +++ b/content/renderer/media/android/webmediaplayer_android.cc
@@ -635,11 +635,8 @@ unsigned textureId = static_cast<unsigned>( (bitmap_.getTexture())->getTextureHandle()); - if (!copyVideoTextureToPlatformTexture( - context3D, - CopyVideoTextureParams(CopyVideoTextureParams::FullCopy, - GL_TEXTURE_2D, textureId, GL_RGBA, - GL_UNSIGNED_BYTE, 0, 0, 0, true, false))) { + if (!copyVideoTextureToPlatformTexture(context3D, textureId, + GL_RGBA, GL_UNSIGNED_BYTE, true, false)) { return; } @@ -663,12 +660,12 @@ bool WebMediaPlayerAndroid::copyVideoTextureToPlatformTexture( blink::WebGraphicsContext3D* web_graphics_context, - const CopyVideoTextureParams& params) { + unsigned int texture, + unsigned int internal_format, + unsigned int type, + bool premultiply_alpha, + bool flip_y) { DCHECK(main_thread_checker_.CalledOnValidThread()); - DCHECK((params.copyType == CopyVideoTextureParams::FullCopy && - !params.xoffset && !params.yoffset) || - (params.copyType == CopyVideoTextureParams::SubCopy && - !params.internalFormat && !params.type)); // Don't allow clients to copy an encrypted video frame. if (needs_external_surface_) return false; @@ -699,17 +696,9 @@ // value down to get the expected result. // flip_y==true means to reverse the video orientation while // flip_y==false means to keep the intrinsic orientation. - if (params.copyType == CopyVideoTextureParams::FullCopy) { - web_graphics_context->copyTextureCHROMIUM( - params.target, src_texture, params.texture, params.internalFormat, - params.type, params.flipY, params.premultiplyAlpha, false); - } else { - web_graphics_context->copySubTextureCHROMIUM( - params.target, src_texture, params.texture, params.xoffset, - params.yoffset, 0, 0, video_frame->natural_size().width(), - video_frame->natural_size().height(), params.flipY, - params.premultiplyAlpha, false); - } + web_graphics_context->copyTextureCHROMIUM( + GL_TEXTURE_2D, src_texture, texture, internal_format, type, + flip_y, premultiply_alpha, false); web_graphics_context->deleteTexture(src_texture); web_graphics_context->flush();
diff --git a/content/renderer/media/android/webmediaplayer_android.h b/content/renderer/media/android/webmediaplayer_android.h index 6b8090f..bb33815 100644 --- a/content/renderer/media/android/webmediaplayer_android.h +++ b/content/renderer/media/android/webmediaplayer_android.h
@@ -138,7 +138,11 @@ bool copyVideoTextureToPlatformTexture( blink::WebGraphicsContext3D* web_graphics_context, - const CopyVideoTextureParams& params) override; + unsigned int texture, + unsigned int internal_format, + unsigned int type, + bool premultiply_alpha, + bool flip_y) override; // True if the loaded media has a playable video/audio track. virtual bool hasVideo() const;
diff --git a/content/renderer/media/webmediaplayer_ms.cc b/content/renderer/media/webmediaplayer_ms.cc index 85c41be..586f180 100644 --- a/content/renderer/media/webmediaplayer_ms.cc +++ b/content/renderer/media/webmediaplayer_ms.cc
@@ -352,13 +352,13 @@ bool WebMediaPlayerMS::copyVideoTextureToPlatformTexture( blink::WebGraphicsContext3D* web_graphics_context, - const CopyVideoTextureParams& params) { + unsigned int texture, + unsigned int internal_format, + unsigned int type, + bool premultiply_alpha, + bool flip_y) { TRACE_EVENT0("media", "WebMediaPlayerMS:copyVideoTextureToPlatformTexture"); DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK((params.copyType == CopyVideoTextureParams::FullCopy && - !params.xoffset && !params.yoffset) || - (params.copyType == CopyVideoTextureParams::SubCopy && - !params.internalFormat && !params.type)); scoped_refptr<media::VideoFrame> video_frame = compositor_->GetCurrentFrame(); @@ -372,15 +372,9 @@ gpu::gles2::GLES2Interface* const gl = static_cast<gpu_blink::WebGraphicsContext3DImpl*>(web_graphics_context) ->GetGLInterface(); - typedef media::SkCanvasVideoRenderer::CopyFrameSingleTextureParams CopyParams; media::SkCanvasVideoRenderer::CopyVideoFrameSingleTextureToGLTexture( - gl, video_frame.get(), - CopyParams(params.copyType == CopyVideoTextureParams::FullCopy - ? CopyParams::FullCopy - : CopyParams::SubCopy, - params.target, params.texture, params.internalFormat, - params.type, params.level, params.xoffset, params.yoffset, - params.premultiplyAlpha, params.flipY)); + gl, video_frame.get(), texture, internal_format, type, premultiply_alpha, + flip_y); return true; }
diff --git a/content/renderer/media/webmediaplayer_ms.h b/content/renderer/media/webmediaplayer_ms.h index ecd160bc..ebf62d24 100644 --- a/content/renderer/media/webmediaplayer_ms.h +++ b/content/renderer/media/webmediaplayer_ms.h
@@ -134,7 +134,11 @@ bool copyVideoTextureToPlatformTexture( blink::WebGraphicsContext3D* web_graphics_context, - const CopyVideoTextureParams& params) override; + unsigned int texture, + unsigned int internal_format, + unsigned int type, + bool premultiply_alpha, + bool flip_y) override; private: // The callback for VideoFrameProvider to signal a new frame is available.
diff --git a/content/renderer/render_view_impl.cc b/content/renderer/render_view_impl.cc index 584854c..dadfdbb 100644 --- a/content/renderer/render_view_impl.cc +++ b/content/renderer/render_view_impl.cc
@@ -38,6 +38,7 @@ #include "content/child/v8_value_converter_impl.h" #include "content/child/webmessageportchannel_impl.h" #include "content/common/content_constants_internal.h" +#include "content/common/content_switches_internal.h" #include "content/common/database_messages.h" #include "content/common/dom_storage/dom_storage_types.h" #include "content/common/drag_messages.h" @@ -745,8 +746,7 @@ // completing initialization. Otherwise, we can finish it now. if (opener_id_ == MSG_ROUTING_NONE) did_show_ = true; - - webview()->setDeviceScaleFactor(device_scale_factor_); + UpdateDeviceScaleFactor(); webview()->setDisplayMode(display_mode_); webview()->settings()->setPreferCompositingToLCDTextEnabled( PreferCompositingToLCDText(compositor_deps_, device_scale_factor_)); @@ -3195,7 +3195,7 @@ void RenderViewImpl::SetDeviceScaleFactor(float device_scale_factor) { RenderWidget::SetDeviceScaleFactor(device_scale_factor); if (webview()) { - webview()->setDeviceScaleFactor(device_scale_factor); + UpdateDeviceScaleFactor(); webview()->settings()->setPreferCompositingToLCDTextEnabled( PreferCompositingToLCDText(compositor_deps_, device_scale_factor_)); } @@ -3703,4 +3703,14 @@ SendUpdateFaviconURL(urls); } +void RenderViewImpl::UpdateDeviceScaleFactor() { + if (IsUseZoomForDSFEnabled()) { + compositor_->SetPaintedDeviceScaleFactor(device_scale_factor_); + webview()->setZoomFactorForDeviceScaleFactor( + device_scale_factor_); + } else { + webview()->setDeviceScaleFactor(device_scale_factor_); + } +} + } // namespace content
diff --git a/content/renderer/render_view_impl.h b/content/renderer/render_view_impl.h index 591cd6b4..73372be 100644 --- a/content/renderer/render_view_impl.h +++ b/content/renderer/render_view_impl.h
@@ -762,6 +762,8 @@ void UpdateThemePrefs() {} #endif + void UpdateDeviceScaleFactor(); + // --------------------------------------------------------------------------- // ADDING NEW FUNCTIONS? Please keep private functions alphabetized and put // it in the same order in the .cc file as it was in the header.
diff --git a/content/renderer/render_widget.cc b/content/renderer/render_widget.cc index 04c3102..10eff2c 100644 --- a/content/renderer/render_widget.cc +++ b/content/renderer/render_widget.cc
@@ -25,6 +25,7 @@ #include "components/scheduler/renderer/render_widget_scheduling_state.h" #include "components/scheduler/renderer/renderer_scheduler.h" #include "content/child/npapi/webplugin.h" +#include "content/common/content_switches_internal.h" #include "content/common/gpu/client/context_provider_command_buffer.h" #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h" #include "content/common/gpu/gpu_process_launch_causes.h" @@ -792,11 +793,15 @@ if (!webwidget_) return; - if (compositor_) { - compositor_->setViewportSize(new_size, physical_backing_size); - } + if (compositor_) + compositor_->setViewportSize(physical_backing_size); + bool resized = size_ != new_size || + physical_backing_size_ != physical_backing_size; + + size_ = new_size; physical_backing_size_ = physical_backing_size; + top_controls_shrink_blink_size_ = top_controls_shrink_blink_size; top_controls_height_ = top_controls_height; visible_viewport_size_ = visible_viewport_size; @@ -810,18 +815,25 @@ webwidget_->setTopControlsHeight(top_controls_height, top_controls_shrink_blink_size_); - if (size_ != new_size) { - size_ = new_size; - + if (resized) { + gfx::Size new_widget_size = + IsUseZoomForDSFEnabled() ? physical_backing_size_ : size_; // When resizing, we want to wait to paint before ACK'ing the resize. This // ensures that we only resize as fast as we can paint. We only need to // send an ACK if we are resized to a non-empty rect. - webwidget_->resize(new_size); + webwidget_->resize(new_widget_size); + } + WebSize pinch_viewport_size; + + if (IsUseZoomForDSFEnabled()) { + gfx::SizeF scaled_visible_viewport_size = + gfx::ScaleSize(gfx::SizeF(visible_viewport_size), device_scale_factor_); + pinch_viewport_size = gfx::ToCeiledSize(scaled_visible_viewport_size); + } else { + pinch_viewport_size = visible_viewport_size_; } - webwidget()->resizePinchViewport(gfx::Size( - visible_viewport_size.width(), - visible_viewport_size.height())); + webwidget()->resizePinchViewport(pinch_viewport_size); if (new_size.IsEmpty() || physical_backing_size.IsEmpty()) { // In this case there is no paint/composite and therefore no @@ -1320,6 +1332,7 @@ // WebWidgetClient void RenderWidget::didAutoResize(const WebSize& new_size) { + // TODO(oshima): support UseZoomForDSFEnabled() if (size_.width() != new_size.width || size_.height() != new_size.height) { size_ = new_size; @@ -1342,14 +1355,14 @@ void RenderWidget::AutoResizeCompositor() { physical_backing_size_ = gfx::ScaleToCeiledSize(size_, device_scale_factor_); if (compositor_) - compositor_->setViewportSize(size_, physical_backing_size_); + compositor_->setViewportSize(physical_backing_size_); } void RenderWidget::initializeLayerTreeView() { DCHECK(!host_closing_); compositor_ = RenderWidgetCompositor::Create(this, compositor_deps_); - compositor_->setViewportSize(size_, physical_backing_size_); + compositor_->setViewportSize(physical_backing_size_); // For background pages and certain tests, we don't want to trigger // OutputSurface creation. @@ -1607,6 +1620,7 @@ } void RenderWidget::setWindowRect(const WebRect& rect) { + // TODO(oshima): Scale back to DIP coordinates. WebRect window_rect = rect; if (popup_origin_scale_for_emulation_) { float scale = popup_origin_scale_for_emulation_; @@ -1977,8 +1991,16 @@ WebRect focus_webrect; WebRect anchor_webrect; webwidget_->selectionBounds(focus_webrect, anchor_webrect); - *focus = focus_webrect; - *anchor = anchor_webrect; + if (IsUseZoomForDSFEnabled()) { + float inverse_scale = 1.f / device_scale_factor_; + gfx::RectF focus_rect(focus_webrect); + *focus = gfx::ToEnclosingRect(gfx::ScaleRect(focus_rect, inverse_scale)); + gfx::RectF anchor_rect(anchor_webrect); + *anchor = gfx::ToEnclosingRect(gfx::ScaleRect(anchor_rect, inverse_scale)); + } else { + *focus = focus_webrect; + *anchor = anchor_webrect; + } } void RenderWidget::UpdateSelectionBounds() { @@ -2126,10 +2148,6 @@ return screen_info_; } -float RenderWidget::deviceScaleFactor() { - return device_scale_factor_; -} - void RenderWidget::resetInputMethod() { ImeEventGuard guard(this); // If the last text input type is not None, then we should finish any
diff --git a/content/renderer/render_widget.h b/content/renderer/render_widget.h index ce9113d..d062a1f 100644 --- a/content/renderer/render_widget.h +++ b/content/renderer/render_widget.h
@@ -188,7 +188,6 @@ blink::WebRect windowResizerRect() override; blink::WebRect rootWindowRect() override; blink::WebScreenInfo screenInfo() override; - float deviceScaleFactor() override; void resetInputMethod() override; void didHandleGestureEvent(const blink::WebGestureEvent& event, bool event_cancelled) override;
diff --git a/content/shell/BUILD.gn b/content/shell/BUILD.gn index 3538f6b..275499d 100644 --- a/content/shell/BUILD.gn +++ b/content/shell/BUILD.gn
@@ -24,6 +24,7 @@ static_library("content_shell_lib") { testonly = true sources = [ + "android/shell_descriptors.h", "android/shell_jni_registrar.cc", "android/shell_jni_registrar.h", "android/shell_manager.cc",
diff --git a/content/shell/browser/shell_devtools_frontend.cc b/content/shell/browser/shell_devtools_frontend.cc index 86a34a8..a584fd3 100644 --- a/content/shell/browser/shell_devtools_frontend.cc +++ b/content/shell/browser/shell_devtools_frontend.cc
@@ -156,8 +156,10 @@ void ShellDevToolsFrontend::RenderViewCreated( RenderViewHost* render_view_host) { if (!frontend_host_) { - frontend_host_.reset( - DevToolsFrontendHost::Create(web_contents()->GetMainFrame(), this)); + frontend_host_.reset(DevToolsFrontendHost::Create( + web_contents()->GetMainFrame(), + base::Bind(&ShellDevToolsFrontend::HandleMessageFromDevToolsFrontend, + base::Unretained(this)))); } } @@ -189,10 +191,12 @@ dict->GetInteger("id", &request_id); dict->GetList("params", ¶ms); - std::string browser_message; - if (method == "sendMessageToBrowser" && params && - params->GetSize() == 1 && params->GetString(0, &browser_message)) { - agent_host_->DispatchProtocolMessage(browser_message); + if (method == "dispatchProtocolMessage" && params && params->GetSize() == 1) { + std::string protocol_message; + if (!params->GetString(0, &protocol_message)) + return; + if (agent_host_) + agent_host_->DispatchProtocolMessage(protocol_message); } else if (method == "loadCompleted") { web_contents()->GetMainFrame()->ExecuteJavaScriptForTests( base::ASCIIToUTF16("DevToolsAPI.setUseSoftMenu(true);")); @@ -252,12 +256,6 @@ SendMessageAck(request_id, nullptr); } -void ShellDevToolsFrontend::HandleMessageFromDevToolsFrontendToBackend( - const std::string& message) { - if (agent_host_) - agent_host_->DispatchProtocolMessage(message); -} - void ShellDevToolsFrontend::DispatchProtocolMessage( DevToolsAgentHost* agent_host, const std::string& message) {
diff --git a/content/shell/browser/shell_devtools_frontend.h b/content/shell/browser/shell_devtools_frontend.h index 15a236e..7ccba08a 100644 --- a/content/shell/browser/shell_devtools_frontend.h +++ b/content/shell/browser/shell_devtools_frontend.h
@@ -27,7 +27,6 @@ class WebContents; class ShellDevToolsFrontend : public WebContentsObserver, - public DevToolsFrontendHost::Delegate, public DevToolsAgentHostClient, public net::URLFetcherDelegate { public: @@ -63,10 +62,7 @@ void DocumentAvailableInMainFrame() override; void WebContentsDestroyed() override; - // content::DevToolsFrontendHost::Delegate implementation. - void HandleMessageFromDevToolsFrontend(const std::string& message) override; - void HandleMessageFromDevToolsFrontendToBackend( - const std::string& message) override; + void HandleMessageFromDevToolsFrontend(const std::string& message); // net::URLFetcherDelegate overrides. void OnURLFetchComplete(const net::URLFetcher* source) override;
diff --git a/google_apis/gaia/gaia_auth_fetcher.cc b/google_apis/gaia/gaia_auth_fetcher.cc index 59fa57a..38e7802 100644 --- a/google_apis/gaia/gaia_auth_fetcher.cc +++ b/google_apis/gaia/gaia_auth_fetcher.cc
@@ -211,9 +211,9 @@ fetcher_->SetRequestContext(getter_); fetcher_->SetUploadData("application/x-www-form-urlencoded", body); - DVLOG(2) << "Gaia fetcher URL: " << gaia_gurl.spec(); - DVLOG(2) << "Gaia fetcher headers: " << headers; - DVLOG(2) << "Gaia fetcher body: " << body; + VLOG(2) << "Gaia fetcher URL: " << gaia_gurl.spec(); + VLOG(2) << "Gaia fetcher headers: " << headers; + VLOG(2) << "Gaia fetcher body: " << body; // The Gaia token exchange requests do not require any cookie-based // identification as part of requests. We suppress sending any cookies to @@ -496,7 +496,7 @@ const char* const service) { DCHECK(!fetch_pending_) << "Tried to fetch two things at once!"; - DVLOG(1) << "Starting IssueAuthToken for: " << service; + VLOG(1) << "Starting IssueAuthToken for: " << service; requested_service_ = service; request_body_ = MakeIssueAuthTokenBody(sid, lsid, service); CreateAndStartGaiaFetcher(request_body_, std::string(), @@ -506,7 +506,7 @@ void GaiaAuthFetcher::StartRevokeOAuth2Token(const std::string& auth_token) { DCHECK(!fetch_pending_) << "Tried to fetch two things at once!"; - DVLOG(1) << "Starting OAuth2 token revocation"; + VLOG(1) << "Starting OAuth2 token revocation"; request_body_ = MakeRevokeTokenBody(auth_token); CreateAndStartGaiaFetcher(request_body_, std::string(), oauth2_revoke_gurl_, kLoadFlagsIgnoreCookies); @@ -523,7 +523,7 @@ const std::string& device_id) { DCHECK(!fetch_pending_) << "Tried to fetch two things at once!"; - DVLOG(1) << "Starting OAuth login token fetch with cookie jar"; + VLOG(1) << "Starting OAuth login token fetch with cookie jar"; std::string encoded_scope = net::EscapeUrlEncodedData( GaiaConstants::kOAuth1LoginScope, true); @@ -558,7 +558,7 @@ const std::string& device_id) { DCHECK(!fetch_pending_) << "Tried to fetch two things at once!"; - DVLOG(1) << "Starting OAuth token pair fetch"; + VLOG(1) << "Starting OAuth token pair fetch"; request_body_ = MakeGetTokenPairBody(auth_code, device_id); CreateAndStartGaiaFetcher(request_body_, std::string(), oauth2_token_gurl_, kLoadFlagsIgnoreCookies); @@ -567,7 +567,7 @@ void GaiaAuthFetcher::StartGetUserInfo(const std::string& lsid) { DCHECK(!fetch_pending_) << "Tried to fetch two things at once!"; - DVLOG(1) << "Starting GetUserInfo for lsid=" << lsid; + VLOG(1) << "Starting GetUserInfo for lsid=" << lsid; request_body_ = MakeGetUserInfoBody(lsid); CreateAndStartGaiaFetcher(request_body_, std::string(), get_user_info_gurl_, kLoadFlagsIgnoreCookies); @@ -577,7 +577,7 @@ const std::string& external_cc_result) { DCHECK(!fetch_pending_) << "Tried to fetch two things at once!"; - DVLOG(1) << "Starting MergeSession with uber_token=" << uber_token; + VLOG(1) << "Starting MergeSession with uber_token=" << uber_token; // The continue URL is a required parameter of the MergeSession API, but in // this case we don't actually need or want to navigate to it. Setting it to @@ -599,7 +599,7 @@ const std::string& access_token) { DCHECK(!fetch_pending_) << "Tried to fetch two things at once!"; - DVLOG(1) << "Starting StartTokenFetchForUberAuthExchange with access_token=" + VLOG(1) << "Starting StartTokenFetchForUberAuthExchange with access_token=" << access_token; std::string authentication_header = base::StringPrintf(kOAuthHeaderFormat, access_token.c_str()); @@ -838,7 +838,7 @@ const net::URLRequestStatus& status, int response_code) { if (status.is_success() && response_code == net::HTTP_OK) { - DVLOG(1) << "ClientLogin successful!"; + VLOG(1) << "ClientLogin successful!"; std::string sid; std::string lsid; std::string token; @@ -866,7 +866,7 @@ const net::URLRequestStatus& status, int response_code) { if (status.is_success() && response_code == net::HTTP_OK) { - DVLOG(1) << "ListIdpSessions successful!"; + VLOG(1) << "ListIdpSessions successful!"; std::string login_hint; if (ParseListIdpSessionsResponse(data, &login_hint)) { consumer_->OnListIdpSessionsSuccess(login_hint); @@ -889,7 +889,7 @@ int expires_in_secs = 0; bool success = false; if (status.is_success() && response_code == net::HTTP_OK) { - DVLOG(1) << "GetTokenResponse successful!"; + VLOG(1) << "GetTokenResponse successful!"; success = ExtractOAuth2TokenPairResponse(data, NULL, &access_token, &expires_in_secs); }
diff --git a/gpu/command_buffer/service/gles2_cmd_decoder.cc b/gpu/command_buffer/service/gles2_cmd_decoder.cc index 1df0361..f90615a 100644 --- a/gpu/command_buffer/service/gles2_cmd_decoder.cc +++ b/gpu/command_buffer/service/gles2_cmd_decoder.cc
@@ -13186,8 +13186,6 @@ return; } } else { - // TODO(dshwang): make GetLevelSize, ValidForTexture and ValidForTarget - // correct for GLImage also. crbug.com/549531 if (!source_texture->GetLevelSize(source_texture->target(), 0, &source_width, &source_height, nullptr)) { LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "glCopySubTextureCHROMIUM", @@ -13195,13 +13193,6 @@ return; } - if (!source_texture->ValidForTexture(source_texture->target(), 0, x, y, 0, - width, height, 1)) { - LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "glCopySubTextureCHROMIUM", - "source texture bad dimensions."); - return; - } - // Check that this type of texture is allowed. if (!texture_manager()->ValidForTarget(source_texture->target(), 0, source_width, source_height, 1)) { @@ -13215,6 +13206,12 @@ GLenum source_internal_format = 0; source_texture->GetLevelType(source_texture->target(), 0, &source_type, &source_internal_format); + if (!source_texture->ValidForTexture(source_texture->target(), 0, x, y, 0, + width, height, 1)) { + LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "glCopySubTextureCHROMIUM", + "source texture bad dimensions."); + return; + } GLenum dest_type = 0; GLenum dest_internal_format = 0; @@ -13518,13 +13515,6 @@ return; } - if (!source_texture->ValidForTexture(source_texture->target(), 0, x, y, 0, - width, height, 1)) { - LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "glCompressedCopySubTextureCHROMIUM", - "source texture bad dimensions."); - return; - } - // Check that this type of texture is allowed. if (!texture_manager()->ValidForTarget(source_texture->target(), 0, source_width, source_height, 1)) { @@ -13538,6 +13528,12 @@ GLenum source_internal_format = 0; source_texture->GetLevelType(source_texture->target(), 0, &source_type, &source_internal_format); + if (!source_texture->ValidForTexture(source_texture->target(), 0, x, y, 0, + width, height, 1)) { + LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "glCompressedCopySubTextureCHROMIUM", + "source texture bad dimensions."); + return; + } GLenum dest_type = 0; GLenum dest_internal_format = 0;
diff --git a/ios/chrome/browser/browser_state/browser_state_keyed_service_factories.mm b/ios/chrome/browser/browser_state/browser_state_keyed_service_factories.mm index f72218ac..cb02ed1 100644 --- a/ios/chrome/browser/browser_state/browser_state_keyed_service_factories.mm +++ b/ios/chrome/browser/browser_state/browser_state_keyed_service_factories.mm
@@ -17,6 +17,8 @@ #include "ios/chrome/browser/enhanced_bookmarks/enhanced_bookmark_model_factory.h" #include "ios/chrome/browser/favicon/favicon_service_factory.h" #include "ios/chrome/browser/favicon/ios_chrome_favicon_loader_factory.h" +#include "ios/chrome/browser/favicon/ios_chrome_large_icon_cache_factory.h" +#include "ios/chrome/browser/favicon/ios_chrome_large_icon_service_factory.h" #include "ios/chrome/browser/google/google_url_tracker_factory.h" #include "ios/chrome/browser/history/history_service_factory.h" #include "ios/chrome/browser/history/top_sites_factory.h" @@ -76,6 +78,8 @@ ios::TopSitesFactory::GetInstance(); ios::WebDataServiceFactory::GetInstance(); ios::WebHistoryServiceFactory::GetInstance(); + IOSChromeLargeIconCacheFactory::GetInstance(); + IOSChromeLargeIconServiceFactory::GetInstance(); IOSChromeFaviconLoaderFactory::GetInstance(); IOSChromePasswordStoreFactory::GetInstance(); OAuth2TokenServiceFactory::GetInstance();
diff --git a/ios/chrome/browser/favicon/ios_chrome_large_icon_cache_factory.cc b/ios/chrome/browser/favicon/ios_chrome_large_icon_cache_factory.cc new file mode 100644 index 0000000..b640f0d --- /dev/null +++ b/ios/chrome/browser/favicon/ios_chrome_large_icon_cache_factory.cc
@@ -0,0 +1,41 @@ +// 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 "ios/chrome/browser/favicon/ios_chrome_large_icon_cache_factory.h" + +#include "base/memory/singleton.h" +#include "components/keyed_service/ios/browser_state_dependency_manager.h" +#include "ios/chrome/browser/browser_state/browser_state_otr_helper.h" +#include "ios/chrome/browser/favicon/large_icon_cache.h" +#include "ios/public/provider/chrome/browser/browser_state/chrome_browser_state.h" + +// static +LargeIconCache* IOSChromeLargeIconCacheFactory::GetForBrowserState( + ios::ChromeBrowserState* browser_state) { + return static_cast<LargeIconCache*>( + GetInstance()->GetServiceForBrowserState(browser_state, true)); +} + +// static +IOSChromeLargeIconCacheFactory* IOSChromeLargeIconCacheFactory::GetInstance() { + return base::Singleton<IOSChromeLargeIconCacheFactory>::get(); +} + +IOSChromeLargeIconCacheFactory::IOSChromeLargeIconCacheFactory() + : BrowserStateKeyedServiceFactory( + "LargeIconCache", + BrowserStateDependencyManager::GetInstance()) {} + +IOSChromeLargeIconCacheFactory::~IOSChromeLargeIconCacheFactory() {} + +scoped_ptr<KeyedService> +IOSChromeLargeIconCacheFactory::BuildServiceInstanceFor( + web::BrowserState* context) const { + return make_scoped_ptr(new LargeIconCache); +} + +web::BrowserState* IOSChromeLargeIconCacheFactory::GetBrowserStateToUse( + web::BrowserState* context) const { + return GetBrowserStateOwnInstanceInIncognito(context); +}
diff --git a/ios/chrome/browser/favicon/ios_chrome_large_icon_cache_factory.h b/ios/chrome/browser/favicon/ios_chrome_large_icon_cache_factory.h new file mode 100644 index 0000000..6a20527 --- /dev/null +++ b/ios/chrome/browser/favicon/ios_chrome_large_icon_cache_factory.h
@@ -0,0 +1,48 @@ +// 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 IOS_CHROME_BROWSER_FAVICON_IOS_CHROME_LARGE_ICON_CACHE_FACTORY_H_ +#define IOS_CHROME_BROWSER_FAVICON_IOS_CHROME_LARGE_ICON_CACHE_FACTORY_H_ + +#include "base/macros.h" +#include "base/memory/scoped_ptr.h" +#include "components/keyed_service/ios/browser_state_keyed_service_factory.h" + +class KeyedService; +class LargeIconCache; + +namespace base { +template <typename T> +struct DefaultSingletonTraits; +} + +namespace ios { +class ChromeBrowserState; +} + +// Singleton that owns all LargeIconCaches and associates them with +// ChromeBrowserState. +class IOSChromeLargeIconCacheFactory : public BrowserStateKeyedServiceFactory { + public: + static LargeIconCache* GetForBrowserState( + ios::ChromeBrowserState* browser_state); + + static IOSChromeLargeIconCacheFactory* GetInstance(); + + private: + friend struct base::DefaultSingletonTraits<IOSChromeLargeIconCacheFactory>; + + IOSChromeLargeIconCacheFactory(); + ~IOSChromeLargeIconCacheFactory() override; + + // BrowserStateKeyedServiceFactory implementation. + scoped_ptr<KeyedService> BuildServiceInstanceFor( + web::BrowserState* context) const override; + web::BrowserState* GetBrowserStateToUse( + web::BrowserState* context) const override; + + DISALLOW_COPY_AND_ASSIGN(IOSChromeLargeIconCacheFactory); +}; + +#endif // IOS_CHROME_BROWSER_FAVICON_IOS_CHROME_LARGE_ICON_CACHE_FACTORY_H_
diff --git a/ios/chrome/browser/favicon/ios_chrome_large_icon_service_factory.cc b/ios/chrome/browser/favicon/ios_chrome_large_icon_service_factory.cc new file mode 100644 index 0000000..354e62bf9 --- /dev/null +++ b/ios/chrome/browser/favicon/ios_chrome_large_icon_service_factory.cc
@@ -0,0 +1,52 @@ +// 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 "ios/chrome/browser/favicon/ios_chrome_large_icon_service_factory.h" + +#include "base/memory/singleton.h" +#include "base/thread_task_runner_handle.h" +#include "components/favicon/core/large_icon_service.h" +#include "components/keyed_service/core/service_access_type.h" +#include "components/keyed_service/ios/browser_state_dependency_manager.h" +#include "ios/chrome/browser/browser_state/browser_state_otr_helper.h" +#include "ios/chrome/browser/favicon/favicon_service_factory.h" +#include "ios/public/provider/chrome/browser/browser_state/chrome_browser_state.h" +#include "ios/web/public/web_thread.h" + +// static +favicon::LargeIconService* IOSChromeLargeIconServiceFactory::GetForBrowserState( + ios::ChromeBrowserState* browser_state) { + return static_cast<favicon::LargeIconService*>( + GetInstance()->GetServiceForBrowserState(browser_state, true)); +} + +// static +IOSChromeLargeIconServiceFactory* +IOSChromeLargeIconServiceFactory::GetInstance() { + return base::Singleton<IOSChromeLargeIconServiceFactory>::get(); +} + +IOSChromeLargeIconServiceFactory::IOSChromeLargeIconServiceFactory() + : BrowserStateKeyedServiceFactory( + "LargeIconService", + BrowserStateDependencyManager::GetInstance()) {} + +IOSChromeLargeIconServiceFactory::~IOSChromeLargeIconServiceFactory() {} + +scoped_ptr<KeyedService> +IOSChromeLargeIconServiceFactory::BuildServiceInstanceFor( + web::BrowserState* context) const { + ios::ChromeBrowserState* browser_state = + ios::ChromeBrowserState::FromBrowserState(context); + + return make_scoped_ptr(new favicon::LargeIconService( + ios::FaviconServiceFactory::GetForBrowserState( + browser_state, ServiceAccessType::EXPLICIT_ACCESS), + web::WebThread::GetBlockingPool())); +} + +web::BrowserState* IOSChromeLargeIconServiceFactory::GetBrowserStateToUse( + web::BrowserState* context) const { + return GetBrowserStateOwnInstanceInIncognito(context); +}
diff --git a/ios/chrome/browser/favicon/ios_chrome_large_icon_service_factory.h b/ios/chrome/browser/favicon/ios_chrome_large_icon_service_factory.h new file mode 100644 index 0000000..d6611c3 --- /dev/null +++ b/ios/chrome/browser/favicon/ios_chrome_large_icon_service_factory.h
@@ -0,0 +1,52 @@ +// 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 IOS_CHROME_BROWSER_FAVICON_IOS_CHROME_LARGE_ICON_SERVICE_FACTORY_H_ +#define IOS_CHROME_BROWSER_FAVICON_IOS_CHROME_LARGE_ICON_SERVICE_FACTORY_H_ + +#include "base/macros.h" +#include "base/memory/scoped_ptr.h" +#include "components/keyed_service/ios/browser_state_keyed_service_factory.h" + +class KeyedService; + +namespace base { +template <typename T> +struct DefaultSingletonTraits; +} + +namespace favicon { +class LargeIconService; +}; + +namespace ios { +class ChromeBrowserState; +} + +// Singleton that owns all LargeIconService and associates them with +// ChromeBrowserState. +class IOSChromeLargeIconServiceFactory + : public BrowserStateKeyedServiceFactory { + public: + static favicon::LargeIconService* GetForBrowserState( + ios::ChromeBrowserState* browser_state); + + static IOSChromeLargeIconServiceFactory* GetInstance(); + + private: + friend struct base::DefaultSingletonTraits<IOSChromeLargeIconServiceFactory>; + + IOSChromeLargeIconServiceFactory(); + ~IOSChromeLargeIconServiceFactory() override; + + // BrowserStateKeyedServiceFactory implementation. + scoped_ptr<KeyedService> BuildServiceInstanceFor( + web::BrowserState* context) const override; + web::BrowserState* GetBrowserStateToUse( + web::BrowserState* context) const override; + + DISALLOW_COPY_AND_ASSIGN(IOSChromeLargeIconServiceFactory); +}; + +#endif // IOS_CHROME_BROWSER_FAVICON_IOS_CHROME_LARGE_ICON_SERVICE_FACTORY_H_
diff --git a/ios/chrome/browser/favicon/large_icon_cache.cc b/ios/chrome/browser/favicon/large_icon_cache.cc new file mode 100644 index 0000000..6575d1e --- /dev/null +++ b/ios/chrome/browser/favicon/large_icon_cache.cc
@@ -0,0 +1,58 @@ +// 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 "ios/chrome/browser/favicon/large_icon_cache.h" + +#include "components/favicon_base/fallback_icon_style.h" +#include "components/favicon_base/favicon_types.h" +#include "url/gurl.h" + +namespace { + +const int kMaxCacheSize = 12; + +} // namespace + +struct LargeIconCacheEntry { + LargeIconCacheEntry() {} + ~LargeIconCacheEntry() {} + + scoped_ptr<favicon_base::LargeIconResult> result; +}; + +LargeIconCache::LargeIconCache() : cache_(kMaxCacheSize) {} + +LargeIconCache::~LargeIconCache() {} + +void LargeIconCache::SetCachedResult( + const GURL& url, + const favicon_base::LargeIconResult& result) { + LargeIconCacheEntry* entry = new LargeIconCacheEntry; + entry->result = CloneLargeIconResult(result); + cache_.Put(url, entry); +} + +scoped_ptr<favicon_base::LargeIconResult> LargeIconCache::GetCachedResult( + const GURL& url) { + auto iter = cache_.Get(url); + if (iter != cache_.end()) { + DCHECK(iter->second->result); + return CloneLargeIconResult(*iter->second->result.get()); + } + + return scoped_ptr<favicon_base::LargeIconResult>(); +} + +scoped_ptr<favicon_base::LargeIconResult> LargeIconCache::CloneLargeIconResult( + const favicon_base::LargeIconResult& large_icon_result) { + scoped_ptr<favicon_base::LargeIconResult> clone; + if (large_icon_result.bitmap.is_valid()) { + clone.reset(new favicon_base::LargeIconResult(large_icon_result.bitmap)); + } else { + clone.reset( + new favicon_base::LargeIconResult(new favicon_base::FallbackIconStyle( + *large_icon_result.fallback_icon_style.get()))); + } + return clone.Pass(); +}
diff --git a/ios/chrome/browser/favicon/large_icon_cache.h b/ios/chrome/browser/favicon/large_icon_cache.h new file mode 100644 index 0000000..67abec9 --- /dev/null +++ b/ios/chrome/browser/favicon/large_icon_cache.h
@@ -0,0 +1,55 @@ +// 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 IOS_CHROME_BROWSER_FAVICON_LARGE_ICON_CACHE_H_ +#define IOS_CHROME_BROWSER_FAVICON_LARGE_ICON_CACHE_H_ + +#include "base/containers/mru_cache.h" +#include "base/macros.h" +#include "base/memory/scoped_ptr.h" +#include "components/keyed_service/core/keyed_service.h" + +class GURL; +struct LargeIconCacheEntry; + +namespace favicon_base { +struct LargeIconResult; +} + +namespace ios { +class ChromeBrowserState; +} + +// Provides a cache of most recently used LargeIconResult. +// +// Example usage: +// LargeIconCache* large_icon_cache = +// IOSChromeLargeIconServiceFactory::GetForBrowserState(browser_state); +// scoped_ptr<favicon_base::LargeIconResult> icon = +// large_icon_cache->GetCachedResult(...); +// +class LargeIconCache : public KeyedService { + public: + LargeIconCache(); + ~LargeIconCache() override; + + // |LargeIconService| does everything on callbacks, and iOS needs to load the + // icons immediately on page load. This caches the LargeIconResult so we can + // immediately load. + void SetCachedResult(const GURL& url, const favicon_base::LargeIconResult&); + + // Returns a cached LargeIconResult. + scoped_ptr<favicon_base::LargeIconResult> GetCachedResult(const GURL& url); + + private: + // Clones a LargeIconResult. + scoped_ptr<favicon_base::LargeIconResult> CloneLargeIconResult( + const favicon_base::LargeIconResult& large_icon_result); + + base::OwningMRUCache<GURL, LargeIconCacheEntry*> cache_; + + DISALLOW_COPY_AND_ASSIGN(LargeIconCache); +}; + +#endif // IOS_CHROME_BROWSER_FAVICON_LARGE_ICON_CACHE_H_
diff --git a/ios/chrome/ios_chrome.gyp b/ios/chrome/ios_chrome.gyp index 025cede0..e49a211c6 100644 --- a/ios/chrome/ios_chrome.gyp +++ b/ios/chrome/ios_chrome.gyp
@@ -226,6 +226,12 @@ 'browser/favicon/favicon_service_factory.h', 'browser/favicon/ios_chrome_favicon_loader_factory.h', 'browser/favicon/ios_chrome_favicon_loader_factory.mm', + 'browser/favicon/ios_chrome_large_icon_cache_factory.cc', + 'browser/favicon/ios_chrome_large_icon_cache_factory.h', + 'browser/favicon/ios_chrome_large_icon_service_factory.cc', + 'browser/favicon/ios_chrome_large_icon_service_factory.h', + 'browser/favicon/large_icon_cache.cc', + 'browser/favicon/large_icon_cache.h', 'browser/file_metadata_util.h', 'browser/file_metadata_util.mm', 'browser/find_in_page/find_in_page_controller.h',
diff --git a/ios/web/web_state/ui/crw_wk_web_view_web_controller.mm b/ios/web/web_state/ui/crw_wk_web_view_web_controller.mm index ba4a08b..31654019 100644 --- a/ios/web/web_state/ui/crw_wk_web_view_web_controller.mm +++ b/ios/web/web_state/ui/crw_wk_web_view_web_controller.mm
@@ -114,9 +114,9 @@ base::scoped_nsobject<CRWWKWebViewCrashDetector> _crashDetector; // The actual URL of the document object (i.e., the last committed URL). - // TODO(stuartmorgan): Remove this in favor of just updating the session - // controller and treating that as authoritative. For now, this allows sharing - // the flow that's currently in the superclass. + // TODO(crbug.com/549616): Remove this in favor of just updating the + // navigation manager and treating that as authoritative. For now, this allows + // sharing the flow that's currently in the superclass. GURL _documentURL; // A set of script managers whose scripts have been injected into the current @@ -174,6 +174,9 @@ // cert status from |didReceiveAuthenticationChallenge:| to // |didFailProvisionalNavigation:| delegate method. scoped_ptr<CertVerificationErrorsCacheType> _certVerificationErrors; + + // YES if the user has touched the content area since the last URL change. + BOOL _touchedSinceLastURLChange; } // Response's MIME type of the last known navigation. @@ -214,6 +217,9 @@ // Returns whether the given navigation is triggered by a user link click. - (BOOL)isLinkNavigation:(WKNavigationType)navigationType; +// Sets _documentURL to newURL, and updates any relevant state information. +- (void)setDocumentURL:(const GURL&)newURL; + // Sets value of the pendingReferrerString property. - (void)setPendingReferrerString:(NSString*)referrer; @@ -408,6 +414,12 @@ [super close]; } +- (void)touched:(BOOL)touched { + [super touched:touched]; + if (touched) + _touchedSinceLastURLChange = YES; +} + #pragma mark - #pragma mark Testing-Only Methods @@ -753,7 +765,7 @@ } _injectedScriptManagers.reset([[NSMutableSet alloc] init]); _crashDetector.reset([self newCrashDetectorWithWebView:_wkWebView]); - _documentURL = [self defaultURL]; + [self setDocumentURL:[self defaultURL]]; } - (BOOL)isLinkNavigation:(WKNavigationType)navigationType { @@ -767,6 +779,13 @@ } } +- (void)setDocumentURL:(const GURL&)newURL { + if (newURL != _documentURL) { + _documentURL = newURL; + _touchedSinceLastURLChange = NO; + } +} + - (void)setPendingReferrerString:(NSString*)referrer { _pendingReferrerString.reset([referrer copy]); } @@ -1134,14 +1153,36 @@ } - (void)registerLoadRequest:(const GURL&)url { - // If load request is registered via WKWebViewWebController, assume transition - // is link or client redirect as other transitions will already be registered - // by web controller or delegates. - // TODO(stuartmorgan): Remove guesswork and replace with information from - // decidePolicyForNavigationAction:. - ui::PageTransition transition = self.userInteractionRegistered - ? ui::PAGE_TRANSITION_LINK - : ui::PAGE_TRANSITION_CLIENT_REDIRECT; + // Get the navigation type from the last main frame load request, and try to + // map that to a PageTransition. + WKNavigationType navigationType = _pendingNavigationTypeForMainFrame + ? *_pendingNavigationTypeForMainFrame + : WKNavigationTypeOther; + ui::PageTransition transition = ui::PAGE_TRANSITION_CLIENT_REDIRECT; + switch (navigationType) { + case WKNavigationTypeLinkActivated: + transition = ui::PAGE_TRANSITION_LINK; + break; + case WKNavigationTypeFormSubmitted: + case WKNavigationTypeFormResubmitted: + transition = ui::PAGE_TRANSITION_FORM_SUBMIT; + break; + case WKNavigationTypeBackForward: + transition = ui::PAGE_TRANSITION_FORWARD_BACK; + break; + case WKNavigationTypeReload: + transition = ui::PAGE_TRANSITION_RELOAD; + break; + case WKNavigationTypeOther: + // The "Other" type covers a variety of very different cases, which may + // or may not be the result of user actions. For now, guess based on + // whether there's been a touch since the last URL change. + // TODO(crbug.com/549301): See if this heuristic can be improved. + transition = _touchedSinceLastURLChange + ? ui::PAGE_TRANSITION_LINK + : ui::PAGE_TRANSITION_CLIENT_REDIRECT; + break; + } // The referrer is not known yet, and will be updated later. const web::Referrer emptyReferrer; [self registerLoadRequest:url referrer:emptyReferrer transition:transition]; @@ -1150,7 +1191,7 @@ - (void)URLDidChangeWithoutDocumentChange:(const GURL&)newURL { DCHECK(newURL == net::GURLWithNSURL([_wkWebView URL])); DCHECK_EQ(_documentURL.host(), newURL.host()); - _documentURL = newURL; + [self setDocumentURL:newURL]; // If called during window.history.pushState or window.history.replaceState // JavaScript evaluation, only update the document URL. This callback does not // have any information about the state object and cannot create (or edit) the @@ -1561,7 +1602,7 @@ [self commitPendingReferrerString]; // This is the point where the document's URL has actually changed. - _documentURL = net::GURLWithNSURL([_wkWebView URL]); + [self setDocumentURL:net::GURLWithNSURL([_wkWebView URL])]; DCHECK(_documentURL == self.lastRegisteredRequestURL); [self webPageChanged];
diff --git a/ipc/ipc_message_attachment.h b/ipc/ipc_message_attachment.h index e7553d2..5ed27ca 100644 --- a/ipc/ipc_message_attachment.h +++ b/ipc/ipc_message_attachment.h
@@ -15,7 +15,7 @@ // Auxiliary data sent with |Message|. This can be a platform file descriptor // or a mojo |MessagePipe|. |GetType()| returns the type of the subclass. class IPC_EXPORT MessageAttachment - : public base::RefCounted<MessageAttachment> { + : public base::RefCountedThreadSafe<MessageAttachment> { public: enum Type { TYPE_PLATFORM_FILE, // The instance is |PlatformFileAttachment|. @@ -30,7 +30,7 @@ #endif // OS_POSIX protected: - friend class base::RefCounted<MessageAttachment>; + friend class base::RefCountedThreadSafe<MessageAttachment>; MessageAttachment(); virtual ~MessageAttachment();
diff --git a/ipc/mach_port_attachment_mac.h b/ipc/mach_port_attachment_mac.h index 48dc9aa..7d8c4d5 100644 --- a/ipc/mach_port_attachment_mac.h +++ b/ipc/mach_port_attachment_mac.h
@@ -67,7 +67,7 @@ private: ~MachPortAttachmentMac() override; - mach_port_t mach_port_; + const mach_port_t mach_port_; // In the sender process, the attachment owns the Mach port of a newly created // message. The attachment broker will eventually take ownership, and set
diff --git a/media/blink/webmediaplayer_impl.cc b/media/blink/webmediaplayer_impl.cc index ff25e22..5be9452d 100644 --- a/media/blink/webmediaplayer_impl.cc +++ b/media/blink/webmediaplayer_impl.cc
@@ -652,12 +652,12 @@ bool WebMediaPlayerImpl::copyVideoTextureToPlatformTexture( blink::WebGraphicsContext3D* web_graphics_context, - const CopyVideoTextureParams& params) { + unsigned int texture, + unsigned int internal_format, + unsigned int type, + bool premultiply_alpha, + bool flip_y) { TRACE_EVENT0("media", "WebMediaPlayerImpl:copyVideoTextureToPlatformTexture"); - DCHECK((params.copyType == CopyVideoTextureParams::FullCopy && - !params.xoffset && !params.yoffset) || - (params.copyType == CopyVideoTextureParams::SubCopy && - !params.internalFormat && !params.type)); scoped_refptr<VideoFrame> video_frame = GetCurrentFrameFromCompositor(); @@ -671,15 +671,9 @@ gpu::gles2::GLES2Interface* gl = static_cast<gpu_blink::WebGraphicsContext3DImpl*>(web_graphics_context) ->GetGLInterface(); - typedef SkCanvasVideoRenderer::CopyFrameSingleTextureParams CopyParams; SkCanvasVideoRenderer::CopyVideoFrameSingleTextureToGLTexture( - gl, video_frame.get(), - CopyParams(params.copyType == CopyVideoTextureParams::FullCopy - ? CopyParams::FullCopy - : CopyParams::SubCopy, - params.target, params.texture, params.internalFormat, - params.type, params.level, params.xoffset, params.yoffset, - params.premultiplyAlpha, params.flipY)); + gl, video_frame.get(), texture, internal_format, type, premultiply_alpha, + flip_y); return true; }
diff --git a/media/blink/webmediaplayer_impl.h b/media/blink/webmediaplayer_impl.h index 497cb5da..e839268d 100644 --- a/media/blink/webmediaplayer_impl.h +++ b/media/blink/webmediaplayer_impl.h
@@ -138,7 +138,11 @@ bool copyVideoTextureToPlatformTexture( blink::WebGraphicsContext3D* web_graphics_context, - const CopyVideoTextureParams& params) override; + unsigned int texture, + unsigned int internal_format, + unsigned int type, + bool premultiply_alpha, + bool flip_y) override; blink::WebAudioSourceProvider* audioSourceProvider() override;
diff --git a/media/capture/content/screen_capture_device_core.cc b/media/capture/content/screen_capture_device_core.cc index d99ca5a..d089eae5 100644 --- a/media/capture/content/screen_capture_device_core.cc +++ b/media/capture/content/screen_capture_device_core.cc
@@ -46,11 +46,11 @@ params.requested_format.pixel_storage == PIXEL_STORAGE_CPU) && !(params.requested_format.pixel_format == PIXEL_FORMAT_ARGB && params.requested_format.pixel_storage == PIXEL_STORAGE_TEXTURE)) { - const std::string error_msg = base::StringPrintf( - "unsupported format: %s", - VideoCaptureFormat::ToString(params.requested_format).c_str()); - DVLOG(1) << error_msg; - client->OnError(error_msg); + client->OnError( + FROM_HERE, + base::StringPrintf( + "unsupported format: %s", + VideoCaptureFormat::ToString(params.requested_format).c_str())); return; } @@ -80,11 +80,8 @@ void ScreenCaptureDeviceCore::CaptureStarted(bool success) { DCHECK(thread_checker_.CalledOnValidThread()); - if (!success) { - std::string reason("Failed to start capture machine."); - DVLOG(1) << reason; - Error(reason); - } + if (!success) + Error(FROM_HERE, "Failed to start capture machine."); } ScreenCaptureDeviceCore::ScreenCaptureDeviceCore( @@ -107,8 +104,9 @@ DCHECK(thread_checker_.CalledOnValidThread()); #ifndef NDEBUG - static const char* kStateNames[] = { - "Idle", "Allocated", "Capturing", "Error"}; + static const char* kStateNames[] = {"Idle", "Capturing", "Error"}; + static_assert(arraysize(kStateNames) == kLastCaptureState, + "Different number of states and textual descriptions"); DVLOG(1) << "State change: " << kStateNames[state_] << " --> " << kStateNames[next_state]; #endif @@ -116,14 +114,15 @@ state_ = next_state; } -void ScreenCaptureDeviceCore::Error(const std::string& reason) { +void ScreenCaptureDeviceCore::Error(const tracked_objects::Location& from_here, + const std::string& reason) { DCHECK(thread_checker_.CalledOnValidThread()); if (state_ == kIdle) return; if (oracle_proxy_.get()) - oracle_proxy_->ReportError(reason); + oracle_proxy_->ReportError(from_here, reason); StopAndDeAllocate(); TransitionStateTo(kError);
diff --git a/media/capture/content/screen_capture_device_core.h b/media/capture/content/screen_capture_device_core.h index 0720094..d7250e74 100644 --- a/media/capture/content/screen_capture_device_core.h +++ b/media/capture/content/screen_capture_device_core.h
@@ -14,6 +14,10 @@ #include "media/capture/content/thread_safe_capture_oracle.h" #include "media/capture/video/video_capture_device.h" +namespace tracked_objects { +class Location; +} // namespace tracked_objects + namespace media { struct VideoCaptureParams; @@ -68,7 +72,7 @@ private: // Flag indicating current state. - enum State { kIdle, kCapturing, kError }; + enum State { kIdle, kCapturing, kError, kLastCaptureState }; void TransitionStateTo(State next_state); @@ -77,7 +81,8 @@ void CaptureStarted(bool success); // Stops capturing and notifies client_ of an error state. - void Error(const std::string& reason); + void Error(const tracked_objects::Location& from_here, + const std::string& reason); // Tracks that all activity occurs on the media stream manager's thread. base::ThreadChecker thread_checker_;
diff --git a/media/capture/content/thread_safe_capture_oracle.cc b/media/capture/content/thread_safe_capture_oracle.cc index 22b1dcfc..bda73de6 100644 --- a/media/capture/content/thread_safe_capture_oracle.cc +++ b/media/capture/content/thread_safe_capture_oracle.cc
@@ -145,10 +145,12 @@ client_.reset(); } -void ThreadSafeCaptureOracle::ReportError(const std::string& reason) { +void ThreadSafeCaptureOracle::ReportError( + const tracked_objects::Location& from_here, + const std::string& reason) { base::AutoLock guard(lock_); if (client_) - client_->OnError(reason); + client_->OnError(from_here, reason); } void ThreadSafeCaptureOracle::DidCaptureFrame(
diff --git a/media/capture/content/thread_safe_capture_oracle.h b/media/capture/content/thread_safe_capture_oracle.h index 1aa905e..a410000 100644 --- a/media/capture/content/thread_safe_capture_oracle.h +++ b/media/capture/content/thread_safe_capture_oracle.h
@@ -14,6 +14,10 @@ #include "media/capture/content/video_capture_oracle.h" #include "media/capture/video/video_capture_device.h" +namespace tracked_objects { +class Location; +} // namespace tracked_objects + namespace media { struct VideoCaptureParams; @@ -63,7 +67,8 @@ void Stop(); // Signal an error to the client. - void ReportError(const std::string& reason); + void ReportError(const tracked_objects::Location& from_here, + const std::string& reason); private: friend class base::RefCountedThreadSafe<ThreadSafeCaptureOracle>;
diff --git a/media/capture/video/android/video_capture_device_android.cc b/media/capture/video/android/video_capture_device_android.cc index 69d8b05..ae38e99 100644 --- a/media/capture/video/android/video_capture_device_android.cc +++ b/media/capture/video/android/video_capture_device_android.cc
@@ -68,7 +68,7 @@ params.requested_format.frame_size.height(), params.requested_format.frame_rate); if (!ret) { - SetErrorState("failed to allocate"); + SetErrorState(FROM_HERE, "failed to allocate"); return; } @@ -96,7 +96,7 @@ ret = Java_VideoCapture_startCapture(env, j_capture_.obj()); if (!ret) { - SetErrorState("failed to start capture"); + SetErrorState(FROM_HERE, "failed to start capture"); return; } @@ -118,7 +118,7 @@ jboolean ret = Java_VideoCapture_stopCapture(env, j_capture_.obj()); if (!ret) { - SetErrorState("failed to stop capture"); + SetErrorState(FROM_HERE, "failed to stop capture"); return; } @@ -171,7 +171,8 @@ void VideoCaptureDeviceAndroid::OnError(JNIEnv* env, jobject obj, jstring message) { - SetErrorState(base::android::ConvertJavaStringToUTF8(env, message)); + SetErrorState(FROM_HERE, + base::android::ConvertJavaStringToUTF8(env, message)); } VideoPixelFormat VideoCaptureDeviceAndroid::GetColorspace() { @@ -191,12 +192,14 @@ } } -void VideoCaptureDeviceAndroid::SetErrorState(const std::string& reason) { +void VideoCaptureDeviceAndroid::SetErrorState( + const tracked_objects::Location& from_here, + const std::string& reason) { { base::AutoLock lock(lock_); state_ = kError; } - client_->OnError(reason); + client_->OnError(from_here, reason); } } // namespace media
diff --git a/media/capture/video/android/video_capture_device_android.h b/media/capture/video/android/video_capture_device_android.h index ccab5e2..3416ef2 100644 --- a/media/capture/video/android/video_capture_device_android.h +++ b/media/capture/video/android/video_capture_device_android.h
@@ -15,6 +15,10 @@ #include "media/base/media_export.h" #include "media/capture/video/video_capture_device.h" +namespace tracked_objects { +class Location; +} // namespace tracked_ + namespace media { // VideoCaptureDevice on Android. The VideoCaptureDevice API's are called @@ -70,7 +74,8 @@ }; VideoPixelFormat GetColorspace(); - void SetErrorState(const std::string& reason); + void SetErrorState(const tracked_objects::Location& from_here, + const std::string& reason); // Prevent racing on accessing |state_| and |client_| since both could be // accessed from different threads.
diff --git a/media/capture/video/fake_video_capture_device_unittest.cc b/media/capture/video/fake_video_capture_device_unittest.cc index 53edf182..fa1a95d 100644 --- a/media/capture/video/fake_video_capture_device_unittest.cc +++ b/media/capture/video/fake_video_capture_device_unittest.cc
@@ -54,7 +54,9 @@ class MockClient : public VideoCaptureDevice::Client { public: - MOCK_METHOD1(OnError, void(const std::string& reason)); + MOCK_METHOD2(OnError, + void(const tracked_objects::Location& from_here, + const std::string& reason)); explicit MockClient(base::Callback<void(const VideoCaptureFormat&)> frame_cb) : frame_cb_(frame_cb) {} @@ -141,7 +143,7 @@ device_enumeration_listener_ = new DeviceEnumerationListener(); } - void SetUp() override { EXPECT_CALL(*client_, OnError(_)).Times(0); } + void SetUp() override { EXPECT_CALL(*client_, OnError(_, _)).Times(0); } void OnFrameCaptured(const VideoCaptureFormat& format) { last_format_ = format;
diff --git a/media/capture/video/file_video_capture_device.cc b/media/capture/video/file_video_capture_device.cc index 073c0a1..d241cc39 100644 --- a/media/capture/video/file_video_capture_device.cc +++ b/media/capture/video/file_video_capture_device.cc
@@ -333,7 +333,7 @@ DCHECK(!file_parser_); file_parser_ = GetVideoFileParser(file_path_, &capture_format_); if (!file_parser_) { - client_->OnError("Could not open Video file"); + client_->OnError(FROM_HERE, "Could not open Video file"); return; }
diff --git a/media/capture/video/linux/v4l2_capture_delegate.cc b/media/capture/video/linux/v4l2_capture_delegate.cc index 88f5075..4bb2b8a 100644 --- a/media/capture/video/linux/v4l2_capture_delegate.cc +++ b/media/capture/video/linux/v4l2_capture_delegate.cc
@@ -180,7 +180,7 @@ // Need to open camera with O_RDWR after Linux kernel 3.3. device_fd_.reset(HANDLE_EINTR(open(device_name_.id().c_str(), O_RDWR))); if (!device_fd_.is_valid()) { - SetErrorState("Failed to open V4L2 device driver file."); + SetErrorState(FROM_HERE, "Failed to open V4L2 device driver file."); return; } @@ -191,7 +191,7 @@ !(cap.capabilities & V4L2_CAP_VIDEO_OUTPUT) && !(cap.capabilities & V4L2_CAP_VIDEO_OUTPUT_MPLANE)))) { device_fd_.reset(); - SetErrorState("This is not a V4L2 video capture device"); + SetErrorState(FROM_HERE, "This is not a V4L2 video capture device"); return; } @@ -208,7 +208,7 @@ best = std::find(desired_v4l2_formats.begin(), best, fmtdesc.pixelformat); } if (best == desired_v4l2_formats.end()) { - SetErrorState("Failed to find a supported camera format."); + SetErrorState(FROM_HERE, "Failed to find a supported camera format."); return; } @@ -216,18 +216,18 @@ video_fmt_.type = capture_type_; if (!FillV4L2Format(&video_fmt_, width, height, *best)) { - SetErrorState("Failed filling in V4L2 Format"); + SetErrorState(FROM_HERE, "Failed filling in V4L2 Format"); return; } if (HANDLE_EINTR(ioctl(device_fd_.get(), VIDIOC_S_FMT, &video_fmt_)) < 0) { - SetErrorState("Failed to set video capture format"); + SetErrorState(FROM_HERE, "Failed to set video capture format"); return; } const VideoPixelFormat pixel_format = V4l2FourCcToChromiumPixelFormat(video_fmt_.fmt.pix.pixelformat); if (pixel_format == PIXEL_FORMAT_UNKNOWN) { - SetErrorState("Unsupported pixel format"); + SetErrorState(FROM_HERE, "Unsupported pixel format"); return; } @@ -247,7 +247,7 @@ if (HANDLE_EINTR(ioctl(device_fd_.get(), VIDIOC_S_PARM, &streamparm)) < 0) { - SetErrorState("Failed to set camera framerate"); + SetErrorState(FROM_HERE, "Failed to set camera framerate"); return; } DVLOG(2) << "Actual camera driverframerate: " @@ -282,19 +282,19 @@ r_buffer.memory = V4L2_MEMORY_MMAP; r_buffer.count = kNumVideoBuffers; if (HANDLE_EINTR(ioctl(device_fd_.get(), VIDIOC_REQBUFS, &r_buffer)) < 0) { - SetErrorState("Error requesting MMAP buffers from V4L2"); + SetErrorState(FROM_HERE, "Error requesting MMAP buffers from V4L2"); return; } for (unsigned int i = 0; i < r_buffer.count; ++i) { if (!MapAndQueueBuffer(i)) { - SetErrorState("Allocate buffer failed"); + SetErrorState(FROM_HERE, "Allocate buffer failed"); return; } } if (HANDLE_EINTR(ioctl(device_fd_.get(), VIDIOC_STREAMON, &capture_type_)) < 0) { - SetErrorState("VIDIOC_STREAMON failed"); + SetErrorState(FROM_HERE, "VIDIOC_STREAMON failed"); return; } @@ -310,7 +310,7 @@ // thus munmap()ing the v4l2_buffers, and then return them to the OS. if (HANDLE_EINTR(ioctl(device_fd_.get(), VIDIOC_STREAMOFF, &capture_type_)) < 0) { - SetErrorState("VIDIOC_STREAMOFF failed"); + SetErrorState(FROM_HERE, "VIDIOC_STREAMOFF failed"); return; } @@ -321,7 +321,7 @@ r_buffer.memory = V4L2_MEMORY_MMAP; r_buffer.count = 0; if (HANDLE_EINTR(ioctl(device_fd_.get(), VIDIOC_REQBUFS, &r_buffer)) < 0) - SetErrorState("Failed to VIDIOC_REQBUFS with count = 0"); + SetErrorState(FROM_HERE, "Failed to VIDIOC_REQBUFS with count = 0"); // At this point we can close the device. // This is also needed for correctly changing settings later via VIDIOC_S_FMT. @@ -377,7 +377,7 @@ device_pfd.events = POLLIN; const int result = HANDLE_EINTR(poll(&device_pfd, 1, kCaptureTimeoutMs)); if (result < 0) { - SetErrorState("Poll failed"); + SetErrorState(FROM_HERE, "Poll failed"); return; } // Check if poll() timed out; track the amount of times it did in a row and @@ -385,7 +385,8 @@ if (result == 0) { timeout_count_++; if (timeout_count_ >= kContinuousTimeoutLimit) { - SetErrorState("Multiple continuous timeouts while read-polling."); + SetErrorState(FROM_HERE, + "Multiple continuous timeouts while read-polling."); timeout_count_ = 0; return; } @@ -399,7 +400,7 @@ FillV4L2Buffer(&buffer, 0); if (HANDLE_EINTR(ioctl(device_fd_.get(), VIDIOC_DQBUF, &buffer)) < 0) { - SetErrorState("Failed to dequeue capture buffer"); + SetErrorState(FROM_HERE, "Failed to dequeue capture buffer"); return; } @@ -407,7 +408,7 @@ SendBuffer(buffer_tracker_pool_[buffer.index], video_fmt_); if (HANDLE_EINTR(ioctl(device_fd_.get(), VIDIOC_QBUF, &buffer)) < 0) { - SetErrorState("Failed to enqueue capture buffer"); + SetErrorState(FROM_HERE, "Failed to enqueue capture buffer"); return; } } @@ -416,10 +417,12 @@ FROM_HERE, base::Bind(&V4L2CaptureDelegate::DoCapture, this)); } -void V4L2CaptureDelegate::SetErrorState(const std::string& reason) { +void V4L2CaptureDelegate::SetErrorState( + const tracked_objects::Location& from_here, + const std::string& reason) { DCHECK(v4l2_task_runner_->BelongsToCurrentThread()); is_capturing_ = false; - client_->OnError(reason); + client_->OnError(from_here, reason); } } // namespace media
diff --git a/media/capture/video/linux/v4l2_capture_delegate.h b/media/capture/video/linux/v4l2_capture_delegate.h index 1bb1735..28cec82 100644 --- a/media/capture/video/linux/v4l2_capture_delegate.h +++ b/media/capture/video/linux/v4l2_capture_delegate.h
@@ -15,6 +15,10 @@ #include "base/memory/ref_counted.h" #include "media/capture/video/video_capture_device.h" +namespace tracked_objects { +class Location; +} // namespace tracked_objects + namespace media { // Class doing the actual Linux capture using V4L2 API. V4L2 SPLANE/MPLANE @@ -137,7 +141,8 @@ // for filling in the planar-dependent parts. void FillV4L2Buffer(v4l2_buffer* buffer, int i) const; void DoCapture(); - void SetErrorState(const std::string& reason); + void SetErrorState(const tracked_objects::Location& from_here, + const std::string& reason); const v4l2_buf_type capture_type_; const scoped_refptr<base::SingleThreadTaskRunner> v4l2_task_runner_;
diff --git a/media/capture/video/linux/video_capture_device_linux.cc b/media/capture/video/linux/video_capture_device_linux.cc index cbf2b490..0d55d27 100644 --- a/media/capture/video/linux/video_capture_device_linux.cc +++ b/media/capture/video/linux/video_capture_device_linux.cc
@@ -101,7 +101,7 @@ capture_impl_ = V4L2CaptureDelegate::CreateV4L2CaptureDelegate( device_name_, v4l2_thread_.task_runner(), line_frequency); if (!capture_impl_) { - client->OnError("Failed to create VideoCaptureDelegate"); + client->OnError(FROM_HERE, "Failed to create VideoCaptureDelegate"); return; } v4l2_thread_.message_loop()->PostTask(
diff --git a/media/capture/video/mac/video_capture_device_avfoundation_mac.mm b/media/capture/video/mac/video_capture_device_avfoundation_mac.mm index deb1408..5f1893ae 100644 --- a/media/capture/video/mac/video_capture_device_avfoundation_mac.mm +++ b/media/capture/video/mac/video_capture_device_avfoundation_mac.mm
@@ -6,6 +6,7 @@ #import <CoreVideo/CoreVideo.h> +#include "base/location.h" #include "base/logging.h" #include "base/mac/foundation_util.h" #include "media/base/video_capture_types.h" @@ -351,7 +352,7 @@ DLOG(ERROR) << [error UTF8String]; base::AutoLock lock(lock_); if (frameReceiver_) - frameReceiver_->ReceiveError([error UTF8String]); + frameReceiver_->ReceiveError(FROM_HERE, [error UTF8String]); } @end
diff --git a/media/capture/video/mac/video_capture_device_decklink_mac.h b/media/capture/video/mac/video_capture_device_decklink_mac.h index e03765ab..8718e03 100644 --- a/media/capture/video/mac/video_capture_device_decklink_mac.h +++ b/media/capture/video/mac/video_capture_device_decklink_mac.h
@@ -19,6 +19,10 @@ class DeckLinkCaptureDelegate; } // namespace +namespace tracked_objects { +class Location; +} // namespace tracked_objects + namespace media { // Extension of VideoCaptureDevice to create and manipulate Blackmagic devices. @@ -52,7 +56,8 @@ base::TimeTicks timestamp); // Forwarder to VideoCaptureDevice::Client::OnError(). - void SendErrorString(const std::string& reason); + void SendErrorString(const tracked_objects::Location& from_here, + const std::string& reason); // Forwarder to VideoCaptureDevice::Client::OnLog(). void SendLogString(const std::string& message);
diff --git a/media/capture/video/mac/video_capture_device_decklink_mac.mm b/media/capture/video/mac/video_capture_device_decklink_mac.mm index c73cb406..6877f96 100644 --- a/media/capture/video/mac/video_capture_device_decklink_mac.mm +++ b/media/capture/video/mac/video_capture_device_decklink_mac.mm
@@ -69,7 +69,8 @@ ULONG Release() override; // Forwarder to VideoCaptureDeviceDeckLinkMac::SendErrorString(). - void SendErrorString(const std::string& reason); + void SendErrorString(const tracked_objects::Location& from_here, + const std::string& reason); // Forwarder to VideoCaptureDeviceDeckLinkMac::SendLogString(). void SendLogString(const std::string& message); @@ -143,21 +144,21 @@ } } if (!decklink_local.get()) { - SendErrorString("Device id not found in the system"); + SendErrorString(FROM_HERE, "Device id not found in the system"); return; } ScopedDeckLinkPtr<IDeckLinkInput> decklink_input_local; if (decklink_local->QueryInterface( IID_IDeckLinkInput, decklink_input_local.ReceiveVoid()) != S_OK) { - SendErrorString("Error querying input interface."); + SendErrorString(FROM_HERE, "Error querying input interface."); return; } ScopedDeckLinkPtr<IDeckLinkDisplayModeIterator> display_mode_iter; if (decklink_input_local->GetDisplayModeIterator( display_mode_iter.Receive()) != S_OK) { - SendErrorString("Error creating Display Mode Iterator"); + SendErrorString(FROM_HERE, "Error creating Display Mode Iterator"); return; } @@ -178,7 +179,7 @@ display_mode.Release(); } if (!chosen_display_mode.get()) { - SendErrorString("Could not find a display mode"); + SendErrorString(FROM_HERE, "Could not find a display mode"); return; } #if !defined(NDEBUG) @@ -194,13 +195,13 @@ if (decklink_input_local->EnableVideoInput( chosen_display_mode->GetDisplayMode(), bmdFormat8BitYUV, bmdVideoInputFlagDefault) != S_OK) { - SendErrorString("Could not select the video format we like."); + SendErrorString(FROM_HERE, "Could not select the video format we like."); return; } decklink_input_local->SetCallback(this); if (decklink_input_local->StartStreams() != S_OK) - SendErrorString("Could not start capturing"); + SendErrorString(FROM_HERE, "Could not start capturing"); decklink_.swap(decklink_local); decklink_input_.swap(decklink_input_local); @@ -244,7 +245,7 @@ pixel_format = media::PIXEL_FORMAT_ARGB; break; default: - SendErrorString("Unsupported pixel format"); + SendErrorString(FROM_HERE, "Unsupported pixel format"); break; } @@ -288,10 +289,12 @@ return ret_value; } -void DeckLinkCaptureDelegate::SendErrorString(const std::string& reason) { +void DeckLinkCaptureDelegate::SendErrorString( + const tracked_objects::Location& from_here, + const std::string& reason) { base::AutoLock lock(lock_); if (frame_receiver_) - frame_receiver_->SendErrorString(reason); + frame_receiver_->SendErrorString(from_here, reason); } void DeckLinkCaptureDelegate::SendLogString(const std::string& message) { @@ -453,11 +456,13 @@ } } -void VideoCaptureDeviceDeckLinkMac::SendErrorString(const std::string& reason) { +void VideoCaptureDeviceDeckLinkMac::SendErrorString( + const tracked_objects::Location& from_here, + const std::string& reason) { DCHECK(thread_checker_.CalledOnValidThread()); base::AutoLock lock(lock_); if (client_) - client_->OnError(reason); + client_->OnError(from_here, reason); } void VideoCaptureDeviceDeckLinkMac::SendLogString(const std::string& message) {
diff --git a/media/capture/video/mac/video_capture_device_mac.h b/media/capture/video/mac/video_capture_device_mac.h index c36248e..1b91c87 100644 --- a/media/capture/video/mac/video_capture_device_mac.h +++ b/media/capture/video/mac/video_capture_device_mac.h
@@ -27,6 +27,10 @@ class SingleThreadTaskRunner; } +namespace tracked_objects { +class Location; +} // namespace tracked_objects + // Small class to bundle device name and connection type into a dictionary. MEDIA_EXPORT @interface DeviceNameAndTransportType : NSObject { @@ -73,13 +77,15 @@ int aspect_denominator); // Forwarder to VideoCaptureDevice::Client::OnError(). - void ReceiveError(const std::string& reason); + void ReceiveError(const tracked_objects::Location& from_here, + const std::string& reason); // Forwarder to VideoCaptureDevice::Client::OnLog(). void LogMessage(const std::string& message); private: - void SetErrorState(const std::string& reason); + void SetErrorState(const tracked_objects::Location& from_here, + const std::string& reason); bool UpdateCaptureResolution(); // Flag indicating the internal state.
diff --git a/media/capture/video/mac/video_capture_device_mac.mm b/media/capture/video/mac/video_capture_device_mac.mm index 5fc083e..cc8608e 100644 --- a/media/capture/video/mac/video_capture_device_mac.mm +++ b/media/capture/video/mac/video_capture_device_mac.mm
@@ -381,7 +381,7 @@ [capture_device_ setFrameReceiver:this]; if (![capture_device_ setCaptureDevice:deviceId]) { - SetErrorState("Could not open capture device."); + SetErrorState(FROM_HERE, "Could not open capture device."); return; } @@ -422,7 +422,7 @@ } if (![capture_device_ startCapture]) { - SetErrorState("Could not start capture device."); + SetErrorState(FROM_HERE, "Could not start capture device."); return; } @@ -530,8 +530,9 @@ if (!AVFoundationGlue::IsAVFoundationSupported()) { capture_format_.frame_size = frame_format.frame_size; } else if (capture_format_.frame_size != frame_format.frame_size) { - ReceiveError("Captured resolution " + frame_format.frame_size.ToString() + - ", and expected " + capture_format_.frame_size.ToString()); + ReceiveError(FROM_HERE, + "Captured resolution " + frame_format.frame_size.ToString() + + ", and expected " + capture_format_.frame_size.ToString()); return; } @@ -539,16 +540,20 @@ 0, base::TimeTicks::Now()); } -void VideoCaptureDeviceMac::ReceiveError(const std::string& reason) { - task_runner_->PostTask(FROM_HERE, - base::Bind(&VideoCaptureDeviceMac::SetErrorState, - weak_factory_.GetWeakPtr(), reason)); +void VideoCaptureDeviceMac::ReceiveError( + const tracked_objects::Location& from_here, + const std::string& reason) { + task_runner_->PostTask( + FROM_HERE, base::Bind(&VideoCaptureDeviceMac::SetErrorState, + weak_factory_.GetWeakPtr(), from_here, reason)); } -void VideoCaptureDeviceMac::SetErrorState(const std::string& reason) { +void VideoCaptureDeviceMac::SetErrorState( + const tracked_objects::Location& from_here, + const std::string& reason) { DCHECK(task_runner_->BelongsToCurrentThread()); state_ = kError; - client_->OnError(reason); + client_->OnError(from_here, reason); } void VideoCaptureDeviceMac::LogMessage(const std::string& message) { @@ -561,7 +566,7 @@ if (![capture_device_ setCaptureHeight:capture_format_.frame_size.height() width:capture_format_.frame_size.width() frameRate:capture_format_.frame_rate]) { - ReceiveError("Could not configure capture device."); + ReceiveError(FROM_HERE, "Could not configure capture device."); return false; } return true;
diff --git a/media/capture/video/mac/video_capture_device_qtkit_mac.mm b/media/capture/video/mac/video_capture_device_qtkit_mac.mm index 1ea4c9e4..9218a11 100644 --- a/media/capture/video/mac/video_capture_device_qtkit_mac.mm +++ b/media/capture/video/mac/video_capture_device_qtkit_mac.mm
@@ -7,6 +7,7 @@ #import <QTKit/QTKit.h> #include "base/debug/crash_logging.h" +#include "base/location.h" #include "base/logging.h" #include "media/base/video_capture_types.h" #include "media/capture/video/mac/video_capture_device_mac.h" @@ -345,7 +346,7 @@ DLOG(ERROR) << [error UTF8String]; [lock_ lock]; if (frameReceiver_) - frameReceiver_->ReceiveError([error UTF8String]); + frameReceiver_->ReceiveError(FROM_HERE, [error UTF8String]); [lock_ unlock]; }
diff --git a/media/capture/video/video_capture_device.h b/media/capture/video/video_capture_device.h index ad0927d..099cf28 100644 --- a/media/capture/video/video_capture_device.h +++ b/media/capture/video/video_capture_device.h
@@ -26,6 +26,10 @@ #include "media/base/video_frame.h" #include "ui/gfx/gpu_memory_buffer.h" +namespace tracked_objects { +class Location; +} // namespace tracked_objects + namespace media { class MEDIA_EXPORT VideoCaptureDevice { @@ -250,7 +254,8 @@ // An error has occurred that cannot be handled and VideoCaptureDevice must // be StopAndDeAllocate()-ed. |reason| is a text description of the error. - virtual void OnError(const std::string& reason) = 0; + virtual void OnError(const tracked_objects::Location& from_here, + const std::string& reason) = 0; // VideoCaptureDevice requests the |message| to be logged. virtual void OnLog(const std::string& message) {}
diff --git a/media/capture/video/video_capture_device_unittest.cc b/media/capture/video/video_capture_device_unittest.cc index b5d1dfc..e907bf60 100644 --- a/media/capture/video/video_capture_device_unittest.cc +++ b/media/capture/video/video_capture_device_unittest.cc
@@ -46,7 +46,6 @@ // main thread for tests. This results in no frame received by // VideoCaptureAndroid. #define MAYBE_AllocateBadSize DISABLED_AllocateBadSize -#define ReAllocateCamera DISABLED_ReAllocateCamera #define DeAllocateCameraWhileRunning DISABLED_DeAllocateCameraWhileRunning #define DeAllocateCameraWhileRunning DISABLED_DeAllocateCameraWhileRunning #define MAYBE_CaptureMjpeg DISABLED_CaptureMjpeg @@ -79,7 +78,9 @@ MOCK_METHOD0(DoReserveOutputBuffer, void(void)); MOCK_METHOD0(DoOnIncomingCapturedBuffer, void(void)); MOCK_METHOD0(DoOnIncomingCapturedVideoFrame, void(void)); - MOCK_METHOD1(OnError, void(const std::string& reason)); + MOCK_METHOD2(OnError, + void(const tracked_objects::Location& from_here, + const std::string& reason)); MOCK_CONST_METHOD0(GetBufferPoolUtilization, double(void)); explicit MockClient(base::Callback<void(const VideoCaptureFormat&)> frame_cb) @@ -281,7 +282,7 @@ } else { // The presence of the actual device is only checked on AllocateAndStart() // and not on creation for QTKit API in Mac OS X platform. - EXPECT_CALL(*client_, OnError(_)).Times(1); + EXPECT_CALL(*client_, OnError(_, _)).Times(1); VideoCaptureParams capture_params; capture_params.requested_format.frame_size.SetSize(640, 480); @@ -311,7 +312,7 @@ ASSERT_TRUE(device); DVLOG(1) << names_->front().id(); - EXPECT_CALL(*client_, OnError(_)).Times(0); + EXPECT_CALL(*client_, OnError(_, _)).Times(0); VideoCaptureParams capture_params; capture_params.requested_format.frame_size.SetSize(width, height); @@ -329,7 +330,7 @@ } #if !defined(OS_ANDROID) -INSTANTIATE_TEST_CASE_P(MAYBE_VideoCaptureDeviceTests, +INSTANTIATE_TEST_CASE_P(VideoCaptureDeviceTests, VideoCaptureDeviceTest, testing::ValuesIn(kCaptureSizes)); #endif @@ -344,7 +345,7 @@ video_capture_device_factory_->Create(names_->front())); ASSERT_TRUE(device); - EXPECT_CALL(*client_, OnError(_)).Times(0); + EXPECT_CALL(*client_, OnError(_, _)).Times(0); const gfx::Size input_size(640, 480); VideoCaptureParams capture_params; @@ -361,14 +362,8 @@ EXPECT_EQ(input_size.GetArea(), last_format().frame_size.GetArea()); } -// Cause hangs on Windows Debug. http://crbug.com/417824 -#if defined(OS_WIN) && !defined(NDEBUG) -#define MAYBE_ReAllocateCamera DISABLED_ReAllocateCamera -#else -#define MAYBE_ReAllocateCamera ReAllocateCamera -#endif - -TEST_F(VideoCaptureDeviceTest, MAYBE_ReAllocateCamera) { +// Cause hangs on Windows, Linux. Fails Android. http://crbug.com/417824 +TEST_F(VideoCaptureDeviceTest, DISABLED_ReAllocateCamera) { names_ = EnumerateDevices(); if (names_->empty()) { DVLOG(1) << "No camera available. Exiting test."; @@ -422,7 +417,7 @@ video_capture_device_factory_->Create(names_->front())); ASSERT_TRUE(device); - EXPECT_CALL(*client_, OnError(_)).Times(0); + EXPECT_CALL(*client_, OnError(_, _)).Times(0); VideoCaptureParams capture_params; capture_params.requested_format.frame_size.SetSize(640, 480); @@ -449,7 +444,7 @@ video_capture_device_factory_->Create(*name)); ASSERT_TRUE(device); - EXPECT_CALL(*client_, OnError(_)).Times(0); + EXPECT_CALL(*client_, OnError(_, _)).Times(0); VideoCaptureParams capture_params; capture_params.requested_format.frame_size.SetSize(1280, 720);
diff --git a/media/capture/video/win/video_capture_device_mf_win.cc b/media/capture/video/win/video_capture_device_mf_win.cc index c55cf4aa..95595bd 100644 --- a/media/capture/video/win/video_capture_device_mf_win.cc +++ b/media/capture/video/win/video_capture_device_mf_win.cc
@@ -7,6 +7,7 @@ #include <mfapi.h> #include <mferror.h> +#include "base/location.h" #include "base/memory/ref_counted.h" #include "base/strings/stringprintf.h" #include "base/strings/sys_string_conversions.h" @@ -260,7 +261,7 @@ } } - OnError(hr); + OnError(FROM_HERE, hr); } void VideoCaptureDeviceMFWin::StopAndDeAllocate() { @@ -311,14 +312,17 @@ // It's not clear to me why this is, but it is possible that it has // something to do with this bug: // http://support.microsoft.com/kb/979567 - OnError(hr); + OnError(FROM_HERE, hr); } } } -void VideoCaptureDeviceMFWin::OnError(HRESULT hr) { +void VideoCaptureDeviceMFWin::OnError( + const tracked_objects::Location& from_here, + HRESULT hr) { if (client_.get()) { client_->OnError( + from_here, base::StringPrintf("VideoCaptureDeviceMFWin: %s", logging::SystemErrorCodeToString(hr).c_str())); }
diff --git a/media/capture/video/win/video_capture_device_mf_win.h b/media/capture/video/win/video_capture_device_mf_win.h index 7894864..bcc9c1f 100644 --- a/media/capture/video/win/video_capture_device_mf_win.h +++ b/media/capture/video/win/video_capture_device_mf_win.h
@@ -22,6 +22,10 @@ interface IMFSourceReader; +namespace tracked_objects { +class Location; +} // namespace tracked_objects + namespace media { class MFReaderCallback; @@ -52,7 +56,7 @@ const base::TimeTicks& time_stamp); private: - void OnError(HRESULT hr); + void OnError(const tracked_objects::Location& from_here, HRESULT hr); Name name_; base::win::ScopedComPtr<IMFActivate> device_;
diff --git a/media/capture/video/win/video_capture_device_win.cc b/media/capture/video/win/video_capture_device_win.cc index 9960406e..92ee2a5 100644 --- a/media/capture/video/win/video_capture_device_win.cc +++ b/media/capture/video/win/video_capture_device_win.cc
@@ -348,14 +348,14 @@ ScopedComPtr<IAMStreamConfig> stream_config; HRESULT hr = output_capture_pin_.QueryInterface(stream_config.Receive()); if (FAILED(hr)) { - SetErrorState("Can't get the Capture format settings"); + SetErrorState(FROM_HERE, "Can't get the Capture format settings"); return; } int count = 0, size = 0; hr = stream_config->GetNumberOfCapabilities(&count, &size); if (FAILED(hr)) { - SetErrorState("Failed to GetNumberOfCapabilities"); + SetErrorState(FROM_HERE, "Failed to GetNumberOfCapabilities"); return; } @@ -368,7 +368,7 @@ hr = stream_config->GetStreamCaps(found_capability.stream_index, media_type.Receive(), caps.get()); if (hr != S_OK) { - SetErrorState("Failed to get capture device capabilities"); + SetErrorState(FROM_HERE, "Failed to get capture device capabilities"); return; } if (media_type->formattype == FORMAT_VideoInfo) { @@ -385,7 +385,7 @@ hr = stream_config->SetFormat(media_type.get()); if (FAILED(hr)) { // TODO(grunell): Log the error. http://crbug.com/405016. - SetErrorState("Failed to set capture device output format"); + SetErrorState(FROM_HERE, "Failed to set capture device output format"); return; } @@ -402,13 +402,14 @@ } if (FAILED(hr)) { - SetErrorState("Failed to connect the Capture graph."); + SetErrorState(FROM_HERE, "Failed to connect the Capture graph."); return; } hr = media_control_->Pause(); if (FAILED(hr)) { SetErrorState( + FROM_HERE, "Failed to pause the Capture device, is it already occupied?"); return; } @@ -420,7 +421,7 @@ // Start capturing. hr = media_control_->Run(); if (FAILED(hr)) { - SetErrorState("Failed to start the Capture device."); + SetErrorState(FROM_HERE, "Failed to start the Capture device."); return; } @@ -434,7 +435,7 @@ HRESULT hr = media_control_->Stop(); if (FAILED(hr)) { - SetErrorState("Failed to stop the capture graph."); + SetErrorState(FROM_HERE, "Failed to stop the capture graph."); return; } @@ -572,9 +573,11 @@ } } -void VideoCaptureDeviceWin::SetErrorState(const std::string& reason) { +void VideoCaptureDeviceWin::SetErrorState( + const tracked_objects::Location& from_here, + const std::string& reason) { DCHECK(thread_checker_.CalledOnValidThread()); state_ = kError; - client_->OnError(reason); + client_->OnError(from_here, reason); } } // namespace media
diff --git a/media/capture/video/win/video_capture_device_win.h b/media/capture/video/win/video_capture_device_win.h index dec02c1..6bd0eb4 100644 --- a/media/capture/video/win/video_capture_device_win.h +++ b/media/capture/video/win/video_capture_device_win.h
@@ -23,6 +23,10 @@ #include "media/capture/video/win/sink_filter_win.h" #include "media/capture/video/win/sink_input_pin_win.h" +namespace tracked_objects { +class Location; +} // namespace tracked_objects + namespace media { // All the methods in the class can only be run on a COM initialized thread. @@ -82,7 +86,8 @@ bool CreateCapabilityMap(); void SetAntiFlickerInCaptureFilter(const VideoCaptureParams& params); - void SetErrorState(const std::string& reason); + void SetErrorState(const tracked_objects::Location& from_here, + const std::string& reason); const Name device_name_; InternalState state_;
diff --git a/media/renderers/skcanvas_video_renderer.cc b/media/renderers/skcanvas_video_renderer.cc index aa8d95e..a382445 100644 --- a/media/renderers/skcanvas_video_renderer.cc +++ b/media/renderers/skcanvas_video_renderer.cc
@@ -162,11 +162,8 @@ DCHECK(source_texture); gl->BindTexture(GL_TEXTURE_2D, source_texture); SkCanvasVideoRenderer::CopyVideoFrameSingleTextureToGLTexture( - gl, video_frame, - SkCanvasVideoRenderer::CopyFrameSingleTextureParams( - SkCanvasVideoRenderer::CopyFrameSingleTextureParams::FullCopy, - GL_TEXTURE_2D, source_texture, GL_RGBA, GL_UNSIGNED_BYTE, 0, 0, 0, - true, false)); + gl, video_frame, source_texture, GL_RGBA, GL_UNSIGNED_BYTE, true, + false); } else { gl->WaitSyncPointCHROMIUM(mailbox_holder.sync_point); source_texture = gl->CreateAndConsumeTextureCHROMIUM( @@ -542,7 +539,11 @@ void SkCanvasVideoRenderer::CopyVideoFrameSingleTextureToGLTexture( gpu::gles2::GLES2Interface* gl, VideoFrame* video_frame, - const CopyFrameSingleTextureParams& params) { + unsigned int texture, + unsigned int internal_format, + unsigned int type, + bool premultiply_alpha, + bool flip_y) { DCHECK(video_frame); DCHECK(video_frame->HasTextures()); DCHECK_EQ(1u, VideoFrame::NumPlanes(video_frame->format())); @@ -563,20 +564,9 @@ // value down to get the expected result. // "flip_y == true" means to reverse the video orientation while // "flip_y == false" means to keep the intrinsic orientation. - if (params.copy_type == CopyFrameSingleTextureParams::FullCopy) { - DCHECK(!params.xoffset && !params.yoffset); - gl->CopyTextureCHROMIUM(params.target, source_texture, params.texture, - params.internal_format, params.type, params.flip_y, - params.premultiply_alpha, false); - } else { - DCHECK_EQ(static_cast<unsigned int>(GL_FALSE), params.internal_format); - DCHECK_EQ(static_cast<unsigned int>(GL_FALSE), params.type); - gl->CopySubTextureCHROMIUM(params.target, source_texture, params.texture, - params.xoffset, params.yoffset, 0, 0, - video_frame->natural_size().width(), - video_frame->natural_size().height(), - params.flip_y, params.premultiply_alpha, false); - } + gl->CopyTextureCHROMIUM(GL_TEXTURE_2D, source_texture, texture, + internal_format, type, flip_y, premultiply_alpha, + false); gl->DeleteTextures(1, &source_texture); gl->Flush(); @@ -591,26 +581,4 @@ last_timestamp_ = kNoTimestamp(); } -SkCanvasVideoRenderer::CopyFrameSingleTextureParams:: - CopyFrameSingleTextureParams(CopyType copy_type, - unsigned target, - unsigned texture, - unsigned internal_format, - unsigned type, - int level, - int xoffset, - int yoffset, - bool premultiply_alpha, - bool flip_y) - : copy_type(copy_type), - target(target), - texture(texture), - internal_format(internal_format), - type(type), - level(level), - xoffset(xoffset), - yoffset(yoffset), - premultiply_alpha(premultiply_alpha), - flip_y(flip_y) {} - } // namespace media
diff --git a/media/renderers/skcanvas_video_renderer.h b/media/renderers/skcanvas_video_renderer.h index 03de24a..71e77ff 100644 --- a/media/renderers/skcanvas_video_renderer.h +++ b/media/renderers/skcanvas_video_renderer.h
@@ -65,33 +65,14 @@ // Copy the contents of texture of |video_frame| to texture |texture|. // |level|, |internal_format|, |type| specify target texture |texture|. // The format of |video_frame| must be VideoFrame::NATIVE_TEXTURE. - struct MEDIA_EXPORT CopyFrameSingleTextureParams { - enum CopyType { FullCopy, SubCopy }; - CopyFrameSingleTextureParams(CopyType copy_type, - unsigned target, - unsigned texture, - unsigned internal_format, - unsigned type, - int level, - int xoffset, - int yoffset, - bool premultiply_alpha, - bool flip_y); - CopyType copy_type; - unsigned int target; - unsigned int texture; - unsigned int internal_format; - unsigned int type; - int level; - int xoffset; - int yoffset; - bool premultiply_alpha; - bool flip_y; - }; static void CopyVideoFrameSingleTextureToGLTexture( gpu::gles2::GLES2Interface* gl, VideoFrame* video_frame, - const CopyFrameSingleTextureParams& params); + unsigned int texture, + unsigned int internal_format, + unsigned int type, + bool premultiply_alpha, + bool flip_y); private: void ResetCache();
diff --git a/media/video/gpu_memory_buffer_video_frame_pool.cc b/media/video/gpu_memory_buffer_video_frame_pool.cc index 5f9543f..13c73c7f 100644 --- a/media/video/gpu_memory_buffer_video_frame_pool.cc +++ b/media/video/gpu_memory_buffer_video_frame_pool.cc
@@ -594,6 +594,14 @@ default: NOTREACHED(); } + + base::TimeTicks render_time; + if (video_frame->metadata()->GetTimeTicks(VideoFrameMetadata::REFERENCE_TIME, + &render_time)) { + frame->metadata()->SetTimeTicks(VideoFrameMetadata::REFERENCE_TIME, + render_time); + } + frame_ready_cb.Run(frame); }
diff --git a/mojo/public/mojo_application.gni b/mojo/public/mojo_application.gni index 33d25d4..705ddc6 100644 --- a/mojo/public/mojo_application.gni +++ b/mojo/public/mojo_application.gni
@@ -74,8 +74,13 @@ } data_deps = [] + if (!defined(invoker.avoid_runner_cycle) || !invoker.avoid_runner_cycle) { + # Give the user an out; as some mojo services are depended on by the + # runner. + data_deps += [ "//mojo/runner:mojo_runner" ] + } if (defined(invoker.data_deps)) { - data_deps = invoker.data_deps + data_deps += invoker.data_deps } # Copy any necessary prebuilt artifacts.
diff --git a/mojo/runner/child/BUILD.gn b/mojo/runner/child/BUILD.gn index 224bc4d..82ea546 100644 --- a/mojo/runner/child/BUILD.gn +++ b/mojo/runner/child/BUILD.gn
@@ -55,6 +55,7 @@ mojo_native_application("apptests") { output_name = "mojo_runner_child_apptest" testonly = true + avoid_runner_cycle = true sources = [ "native_apptest.cc",
diff --git a/mojo/runner/child/native_apptest_target.cc b/mojo/runner/child/native_apptest_target.cc index a2d3532..ebe8750d 100644 --- a/mojo/runner/child/native_apptest_target.cc +++ b/mojo/runner/child/native_apptest_target.cc
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include <windows.h> - #include "base/at_exit.h" #include "base/command_line.h" #include "base/debug/stack_trace.h" @@ -25,6 +23,10 @@ #include "third_party/mojo/src/mojo/edk/embedder/embedder.h" #include "third_party/mojo/src/mojo/edk/embedder/process_delegate.h" +#if defined(OS_WIN) +#include <windows.h> +#endif + namespace { class EDKState : public mojo::embedder::ProcessDelegate {
diff --git a/mojo/services/tracing/BUILD.gn b/mojo/services/tracing/BUILD.gn index a1a7b9c..63d3a9c 100644 --- a/mojo/services/tracing/BUILD.gn +++ b/mojo/services/tracing/BUILD.gn
@@ -9,6 +9,8 @@ "main.cc", ] + avoid_runner_cycle = true + deps = [ ":lib", "//mojo/application/public/cpp",
diff --git a/net/BUILD.gn b/net/BUILD.gn index d355d46..3f9df86 100644 --- a/net/BUILD.gn +++ b/net/BUILD.gn
@@ -599,6 +599,8 @@ "test/channel_id_test_util.h", "test/ct_test_util.cc", "test/ct_test_util.h", + "test/embedded_test_server/default_handlers.cc", + "test/embedded_test_server/default_handlers.h", "test/embedded_test_server/embedded_test_server.cc", "test/embedded_test_server/embedded_test_server.h", "test/embedded_test_server/http_connection.cc",
diff --git a/net/net.gyp b/net/net.gyp index e9088d78..a4536a9 100644 --- a/net/net.gyp +++ b/net/net.gyp
@@ -557,6 +557,8 @@ 'test/channel_id_test_util.h', 'test/ct_test_util.cc', 'test/ct_test_util.h', + 'test/embedded_test_server/default_handlers.cc', + 'test/embedded_test_server/default_handlers.h', 'test/embedded_test_server/embedded_test_server.cc', 'test/embedded_test_server/embedded_test_server.h', 'test/embedded_test_server/http_connection.cc',
diff --git a/net/test/embedded_test_server/default_handlers.cc b/net/test/embedded_test_server/default_handlers.cc new file mode 100644 index 0000000..b1fe69d4 --- /dev/null +++ b/net/test/embedded_test_server/default_handlers.cc
@@ -0,0 +1,639 @@ +// 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 "net/test/embedded_test_server/default_handlers.h" + +#include <stdlib.h> +#include <ctime> +#include <map> +#include <sstream> +#include <string> + +#include "base/base64.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/format_macros.h" +#include "base/macros.h" +#include "base/md5.h" +#include "base/path_service.h" +#include "base/strings/string_split.h" +#include "base/strings/string_util.h" +#include "base/strings/stringprintf.h" +#include "base/thread_task_runner_handle.h" +#include "base/time/time.h" +#include "net/base/escape.h" +#include "net/base/url_util.h" +#include "net/test/embedded_test_server/http_request.h" +#include "net/test/embedded_test_server/http_response.h" +#include "net/test/embedded_test_server/request_handler_util.h" + +namespace net { +namespace test_server { +namespace { + +const UnescapeRule::Type kUnescapeAll = + UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS | + UnescapeRule::SPOOFING_AND_CONTROL_CHARS | + UnescapeRule::REPLACE_PLUS_WITH_SPACE; + +const char kDefaultRealm[] = "testrealm"; +const char kDefaultPassword[] = "secret"; +const char kEtag[] = "abc"; +const char kLogoPath[] = "chrome/test/data/google/logo.gif"; + +// method: CONNECT +// Responses with a BAD_REQUEST to any CONNECT requests. +scoped_ptr<HttpResponse> HandleDefaultConnect(const HttpRequest& request) { + if (request.method != METHOD_CONNECT) + return nullptr; + + scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + http_response->set_code(HTTP_BAD_REQUEST); + http_response->set_content( + "Your client has issued a malformed or illegal request."); + http_response->set_content_type("text/html"); + return http_response.Pass(); +} + +// /cachetime +// Returns a cacheable response. +scoped_ptr<HttpResponse> HandleCacheTime(const HttpRequest& request) { + scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + http_response->set_content( + "<html><head><title>Cache: max-age=60</title></head></html>"); + http_response->set_content_type("text/html"); + http_response->AddCustomHeader("Cache-Control", "max-age=60"); + return http_response.Pass(); +} + +// /echoheader | /echoheadercache +// Responds with the headers echoed in the message body. +// echoheader does not cache the results, while echoheadercache does. +scoped_ptr<HttpResponse> HandleEchoHeader(const std::string& url, + const std::string& cache_control, + const HttpRequest& request) { + if (!ShouldHandle(request, url)) + return nullptr; + + scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + + GURL request_url = request.GetURL(); + if (request_url.has_query()) { + std::string header_name = request_url.query(); + http_response->AddCustomHeader("Vary", header_name); + if (request.headers.find(header_name) != request.headers.end()) + http_response->set_content(request.headers.at(header_name)); + else + http_response->set_content("None"); + } + + http_response->set_content_type("text/plain"); + http_response->AddCustomHeader("Cache-Control", cache_control); + return http_response.Pass(); +} + +// /echo?status=STATUS +// Responds with the request body as the response body and +// a status code of STATUS. +scoped_ptr<HttpResponse> HandleEcho(const HttpRequest& request) { + scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + + GURL request_url = request.GetURL(); + if (request_url.has_query()) { + RequestQuery query = ParseQuery(request_url); + if (query.find("status") != query.end()) + http_response->set_code(static_cast<HttpStatusCode>( + std::atoi(query["status"].front().c_str()))); + } + + http_response->set_content_type("text/html"); + if (request.method != METHOD_POST && request.method != METHOD_PUT) + http_response->set_content("Echo"); + else + http_response->set_content(request.content); + return http_response.Pass(); +} + +// /echotitle +// Responds with the request body as the title. +scoped_ptr<HttpResponse> HandleEchoTitle(const HttpRequest& request) { + scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + http_response->set_content_type("text/html"); + http_response->set_content("<html><head><title>" + request.content + + "</title></head></html>"); + return http_response.Pass(); +} + +// /echoall?QUERY +// Responds with the list of QUERY and the request headers. +scoped_ptr<HttpResponse> HandleEchoAll(const HttpRequest& request) { + scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + + std::string body = + "<html><head><style>" + "pre { border: 1px solid black; margin: 5px; padding: 5px }" + "</style></head><body>" + "<div style=\"float: right\">" + "<a href=\"/echo\">back to referring page</a></div>" + "<h1>Request Body:</h1><pre>"; + + if (request.has_content) { + std::vector<std::string> query_list = base::SplitString( + request.content, "&", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); + for (const auto& query : query_list) + body += query + "\n"; + } + + body += + "</pre>" + "<h1>Request Headers:</h1><pre>" + + request.all_headers + + "</pre>" + "</body></html>"; + + http_response->set_content_type("text/html"); + http_response->set_content(body); + return http_response.Pass(); +} + +// /set-cookie?COOKIES +// Sets response cookies to be COOKIES. +scoped_ptr<HttpResponse> HandleSetCookie(const HttpRequest& request) { + scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + http_response->set_content_type("text/html"); + std::string content; + GURL request_url = request.GetURL(); + if (request_url.has_query()) { + std::vector<std::string> cookies = base::SplitString( + request_url.query(), "&", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); + for (const auto& cookie : cookies) { + http_response->AddCustomHeader("Set-Cookie", cookie); + content += cookie; + } + } + + http_response->set_content(content); + return http_response.Pass(); +} + +// /set-many-cookies?N +// Sets N cookies in the response. +scoped_ptr<HttpResponse> HandleSetManyCookies(const HttpRequest& request) { + std::string content; + + GURL request_url = request.GetURL(); + size_t num = 0; + if (request_url.has_query()) + num = std::atoi(request_url.query().c_str()); + + scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + http_response->set_content_type("text/html"); + for (size_t i = 0; i < num; ++i) { + http_response->AddCustomHeader("Set-Cookie", "a="); + } + + http_response->set_content( + base::StringPrintf("%" PRIuS " cookies were sent", num)); + return http_response.Pass(); +} + +// /expect-and-set-cookie?expect=EXPECTED&set=SET&data=DATA +// Verifies that the request cookies match EXPECTED and then returns cookies +// that match SET and a content that matches DATA. +scoped_ptr<HttpResponse> HandleExpectAndSetCookie(const HttpRequest& request) { + std::vector<std::string> received_cookies; + if (request.headers.find("Cookie") != request.headers.end()) { + received_cookies = + base::SplitString(request.headers.at("Cookie"), ";", + base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); + } + + bool got_all_expected = true; + GURL request_url = request.GetURL(); + RequestQuery query_list = ParseQuery(request_url); + if (query_list.find("expect") != query_list.end()) { + for (const auto& expected_cookie : query_list.at("expect")) { + bool found = false; + for (const auto& received_cookie : received_cookies) { + if (expected_cookie == received_cookie) + found = true; + } + got_all_expected &= found; + } + } + + scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + http_response->set_content_type("text/html"); + if (got_all_expected) { + for (const auto& cookie : query_list.at("set")) { + http_response->AddCustomHeader( + "Set-Cookie", net::UnescapeURLComponent(cookie, kUnescapeAll)); + } + } + + std::string content; + if (query_list.find("data") != query_list.end()) { + for (const auto& item : query_list.at("data")) + content += item; + } + + http_response->set_content(content); + return http_response.Pass(); +} + +// /set-header?HEADERS +// Returns a response with HEADERS set as the response headers. +scoped_ptr<HttpResponse> HandleSetHeader(const HttpRequest& request) { + std::string content; + + GURL request_url = request.GetURL(); + + scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + http_response->set_content_type("text/html"); + if (request_url.has_query()) { + RequestQuery headers = ParseQuery(request_url); + for (const auto& header : headers) { + size_t delimiter = header.first.find(": "); + if (delimiter == std::string::npos) + continue; + std::string key = header.first.substr(0, delimiter); + std::string value = header.first.substr(delimiter + 2); + http_response->AddCustomHeader(key, value); + content += header.first; + } + } + + http_response->set_content(content); + return http_response.Pass(); +} + +// /nocontent +// Returns a NO_CONTENT response. +scoped_ptr<HttpResponse> HandleNoContent(const HttpRequest& request) { + scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + http_response->set_code(HTTP_NO_CONTENT); + return http_response.Pass(); +} + +// /close-socket +// Immediately closes the connection. +scoped_ptr<HttpResponse> HandleCloseSocket(const HttpRequest& request) { + scoped_ptr<RawHttpResponse> http_response(new RawHttpResponse("", "")); + return http_response.Pass(); +} + +// /auth-basic?password=PASS&realm=REALM +// Performs "Basic" HTTP authentication using expected password PASS and +// realm REALM. +scoped_ptr<HttpResponse> HandleAuthBasic(const HttpRequest& request) { + GURL request_url = request.GetURL(); + RequestQuery query = ParseQuery(request_url); + + std::string expected_password = kDefaultPassword; + if (query.find("password") != query.end()) + expected_password = query.at("password").front(); + std::string realm = kDefaultRealm; + if (query.find("realm") != query.end()) + realm = query.at("realm").front(); + + bool authed = false; + std::string error; + std::string auth; + std::string username; + std::string userpass; + std::string password; + std::string b64str; + if (request.headers.find("Authorization") == request.headers.end()) { + error = "Missing Authorization Header"; + } else { + auth = request.headers.at("Authorization"); + if (auth.find("Basic ") == std::string::npos) { + error = "Invalid Authorization Header"; + } else { + b64str = auth.substr(std::string("Basic ").size()); + base::Base64Decode(b64str, &userpass); + size_t delimiter = userpass.find(":"); + if (delimiter != std::string::npos) { + username = userpass.substr(0, delimiter); + password = userpass.substr(delimiter + 1); + if (password == expected_password) + authed = true; + else + error = "Invalid Credentials"; + } else { + error = "Invalid Credentials"; + } + } + } + + scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + if (!authed) { + http_response->set_code(HTTP_UNAUTHORIZED); + http_response->set_content_type("text/html"); + http_response->AddCustomHeader("WWW-Authenticate", + "Basic realm=\"" + realm + "\""); + if (query.find("set-cookie-if-challenged") != query.end()) + http_response->AddCustomHeader("Set-Cookie", "got_challenged=true"); + http_response->set_content(base::StringPrintf( + "<html><head><title>Denied: %s</title></head>" + "<body>auth=%s<p>b64str=%s<p>username: %s<p>userpass: %s<p>" + "password: %s<p>You sent:<br>%s<p></body></html>", + error.c_str(), auth.c_str(), b64str.c_str(), username.c_str(), + userpass.c_str(), password.c_str(), request.all_headers.c_str())); + return http_response.Pass(); + } + + if (request.headers.find("If-None-Match") != request.headers.end() && + request.headers.at("If-None-Match") == kEtag) { + http_response->set_code(HTTP_NOT_MODIFIED); + return http_response.Pass(); + } + + base::FilePath file_path = + base::FilePath().AppendASCII(request.relative_url.substr(1)); + if (file_path.FinalExtension() == FILE_PATH_LITERAL("gif")) { + base::FilePath server_root; + PathService::Get(base::DIR_SOURCE_ROOT, &server_root); + base::FilePath gif_path = server_root.AppendASCII(kLogoPath); + std::string gif_data; + base::ReadFileToString(gif_path, &gif_data); + http_response->set_content_type("image/gif"); + http_response->set_content(gif_data); + } else { + http_response->set_content_type("text/html"); + http_response->set_content( + base::StringPrintf("<html><head><title>%s/%s</title></head>" + "<body>auth=%s<p>You sent:<br>%s<p></body></html>", + username.c_str(), password.c_str(), auth.c_str(), + request.all_headers.c_str())); + } + + http_response->AddCustomHeader("Cache-Control", "max-age=60000"); + http_response->AddCustomHeader("Etag", kEtag); + return http_response.Pass(); +} + +// /auth-digest +// Performs "Digest" HTTP authentication. +scoped_ptr<HttpResponse> HandleAuthDigest(const HttpRequest& request) { + std::string nonce = base::MD5String( + base::StringPrintf("privatekey%s", request.relative_url.c_str())); + std::string opaque = base::MD5String("opaque"); + std::string password = kDefaultPassword; + std::string realm = kDefaultRealm; + + bool authed = false; + std::string error; + std::string auth; + std::string digest_str = "Digest"; + std::string username; + if (request.headers.find("Authorization") == request.headers.end()) { + error = "no auth"; + } else if (request.headers.at("Authorization").substr(0, digest_str.size()) != + digest_str) { + error = "not digest"; + } else { + auth = request.headers.at("Authorization").substr(digest_str.size() + 1); + + std::map<std::string, std::string> auth_pairs; + base::StringPairs auth_vector; + base::SplitStringIntoKeyValuePairs(auth, '=', ',', &auth_vector); + for (const auto& auth_pair : auth_vector) { + std::string key; + std::string value; + base::TrimWhitespaceASCII(auth_pair.first, base::TRIM_ALL, &key); + base::TrimWhitespaceASCII(auth_pair.second, base::TRIM_ALL, &value); + if (value.size() > 2 && value.at(0) == '"' && + value.at(value.size() - 1) == '"') { + value = value.substr(1, value.size() - 2); + } + auth_pairs[key] = value; + } + + if (auth_pairs["nonce"] != nonce) { + error = "wrong nonce"; + } else if (auth_pairs["opaque"] != opaque) { + error = "wrong opaque"; + } else { + username = auth_pairs["username"]; + + std::string hash1 = base::MD5String( + base::StringPrintf("%s:%s:%s", auth_pairs["username"].c_str(), + realm.c_str(), password.c_str())); + std::string hash2 = base::MD5String(base::StringPrintf( + "%s:%s", request.method_string.c_str(), auth_pairs["uri"].c_str())); + + std::string response; + if (auth_pairs.find("qop") != auth_pairs.end() && + auth_pairs.find("nc") != auth_pairs.end() && + auth_pairs.find("cnonce") != auth_pairs.end()) { + response = base::MD5String(base::StringPrintf( + "%s:%s:%s:%s:%s:%s", hash1.c_str(), nonce.c_str(), + auth_pairs["nc"].c_str(), auth_pairs["cnonce"].c_str(), + auth_pairs["qop"].c_str(), hash2.c_str())); + } else { + response = base::MD5String(base::StringPrintf( + "%s:%s:%s", hash1.c_str(), nonce.c_str(), hash2.c_str())); + } + + if (auth_pairs["response"] == response) + authed = true; + else + error = "wrong password"; + } + } + + scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + if (!authed) { + http_response->set_code(HTTP_UNAUTHORIZED); + http_response->set_content_type("text/html"); + std::string auth_header = base::StringPrintf( + "Digest realm=\"%s\", " + "domain=\"/\", qop=\"auth\", algorithm=MD5, nonce=\"%s\", " + "opaque=\"%s\"", + realm.c_str(), nonce.c_str(), opaque.c_str()); + http_response->AddCustomHeader("WWW-Authenticate", auth_header); + http_response->set_content(base::StringPrintf( + "<html><head><title>Denied: %s</title></head>" + "<body>auth=%s<p>" + "You sent:<br>%s<p>We are replying:<br>%s<p></body></html>", + error.c_str(), auth.c_str(), request.all_headers.c_str(), + auth_header.c_str())); + return http_response.Pass(); + } + + http_response->set_content_type("text/html"); + http_response->set_content( + base::StringPrintf("<html><head><title>%s/%s</title></head>" + "<body>auth=%s<p></body></html>", + username.c_str(), password.c_str(), auth.c_str())); + + return http_response.Pass(); +} + +// /server-redirect?URL +// Returns a server-redirect (301) to URL. +scoped_ptr<HttpResponse> HandleServerRedirect(const HttpRequest& request) { + GURL request_url = request.GetURL(); + std::string dest = + net::UnescapeURLComponent(request_url.query(), kUnescapeAll); + + scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + http_response->set_code(HTTP_MOVED_PERMANENTLY); + http_response->AddCustomHeader("Location", dest); + http_response->set_content_type("text/html"); + http_response->set_content(base::StringPrintf( + "<html><head></head><body>Redirecting to %s</body></html>", + dest.c_str())); + return http_response.Pass(); +} + +// /cross-site?URL +// Returns a cross-site redirect to URL. +scoped_ptr<HttpResponse> HandleCrossSiteRedirect(EmbeddedTestServer* server, + const HttpRequest& request) { + if (!ShouldHandle(request, "/cross-site")) + return nullptr; + + std::string dest_all = net::UnescapeURLComponent( + request.relative_url.substr(std::string("/cross-site").size() + 1), + kUnescapeAll); + + std::string dest; + size_t delimiter = dest_all.find("/"); + if (delimiter != std::string::npos) { + dest = base::StringPrintf( + "//%s:%hu/%s", dest_all.substr(0, delimiter).c_str(), server->port(), + dest_all.substr(delimiter + 1).c_str()); + } + + scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + http_response->set_code(HTTP_MOVED_PERMANENTLY); + http_response->AddCustomHeader("Location", dest); + http_response->set_content_type("text/html"); + http_response->set_content(base::StringPrintf( + "<html><head></head><body>Redirecting to %s</body></html>", + dest.c_str())); + return http_response.Pass(); +} + +// /client-redirect?URL +// Returns a meta redirect to URL. +scoped_ptr<HttpResponse> HandleClientRedirect(const HttpRequest& request) { + GURL request_url = request.GetURL(); + std::string dest = + net::UnescapeURLComponent(request_url.query(), kUnescapeAll); + + scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + http_response->set_content_type("text/html"); + http_response->set_content(base::StringPrintf( + "<html><head><meta http-equiv=\"refresh\" content=\"0;url=%s\"></head>" + "<body>Redirecting to %s</body></html>", + dest.c_str(), dest.c_str())); + return http_response.Pass(); +} + +// /defaultresponse +// Returns a valid 200 response. +scoped_ptr<HttpResponse> HandleDefaultResponse(const HttpRequest& request) { + scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + http_response->set_content_type("text/html"); + http_response->set_content("Default response given for path: " + + request.relative_url); + return http_response.Pass(); +} + +// Delays |delay| seconds before sending a response to the client. +class DelayedHttpResponse : public BasicHttpResponse { + public: + explicit DelayedHttpResponse(double delay) : delay_(delay) {} + + void SendResponse(const SendBytesCallback& send, + const SendCompleteCallback& done) override { + base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( + FROM_HERE, base::Bind(send, ToResponseString(), done), + base::TimeDelta::FromSecondsD(delay_)); + } + + private: + const double delay_; + + DISALLOW_COPY_AND_ASSIGN(DelayedHttpResponse); +}; + +// /slow?N +// Returns a response to the server delayed by N seconds. +scoped_ptr<HttpResponse> HandleSlowServer(const HttpRequest& request) { + double delay = 1.0f; + + GURL request_url = request.GetURL(); + if (request_url.has_query()) + delay = std::atof(request_url.query().c_str()); + + scoped_ptr<BasicHttpResponse> http_response(new DelayedHttpResponse(delay)); + http_response->set_content_type("text/plain"); + http_response->set_content(base::StringPrintf("waited %.1f seconds", delay)); + return http_response.Pass(); +} + +} // namespace anonymous + +#define PREFIXED_HANDLER(prefix, handler) \ + base::Bind(&HandlePrefixedRequest, prefix, base::Bind(handler)) + +void RegisterDefaultHandlers(EmbeddedTestServer* server) { + server->RegisterDefaultHandler(base::Bind(&HandleDefaultConnect)); + + server->RegisterDefaultHandler( + PREFIXED_HANDLER("/cachetime", &HandleCacheTime)); + server->RegisterDefaultHandler( + base::Bind(&HandleEchoHeader, "/echoheader", "no-cache")); + server->RegisterDefaultHandler( + base::Bind(&HandleEchoHeader, "/echoheadercache", "max-age=60000")); + server->RegisterDefaultHandler(PREFIXED_HANDLER("/echo", &HandleEcho)); + server->RegisterDefaultHandler( + PREFIXED_HANDLER("/echotitle", &HandleEchoTitle)); + server->RegisterDefaultHandler(PREFIXED_HANDLER("/echoall", &HandleEchoAll)); + server->RegisterDefaultHandler( + PREFIXED_HANDLER("/set-cookie", &HandleSetCookie)); + server->RegisterDefaultHandler( + PREFIXED_HANDLER("/set-many-cookies", &HandleSetManyCookies)); + server->RegisterDefaultHandler( + PREFIXED_HANDLER("/expect-and-set-cookie", &HandleExpectAndSetCookie)); + server->RegisterDefaultHandler( + PREFIXED_HANDLER("/set-header", &HandleSetHeader)); + server->RegisterDefaultHandler( + PREFIXED_HANDLER("/nocontent", &HandleNoContent)); + server->RegisterDefaultHandler( + PREFIXED_HANDLER("/close-socket", &HandleCloseSocket)); + server->RegisterDefaultHandler( + PREFIXED_HANDLER("/auth-basic", &HandleAuthBasic)); + server->RegisterDefaultHandler( + PREFIXED_HANDLER("/auth-digest", &HandleAuthDigest)); + server->RegisterDefaultHandler( + PREFIXED_HANDLER("/server-redirect", &HandleServerRedirect)); + server->RegisterDefaultHandler(base::Bind(&HandleCrossSiteRedirect, server)); + server->RegisterDefaultHandler( + PREFIXED_HANDLER("/client-redirect", &HandleClientRedirect)); + server->RegisterDefaultHandler( + PREFIXED_HANDLER("/defaultresponse", &HandleDefaultResponse)); + server->RegisterDefaultHandler(PREFIXED_HANDLER("/slow", &HandleSlowServer)); + + // TODO(svaldez): HandleDownload + // TODO(svaldez): HandleDownloadFinish + // TODO(svaldez): HandleZipFile + // TODO(svaldez): HandleRangeReset + // TODO(svaldez): HandleSSLManySmallRecords + // TODO(svaldez): HandleChunkedServer + // TODO(svaldez): HandleGetSSLSessionCache + // TODO(svaldez): HandleGetChannelID + // TODO(svaldez): HandleGetClientCert + // TODO(svaldez): HandleClientCipherList + // TODO(svaldez): HandleEchoMultipartPost +} + +#undef PREFIXED_HANDLER + +} // namespace test_server +} // namespace net
diff --git a/net/test/embedded_test_server/default_handlers.h b/net/test/embedded_test_server/default_handlers.h new file mode 100644 index 0000000..90e6f1e --- /dev/null +++ b/net/test/embedded_test_server/default_handlers.h
@@ -0,0 +1,23 @@ +// 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 NET_TEST_EMBEDDED_TEST_SERVER_DEFAULT_HANDLERS_H_ +#define NET_TEST_EMBEDDED_TEST_SERVER_DEFAULT_HANDLERS_H_ + +#include "net/test/embedded_test_server/embedded_test_server.h" + +namespace net { +namespace test_server { + +// This file is only meant for compatibility with testserver.py. No +// additional handlers should be added here that don't affect multiple +// distinct tests. + +// Registers default handlers for use in tests. +void RegisterDefaultHandlers(EmbeddedTestServer* server); + +} // namespace test_server +} // namespace net + +#endif // NET_TEST_EMBEDDED_TEST_SERVER_DEFAULT_HANDLERS_H_
diff --git a/net/test/embedded_test_server/embedded_test_server.cc b/net/test/embedded_test_server/embedded_test_server.cc index fba8b0f0..6131ceef 100644 --- a/net/test/embedded_test_server/embedded_test_server.cc +++ b/net/test/embedded_test_server/embedded_test_server.cc
@@ -29,6 +29,7 @@ #include "net/socket/tcp_server_socket.h" #include "net/ssl/ssl_server_config.h" #include "net/test/cert_test_util.h" +#include "net/test/embedded_test_server/default_handlers.h" #include "net/test/embedded_test_server/embedded_test_server_connection_listener.h" #include "net/test/embedded_test_server/http_connection.h" #include "net/test/embedded_test_server/http_request.h" @@ -255,7 +256,7 @@ } void EmbeddedTestServer::AddDefaultHandlers(const base::FilePath& directory) { - // TODO(svaldez): Add additional default handlers. + RegisterDefaultHandlers(this); ServeFilesFromSourceDirectory(directory); }
diff --git a/printing/android/java/src/org/chromium/printing/PrintManagerDelegateImpl.java b/printing/android/java/src/org/chromium/printing/PrintManagerDelegateImpl.java index 7cdaeae..15a15df 100644 --- a/printing/android/java/src/org/chromium/printing/PrintManagerDelegateImpl.java +++ b/printing/android/java/src/org/chromium/printing/PrintManagerDelegateImpl.java
@@ -5,6 +5,7 @@ package org.chromium.printing; import android.annotation.TargetApi; +import android.app.Activity; import android.content.Context; import android.os.Build; import android.print.PrintAttributes; @@ -27,8 +28,8 @@ private static final String TAG = "cr.printing"; private final PrintManager mPrintManager; - public PrintManagerDelegateImpl(Context context) { - mPrintManager = (PrintManager) context.getSystemService(Context.PRINT_SERVICE); + public PrintManagerDelegateImpl(Activity activity) { + mPrintManager = (PrintManager) activity.getSystemService(Context.PRINT_SERVICE); } @Override
diff --git a/remoting/host/video_frame_pump.cc b/remoting/host/video_frame_pump.cc index 58b72db..9c82efe 100644 --- a/remoting/host/video_frame_pump.cc +++ b/remoting/host/video_frame_pump.cc
@@ -162,6 +162,9 @@ packet->set_capture_time_ms(frame->capture_time_ms()); timestamps->encode_ended_time = base::TimeTicks::Now(); + packet->set_encode_time_ms( + (timestamps->encode_ended_time - timestamps->encode_started_time) + .InMilliseconds()); return make_scoped_ptr( new PacketWithTimestamps(packet.Pass(), timestamps.Pass()));
diff --git a/remoting/protocol/channel_dispatcher_base.cc b/remoting/protocol/channel_dispatcher_base.cc index 6545061..0336e4fa3 100644 --- a/remoting/protocol/channel_dispatcher_base.cc +++ b/remoting/protocol/channel_dispatcher_base.cc
@@ -32,7 +32,7 @@ switch (config.transport) { case ChannelConfig::TRANSPORT_MUX_STREAM: channel_factory_ = - session->GetTransportSession()->GetMultiplexedChannelFactory(); + session->GetTransport()->GetMultiplexedChannelFactory(); break; case ChannelConfig::TRANSPORT_QUIC_STREAM: @@ -40,8 +40,7 @@ break; case ChannelConfig::TRANSPORT_STREAM: - channel_factory_ = - session->GetTransportSession()->GetStreamChannelFactory(); + channel_factory_ = session->GetTransport()->GetStreamChannelFactory(); break; default:
diff --git a/remoting/protocol/channel_multiplexer_unittest.cc b/remoting/protocol/channel_multiplexer_unittest.cc index d8394bf0..afc4458 100644 --- a/remoting/protocol/channel_multiplexer_unittest.cc +++ b/remoting/protocol/channel_multiplexer_unittest.cc
@@ -73,10 +73,10 @@ void SetUp() override { // Create pair of multiplexers and connect them to each other. host_mux_.reset(new ChannelMultiplexer( - host_session_.GetTransportSession()->GetStreamChannelFactory(), + host_session_.GetTransport()->GetStreamChannelFactory(), kMuxChannelName)); client_mux_.reset(new ChannelMultiplexer( - client_session_.GetTransportSession()->GetStreamChannelFactory(), + client_session_.GetTransport()->GetStreamChannelFactory(), kMuxChannelName)); } @@ -84,11 +84,11 @@ // one channel with each multiplexer. void ConnectSockets() { FakeStreamSocket* host_socket = - host_session_.GetTransportSession() + host_session_.GetTransport() ->GetStreamChannelFactory() ->GetFakeChannel(ChannelMultiplexer::kMuxChannelName); FakeStreamSocket* client_socket = - client_session_.GetTransportSession() + client_session_.GetTransport() ->GetStreamChannelFactory() ->GetFakeChannel(ChannelMultiplexer::kMuxChannelName); host_socket->PairWith(client_socket); @@ -249,9 +249,9 @@ ConnectSockets(); - FakeStreamSocket* socket = host_session_.GetTransportSession() - ->GetStreamChannelFactory() - ->GetFakeChannel(kMuxChannelName); + FakeStreamSocket* socket = + host_session_.GetTransport()->GetStreamChannelFactory()->GetFakeChannel( + kMuxChannelName); socket->set_next_write_error(net::ERR_FAILED); socket->set_async_write(false); @@ -285,9 +285,9 @@ ConnectSockets(); - FakeStreamSocket* socket = host_session_.GetTransportSession() - ->GetStreamChannelFactory() - ->GetFakeChannel(kMuxChannelName); + FakeStreamSocket* socket = + host_session_.GetTransport()->GetStreamChannelFactory()->GetFakeChannel( + kMuxChannelName); socket->set_next_write_error(net::ERR_FAILED); socket->set_async_write(true); @@ -320,9 +320,9 @@ ConnectSockets(); - FakeStreamSocket* socket = host_session_.GetTransportSession() - ->GetStreamChannelFactory() - ->GetFakeChannel(kMuxChannelName); + FakeStreamSocket* socket = + host_session_.GetTransport()->GetStreamChannelFactory()->GetFakeChannel( + kMuxChannelName); socket->set_next_write_error(net::ERR_FAILED); socket->set_async_write(true); @@ -356,9 +356,9 @@ } TEST_F(ChannelMultiplexerTest, SessionFail) { - host_session_.GetTransportSession()->GetStreamChannelFactory() + host_session_.GetTransport()->GetStreamChannelFactory() ->set_asynchronous_create(true); - host_session_.GetTransportSession()->GetStreamChannelFactory() + host_session_.GetTransport()->GetStreamChannelFactory() ->set_fail_create(true); MockConnectCallback cb1;
diff --git a/remoting/protocol/channel_socket_adapter.h b/remoting/protocol/channel_socket_adapter.h index 47d606b..f4a339f6 100644 --- a/remoting/protocol/channel_socket_adapter.h +++ b/remoting/protocol/channel_socket_adapter.h
@@ -21,8 +21,8 @@ namespace protocol { // TransportChannelSocketAdapter implements P2PDatagramSocket interface on -// top of libjingle's TransportChannel. It is used by IceTransportSession -// to provide P2PDatagramSocket interface for channels. +// top of libjingle's TransportChannel. It is used by IceTransport to provide +// P2PDatagramSocket interface for channels. class TransportChannelSocketAdapter : public P2PDatagramSocket, public sigslot::has_slots<> { public:
diff --git a/remoting/protocol/client_video_dispatcher_unittest.cc b/remoting/protocol/client_video_dispatcher_unittest.cc index 74bf7a3..8753fc8 100644 --- a/remoting/protocol/client_video_dispatcher_unittest.cc +++ b/remoting/protocol/client_video_dispatcher_unittest.cc
@@ -73,7 +73,7 @@ base::RunLoop().RunUntilIdle(); DCHECK(initialized_); host_socket_.PairWith( - session_.GetTransportSession()->GetStreamChannelFactory()->GetFakeChannel( + session_.GetTransport()->GetStreamChannelFactory()->GetFakeChannel( kVideoChannelName)); reader_.StartReading(&host_socket_, base::Bind(&ClientVideoDispatcherTest::OnReadError,
diff --git a/remoting/protocol/connection_to_client_unittest.cc b/remoting/protocol/connection_to_client_unittest.cc index 0dc9281e..e62c2cb 100644 --- a/remoting/protocol/connection_to_client_unittest.cc +++ b/remoting/protocol/connection_to_client_unittest.cc
@@ -74,9 +74,9 @@ // Verify that something has been written. // TODO(sergeyu): Verify that the correct data has been written. - FakeStreamSocket* channel = session_->GetTransportSession() - ->GetStreamChannelFactory() - ->GetFakeChannel(kVideoChannelName); + FakeStreamSocket* channel = + session_->GetTransport()->GetStreamChannelFactory()->GetFakeChannel( + kVideoChannelName); ASSERT_TRUE(channel); EXPECT_FALSE(channel->written_data().empty());
diff --git a/remoting/protocol/fake_session.cc b/remoting/protocol/fake_session.cc index 9e7d8fc..afebf4b 100644 --- a/remoting/protocol/fake_session.cc +++ b/remoting/protocol/fake_session.cc
@@ -9,30 +9,30 @@ const char kTestJid[] = "host1@gmail.com/chromoting123"; -FakeTransportSession::FakeTransportSession() {} -FakeTransportSession::~FakeTransportSession() {} +FakeTransport::FakeTransport() {} +FakeTransport::~FakeTransport() {} -void FakeTransportSession::Start(EventHandler* event_handler, +void FakeTransport::Start(EventHandler* event_handler, Authenticator* authenticator) { NOTREACHED(); } -bool FakeTransportSession::ProcessTransportInfo( +bool FakeTransport::ProcessTransportInfo( buzz::XmlElement* transport_info) { NOTREACHED(); return true; } -DatagramChannelFactory* FakeTransportSession::GetDatagramChannelFactory() { +DatagramChannelFactory* FakeTransport::GetDatagramChannelFactory() { NOTIMPLEMENTED(); return nullptr; } -FakeStreamChannelFactory* FakeTransportSession::GetStreamChannelFactory() { +FakeStreamChannelFactory* FakeTransport::GetStreamChannelFactory() { return &channel_factory_; } -FakeStreamChannelFactory* FakeTransportSession::GetMultiplexedChannelFactory() { +FakeStreamChannelFactory* FakeTransport::GetMultiplexedChannelFactory() { return &channel_factory_; } @@ -61,12 +61,12 @@ return *config_; } -FakeTransportSession* FakeSession::GetTransportSession() { - return &transport_session_; +FakeTransport* FakeSession::GetTransport() { + return &transport_; } FakeStreamChannelFactory* FakeSession::GetQuicChannelFactory() { - return transport_session_.GetStreamChannelFactory(); + return transport_.GetStreamChannelFactory(); } void FakeSession::Close() {
diff --git a/remoting/protocol/fake_session.h b/remoting/protocol/fake_session.h index 3ca7fc3..6800692 100644 --- a/remoting/protocol/fake_session.h +++ b/remoting/protocol/fake_session.h
@@ -19,12 +19,12 @@ extern const char kTestJid[]; -class FakeTransportSession : public TransportSession { +class FakeTransport : public Transport { public: - FakeTransportSession(); - ~FakeTransportSession() override; + FakeTransport(); + ~FakeTransport() override; - // TransportSession interface. + // Transport interface. void Start(EventHandler* event_handler, Authenticator* authenticator) override; bool ProcessTransportInfo(buzz::XmlElement* transport_info) override; @@ -54,7 +54,7 @@ ErrorCode error() override; const std::string& jid() override; const SessionConfig& config() override; - FakeTransportSession* GetTransportSession() override; + FakeTransport* GetTransport() override; FakeStreamChannelFactory* GetQuicChannelFactory() override; void Close() override; @@ -64,7 +64,7 @@ std::string jid_; - FakeTransportSession transport_session_; + FakeTransport transport_; ErrorCode error_; bool closed_;
diff --git a/remoting/protocol/ice_transport_session.cc b/remoting/protocol/ice_transport.cc similarity index 74% rename from remoting/protocol/ice_transport_session.cc rename to remoting/protocol/ice_transport.cc index 89f854a3..badc62cc 100644 --- a/remoting/protocol/ice_transport_session.cc +++ b/remoting/protocol/ice_transport.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 "remoting/protocol/ice_transport_session.h" +#include "remoting/protocol/ice_transport.h" #include "base/bind.h" #include "remoting/protocol/channel_authenticator.h" @@ -22,27 +22,26 @@ // Name of the multiplexed channel. static const char kMuxChannelName[] = "mux"; -IceTransportSession::IceTransportSession( - cricket::PortAllocator* port_allocator, - const NetworkSettings& network_settings, - TransportRole role) +IceTransport::IceTransport(cricket::PortAllocator* port_allocator, + const NetworkSettings& network_settings, + TransportRole role) : port_allocator_(port_allocator), network_settings_(network_settings), role_(role), weak_factory_(this) {} -IceTransportSession::~IceTransportSession() { +IceTransport::~IceTransport() { channel_multiplexer_.reset(); DCHECK(channels_.empty()); } -base::Closure IceTransportSession::GetCanStartClosure() { - return base::Bind(&IceTransportSession::OnCanStart, +base::Closure IceTransport::GetCanStartClosure() { + return base::Bind(&IceTransport::OnCanStart, weak_factory_.GetWeakPtr()); } -void IceTransportSession::Start(TransportSession::EventHandler* event_handler, - Authenticator* authenticator) { +void IceTransport::Start(Transport::EventHandler* event_handler, + Authenticator* authenticator) { DCHECK(event_handler); DCHECK(!event_handler_); @@ -52,8 +51,7 @@ pseudotcp_channel_factory_.get(), authenticator)); } -bool IceTransportSession::ProcessTransportInfo( - buzz::XmlElement* transport_info_xml) { +bool IceTransport::ProcessTransportInfo(buzz::XmlElement* transport_info_xml) { IceTransportInfo transport_info; if (!transport_info.ParseXml(transport_info_xml)) return false; @@ -85,15 +83,15 @@ return true; } -DatagramChannelFactory* IceTransportSession::GetDatagramChannelFactory() { +DatagramChannelFactory* IceTransport::GetDatagramChannelFactory() { return this; } -StreamChannelFactory* IceTransportSession::GetStreamChannelFactory() { +StreamChannelFactory* IceTransport::GetStreamChannelFactory() { return secure_channel_factory_.get(); } -StreamChannelFactory* IceTransportSession::GetMultiplexedChannelFactory() { +StreamChannelFactory* IceTransport::GetMultiplexedChannelFactory() { if (!channel_multiplexer_.get()) { channel_multiplexer_.reset( new ChannelMultiplexer(GetStreamChannelFactory(), kMuxChannelName)); @@ -101,7 +99,7 @@ return channel_multiplexer_.get(); } -void IceTransportSession::OnCanStart() { +void IceTransport::OnCanStart() { DCHECK(!can_start_); can_start_ = true; @@ -111,9 +109,8 @@ } } -void IceTransportSession::CreateChannel( - const std::string& name, - const ChannelCreatedCallback& callback) { +void IceTransport::CreateChannel(const std::string& name, + const ChannelCreatedCallback& callback) { DCHECK(!channels_[name]); scoped_ptr<IceTransportChannel> channel( @@ -125,7 +122,7 @@ channels_[name] = channel.release(); } -void IceTransportSession::CancelChannelCreation(const std::string& name) { +void IceTransport::CancelChannelCreation(const std::string& name) { ChannelsMap::iterator it = channels_.find(name); if (it != channels_.end()) { DCHECK(!it->second->is_connected()); @@ -134,8 +131,7 @@ } } -void IceTransportSession::AddPendingRemoteTransportInfo( - IceTransportChannel* channel) { +void IceTransport::AddPendingRemoteTransportInfo(IceTransportChannel* channel) { std::list<IceTransportInfo::IceCredentials>::iterator credentials = pending_remote_ice_credentials_.begin(); while (credentials != pending_remote_ice_credentials_.end()) { @@ -159,40 +155,38 @@ } } -void IceTransportSession::OnTransportIceCredentials( - IceTransportChannel* channel, - const std::string& ufrag, - const std::string& password) { +void IceTransport::OnTransportIceCredentials(IceTransportChannel* channel, + const std::string& ufrag, + const std::string& password) { EnsurePendingTransportInfoMessage(); pending_transport_info_message_->ice_credentials.push_back( IceTransportInfo::IceCredentials(channel->name(), ufrag, password)); } -void IceTransportSession::OnTransportCandidate( - IceTransportChannel* channel, - const cricket::Candidate& candidate) { +void IceTransport::OnTransportCandidate(IceTransportChannel* channel, + const cricket::Candidate& candidate) { EnsurePendingTransportInfoMessage(); pending_transport_info_message_->candidates.push_back( IceTransportInfo::NamedCandidate(channel->name(), candidate)); } -void IceTransportSession::OnTransportRouteChange(IceTransportChannel* channel, - const TransportRoute& route) { +void IceTransport::OnTransportRouteChange(IceTransportChannel* channel, + const TransportRoute& route) { if (event_handler_) event_handler_->OnTransportRouteChange(channel->name(), route); } -void IceTransportSession::OnTransportFailed(IceTransportChannel* channel) { +void IceTransport::OnTransportFailed(IceTransportChannel* channel) { event_handler_->OnTransportError(CHANNEL_CONNECTION_ERROR); } -void IceTransportSession::OnTransportDeleted(IceTransportChannel* channel) { +void IceTransport::OnTransportDeleted(IceTransportChannel* channel) { ChannelsMap::iterator it = channels_.find(channel->name()); DCHECK_EQ(it->second, channel); channels_.erase(it); } -void IceTransportSession::EnsurePendingTransportInfoMessage() { +void IceTransport::EnsurePendingTransportInfoMessage() { // |transport_info_timer_| must be running iff // |pending_transport_info_message_| exists. DCHECK_EQ(pending_transport_info_message_ != nullptr, @@ -204,11 +198,11 @@ // that we can send in one message. transport_info_timer_.Start( FROM_HERE, base::TimeDelta::FromMilliseconds(kTransportInfoSendDelayMs), - this, &IceTransportSession::SendTransportInfo); + this, &IceTransport::SendTransportInfo); } } -void IceTransportSession::SendTransportInfo() { +void IceTransport::SendTransportInfo() { DCHECK(pending_transport_info_message_); event_handler_->OnOutgoingTransportInfo( pending_transport_info_message_->ToXml());
diff --git a/remoting/protocol/ice_transport_session.h b/remoting/protocol/ice_transport.h similarity index 80% rename from remoting/protocol/ice_transport_session.h rename to remoting/protocol/ice_transport.h index 437f44f0..0e62f2f 100644 --- a/remoting/protocol/ice_transport_session.h +++ b/remoting/protocol/ice_transport.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 REMOTING_PROTOCOL_ICE_TRANSPORT_SESSION_H_ -#define REMOTING_PROTOCOL_ICE_TRANSPORT_SESSION_H_ +#ifndef REMOTING_PROTOCOL_ICE_TRANSPORT_H_ +#define REMOTING_PROTOCOL_ICE_TRANSPORT_H_ #include <list> #include <map> @@ -23,22 +23,22 @@ class PseudoTcpChannelFactory; class SecureChannelFactory; -class IceTransportSession : public TransportSession, - public IceTransportChannel::Delegate, - public DatagramChannelFactory { +class IceTransport : public Transport, + public IceTransportChannel::Delegate, + public DatagramChannelFactory { public: // |port_allocator| must outlive the session. - IceTransportSession(cricket::PortAllocator* port_allocator, - const NetworkSettings& network_settings, - TransportRole role); - ~IceTransportSession() override; + IceTransport(cricket::PortAllocator* port_allocator, + const NetworkSettings& network_settings, + TransportRole role); + ~IceTransport() override; // Returns a closure that must be called before transport channels start // connecting . base::Closure GetCanStartClosure(); - // TransportSession interface. - void Start(TransportSession::EventHandler* event_handler, + // Transport interface. + void Start(EventHandler* event_handler, Authenticator* authenticator) override; bool ProcessTransportInfo(buzz::XmlElement* transport_info) override; DatagramChannelFactory* GetDatagramChannelFactory() override; @@ -83,7 +83,7 @@ bool can_start_ = false; - TransportSession::EventHandler* event_handler_ = nullptr; + Transport::EventHandler* event_handler_ = nullptr; ChannelsMap channels_; scoped_ptr<PseudoTcpChannelFactory> pseudotcp_channel_factory_; @@ -98,13 +98,13 @@ scoped_ptr<IceTransportInfo> pending_transport_info_message_; base::OneShotTimer transport_info_timer_; - base::WeakPtrFactory<IceTransportSession> weak_factory_; + base::WeakPtrFactory<IceTransport> weak_factory_; - DISALLOW_COPY_AND_ASSIGN(IceTransportSession); + DISALLOW_COPY_AND_ASSIGN(IceTransport); }; } // namespace protocol } // namespace remoting -#endif // REMOTING_PROTOCOL_ICE_TRANSPORT_SESSION_H_ +#endif // REMOTING_PROTOCOL_ICE_TRANSPORT_H_
diff --git a/remoting/protocol/ice_transport_channel.h b/remoting/protocol/ice_transport_channel.h index ccaf106..a0dd6e7b 100644 --- a/remoting/protocol/ice_transport_channel.h +++ b/remoting/protocol/ice_transport_channel.h
@@ -64,7 +64,7 @@ TransportRole role); ~IceTransportChannel() override; - // Called by IceTransportSession when it has fresh Jingle info. + // Called by IceTransport when it has fresh Jingle info. void OnCanStart(); // Connects the channel and calls the |callback| after that.
diff --git a/remoting/protocol/ice_transport_factory.cc b/remoting/protocol/ice_transport_factory.cc index a4bc94d..19b14cb 100644 --- a/remoting/protocol/ice_transport_factory.cc +++ b/remoting/protocol/ice_transport_factory.cc
@@ -6,7 +6,7 @@ #include "base/single_thread_task_runner.h" #include "base/thread_task_runner_handle.h" -#include "remoting/protocol/ice_transport_session.h" +#include "remoting/protocol/ice_transport.h" #include "third_party/webrtc/p2p/client/httpportallocator.h" namespace remoting { @@ -33,10 +33,9 @@ task_runner->DeleteSoon(FROM_HERE, port_allocator_.release()); } -scoped_ptr<TransportSession> -IceTransportFactory::CreateTransportSession() { - scoped_ptr<IceTransportSession> result( - new IceTransportSession(port_allocator_.get(), network_settings_, role_)); +scoped_ptr<Transport> IceTransportFactory::CreateTransport() { + scoped_ptr<IceTransport> result( + new IceTransport(port_allocator_.get(), network_settings_, role_)); EnsureFreshJingleInfo();
diff --git a/remoting/protocol/ice_transport_factory.h b/remoting/protocol/ice_transport_factory.h index 63efe70..deaf72e 100644 --- a/remoting/protocol/ice_transport_factory.h +++ b/remoting/protocol/ice_transport_factory.h
@@ -32,7 +32,7 @@ ~IceTransportFactory() override; // TransportFactory interface. - scoped_ptr<TransportSession> CreateTransportSession() override; + scoped_ptr<Transport> CreateTransport() override; private: void EnsureFreshJingleInfo();
diff --git a/remoting/protocol/jingle_session.cc b/remoting/protocol/jingle_session.cc index 79654d1..c1b8b7b5 100644 --- a/remoting/protocol/jingle_session.cc +++ b/remoting/protocol/jingle_session.cc
@@ -66,7 +66,7 @@ JingleSession::~JingleSession() { quic_channel_factory_.reset(); - transport_session_.reset(); + transport_.reset(); STLDeleteContainerPointers(pending_requests_.begin(), pending_requests_.end()); @@ -102,8 +102,7 @@ // clients generate the same session ID concurrently. session_id_ = base::Uint64ToString(base::RandGenerator(kuint64max)); - transport_session_ = - session_manager_->transport_factory_->CreateTransportSession(); + transport_ = session_manager_->transport_factory_->CreateTransport(); quic_channel_factory_.reset(new QuicChannelFactory(session_id_, false)); // Send session-initiate message. @@ -151,8 +150,7 @@ } } - transport_session_ = - session_manager_->transport_factory_->CreateTransportSession(); + transport_ = session_manager_->transport_factory_->CreateTransport(); } void JingleSession::AcceptIncomingConnection( @@ -222,9 +220,9 @@ return *config_; } -TransportSession* JingleSession::GetTransportSession() { +Transport* JingleSession::GetTransport() { DCHECK(CalledOnValidThread()); - return transport_session_.get(); + return transport_.get(); } StreamChannelFactory* JingleSession::GetQuicChannelFactory() { @@ -368,8 +366,7 @@ break; case JingleMessage::TRANSPORT_INFO: - if (transport_session_->ProcessTransportInfo( - message.transport_info.get())) { + if (transport_->ProcessTransportInfo(message.transport_info.get())) { reply_callback.Run(JingleMessageReply::NONE); } else { reply_callback.Run(JingleMessageReply::BAD_REQUEST); @@ -547,12 +544,11 @@ } void JingleSession::OnAuthenticated() { - transport_session_->Start(this, authenticator_.get()); + transport_->Start(this, authenticator_.get()); if (quic_channel_factory_) { - quic_channel_factory_->Start( - transport_session_->GetDatagramChannelFactory(), - authenticator_->GetAuthKey()); + quic_channel_factory_->Start(transport_->GetDatagramChannelFactory(), + authenticator_->GetAuthKey()); } SetState(AUTHENTICATED);
diff --git a/remoting/protocol/jingle_session.h b/remoting/protocol/jingle_session.h index 9e595afe..f4734641 100644 --- a/remoting/protocol/jingle_session.h +++ b/remoting/protocol/jingle_session.h
@@ -33,7 +33,7 @@ // created by the JingleSessionManager. class JingleSession : public base::NonThreadSafe, public Session, - public TransportSession::EventHandler { + public Transport::EventHandler { public: ~JingleSession() override; @@ -42,7 +42,7 @@ ErrorCode error() override; const std::string& jid() override; const SessionConfig& config() override; - TransportSession* GetTransportSession() override; + Transport* GetTransport() override; StreamChannelFactory* GetQuicChannelFactory() override; void Close() override; @@ -72,7 +72,7 @@ IqRequest* request, const buzz::XmlElement* response); - // TransportSession::Delegate interface. + // Transport::EventHandler interface. void OnOutgoingTransportInfo( scoped_ptr<buzz::XmlElement> transport_info) override; void OnTransportRouteChange(const std::string& component, @@ -136,7 +136,7 @@ scoped_ptr<Authenticator> authenticator_; - scoped_ptr<TransportSession> transport_session_; + scoped_ptr<Transport> transport_; // Pending Iq requests. Used for all messages except transport-info. std::set<IqRequest*> pending_requests_;
diff --git a/remoting/protocol/jingle_session_unittest.cc b/remoting/protocol/jingle_session_unittest.cc index 8a7a910a..d578712 100644 --- a/remoting/protocol/jingle_session_unittest.cc +++ b/remoting/protocol/jingle_session_unittest.cc
@@ -255,16 +255,12 @@ } void CreateChannel() { - client_session_->GetTransportSession() - ->GetStreamChannelFactory() - ->CreateChannel(kChannelName, - base::Bind(&JingleSessionTest::OnClientChannelCreated, - base::Unretained(this))); - host_session_->GetTransportSession() - ->GetStreamChannelFactory() - ->CreateChannel(kChannelName, - base::Bind(&JingleSessionTest::OnHostChannelCreated, - base::Unretained(this))); + client_session_->GetTransport()->GetStreamChannelFactory()->CreateChannel( + kChannelName, base::Bind(&JingleSessionTest::OnClientChannelCreated, + base::Unretained(this))); + host_session_->GetTransport()->GetStreamChannelFactory()->CreateChannel( + kChannelName, base::Bind(&JingleSessionTest::OnHostChannelCreated, + base::Unretained(this))); int counter = 2; ExpectRouteChange(kChannelName); @@ -500,12 +496,12 @@ ASSERT_NO_FATAL_FAILURE( InitiateConnection(1, FakeAuthenticator::ACCEPT, false)); - client_session_->GetTransportSession() + client_session_->GetTransport() ->GetMultiplexedChannelFactory() ->CreateChannel(kChannelName, base::Bind(&JingleSessionTest::OnClientChannelCreated, base::Unretained(this))); - host_session_->GetTransportSession() + host_session_->GetTransport() ->GetMultiplexedChannelFactory() ->CreateChannel(kChannelName, base::Bind(&JingleSessionTest::OnHostChannelCreated, @@ -624,16 +620,12 @@ ASSERT_NO_FATAL_FAILURE( InitiateConnection(1, FakeAuthenticator::ACCEPT, false)); - client_session_->GetTransportSession() - ->GetStreamChannelFactory() - ->CreateChannel(kChannelName, - base::Bind(&JingleSessionTest::OnClientChannelCreated, - base::Unretained(this))); - host_session_->GetTransportSession() - ->GetStreamChannelFactory() - ->CreateChannel(kChannelName, - base::Bind(&JingleSessionTest::OnHostChannelCreated, - base::Unretained(this))); + client_session_->GetTransport()->GetStreamChannelFactory()->CreateChannel( + kChannelName, base::Bind(&JingleSessionTest::OnClientChannelCreated, + base::Unretained(this))); + host_session_->GetTransport()->GetStreamChannelFactory()->CreateChannel( + kChannelName, base::Bind(&JingleSessionTest::OnHostChannelCreated, + base::Unretained(this))); // Terminate the message loop when we get rejection notification // from the host. @@ -643,7 +635,7 @@ message_loop_->Run(); - client_session_->GetTransportSession() + client_session_->GetTransport() ->GetStreamChannelFactory() ->CancelChannelCreation(kChannelName); @@ -655,12 +647,12 @@ ASSERT_NO_FATAL_FAILURE( InitiateConnection(1, FakeAuthenticator::ACCEPT, false)); - client_session_->GetTransportSession() + client_session_->GetTransport() ->GetStreamChannelFactory() ->CreateChannel(kChannelName, base::Bind(&JingleSessionTest::OnClientChannelCreated, base::Unretained(this))); - client_session_->GetTransportSession() + client_session_->GetTransport() ->GetStreamChannelFactory() ->CancelChannelCreation(kChannelName);
diff --git a/remoting/protocol/protocol_mock_objects.h b/remoting/protocol/protocol_mock_objects.h index 0e65e84..6c67588 100644 --- a/remoting/protocol/protocol_mock_objects.h +++ b/remoting/protocol/protocol_mock_objects.h
@@ -202,7 +202,7 @@ MOCK_METHOD1(SetEventHandler, void(Session::EventHandler* event_handler)); MOCK_METHOD0(error, ErrorCode()); - MOCK_METHOD0(GetTransportSession, TransportSession*()); + MOCK_METHOD0(GetTransport, Transport*()); MOCK_METHOD0(GetQuicChannelFactory, StreamChannelFactory*()); MOCK_METHOD0(jid, const std::string&()); MOCK_METHOD0(candidate_config, const CandidateSessionConfig*());
diff --git a/remoting/protocol/session.h b/remoting/protocol/session.h index 4f068f8..9e539e5e 100644 --- a/remoting/protocol/session.h +++ b/remoting/protocol/session.h
@@ -14,7 +14,7 @@ namespace protocol { class StreamChannelFactory; -class TransportSession; +class Transport; struct TransportRoute; // Generic interface for Chromotocol connection used by both client and host. @@ -82,8 +82,8 @@ // Returned pointer is valid until connection is closed. virtual const SessionConfig& config() = 0; - // Returns TransportSession that can be used to create transport channels. - virtual TransportSession* GetTransportSession() = 0; + // Returns Transport that can be used to create transport channels. + virtual Transport* GetTransport() = 0; // Channel factory for QUIC-based channels. Returns nullptr when QUIC is // disabled for the session.
diff --git a/remoting/protocol/transport.h b/remoting/protocol/transport.h index 77b328e..08d0aa3 100644 --- a/remoting/protocol/transport.h +++ b/remoting/protocol/transport.h
@@ -53,9 +53,9 @@ net::IPEndPoint local_address; }; -// TransportSession represents a P2P connection that consists of one or more +// Transport represents a P2P connection that consists of one or more // channels. -class TransportSession { +class Transport { public: class EventHandler { public: @@ -71,10 +71,10 @@ virtual void OnTransportError(ErrorCode error) = 0; }; - TransportSession() {} - virtual ~TransportSession() {} + Transport() {} + virtual ~Transport() {} - // Starts transport session. Both parameters must outlive TransportSession. + // Starts transport session. Both parameters must outlive Transport. virtual void Start(EventHandler* event_handler, Authenticator* authenticator) = 0; @@ -93,7 +93,7 @@ virtual StreamChannelFactory* GetMultiplexedChannelFactory() = 0; private: - DISALLOW_COPY_AND_ASSIGN(TransportSession); + DISALLOW_COPY_AND_ASSIGN(Transport); }; class TransportFactory { @@ -101,8 +101,8 @@ TransportFactory() { } virtual ~TransportFactory() { } - // Creates a new TransportSession. The factory must outlive the session. - virtual scoped_ptr<TransportSession> CreateTransportSession() = 0; + // Creates a new Transport. The factory must outlive the session. + virtual scoped_ptr<Transport> CreateTransport() = 0; private: DISALLOW_COPY_AND_ASSIGN(TransportFactory);
diff --git a/remoting/remoting_srcs.gypi b/remoting/remoting_srcs.gypi index 7b96787d..aa41729 100644 --- a/remoting/remoting_srcs.gypi +++ b/remoting/remoting_srcs.gypi
@@ -125,8 +125,8 @@ 'protocol/ice_transport_channel.h', 'protocol/ice_transport_factory.cc', 'protocol/ice_transport_factory.h', - 'protocol/ice_transport_session.cc', - 'protocol/ice_transport_session.h', + 'protocol/ice_transport.cc', + 'protocol/ice_transport.h', 'protocol/input_event_tracker.cc', 'protocol/input_event_tracker.h', 'protocol/input_filter.cc',
diff --git a/sandbox/win/BUILD.gn b/sandbox/win/BUILD.gn index 28244db..c8bb770 100644 --- a/sandbox/win/BUILD.gn +++ b/sandbox/win/BUILD.gn
@@ -107,8 +107,6 @@ "src/security_level.h", "src/service_resolver.cc", "src/service_resolver.h", - "src/shared_handles.cc", - "src/shared_handles.h", "src/sharedmem_ipc_client.cc", "src/sharedmem_ipc_client.h", "src/sharedmem_ipc_server.cc",
diff --git a/sandbox/win/sandbox_win.gypi b/sandbox/win/sandbox_win.gypi index ebd17cb..08d512a 100644 --- a/sandbox/win/sandbox_win.gypi +++ b/sandbox/win/sandbox_win.gypi
@@ -114,8 +114,6 @@ 'src/security_level.h', 'src/service_resolver.cc', 'src/service_resolver.h', - 'src/shared_handles.cc', - 'src/shared_handles.h', 'src/sharedmem_ipc_client.cc', 'src/sharedmem_ipc_client.h', 'src/sharedmem_ipc_server.cc',
diff --git a/sandbox/win/src/shared_handles.cc b/sandbox/win/src/shared_handles.cc deleted file mode 100644 index 423b67b..0000000 --- a/sandbox/win/src/shared_handles.cc +++ /dev/null
@@ -1,67 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "sandbox/win/src/shared_handles.h" - -namespace sandbox { - -// Note once again the the assumption here is that the shared memory is -// initialized with zeros in the process that calls SetHandle and that -// the process that calls GetHandle 'sees' this memory. - -SharedHandles::SharedHandles() { - shared_.items = NULL; - shared_.max_items = 0; -} - -bool SharedHandles::Init(void* raw_mem, size_t size_bytes) { - if (size_bytes < sizeof(shared_.items[0])) { - // The shared memory is too small! - return false; - } - shared_.items = static_cast<SharedItem*>(raw_mem); - shared_.max_items = size_bytes / sizeof(shared_.items[0]); - return true; -} - -// Note that an empty slot is marked with a tag == 0 that is why is -// not a valid imput tag -bool SharedHandles::SetHandle(uint32 tag, HANDLE handle) { - if (0 == tag) { - // Invalid tag - return false; - } - // Find empty slot and put the tag and the handle there - SharedItem* empty_slot = FindByTag(0); - if (NULL == empty_slot) { - return false; - } - empty_slot->tag = tag; - empty_slot->item = handle; - return true; -} - -bool SharedHandles::GetHandle(uint32 tag, HANDLE* handle) { - if (0 == tag) { - // Invalid tag - return false; - } - SharedItem* found = FindByTag(tag); - if (NULL == found) { - return false; - } - *handle = found->item; - return true; -} - -SharedHandles::SharedItem* SharedHandles::FindByTag(uint32 tag) { - for (size_t ix = 0; ix != shared_.max_items; ++ix) { - if (tag == shared_.items[ix].tag) { - return &shared_.items[ix]; - } - } - return NULL; -} - -} // namespace sandbox
diff --git a/sandbox/win/src/shared_handles.h b/sandbox/win/src/shared_handles.h deleted file mode 100644 index 2c76bfb2..0000000 --- a/sandbox/win/src/shared_handles.h +++ /dev/null
@@ -1,108 +0,0 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef SANDBOX_SRC_SHARED_HANDLES_H__ -#define SANDBOX_SRC_SHARED_HANDLES_H__ - -#include "base/basictypes.h" - -#ifndef HANDLE -// We can provide our own windows compatilble handle definition, but -// in general we want to rely on the client of this api to include -// the proper windows headers. Note that we don't want to bring the -// whole <windows.h> into scope if we don't have to. -typedef void* HANDLE; -#endif - -namespace sandbox { - -// SharedHandles is a simple class to stash and find windows object handles -// given a raw block of memory which is shared between two processes. -// It addresses the need to communicate a handle value between two windows -// processes given that they are already sharing some memory. -// -// This class is not exposed directly to users of the sanbox API, instead -// we expose the wrapper methods TargetProcess::TransferHandle( ) and -// TargetServices::GetTransferHandle() -// -// Use it for a small number of items, since internaly uses linear seach -// -// The use is very simple. Given a shared memory between proces A and B: -// process A: -// HANDLE handle = SomeFunction(..); -// SharedHandles shared_handes; -// shared_handles.Init(memory) -// shared_handles.SetHandle(3, handle); -// -// process B: -// SharedHandles shared_handes; -// shared_handles.Init(memory) -// HANDLE handle = shared_handles.GetHandle(3); -// -// Note that '3' in this example is a unique id, that must be agreed before -// transfer -// -// Note2: While this class can be used in a single process, there are -// better alternatives such as STL -// -// Note3: Under windows a kernel object handle in one process does not -// make sense for another process unless there is a DuplicateHandle( ) -// call involved which this class DOES NOT do that for you. -// -// Note4: Under windows, shared memory when created is initialized to -// zeros always. If you are not using shared memory it is your responsability -// to zero it for the setter process and to copy it to the getter process. -class SharedHandles { - public: - SharedHandles(); - - // Initializes the shared memory for use. - // Pass the shared memory base and size. It will internally compute - // how many handles can it store. If initialization fails the return value - // is false. - bool Init(void* raw_mem, size_t size_bytes); - - // Sets a handle in the shared memory for transfer. - // Parameters: - // tag : an integer, different from zero that uniquely identfies the - // handle to transfer. - // handle: the handle value associated with 'tag' to tranfer - // Returns false if there is not enough space in the shared memory for - // this handle. - bool SetHandle(uint32 tag, HANDLE handle); - - // Gets a handle previously stored by SetHandle. - // Parameters: - // tag: an integer different from zero that uniquely identfies the handle - // to retrieve. - // *handle: output handle value if the call was succesful. - // If a handle with the provided tag is not found the return value is false. - // If the tag is found the return value is true. - bool GetHandle(uint32 tag, HANDLE* handle); - - private: - // A single item is the tuple handle/tag - struct SharedItem { - uint32 tag; - void* item; - }; - - // SharedMem is used to layout the memory as an array of SharedItems - struct SharedMem { - size_t max_items; - SharedItem* items; - }; - - // Finds an Item tuple provided the handle tag. - // Uses linear search because we expect the number of handles to be - // small (say less than ~100). - SharedItem* FindByTag(uint32 tag); - - SharedMem shared_; - DISALLOW_COPY_AND_ASSIGN(SharedHandles); -}; - -} // namespace sandbox - -#endif // SANDBOX_SRC_SHARED_HANDLES_H__
diff --git a/skia/ext/skia_utils_ios.h b/skia/ext/skia_utils_ios.h index 6a854ce..8e1ba9ad 100644 --- a/skia/ext/skia_utils_ios.h +++ b/skia/ext/skia_utils_ios.h
@@ -9,11 +9,14 @@ #include <vector> #include "third_party/skia/include/core/SkBitmap.h" +#include "third_party/skia/include/core/SkColor.h" #ifdef __OBJC__ +@class UIColor; @class UIImage; @class NSData; #else +class UIColor; class UIImage; class NSData; #endif @@ -35,6 +38,9 @@ // vector if none can be decoded. SK_API std::vector<SkBitmap> ImageDataToSkBitmaps(NSData* image_data); +// Returns a UIColor for an SKColor. Used by iOS downstream. +SK_API UIColor* UIColorFromSkColor(SkColor color); + } // namespace gfx #endif // SKIA_EXT_SKIA_UTILS_IOS_H_
diff --git a/skia/ext/skia_utils_ios.mm b/skia/ext/skia_utils_ios.mm index 5655d22..ec76cd5c 100644 --- a/skia/ext/skia_utils_ios.mm +++ b/skia/ext/skia_utils_ios.mm
@@ -123,4 +123,11 @@ return frames; } +UIColor* UIColorFromSkColor(SkColor color) { + return [UIColor colorWithRed:SkColorGetR(color) / 255.0f + green:SkColorGetG(color) / 255.0f + blue:SkColorGetB(color) / 255.0f + alpha:SkColorGetA(color) / 255.0f]; +} + } // namespace gfx
diff --git a/skia/ext/skia_utils_ios_unittest.mm b/skia/ext/skia_utils_ios_unittest.mm index 71f46a4e..02994727 100644 --- a/skia/ext/skia_utils_ios_unittest.mm +++ b/skia/ext/skia_utils_ios_unittest.mm
@@ -749,5 +749,16 @@ EXPECT_EQ(1UL, bitmaps.size()); } +TEST_F(SkiaUtilsIosTest, UIColorFromSkColor) { + SkColor color = SkColorSetARGB(50, 100, 150, 200); + UIColor* ios_color = gfx::UIColorFromSkColor(color); + CGFloat red, green, blue, alpha; + [ios_color getRed:&red green:&green blue:&blue alpha:&alpha]; + EXPECT_EQ(50, static_cast<int>(alpha * 255 + 0.5f)); + EXPECT_EQ(100, static_cast<int>(red * 255 + 0.5f)); + EXPECT_EQ(150, static_cast<int>(green * 255 + 0.5f)); + EXPECT_EQ(200, static_cast<int>(blue * 255 + 0.5f)); +} + } // namespace
diff --git a/storage/browser/blob/blob_data_builder.cc b/storage/browser/blob/blob_data_builder.cc index 94fb9e5..2ebfe89 100644 --- a/storage/browser/blob/blob_data_builder.cc +++ b/storage/browser/blob/blob_data_builder.cc
@@ -4,6 +4,8 @@ #include "storage/browser/blob/blob_data_builder.h" +#include "base/numerics/safe_conversions.h" +#include "base/numerics/safe_math.h" #include "base/time/time.h" #include "net/disk_cache/disk_cache.h" #include "storage/browser/blob/shareable_file_reference.h" @@ -15,6 +17,34 @@ BlobDataBuilder::~BlobDataBuilder() { } +void BlobDataBuilder::AppendIPCDataElement(const DataElement& ipc_data) { + uint64 length = ipc_data.length(); + switch (ipc_data.type()) { + case DataElement::TYPE_BYTES: + DCHECK(!ipc_data.offset()); + AppendData(ipc_data.bytes(), base::checked_cast<size_t, uint64>(length)); + break; + case DataElement::TYPE_FILE: + AppendFile(ipc_data.path(), ipc_data.offset(), length, + ipc_data.expected_modification_time()); + break; + case DataElement::TYPE_FILE_FILESYSTEM: + AppendFileSystemFile(ipc_data.filesystem_url(), ipc_data.offset(), length, + ipc_data.expected_modification_time()); + break; + case DataElement::TYPE_BLOB: + // This is a temporary item that will be deconstructed later in + // BlobStorageContext. + AppendBlob(ipc_data.blob_uuid(), ipc_data.offset(), ipc_data.length()); + break; + case DataElement::TYPE_BYTES_DESCRIPTION: + case DataElement::TYPE_UNKNOWN: + case DataElement::TYPE_DISK_CACHE_ENTRY: // This type can't be sent by IPC. + NOTREACHED(); + break; + } +} + void BlobDataBuilder::AppendData(const char* data, size_t length) { if (!length) return; @@ -23,6 +53,46 @@ items_.push_back(new BlobDataItem(element.Pass())); } +size_t BlobDataBuilder::AppendFutureData(size_t length) { + CHECK_NE(length, 0u); + scoped_ptr<DataElement> element(new DataElement()); + element->SetToBytesDescription(length); + items_.push_back(new BlobDataItem(element.Pass())); + return items_.size() - 1; +} + +bool BlobDataBuilder::PopulateFutureData(size_t index, + const char* data, + size_t offset, + size_t length) { + DCHECK(data); + DataElement* element = items_.at(index)->data_element_ptr(); + + // We lazily allocate our data buffer by waiting until the first + // PopulateFutureData call. + // Why? The reason we have the AppendFutureData method is to create our Blob + // record when the Renderer tells us about the blob without actually + // allocating the memory yet, as we might not have the quota yet. So we don't + // want to allocate the memory until we're actually receiving the data (which + // the browser process only does when it has quota). + if (element->type() == DataElement::TYPE_BYTES_DESCRIPTION) { + element->SetToAllocatedBytes(element->length()); + // The type of the element is now TYPE_BYTES. + } + if (element->type() != DataElement::TYPE_BYTES) { + DVLOG(1) << "Invalid item type."; + return false; + } + base::CheckedNumeric<size_t> checked_end = offset; + checked_end += length; + if (!checked_end.IsValid() || checked_end.ValueOrDie() > element->length()) { + DVLOG(1) << "Invalid offset or length."; + return false; + } + std::memcpy(element->mutable_bytes() + offset, data, length); + return true; +} + void BlobDataBuilder::AppendFile(const base::FilePath& file_path, uint64_t offset, uint64_t length, @@ -54,7 +124,7 @@ uint64_t offset, uint64_t length, const base::Time& expected_modification_time) { - DCHECK(length > 0); + DCHECK_GT(length, 0ul); scoped_ptr<DataElement> element(new DataElement()); element->SetToFileSystemUrlRange(url, offset, length, expected_modification_time); @@ -73,4 +143,23 @@ disk_cache_stream_index)); } +void BlobDataBuilder::Clear() { + items_.clear(); + content_disposition_.clear(); + content_type_.clear(); + uuid_.clear(); +} + +void PrintTo(const BlobDataBuilder& x, std::ostream* os) { + DCHECK(os); + *os << "<BlobDataBuilder>{uuid: " << x.uuid() + << ", content_type: " << x.content_type_ + << ", content_disposition: " << x.content_disposition_ << ", items: ["; + for (const auto& item : x.items_) { + PrintTo(*item, os); + *os << ", "; + } + *os << "]}"; +} + } // namespace storage
diff --git a/storage/browser/blob/blob_data_builder.h b/storage/browser/blob/blob_data_builder.h index 115d1f4..8627ebaf 100644 --- a/storage/browser/blob/blob_data_builder.h +++ b/storage/browser/blob/blob_data_builder.h
@@ -6,6 +6,7 @@ #define STORAGE_BROWSER_BLOB_BLOB_DATA_BUILDER_H_ #include <stdint.h> +#include <ostream> #include <string> #include <vector> @@ -32,12 +33,38 @@ const std::string& uuid() const { return uuid_; } + // Validates the data element that was sent over IPC, and copies the data if + // it's a 'bytes' element. Data elements of BYTES_DESCRIPTION or + // DISK_CACHE_ENTRY types are not valid IPC data element types, and cannot be + // given to this method. + void AppendIPCDataElement(const DataElement& ipc_data); + + // Copies the given data into the blob. void AppendData(const std::string& data) { AppendData(data.c_str(), data.size()); } + // Copies the given data into the blob. void AppendData(const char* data, size_t length); + // Adds an item that is flagged for future data population. The memory is not + // allocated until the first call to PopulateFutureData. Returns the index of + // the item (to be used in PopulateFutureData). + // Length cannot be 0. + size_t AppendFutureData(size_t length); + + // Populates a part of an item previously allocated with AppendFutureData. + // The first call to PopulateFutureData lazily allocates the memory for the + // data element. + // Returns true if: + // * The item was created by using AppendFutureData, + // * The offset and length are valid, and + // * data is a valid pointer. + bool PopulateFutureData(size_t index, + const char* data, + size_t offset, + size_t length); + // You must know the length of the file, you cannot use kuint64max to specify // the whole file. This method creates a ShareableFileReference to the given // file, which is stored in this builder. @@ -67,10 +94,15 @@ content_disposition_ = content_disposition; } + void Clear(); + private: friend class BlobStorageContext; + friend class BlobAsyncBuilderHostTest; friend bool operator==(const BlobDataBuilder& a, const BlobDataBuilder& b); friend bool operator==(const BlobDataSnapshot& a, const BlobDataBuilder& b); + friend STORAGE_EXPORT void PrintTo(const BlobDataBuilder& x, + ::std::ostream* os); std::string uuid_; std::string content_type_; @@ -89,7 +121,7 @@ if (a.items_.size() != b.items_.size()) return false; for (size_t i = 0; i < a.items_.size(); ++i) { - if (a.items_[i] != b.items_[i]) + if (*(a.items_[i]) != *(b.items_[i])) return false; } return true; @@ -119,6 +151,7 @@ inline bool operator!=(const BlobDataBuilder& a, const BlobDataBuilder& b) { return !(a == b); } + #endif // defined(UNIT_TEST) } // namespace storage
diff --git a/storage/browser/blob/blob_data_item.cc b/storage/browser/blob/blob_data_item.cc index c1ec3b3..b9ac29bc 100644 --- a/storage/browser/blob/blob_data_item.cc +++ b/storage/browser/blob/blob_data_item.cc
@@ -33,7 +33,15 @@ disk_cache_stream_index_(disk_cache_stream_index) { } -BlobDataItem::~BlobDataItem() { +BlobDataItem::~BlobDataItem() {} + +void PrintTo(const BlobDataItem& x, ::std::ostream* os) { + DCHECK(os); + *os << "<BlobDataItem>{item: "; + PrintTo(*x.item_, os); + *os << ", has_data_handle: " << (x.data_handle_.get() ? "true" : "false") + << ", disk_cache_entry_ptr: " << x.disk_cache_entry_ + << ", disk_cache_stream_index_: " << x.disk_cache_stream_index_ << "}"; } } // namespace storage
diff --git a/storage/browser/blob/blob_data_item.h b/storage/browser/blob/blob_data_item.h index 5b25db4..d04a02c85 100644 --- a/storage/browser/blob/blob_data_item.h +++ b/storage/browser/blob/blob_data_item.h
@@ -5,6 +5,9 @@ #ifndef STORAGE_BROWSER_BLOB_BLOB_DATA_ITEM_H_ #define STORAGE_BROWSER_BLOB_BLOB_DATA_ITEM_H_ +#include <ostream> +#include <string> + #include "base/basictypes.h" #include "base/memory/ref_counted.h" #include "storage/browser/storage_browser_export.h" @@ -50,6 +53,7 @@ } const DataElement& data_element() const { return *item_; } const DataElement* data_element_ptr() const { return item_.get(); } + DataElement* data_element_ptr() { return item_.get(); } disk_cache::Entry* disk_cache_entry() const { return disk_cache_entry_; } int disk_cache_stream_index() const { return disk_cache_stream_index_; } @@ -58,8 +62,9 @@ friend class BlobDataBuilder; friend class BlobStorageContext; friend class base::RefCounted<BlobDataItem>; + friend STORAGE_EXPORT void PrintTo(const BlobDataItem& x, ::std::ostream* os); - BlobDataItem(scoped_ptr<DataElement> item); + explicit BlobDataItem(scoped_ptr<DataElement> item); BlobDataItem(scoped_ptr<DataElement> item, const scoped_refptr<DataHandle>& data_handle); BlobDataItem(scoped_ptr<DataElement> item,
diff --git a/storage/browser/blob/blob_reader.cc b/storage/browser/blob/blob_reader.cc index ccb4e55..9c6375d 100644 --- a/storage/browser/blob/blob_reader.cc +++ b/storage/browser/blob/blob_reader.cc
@@ -539,6 +539,7 @@ .Pass(); case DataElement::TYPE_BLOB: case DataElement::TYPE_BYTES: + case DataElement::TYPE_BYTES_DESCRIPTION: case DataElement::TYPE_DISK_CACHE_ENTRY: case DataElement::TYPE_UNKNOWN: break;
diff --git a/storage/browser/blob/view_blob_internals_job.cc b/storage/browser/blob/view_blob_internals_job.cc index 1b5e91ef..185338bb 100644 --- a/storage/browser/blob/view_blob_internals_job.cc +++ b/storage/browser/blob/view_blob_internals_job.cc
@@ -223,6 +223,7 @@ AddHTMLListItem(kType, "disk cache entry", out); AddHTMLListItem(kURL, item.disk_cache_entry()->GetKey(), out); break; + case DataElement::TYPE_BYTES_DESCRIPTION: case DataElement::TYPE_UNKNOWN: NOTREACHED(); break;
diff --git a/storage/common/BUILD.gn b/storage/common/BUILD.gn index c6bfd6a..605fd41 100644 --- a/storage/common/BUILD.gn +++ b/storage/common/BUILD.gn
@@ -6,6 +6,11 @@ component("common") { output_name = "storage_common" sources = [ + "blob_storage/blob_item_bytes_request.cc", + "blob_storage/blob_item_bytes_request.h", + "blob_storage/blob_item_bytes_response.cc", + "blob_storage/blob_item_bytes_response.h", + "blob_storage/blob_storage_constants.h", "data_element.cc", "data_element.h", "database/database_connections.cc",
diff --git a/storage/common/blob_storage/blob_item_bytes_request.cc b/storage/common/blob_storage/blob_item_bytes_request.cc new file mode 100644 index 0000000..13ef4840 --- /dev/null +++ b/storage/common/blob_storage/blob_item_bytes_request.cc
@@ -0,0 +1,81 @@ +// 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 "storage/common/blob_storage/blob_item_bytes_request.h" + +namespace storage { + +BlobItemBytesRequest BlobItemBytesRequest::CreateIPCRequest( + size_t request_number, + size_t renderer_item_index, + size_t renderer_item_offset, + size_t size) { + return BlobItemBytesRequest(request_number, IPCBlobItemRequestStrategy::IPC, + renderer_item_index, renderer_item_offset, size, + kInvalidIndex, kInvalidSize); +} +BlobItemBytesRequest BlobItemBytesRequest::CreateSharedMemoryRequest( + size_t request_number, + size_t renderer_item_index, + size_t renderer_item_offset, + size_t size, + size_t handle_index, + uint64_t handle_offset) { + return BlobItemBytesRequest(request_number, + IPCBlobItemRequestStrategy::SHARED_MEMORY, + renderer_item_index, renderer_item_offset, size, + handle_index, handle_offset); +} + +BlobItemBytesRequest BlobItemBytesRequest::CreateFileRequest( + size_t request_number, + size_t renderer_item_index, + uint64_t renderer_item_offset, + uint64_t size, + size_t handle_index, + uint64_t handle_offset) { + return BlobItemBytesRequest(request_number, IPCBlobItemRequestStrategy::FILE, + renderer_item_index, renderer_item_offset, size, + handle_index, handle_offset); +} + +BlobItemBytesRequest::BlobItemBytesRequest() + : request_number(kInvalidIndex), + transport_strategy(IPCBlobItemRequestStrategy::UNKNOWN), + renderer_item_index(kInvalidIndex), + renderer_item_offset(kInvalidSize), + size(kInvalidSize), + handle_index(kInvalidIndex), + handle_offset(kInvalidSize) {} + +BlobItemBytesRequest::BlobItemBytesRequest( + size_t request_number, + IPCBlobItemRequestStrategy transport_strategy, + size_t renderer_item_index, + uint64_t renderer_item_offset, + uint64_t size, + size_t handle_index, + uint64_t handle_offset) + : request_number(request_number), + transport_strategy(transport_strategy), + renderer_item_index(renderer_item_index), + renderer_item_offset(renderer_item_offset), + size(size), + handle_index(handle_index), + handle_offset(handle_offset) {} + +BlobItemBytesRequest::~BlobItemBytesRequest() {} + +void PrintTo(const BlobItemBytesRequest& request, std::ostream* os) { + *os << "{request_number: " << request.request_number + << ", transport_strategy: " + << static_cast<int>(request.transport_strategy) + << ", renderer_item_index: " << request.renderer_item_index + << ", renderer_item_offset: " << request.renderer_item_offset + << ", size: " << request.size + << ", handle_index: " << request.handle_index + << ", handle_offset: " << request.handle_offset << "}"; +} + +} // namespace storage
diff --git a/storage/common/blob_storage/blob_item_bytes_request.h b/storage/common/blob_storage/blob_item_bytes_request.h new file mode 100644 index 0000000..4031309 --- /dev/null +++ b/storage/common/blob_storage/blob_item_bytes_request.h
@@ -0,0 +1,86 @@ +// 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 STORAGE_COMMON_BLOB_STORAGE_BLOB_ITEM_BYTES_REQUEST_H_ +#define STORAGE_COMMON_BLOB_STORAGE_BLOB_ITEM_BYTES_REQUEST_H_ + +#include <stdint.h> +#include <ostream> + +#include "base/basictypes.h" +#include "storage/common/blob_storage/blob_storage_constants.h" +#include "storage/common/storage_common_export.h" + +namespace storage { + +// This class is serialized over IPC to request bytes from a blob item. +struct STORAGE_COMMON_EXPORT BlobItemBytesRequest { + // Not using std::numeric_limits<T>::max() because of non-C++11 builds. + static const size_t kInvalidIndex = SIZE_MAX; + static const uint64_t kInvalidSize = kuint64max; + + static BlobItemBytesRequest CreateIPCRequest(size_t request_number, + size_t renderer_item_index, + size_t renderer_item_offset, + size_t size); + + static BlobItemBytesRequest CreateSharedMemoryRequest( + size_t request_number, + size_t renderer_item_index, + size_t renderer_item_offset, + size_t size, + size_t handle_index, + uint64_t handle_offset); + + static BlobItemBytesRequest CreateFileRequest(size_t request_number, + size_t renderer_item_index, + uint64_t renderer_item_offset, + uint64_t size, + size_t handle_index, + uint64_t handle_offset); + + BlobItemBytesRequest(); + BlobItemBytesRequest(size_t request_number, + IPCBlobItemRequestStrategy transport_strategy, + size_t renderer_item_index, + uint64_t renderer_item_offset, + uint64_t size, + size_t handle_index, + uint64_t handle_offset); + ~BlobItemBytesRequest(); + + // The request number uniquely identifies the memory request. We can't use + // the renderer item index or browser item index as there can be multiple + // requests for both (as segmentation boundaries can exist in both). + size_t request_number; + IPCBlobItemRequestStrategy transport_strategy; + size_t renderer_item_index; + uint64_t renderer_item_offset; + uint64_t size; + size_t handle_index; + uint64_t handle_offset; +}; + +STORAGE_COMMON_EXPORT void PrintTo(const BlobItemBytesRequest& request, + std::ostream* os); + +#if defined(UNIT_TEST) +STORAGE_COMMON_EXPORT inline bool operator==(const BlobItemBytesRequest& a, + const BlobItemBytesRequest& b) { + return a.request_number == b.request_number && + a.transport_strategy == b.transport_strategy && + a.renderer_item_index == b.renderer_item_index && + a.renderer_item_offset == b.renderer_item_offset && a.size == b.size && + a.handle_index == b.handle_index && a.handle_offset == b.handle_offset; +} + +STORAGE_COMMON_EXPORT inline bool operator!=(const BlobItemBytesRequest& a, + const BlobItemBytesRequest& b) { + return !(a == b); +} +#endif // defined(UNIT_TEST) + +} // namespace storage + +#endif // STORAGE_COMMON_BLOB_STORAGE_BLOB_ITEM_BYTES_REQUEST_H_
diff --git a/storage/common/blob_storage/blob_item_bytes_response.cc b/storage/common/blob_storage/blob_item_bytes_response.cc new file mode 100644 index 0000000..ccb2598 --- /dev/null +++ b/storage/common/blob_storage/blob_item_bytes_response.cc
@@ -0,0 +1,39 @@ +// 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 "storage/common/blob_storage/blob_item_bytes_response.h" + +#include <algorithm> +#include <string> + +#include "base/strings/string_number_conversions.h" + +namespace storage { + +BlobItemBytesResponse::BlobItemBytesResponse() + : request_number(kInvalidIndex) {} + +BlobItemBytesResponse::BlobItemBytesResponse(size_t request_number) + : request_number(request_number) {} + +BlobItemBytesResponse::~BlobItemBytesResponse() {} + +void PrintTo(const BlobItemBytesResponse& response, ::std::ostream* os) { + const size_t kMaxDataPrintLength = 40; + size_t length = std::min(response.inline_data.size(), kMaxDataPrintLength); + *os << "{request_number: " << response.request_number + << ", inline_data size: " << response.inline_data.size() + << ", inline_data: ["; + if (length == 0) { + *os << "<empty>"; + } else { + *os << base::HexEncode(&response.inline_data[0], length); + if (length < response.inline_data.size()) { + *os << "<...truncated due to length...>"; + } + } + *os << "]}"; +} + +} // namespace storage
diff --git a/storage/common/blob_storage/blob_item_bytes_response.h b/storage/common/blob_storage/blob_item_bytes_response.h new file mode 100644 index 0000000..f2aa9c70 --- /dev/null +++ b/storage/common/blob_storage/blob_item_bytes_response.h
@@ -0,0 +1,58 @@ +// 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 STORAGE_COMMON_BLOB_STORAGE_BLOB_ITEM_BYTES_RESPONSE_H_ +#define STORAGE_COMMON_BLOB_STORAGE_BLOB_ITEM_BYTES_RESPONSE_H_ + +#include <stdint.h> +#include <algorithm> +#include <ostream> +#include <vector> + +#include "base/basictypes.h" +#include "storage/common/storage_common_export.h" + +namespace storage { + +// This class is serialized over IPC to send blob item data, or to signal that +// the memory has been populated. +struct STORAGE_COMMON_EXPORT BlobItemBytesResponse { + // not using std::numeric_limits<T>::max() because of non-C++11 builds. + static const size_t kInvalidIndex = SIZE_MAX; + + BlobItemBytesResponse(); + explicit BlobItemBytesResponse(size_t request_number); + ~BlobItemBytesResponse(); + + char* allocate_mutable_data(size_t size) { + inline_data.resize(size); + return &inline_data[0]; + } + + size_t request_number; + std::vector<char> inline_data; +}; + +STORAGE_COMMON_EXPORT void PrintTo(const BlobItemBytesResponse& response, + std::ostream* os); + +#if defined(UNIT_TEST) +STORAGE_COMMON_EXPORT inline bool operator==(const BlobItemBytesResponse& a, + const BlobItemBytesResponse& b) { + return a.request_number == b.request_number && + a.inline_data.size() == b.inline_data.size() && + std::equal(a.inline_data.begin(), + a.inline_data.begin() + a.inline_data.size(), + b.inline_data.begin()); +} + +STORAGE_COMMON_EXPORT inline bool operator!=(const BlobItemBytesResponse& a, + const BlobItemBytesResponse& b) { + return !(a == b); +} +#endif // defined(UNIT_TEST) + +} // namespace storage + +#endif // STORAGE_COMMON_BLOB_STORAGE_BLOB_ITEM_BYTES_RESPONSE_H_
diff --git a/storage/common/blob_storage/blob_storage_constants.h b/storage/common/blob_storage/blob_storage_constants.h new file mode 100644 index 0000000..ddf97ec0 --- /dev/null +++ b/storage/common/blob_storage/blob_storage_constants.h
@@ -0,0 +1,37 @@ +// 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 STORAGE_COMMON_BLOB_STORAGE_BLOB_STORAGE_CONSTANTS_H_ +#define STORAGE_COMMON_BLOB_STORAGE_BLOB_STORAGE_CONSTANTS_H_ + +namespace storage { + +// TODO(michaeln): use base::SysInfo::AmountOfPhysicalMemoryMB() in some +// way to come up with a better limit. +const int64 kBlobStorageMaxMemoryUsage = 500 * 1024 * 1024; // Half a gig. +const size_t kBlobStorageIPCThresholdBytes = 250 * 1024; +const size_t kBlobStorageMaxSharedMemoryBytes = 10 * 1024 * 1024; +const uint64_t kBlobStorageMaxFileSizeBytes = 100 * 1024 * 1024; +const uint64_t kBlobStorageMinFileSizeBytes = 1 * 1024 * 1024; +const size_t kBlobStorageMaxBlobMemorySize = + kBlobStorageMaxMemoryUsage - kBlobStorageMinFileSizeBytes; + +enum class IPCBlobItemRequestStrategy { + UNKNOWN = 0, + IPC, + SHARED_MEMORY, + FILE, + LAST = FILE +}; + +enum class IPCBlobCreationCancelCode { + UNKNOWN = 0, + OUT_OF_MEMORY, + FILE_WRITE_FAILED, + LAST = FILE_WRITE_FAILED +}; + +} // namespace storage + +#endif // STORAGE_COMMON_BLOB_STORAGE_BLOB_STORAGE_CONSTANTS_H_
diff --git a/storage/common/data_element.cc b/storage/common/data_element.cc index f26058b..c9bbf0e4 100644 --- a/storage/common/data_element.cc +++ b/storage/common/data_element.cc
@@ -4,6 +4,10 @@ #include "storage/common/data_element.h" +#include <algorithm> + +#include "base/strings/string_number_conversions.h" + namespace storage { DataElement::DataElement() @@ -52,4 +56,41 @@ length_ = length; } +void PrintTo(const DataElement& x, std::ostream* os) { + const uint64 kMaxDataPrintLength = 40; + *os << "<DataElement>{type: "; + switch (x.type()) { + case DataElement::TYPE_BYTES: { + uint64 length = std::min(x.length(), kMaxDataPrintLength); + *os << "TYPE_BYTES, data: [" + << base::HexEncode(x.bytes(), static_cast<size_t>(length)); + if (length < x.length()) { + *os << "<...truncated due to length...>"; + } + *os << "]"; + break; + } + case DataElement::TYPE_FILE: + *os << "TYPE_FILE, path: " << x.path().AsUTF8Unsafe() + << ", expected_modification_time: " << x.expected_modification_time(); + break; + case DataElement::TYPE_BLOB: + *os << "TYPE_BLOB, uuid: " << x.blob_uuid(); + break; + case DataElement::TYPE_FILE_FILESYSTEM: + *os << "TYPE_FILE_FILESYSTEM, filesystem_url: " << x.filesystem_url(); + break; + case DataElement::TYPE_DISK_CACHE_ENTRY: + *os << "TYPE_DISK_CACHE_ENTRY"; + break; + case DataElement::TYPE_BYTES_DESCRIPTION: + *os << "TYPE_BYTES_DESCRIPTION"; + break; + case DataElement::TYPE_UNKNOWN: + *os << "TYPE_UNKNOWN"; + break; + } + *os << ", length: " << x.length() << ", offset: " << x.offset() << "}"; +} + } // namespace storage
diff --git a/storage/common/data_element.h b/storage/common/data_element.h index 2eeca8e..4cd68630 100644 --- a/storage/common/data_element.h +++ b/storage/common/data_element.h
@@ -5,6 +5,7 @@ #ifndef STORAGE_COMMON_DATA_ELEMENT_H_ #define STORAGE_COMMON_DATA_ELEMENT_H_ +#include <ostream> #include <string> #include <vector> @@ -24,6 +25,8 @@ enum Type { TYPE_UNKNOWN = -1, TYPE_BYTES, + // Only used with BlobStorageMsg_StartBuildingBlob + TYPE_BYTES_DESCRIPTION, TYPE_FILE, TYPE_BLOB, TYPE_FILE_FILESYSTEM, @@ -44,9 +47,14 @@ return expected_modification_time_; } + // For use with SetToAllocatedBytes. Should only be used after calling + // SetToAllocatedBytes. + char* mutable_bytes() { return &buf_[0]; } + // Sets TYPE_BYTES data. This copies the given data into the element. void SetToBytes(const char* bytes, int bytes_len) { type_ = TYPE_BYTES; + bytes_ = nullptr; buf_.assign(bytes, bytes + bytes_len); length_ = buf_.size(); } @@ -70,6 +78,12 @@ length_ = buf_.size(); } + void SetToBytesDescription(size_t bytes_len) { + type_ = TYPE_BYTES_DESCRIPTION; + bytes_ = nullptr; + length_ = bytes_len; + } + // Sets TYPE_BYTES data. This does NOT copy the given data and the caller // should make sure the data is alive when this element is accessed. // You cannot use AppendBytes with this method. @@ -79,6 +93,16 @@ length_ = bytes_len; } + // Sets TYPE_BYTES data. This allocates the space for the bytes in the + // internal vector but does not populate it with anything. The caller can + // then use the bytes() method to access this buffer and populate it. + void SetToAllocatedBytes(size_t bytes_len) { + type_ = TYPE_BYTES; + bytes_ = nullptr; + buf_.resize(bytes_len); + length_ = bytes_len; + } + // Sets TYPE_FILE data. void SetToFilePath(const base::FilePath& path) { SetToFilePathRange(path, 0, kuint64max, base::Time()); @@ -107,6 +131,8 @@ void SetToDiskCacheEntryRange(uint64 offset, uint64 length); private: + friend STORAGE_COMMON_EXPORT void PrintTo(const DataElement& x, + ::std::ostream* os); Type type_; std::vector<char> buf_; // For TYPE_BYTES. const char* bytes_; // For TYPE_BYTES. @@ -138,6 +164,8 @@ // We compare only length and offset; we trust the entry itself was // compared at some higher level such as in BlobDataItem. return true; + case DataElement::TYPE_BYTES_DESCRIPTION: + return true; case DataElement::TYPE_UNKNOWN: NOTREACHED(); return false;
diff --git a/storage/storage_common.gyp b/storage/storage_common.gyp index 74b91391..305a612 100644 --- a/storage/storage_common.gyp +++ b/storage/storage_common.gyp
@@ -20,6 +20,11 @@ ], 'defines': ['STORAGE_COMMON_IMPLEMENTATION'], 'sources': [ + 'common/blob_storage/blob_item_bytes_request.cc', + 'common/blob_storage/blob_item_bytes_request.h', + 'common/blob_storage/blob_item_bytes_response.cc', + 'common/blob_storage/blob_item_bytes_response.h', + 'common/blob_storage/blob_storage_constants.h', 'common/data_element.cc', 'common/data_element.h', 'common/database/database_connections.cc',
diff --git a/third_party/WebKit/LayoutTests/TestExpectations b/third_party/WebKit/LayoutTests/TestExpectations index d71c9f6..b04fbf3 100644 --- a/third_party/WebKit/LayoutTests/TestExpectations +++ b/third_party/WebKit/LayoutTests/TestExpectations
@@ -1551,8 +1551,6 @@ crbug.com/538717 [ Win Mac Linux ] http/tests/permissions/chromium/test-request-multiple-worker.html [ Failure Pass Timeout ] crbug.com/538717 [ Win Mac Linux ] http/tests/permissions/chromium/test-request-multiple-sharedworker.html [ Failure Pass Timeout ] -crbug.com/549594 [ SnowLeopard ] svg/text/text-selection-ws-02-t.svg [ NeedsRebaseline ] - crbug.com/541601 svg/overflow/overflow-on-outermost-svg-element-in-xhtml-defaults.xhtml [ Failure ] crbug.com/543369 [ Linux ] fast/forms/select/popup-menu-appearance-tall.html [ Failure ] @@ -1567,3 +1565,7 @@ crbug.com/549314 [ XP ] inspector-protocol/layout-fonts/unicode-range-combining-chars-fallback.html [ Failure ] +crbug.com/540761 fast/canvas/canvas-imageSmoothingQuality-pixel.html [ NeedsRebaseline ] +crbug.com/540761 virtual/gpu/fast/canvas/canvas-imageSmoothingQuality-pixel.html [ NeedsRebaseline ] +crbug.com/540761 virtual/display_list_2d_canvas/fast/canvas/canvas-imageSmoothingQuality-pixel.html [ NeedsRebaseline ] +
diff --git a/third_party/WebKit/LayoutTests/compositing/squashing/add-remove-squashed-layers-expected.txt b/third_party/WebKit/LayoutTests/compositing/squashing/add-remove-squashed-layers-expected.txt index 42c3afca..49a7939d 100644 --- a/third_party/WebKit/LayoutTests/compositing/squashing/add-remove-squashed-layers-expected.txt +++ b/third_party/WebKit/LayoutTests/compositing/squashing/add-remove-squashed-layers-expected.txt
@@ -157,7 +157,6 @@ "repaintRects": [ [80, 80, 100, 100], [0, 0, 100, 100], - [0, 0, 100, 100], [0, 0, 100, 100] ] } @@ -194,7 +193,6 @@ [80, 80, 100, 100], [80, 80, 100, 100], [0, 0, 100, 100], - [0, 0, 100, 100], [0, 0, 100, 100] ] }
diff --git a/third_party/WebKit/LayoutTests/compositing/will-change/containing-block-added-expected.html b/third_party/WebKit/LayoutTests/compositing/will-change/containing-block-added-expected.html deleted file mode 100644 index a45bfef..0000000 --- a/third_party/WebKit/LayoutTests/compositing/will-change/containing-block-added-expected.html +++ /dev/null
@@ -1,32 +0,0 @@ -<!DOCTYPE html> -<html> -<head> - <style> - #container { - transform: translateZ(0); - position: absolute; - left: 200px; - top: 100px; - width: 100px; - height: 100px; - background-color: blue; - } - - .fixed { - position: fixed; - left: 50px; - top: 50px; - width: 75px; - height: 75px; - background-color: green - } - </style> -</head> - -<body> - <div id="container"> - <div class="fixed"></div> - </div> -</body> - -</html>
diff --git a/third_party/WebKit/LayoutTests/compositing/will-change/containing-block-added-expected.png b/third_party/WebKit/LayoutTests/compositing/will-change/containing-block-added-expected.png new file mode 100644 index 0000000..fbe3c719 --- /dev/null +++ b/third_party/WebKit/LayoutTests/compositing/will-change/containing-block-added-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/compositing/will-change/containing-block-added-expected.txt b/third_party/WebKit/LayoutTests/compositing/will-change/containing-block-added-expected.txt new file mode 100644 index 0000000..65e90a6 --- /dev/null +++ b/third_party/WebKit/LayoutTests/compositing/will-change/containing-block-added-expected.txt
@@ -0,0 +1,32 @@ +{ + "bounds": [800, 600], + "children": [ + { + "bounds": [800, 600], + "contentsOpaque": true, + "drawsContent": true, + "repaintRects": [ + [50, 50, 75, 75] + ], + "paintInvalidationClients": [ + "LayoutBlockFlow (positioned) DIV class='fixed'" + ], + "children": [ + { + "position": [200, 100], + "transformOrigin": [50, 50], + "bounds": [125, 125], + "drawsContent": true, + "backgroundColor": "#0000FF", + "repaintRects": [ + [50, 50, 75, 75] + ], + "paintInvalidationClients": [ + "LayoutBlockFlow (positioned) DIV class='fixed'" + ] + } + ] + } + ] +} +
diff --git a/third_party/WebKit/LayoutTests/compositing/will-change/containing-block-added.html b/third_party/WebKit/LayoutTests/compositing/will-change/containing-block-added.html index 37498dc..dd65d4d 100644 --- a/third_party/WebKit/LayoutTests/compositing/will-change/containing-block-added.html +++ b/third_party/WebKit/LayoutTests/compositing/will-change/containing-block-added.html
@@ -21,26 +21,16 @@ background-color: green } </style> - <script type="text/javascript"> - if (window.testRunner) { - testRunner.waitUntilDone(); - } - - function doTest() + <script src="../../fast/repaint/resources/text-based-repaint.js"></script> + <script> + function repaintTest() { - if (window.internals) { - window.internals.forceCompositingUpdate(document); - } // Adding "will-change: -webkit-transform" to the container div should // make this div become the containing block for its fixed position // descendant. - document.getElementById("container").style.willChange = "-webkit-transform"; - if (window.testRunner) { - testRunner.notifyDone(); - } + document.getElementById("container").style.willChange = "transform"; } - - window.addEventListener('load', doTest, false); + onload = runRepaintAndPixelTest; </script> </head>
diff --git a/third_party/WebKit/LayoutTests/compositing/will-change/containing-block-removed-expected.html b/third_party/WebKit/LayoutTests/compositing/will-change/containing-block-removed-expected.html deleted file mode 100644 index 126c6b8..0000000 --- a/third_party/WebKit/LayoutTests/compositing/will-change/containing-block-removed-expected.html +++ /dev/null
@@ -1,31 +0,0 @@ -<!DOCTYPE html> -<html> -<head> - <style> - #container { - position: absolute; - left: 200px; - top: 100px; - width: 100px; - height: 100px; - background-color: blue; - } - - .fixed { - position: fixed; - left: 50px; - top: 50px; - width: 75px; - height: 75px; - background-color: green - } - </style> -</head> - -<body> - <div id="container"> - <div class="fixed"></div> - </div> -</body> - -</html>
diff --git a/third_party/WebKit/LayoutTests/compositing/will-change/containing-block-removed-expected.png b/third_party/WebKit/LayoutTests/compositing/will-change/containing-block-removed-expected.png new file mode 100644 index 0000000..eb14be6 --- /dev/null +++ b/third_party/WebKit/LayoutTests/compositing/will-change/containing-block-removed-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/compositing/will-change/containing-block-removed-expected.txt b/third_party/WebKit/LayoutTests/compositing/will-change/containing-block-removed-expected.txt new file mode 100644 index 0000000..c47b6f0 --- /dev/null +++ b/third_party/WebKit/LayoutTests/compositing/will-change/containing-block-removed-expected.txt
@@ -0,0 +1,38 @@ +CONSOLE MESSAGE: line 30: debug +{ + "bounds": [800, 600], + "children": [ + { + "bounds": [800, 600], + "contentsOpaque": true, + "drawsContent": true, + "repaintRects": [ + [50, 50, 75, 75] + ], + "paintInvalidationClients": [ + "LayoutBlockFlow (positioned) DIV class='fixed'" + ], + "children": [ + { + "position": [200, 100], + "bounds": [100, 100], + "contentsOpaque": true, + "drawsContent": true, + "backgroundColor": "#0000FF", + "repaintRects": [ + [50, 50, 75, 75], + [0, 0, 100, 100], + [0, 0, 100, 100] + ], + "paintInvalidationClients": [ + "LayoutBlockFlow (positioned) DIV class='fixed'", + "LayoutBlockFlow (positioned) DIV id='container'", + "LayoutBlockFlow (positioned) DIV class='fixed'", + "LayoutBlockFlow (positioned) DIV id='container'" + ] + } + ] + } + ] +} +
diff --git a/third_party/WebKit/LayoutTests/compositing/will-change/containing-block-removed.html b/third_party/WebKit/LayoutTests/compositing/will-change/containing-block-removed.html index 0645f9f..8f866ca 100644 --- a/third_party/WebKit/LayoutTests/compositing/will-change/containing-block-removed.html +++ b/third_party/WebKit/LayoutTests/compositing/will-change/containing-block-removed.html
@@ -3,7 +3,7 @@ <head> <style> #container { - will-change: -webkit-transform; + will-change: transform; position: absolute; left: 200px; top: 100px; @@ -21,26 +21,16 @@ background-color: green } </style> - <script type="text/javascript"> - if (window.testRunner) { - testRunner.waitUntilDone(); - } - - function doTest() + <script src="../../fast/repaint/resources/text-based-repaint.js"></script> + <script> + function repaintTest() { - if (window.internals) { - window.internals.forceCompositingUpdate(document); - } - // Removing "will-change: -webkit-transform" to the container div should - // make this div no longer be the containing block for its fixed position - // descendant. + // Removing "will-change: transform" to the container div should make this + // div no longer be the containing block for its fixed position descendant. + console.log('debug'); document.getElementById("container").style.willChange = "top"; - if (window.testRunner) { - testRunner.notifyDone(); - } } - - window.addEventListener('load', doTest, false); + onload = runRepaintAndPixelTest; </script> </head>
diff --git a/third_party/WebKit/LayoutTests/fast/canvas/canvas-imageSmoothingQuality-expected.txt b/third_party/WebKit/LayoutTests/fast/canvas/canvas-imageSmoothingQuality-expected.txt new file mode 100644 index 0000000..feaa9a70 --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/canvas/canvas-imageSmoothingQuality-expected.txt
@@ -0,0 +1,68 @@ +CONSOLE WARNING: The provided value '3223' is not a valid enum value of type ImageSmoothingQuality. +CONSOLE WARNING: The provided value 'bad_input' is not a valid enum value of type ImageSmoothingQuality. +CONSOLE WARNING: The provided value 'LOW' is not a valid enum value of type ImageSmoothingQuality. +CONSOLE WARNING: The provided value 'Medium' is not a valid enum value of type ImageSmoothingQuality. +Tests for the imageSmoothingQuality attribute. + +On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". + + +On getting, must return the last value it was set to. +PASS lowContext.imageSmoothingQuality is 'low' +PASS mediumContext.imageSmoothingQuality is 'medium' +PASS highContext.imageSmoothingQuality is 'high' + +PASS lowData is not mediumData +PASS mediumData is not highData +PASS lowData is not highData + +PASS sampleAlpha(noFilterData) is > sampleAlpha(lowData) +PASS sampleAlpha(lowData) is > sampleAlpha(mediumData) +PASS sampleAlpha(mediumData) is > sampleAlpha(highData) + + +On setting, it must be set to the new value. +highContext.imageSmoothingQuality = 'medium'; +PASS highContext.imageSmoothingQuality is 'medium' +PASS scaleImageData(highCanvas, highCanvas.imageSmoothingQuality); is mediumData +highContext.imageSmoothingQuality = 'high'; +PASS highContext.imageSmoothingQuality is 'high' +PASS scaleImageData(highCanvas, highCanvas.imageSmoothingQuality); is highData + + +When the CanvasRenderingContext2D object is created, the attribute must be set to 'low'. +PASS document.getElementById("default").getContext("2d").imageSmoothingQuality is 'low' + + +ImageSmoothingQuality can be set without real effect when imageSmoothingEnabled is false. +highContext.imageSmoothingEnabled = false; +PASS highContext.imageSmoothingQuality is 'high' +PASS scaleImageData(highCanvas, highCanvas.imageSmoothingQuality) is noFilterData +highContext.imageSmoothingQuality = 'medium' +PASS highContext.imageSmoothingQuality is 'medium' +PASS scaleImageData(highCanvas, highCanvas.imageSmoothingQuality) is noFilterData + + +Invalid Input is not accpeted. +highContext.imageSmoothingEnabled = true; highContext.imageSmoothingQuality = 'high'; +PASS scaleImageData(highCanvas, '3223') did not throw exception. +PASS highContext.imageSmoothingQuality is 'high' +PASS scaleImageData(highCanvas, 'bad_input') did not throw exception. +PASS highContext.imageSmoothingQuality is 'high' +PASS scaleImageData(highCanvas, 'LOW') did not throw exception. +PASS highContext.imageSmoothingQuality is 'high' +PASS scaleImageData(highCanvas, 'Medium') did not throw exception. +PASS highContext.imageSmoothingQuality is 'high' + + +The save() and restore() should work. +highContext.save(); highContext.imageSmoothingQuality = 'medium'; +PASS highContext.imageSmoothingQuality is 'medium' +PASS scaleImageData(highCanvas, highCanvas.imageSmoothingQuality); is mediumData +PASS highContext.restore(); highContext.imageSmoothingQuality is 'high' +PASS scaleImageData(highCanvas, highCanvas.imageSmoothingQuality); is highData + +PASS successfullyParsed is true + +TEST COMPLETE +
diff --git a/third_party/WebKit/LayoutTests/fast/canvas/canvas-imageSmoothingQuality-pixel-expected.txt b/third_party/WebKit/LayoutTests/fast/canvas/canvas-imageSmoothingQuality-pixel-expected.txt new file mode 100644 index 0000000..37ed426a --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/canvas/canvas-imageSmoothingQuality-pixel-expected.txt
@@ -0,0 +1,12 @@ +PASS successfullyParsed is true + +TEST COMPLETE +Scale Up +low +medium +high +Scale Down +low +medium +high +
diff --git a/third_party/WebKit/LayoutTests/fast/canvas/canvas-imageSmoothingQuality-pixel.html b/third_party/WebKit/LayoutTests/fast/canvas/canvas-imageSmoothingQuality-pixel.html new file mode 100644 index 0000000..052d407d --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/canvas/canvas-imageSmoothingQuality-pixel.html
@@ -0,0 +1,126 @@ +<!DOCTYPE html> +<html> + <head> + <style> +.hide {display:none} +.row {display:table-row} +.cell {display:table-cell; padding:10px} +#test-output {display:table} +label {display:row} + </style> + </head> + <body> + + <script src="../../resources/js-test.js"></script> + <canvas class="hide" id="source-up-canvas"></canvas> + <canvas class="hide" id="source-down-canvas"></canvas> + <div id="test-output"> + <label>Scale Up</label> + <div id="up" class="row"> + <div class="cell"> + <div id="low-up"></div> + <canvas id="low-up-canvas"></canvas> + </div> + <div class="cell"> + <div id="medium-up"></div> + <canvas id="medium-up-canvas"></canvas> + </div> + <div class="cell"> + <div id="high-up"></div> + <canvas id="high-up-canvas"></canvas> + </div> + </div> + + <label>Scale Down</label> + <div id="down" class="row"> + <div class="cell"> + <div id="low-down"></div> + <canvas id="low-down-canvas"></canvas> + </div> + <div class="cell"> + <div id="medium-down"></div> + <canvas id="medium-down-canvas"></canvas> + </div> + <div class="cell"> + <div id="high-down"></div> + <canvas id="high-down-canvas"></canvas> + </div> + </div> + </div> + <script> +if (window.testRunner) + window.testRunner.dumpAsTextWithPixelResults(); + +drawCanvas("source", "up", drawPicture); +drawCanvas("source", "down", drawWord); + +qualities = ["low", "medium", "high"]; +scales = ["up", "down"]; +for (var i = 0; i < scales.length; i++) { + for (var j = 0; j < qualities.length; j++) { + drawCanvas(qualities[j], scales[i], copyPicture); + } +} + +function drawCanvas(quality, scale, drawFunc) { + var id = quality + "-" + scale; + var canvas = document.getElementById(id + "-canvas"); + var context = canvas.getContext("2d"); + var testCaseTitle = document.getElementById(id); + if (testCaseTitle) { + testCaseTitle.innerHTML = quality; + } + drawFunc(canvas, context, quality, scale); +} + +function copyPicture(canvas, context, quality, scale) { + var source = document.getElementById("source-" + scale + "-canvas"); + canvas.width = 100; + canvas.height = 100; + context.imageSmoothingQuality = quality; + context.drawImage(source, 0, 0, canvas.width, canvas.height); +} + +function drawWord(canvas, context) { + canvas.width = 1800; + canvas.height = 1800; + context.font = '250pt Calibri'; + context.textAlign = 'center'; + context.fillStyle = 'blue'; + context.fillText('Hello World!', canvas.width/2, canvas.height/2); +} + + +function drawPicture(canvas, context) { + canvas.width = 5; + canvas.height = 5; + + var image = context.createImageData(canvas.width, canvas.height); + + function drawBlackDot(x, y, col) { + var offset = y * 4 * canvas.width + x * 4; + image.data[offset + 0] = col[0]; // R + image.data[offset + 1] = col[1] ; // G + image.data[offset + 2] = col[2] ; // B + image.data[offset + 3] = 225; // Alpha + } + + var imageData = [ + ['b', 'w', 'b', 'w', 'b',],['w', 'b', 'w', 'b', 'w',], + ['b', 'w', 'b', 'w', 'b',],['w', 'b', 'w', 'b', 'w',], + ['b', 'w', 'b', 'w', 'b',], + ] + var nameToColor = { + 'w' : [255,255,255], + 'b' : [0,0,0], + } + for (var x = 0 ; x < canvas.width; x++) { + for (var y = 0; y < canvas.height; y++) { + drawBlackDot(x, y, nameToColor[imageData[x][y]]); + } + } + context.putImageData(image, 0, 0); +} + </script> + </body> +</html>
diff --git a/third_party/WebKit/LayoutTests/fast/canvas/canvas-imageSmoothingQuality.html b/third_party/WebKit/LayoutTests/fast/canvas/canvas-imageSmoothingQuality.html new file mode 100644 index 0000000..b3f327e --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/canvas/canvas-imageSmoothingQuality.html
@@ -0,0 +1,142 @@ +<!DOCTYPE html> +<html> + <body> + <script src="../../resources/js-test.js"></script> + <canvas id="source"></canvas> + <canvas id="default"></canvas> + <script> + +description("Tests for the imageSmoothingQuality attribute."); + +var source = document.getElementById("source"); +source.width = 60; +source.height = 12; +var sourceContext = source.getContext("2d"); +var sourceImage = sourceContext.createImageData(source.width, source.height); + +function drawBlackDot(x, y) { + var offset = y * 4 * source.width + x * 4; + sourceImage.data[offset + 0] = 0 ; // R + sourceImage.data[offset + 1] = 0 ; // G + sourceImage.data[offset + 2] = 0 ; // B + sourceImage.data[offset + 3] = 202 - y ; // Alpha +} + +for (var x = 0; x < source.width; x++) { + for (var y = 2; y < 4; y++) { + drawBlackDot(x, y); + } +} + +sourceContext.putImageData(sourceImage, 0, 0); + +function scaleTestResults(quality){ + var canvas = document.createElement("canvas"); + canvas.id = quality + "Canvas"; + document.body.appendChild(canvas); + canvas.width = sourceImage.width / 4; + canvas.height = sourceImage.height / 4; + return scaleImageData(canvas, quality); +} + +function scaleImageData(destinationCanvas, quality) { + var context = destinationCanvas.getContext("2d"); + + if (quality) + context.imageSmoothingQuality = quality; + + context.drawImage(source, 0, 0, destinationCanvas.width, + destinationCanvas.height); + var data = context.getImageData(0, 0, 1, 1).data; + context.clearRect(0, 0, destinationCanvas.width, destinationCanvas.height); + return JSON.stringify(data); +} + +function testInvalidInput(badInput){ + shouldNotThrow(badInput); + shouldBe("highContext.imageSmoothingQuality", "'high'"); +} + +function sampleAlpha(data){ + return JSON.parse(data)[3] +} + +debug("On getting, must return the last value it was set to."); +var lowData = scaleTestResults("low"); +var lowContext = document.getElementById("lowCanvas").getContext('2d'); +shouldBe("lowContext.imageSmoothingQuality", "'low'"); + +var mediumData = scaleTestResults("medium"); +var mediumContext = document.getElementById("mediumCanvas").getContext('2d'); +shouldBe("mediumContext.imageSmoothingQuality", "'medium'"); + +var highData = scaleTestResults("high"); +var highContext = document.getElementById("highCanvas").getContext('2d'); +var highCanvas = document.getElementById("highCanvas"); +shouldBe("highContext.imageSmoothingQuality", "'high'"); + +lowContext.imageSmoothingEnabled = false; +var noFilterData = scaleImageData(lowCanvas, lowCanvas.imageSmoothingQuality); + +debug(""); +shouldNotBe("lowData", "mediumData"); +shouldNotBe("mediumData", "highData"); +shouldNotBe("lowData", "highData"); + +debug(""); +shouldBeGreaterThan("sampleAlpha(noFilterData)", "sampleAlpha(lowData)"); +shouldBeGreaterThan("sampleAlpha(lowData)", "sampleAlpha(mediumData)"); +shouldBeGreaterThan("sampleAlpha(mediumData)", "sampleAlpha(highData)"); + + +debug("\n\nOn setting, it must be set to the new value."); +evalAndLog("highContext.imageSmoothingQuality = 'medium';"); +shouldBe("highContext.imageSmoothingQuality", "'medium'"); +shouldBe("scaleImageData(highCanvas, highCanvas.imageSmoothingQuality);", + "mediumData"); +evalAndLog("highContext.imageSmoothingQuality = 'high';"); +shouldBe("highContext.imageSmoothingQuality", "'high'"); +shouldBe("scaleImageData(highCanvas, highCanvas.imageSmoothingQuality);", + "highData"); + + +debug("\n\nWhen the CanvasRenderingContext2D object is created, " + + "the attribute must be set to 'low'."); +shouldBe('document.getElementById("default").getContext("2d").' + + 'imageSmoothingQuality', "'low'"); + + +debug("\n\nImageSmoothingQuality can be set without real effect when " + + "imageSmoothingEnabled is false."); +evalAndLog("highContext.imageSmoothingEnabled = false;"); +shouldBe("highContext.imageSmoothingQuality", "'high'"); +shouldBe("scaleImageData(highCanvas, highCanvas.imageSmoothingQuality)", + "noFilterData"); +evalAndLog("highContext.imageSmoothingQuality = 'medium'"); +shouldBe("highContext.imageSmoothingQuality", "'medium'"); +shouldBe("scaleImageData(highCanvas, highCanvas.imageSmoothingQuality)", + "noFilterData"); + + +debug("\n\nInvalid Input is not accpeted."); +evalAndLog("highContext.imageSmoothingEnabled = true; " + + "highContext.imageSmoothingQuality = 'high';"); +testInvalidInput("scaleImageData(highCanvas, '3223')"); +testInvalidInput("scaleImageData(highCanvas, 'bad_input')"); +testInvalidInput("scaleImageData(highCanvas, 'LOW')"); +testInvalidInput("scaleImageData(highCanvas, 'Medium')"); + + +debug("\n\nThe save() and restore() should work."); +evalAndLog("highContext.save(); highContext.imageSmoothingQuality = 'medium';"); +shouldBe("highContext.imageSmoothingQuality", "'medium'"); +shouldBe("scaleImageData(highCanvas, highCanvas.imageSmoothingQuality);", + "mediumData"); +shouldBe("highContext.restore(); highContext.imageSmoothingQuality", "'high'"); +shouldBe("scaleImageData(highCanvas, highCanvas.imageSmoothingQuality);", + "highData"); + +debug(""); + </script> + </body> +</html>
diff --git a/third_party/WebKit/LayoutTests/fast/loader/meta-refresh-vs-open.html b/third_party/WebKit/LayoutTests/fast/loader/meta-refresh-vs-open.html index 3644877b..06341f8 100644 --- a/third_party/WebKit/LayoutTests/fast/loader/meta-refresh-vs-open.html +++ b/third_party/WebKit/LayoutTests/fast/loader/meta-refresh-vs-open.html
@@ -24,9 +24,9 @@ setTimeout(function () { // Test succeeded, now remove traps and return to a state that won't confuse our test runner. document.body.onload = function() {}; + document.getElementById("ifrm").contentDocument.close(); if (window.stop) stop(); - document.getElementById("ifrm").contentDocument.close(); if (window.testRunner) testRunner.notifyDone(); }, 500);
diff --git a/third_party/WebKit/LayoutTests/fast/loader/subframe-removes-itself-expected.txt b/third_party/WebKit/LayoutTests/fast/loader/subframe-removes-itself-expected.txt index cb5e385..de246c99 100644 --- a/third_party/WebKit/LayoutTests/fast/loader/subframe-removes-itself-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/loader/subframe-removes-itself-expected.txt
@@ -1,7 +1,6 @@ frame "<!--framePath //<!--frame0-->-->" - didStartProvisionalLoadForFrame main frame - didFinishDocumentLoadForFrame frame "<!--framePath //<!--frame0-->-->" - didCommitLoadForFrame -frame "<!--framePath //<!--frame0-->-->" - didFinishDocumentLoadForFrame frame "<!--framePath //<!--frame0-->-->" - didFailLoadWithError main frame - didHandleOnloadEventsForFrame main frame - didFinishLoadForFrame
diff --git a/third_party/WebKit/LayoutTests/fast/repaint/absolute-position-change-containing-block-expected.txt b/third_party/WebKit/LayoutTests/fast/repaint/absolute-position-change-containing-block-expected.txt index 19df481..2c3e90d 100644 --- a/third_party/WebKit/LayoutTests/fast/repaint/absolute-position-change-containing-block-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/repaint/absolute-position-change-containing-block-expected.txt
@@ -7,14 +7,13 @@ "drawsContent": true, "repaintRects": [ [108, 5100, 100, 100], - [108, 5100, 100, 100], [100, 100, 100, 100], [8, 5000, 100, 100], - [8, 5000, 100, 100], [8, 8, 784, 2000], [8, 8, 100, 100] ], "paintInvalidationClients": [ + "LayoutBlockFlow (positioned) DIV class='absolute green'", "LayoutBlockFlow (positioned) DIV id='container' class='fixed blue'", "LayoutBlockFlow (positioned) DIV class='absolute green'", "LayoutBlockFlow DIV id='container' class='fixed blue'",
diff --git a/third_party/WebKit/LayoutTests/fast/repaint/containing-block-position-change-expected.txt b/third_party/WebKit/LayoutTests/fast/repaint/containing-block-position-change-expected.txt index 399c20a..f2e43399 100644 --- a/third_party/WebKit/LayoutTests/fast/repaint/containing-block-position-change-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/repaint/containing-block-position-change-expected.txt
@@ -10,6 +10,7 @@ [100, 70, 50, 50] ], "paintInvalidationClients": [ + "LayoutBlockFlow (positioned) DIV", "LayoutBlockFlow (relative positioned) DIV id='t'", "LayoutBlockFlow (positioned) DIV" ]
diff --git a/third_party/WebKit/LayoutTests/fast/repaint/filter-invalidation-after-display-expected.txt b/third_party/WebKit/LayoutTests/fast/repaint/filter-invalidation-after-display-expected.txt index 5f01b461..9897296 100644 --- a/third_party/WebKit/LayoutTests/fast/repaint/filter-invalidation-after-display-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/repaint/filter-invalidation-after-display-expected.txt
@@ -7,7 +7,6 @@ "drawsContent": true, "repaintRects": [ [300, 8, 328, 328], - [300, 8, 328, 328], [300, 8, 200, 200] ], "paintInvalidationClients": [
diff --git a/third_party/WebKit/LayoutTests/fast/repaint/fixed-and-absolute-position-scrolled-expected.txt b/third_party/WebKit/LayoutTests/fast/repaint/fixed-and-absolute-position-scrolled-expected.txt index 046ddc0e..83cf814 100644 --- a/third_party/WebKit/LayoutTests/fast/repaint/fixed-and-absolute-position-scrolled-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/repaint/fixed-and-absolute-position-scrolled-expected.txt
@@ -14,6 +14,7 @@ [0, 0, 800, 2016] ], "paintInvalidationClients": [ + "LayoutBlockFlow (positioned) DIV id='absoluteDiv' class='absolute green'", "LayoutView #document", "LayoutBlockFlow HTML", "LayoutBlockFlow DIV id='container' class='relative'",
diff --git a/third_party/WebKit/LayoutTests/fast/repaint/fixed-to-relative-position-with-absolute-child-expected.txt b/third_party/WebKit/LayoutTests/fast/repaint/fixed-to-relative-position-with-absolute-child-expected.txt index 5ab063ca..9097b4c 100644 --- a/third_party/WebKit/LayoutTests/fast/repaint/fixed-to-relative-position-with-absolute-child-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/repaint/fixed-to-relative-position-with-absolute-child-expected.txt
@@ -8,10 +8,8 @@ "repaintRects": [ [108, 308, 100, 100], [108, 300, 100, 100], - [108, 300, 100, 100], [8, 208, 100, 100], [8, 200, 100, 100], - [8, 200, 100, 100], [8, 8, 784, 2000] ], "paintInvalidationClients": [
diff --git a/third_party/WebKit/LayoutTests/fast/repaint/reflection-invalidation-after-display-expected.txt b/third_party/WebKit/LayoutTests/fast/repaint/reflection-invalidation-after-display-expected.txt index 8ca484b4..5c51c848 100644 --- a/third_party/WebKit/LayoutTests/fast/repaint/reflection-invalidation-after-display-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/repaint/reflection-invalidation-after-display-expected.txt
@@ -7,7 +7,6 @@ "drawsContent": true, "repaintRects": [ [300, 8, 450, 200], - [300, 8, 450, 200], [300, 8, 200, 200] ], "paintInvalidationClients": [
diff --git a/third_party/WebKit/LayoutTests/fast/repaint/stacking-context-lost-expected.txt b/third_party/WebKit/LayoutTests/fast/repaint/stacking-context-lost-expected.txt index 5afb8687..2fb18f5 100644 --- a/third_party/WebKit/LayoutTests/fast/repaint/stacking-context-lost-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/repaint/stacking-context-lost-expected.txt
@@ -5,9 +5,6 @@ "bounds": [800, 600], "contentsOpaque": true, "drawsContent": true, - "repaintRects": [ - [0, 0, 100, 100] - ], "paintInvalidationClients": [ "LayoutBlockFlow (relative positioned) DIV id='inner'" ],
diff --git a/third_party/WebKit/LayoutTests/fast/repaint/transform-rotate-and-remove-expected.txt b/third_party/WebKit/LayoutTests/fast/repaint/transform-rotate-and-remove-expected.txt index 4063dbed..09fb408 100644 --- a/third_party/WebKit/LayoutTests/fast/repaint/transform-rotate-and-remove-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/repaint/transform-rotate-and-remove-expected.txt
@@ -7,7 +7,6 @@ "drawsContent": true, "repaintRects": [ [20, -64, 196, 214], - [20, -64, 196, 214], [8, 8, 220, 70] ], "paintInvalidationClients": [
diff --git a/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/resources/protocol-test.html b/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/resources/protocol-test.html index b7f826a03..f92779b3 100644 --- a/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/resources/protocol-test.html +++ b/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/resources/protocol-test.html
@@ -32,6 +32,7 @@ InspectorTest._dispatchTable = []; InspectorTest._requestId = -1; InspectorTest._dumpInspectorProtocolMessages = false; +InspectorTest._embedderRequestId = -1; InspectorTest.eventHandler = {}; InspectorTest.startDumpingProtocolMessages = function() @@ -54,8 +55,8 @@ if (InspectorTest._dumpInspectorProtocolMessages) testRunner.logToStderr("frontend: " + JSON.stringify(messageObject)); - DevToolsHost.sendMessageToBackend(JSON.stringify(messageObject)); - + var embedderMessage = { "id": ++this._embedderRequestId, "method": "dispatchProtocolMessage", "params": [JSON.stringify(messageObject)] }; + DevToolsHost.sendMessageToEmbedder(JSON.stringify(embedderMessage)); return this._requestId; } @@ -131,7 +132,8 @@ InspectorTest.sendRawCommand = function(command, handler) { this._dispatchTable[++this._requestId] = handler; - DevToolsHost.sendMessageToBackend(command); + var embedderMessage = { "id": ++this._embedderRequestId, "method": "dispatchProtocolMessage", "params": [command] }; + DevToolsHost.sendMessageToEmbedder(JSON.stringify(embedderMessage)); return this._requestId; }
diff --git a/third_party/WebKit/LayoutTests/http/tests/misc/onload-write-during-xframe-deny-expected.txt b/third_party/WebKit/LayoutTests/http/tests/misc/onload-write-during-xframe-deny-expected.txt index 7ef22e9..5a523a8 100644 --- a/third_party/WebKit/LayoutTests/http/tests/misc/onload-write-during-xframe-deny-expected.txt +++ b/third_party/WebKit/LayoutTests/http/tests/misc/onload-write-during-xframe-deny-expected.txt
@@ -1 +1,2 @@ +CONSOLE ERROR: Refused to display 'http://127.0.0.1:8000/security/XFrameOptions/resources/x-frame-options-deny-meta-tag-subframe-in-body.html' in a frame because it set 'X-Frame-Options' to 'deny'. PASS
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/contentSecurityPolicy/1.1/scripthash-unicode-normalization-expected.txt b/third_party/WebKit/LayoutTests/http/tests/security/contentSecurityPolicy/1.1/scripthash-unicode-normalization-expected.txt index 8c74f27..bb35ec9 100644 --- a/third_party/WebKit/LayoutTests/http/tests/security/contentSecurityPolicy/1.1/scripthash-unicode-normalization-expected.txt +++ b/third_party/WebKit/LayoutTests/http/tests/security/contentSecurityPolicy/1.1/scripthash-unicode-normalization-expected.txt
@@ -1,3 +1,4 @@ -ALERT: PASS -ALERT: PASS -This tests Unicode normalization. While appearing the same, the strings in the scripts are different Unicode points, but through normalization, should be the same when the hash is taken. +ALERT: PASS (1/1) +CONSOLE ERROR: line 20: Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'sha1-zv73epHrGLk/k/onuSBPoZAxzaA=' 'sha256-6VVrnAGI98OnlK9Y20hAMwfwBE8c8FOtE/jDYM7tPFk='". Either the 'unsafe-inline' keyword, a hash ('sha256-1YpMZRdgC0WhwwFBK0bksRyUnuhzlCJp0nKmbZYUi+Q='), or a nonce ('nonce-...') is required to enable inline execution. + +This tests Unicode normalization. While appearing the same, the strings in the scripts are different Unicode points. Unicode NFC normalization would make both match the hash, but normalization should not be performed, and so the second script should not run.
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/contentSecurityPolicy/1.1/scripthash-unicode-normalization.html b/third_party/WebKit/LayoutTests/http/tests/security/contentSecurityPolicy/1.1/scripthash-unicode-normalization.html index b8264b4..86a21890c 100644 --- a/third_party/WebKit/LayoutTests/http/tests/security/contentSecurityPolicy/1.1/scripthash-unicode-normalization.html +++ b/third_party/WebKit/LayoutTests/http/tests/security/contentSecurityPolicy/1.1/scripthash-unicode-normalization.html
@@ -2,30 +2,32 @@ <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> - <meta http-equiv="Content-Security-Policy" content="script-src 'sha1-zv73epHrGLk/k/onuSBPoZAxzaA=' 'sha1-gbGNUiHncUNJ+diPbIoc+x6KrLo='"> + <meta http-equiv="Content-Security-Policy" content="script-src 'sha1-zv73epHrGLk/k/onuSBPoZAxzaA=' 'sha256-6VVrnAGI98OnlK9Y20hAMwfwBE8c8FOtE/jDYM7tPFk='"> <script> if (window.testRunner) testRunner.dumpAsText(); </script> <!-- The following two scripts contain two separate code points (U+00C5 and U+212B, respectively) which, depending on your text editor, might be - rendered the same. However, their difference is important as they should - be NFC normalized to the same code point, thus they should hash to the - same value.--> - <script> + rendered the same. However, their difference is important as they would + be NFC normalized to the same code point, matching the hash. Since NFC + normalization should not be performed, the second script should not + match the hash and must not be executed. --> + <script data-alert="PASS (1/1)"> 'Å'; - alert('PASS'); + alert(document.currentScript.dataset.alert); </script> - <script> + <script data-alert="FAIL"> 'â„«'; - alert('PASS'); + alert(document.currentScript.dataset.alert); </script> </head> <body> <p> This tests Unicode normalization. While appearing the same, the - strings in the scripts are different Unicode points, but through - normalization, should be the same when the hash is taken. + strings in the scripts are different Unicode points. Unicode NFC + normalization would make both match the hash, but normalization + should not be performed, and so the second script should not run. </p> </body> </html>
diff --git a/third_party/WebKit/LayoutTests/inspector/components/viewport-datagrid.html b/third_party/WebKit/LayoutTests/inspector/components/viewport-datagrid.html index 74b3074..325105b 100644 --- a/third_party/WebKit/LayoutTests/inspector/components/viewport-datagrid.html +++ b/third_party/WebKit/LayoutTests/inspector/components/viewport-datagrid.html
@@ -60,7 +60,8 @@ containerElement.style.width = "300px"; containerElement.style.height = "300px"; containerElement.style.overflow = "hidden"; - dataGrid.show(containerElement); + containerElement.appendChild(dataGrid.element); + dataGrid.wasShown(); dataGrid.element.style.width = "100%"; InspectorTest.addResult("Building tree.");
diff --git a/third_party/WebKit/LayoutTests/media/controls-repaint-for-network-change-expected.html b/third_party/WebKit/LayoutTests/media/controls-repaint-for-network-change-expected.html new file mode 100644 index 0000000..a4ac8c22 --- /dev/null +++ b/third_party/WebKit/LayoutTests/media/controls-repaint-for-network-change-expected.html
@@ -0,0 +1,30 @@ +<!DOCTYPE html> +<style> + /* restrict to just the play button, so the slider doesn't mismatch */ + audio { + width: 40px; + height: 40px; + } +</style> +<script src="../resources/run-after-layout-and-paint.js"></script> +<script src=media-file.js></script> +<script> + +testRunner.waitUntilDone(); + +function test() { + var src = findMediaFile("audio", "content/empty"); + document.getElementById("audio1").src = src; + + runAfterLayoutAndPaint(function() { + testRunner.notifyDone(); + }); +} +</script> + +<body onload="test()"> + <audio controls></audio> + <audio id="audio1" controls></audio> + <p>Test that network state transitions paint audio controls properly.</p> +</body> +
diff --git a/third_party/WebKit/LayoutTests/media/controls-repaint-for-network-change.html b/third_party/WebKit/LayoutTests/media/controls-repaint-for-network-change.html new file mode 100644 index 0000000..6c1356c --- /dev/null +++ b/third_party/WebKit/LayoutTests/media/controls-repaint-for-network-change.html
@@ -0,0 +1,34 @@ +<!DOCTYPE html> +<style> + /* restrict to just the play button, so the slider doesn't mismatch */ + audio { + width: 40px; + height: 40px; + } +</style> +<script src="../resources/run-after-layout-and-paint.js"></script> +<script src=media-file.js></script> + +<audio controls></audio> +<audio controls></audio> +<p>Test that network state transitions paint audio controls properly.</p> + +<script> + +testRunner.waitUntilDone(); + +var audios = document.querySelectorAll("audio"); +var src = findMediaFile("audio", "content/empty"); + +runAfterLayoutAndPaint(function() { + window.internals.setMediaElementNetworkState(audios[0], 0); + window.internals.setMediaElementNetworkState(audios[1], 0); + + // These will cause the play buttons to become enabled, and should + // also cause a repaint. + window.internals.setMediaElementNetworkState(audios[1], 2); + + testRunner.notifyDone(); +}); +</script> +
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/invalidate-descendants-when-receiving-paint-layer-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/invalidate-descendants-when-receiving-paint-layer-expected.txt index 7b8f437..c22ba9ce 100644 --- a/third_party/WebKit/LayoutTests/paint/invalidation/invalidate-descendants-when-receiving-paint-layer-expected.txt +++ b/third_party/WebKit/LayoutTests/paint/invalidation/invalidate-descendants-when-receiving-paint-layer-expected.txt
@@ -5,10 +5,6 @@ "bounds": [800, 600], "contentsOpaque": true, "drawsContent": true, - "repaintRects": [ - [1, 1, 100, 100], - [1, 1, 100, 100] - ], "paintInvalidationClients": [ "LayoutBlockFlow DIV id='target'", "LayoutBlockFlow DIV id='child'"
diff --git a/third_party/WebKit/LayoutTests/platform/android/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.png b/third_party/WebKit/LayoutTests/platform/android/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.png new file mode 100644 index 0000000..c4e74ac --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/android/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/android/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.txt b/third_party/WebKit/LayoutTests/platform/android/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.txt new file mode 100644 index 0000000..c4cbd77d --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/android/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.txt
@@ -0,0 +1,39 @@ +layer at (0,0) size 480x360 + LayoutView at (0,0) size 480x360 +layer at (0,0) size 480x360 + LayoutSVGRoot {svg} at (0,0) size 480x360 + LayoutSVGHiddenContainer {defs} at (0,0) size 0x0 + LayoutSVGContainer {g} at (10,7) size 365x296 + LayoutSVGContainer {g} at (10,7) size 365x296 + LayoutSVGContainer {g} at (16,7) size 359x157 [transform={m=((1.00,0.00)(0.00,1.00)) t=(70.00,-60.00)}] + LayoutSVGText {text} at (30,130) size 342x25 contains 1 chunk(s) + LayoutSVGInlineText {#text} at (0,0) size 342x25 + chunk 1 text run 1 at (30.00,150.00) startOffset 0 endOffset 37 width 341.12: "Rotated Text for testing SVGLocatable" + LayoutSVGText {text} at (100,111) size 301x24 contains 1 chunk(s) + LayoutSVGInlineText {#text} at (0,0) size 301x23 + chunk 1 text run 1 at (100.00,130.00) startOffset 0 endOffset 35 width 300.64: "Some other text with id 'otherText'" + LayoutSVGViewportContainer {svg} at (275,45) size 100x100 + LayoutSVGEllipse {circle} at (275,45) size 100x100 [fill={[type=SOLID] [color=#0000FF]}] [cx=0.00] [cy=0.00] [r=50.00] + LayoutSVGText {text} at (10,188) size 279x15 contains 1 chunk(s) + LayoutSVGInlineText {#text} at (0,0) size 279x15 + chunk 1 text run 1 at (10.00,200.00) startOffset 0 endOffset 50 width 279.00: ".getScreenCTM(): 0.42,0.42,-0.42,0.42,70.00,-60.00" + LayoutSVGText {text} at (10,208) size 240x15 contains 1 chunk(s) + LayoutSVGInlineText {#text} at (0,0) size 240x15 + chunk 1 text run 1 at (10.00,220.00) startOffset 0 endOffset 44 width 240.00: ".getCTM(): 0.42,0.42,-0.42,0.42,70.00,-60.00" + LayoutSVGText {text} at (10,228) size 313x15 contains 1 chunk(s) + LayoutSVGInlineText {#text} at (0,0) size 313x15 + chunk 1 text run 1 at (10.00,240.00) startOffset 0 endOffset 56 width 312.22: ".getTransformToElement(): 0.42,0.42,-0.42,0.42,0.00,0.00" + LayoutSVGText {text} at (10,248) size 342x15 contains 1 chunk(s) + LayoutSVGInlineText {#text} at (0,0) size 342x15 + chunk 1 text run 1 at (10.00,260.00) startOffset 0 endOffset 65 width 342.00: ".getBBox() for 'blueCircle': .x=-50,.y=-50,.width=100,.height=100" + LayoutSVGText {text} at (10,268) size 260x15 contains 1 chunk(s) + LayoutSVGInlineText {#text} at (0,0) size 260x15 + chunk 1 text run 1 at (10.00,280.00) startOffset 0 endOffset 47 width 259.78: ".farthestViewportElement of blueCircle=svg-root" + LayoutSVGText {text} at (10,288) size 279x15 contains 1 chunk(s) + LayoutSVGInlineText {#text} at (0,0) size 279x15 + chunk 1 text run 1 at (10.00,300.00) startOffset 0 endOffset 47 width 278.78: ".nearestViewportElement of blueCircle=nestedSVG" + LayoutSVGContainer {g} at (10,311) size 228x36 + LayoutSVGText {text} at (10,311) size 228x36 contains 1 chunk(s) + LayoutSVGInlineText {#text} at (0,0) size 228x36 + chunk 1 text run 1 at (10.00,340.00) startOffset 0 endOffset 16 width 228.00: "$Revision: 1.6 $" + LayoutSVGRect {rect} at (0,0) size 480x360 [stroke={[type=SOLID] [color=#000000]}] [x=1.00] [y=1.00] [width=478.00] [height=358.00]
diff --git a/third_party/WebKit/LayoutTests/platform/android/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.png b/third_party/WebKit/LayoutTests/platform/android/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.png new file mode 100644 index 0000000..d754fac --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/android/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/android/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.txt b/third_party/WebKit/LayoutTests/platform/android/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.txt new file mode 100644 index 0000000..4333783 --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/android/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.txt
@@ -0,0 +1,37 @@ +layer at (0,0) size 480x360 + LayoutView at (0,0) size 480x360 +layer at (0,0) size 480x360 + LayoutSVGRoot {svg} at (0,0) size 480x360 + LayoutSVGContainer {g} at (10,7) size 365x296 + LayoutSVGContainer {g} at (10,7) size 365x296 + LayoutSVGContainer {g} at (16,7) size 359x157 [transform={m=((1.00,0.00)(0.00,1.00)) t=(70.00,-60.00)}] + LayoutSVGText {text} at (30,130) size 342x25 contains 1 chunk(s) + LayoutSVGInlineText {#text} at (0,0) size 342x25 + chunk 1 text run 1 at (30.00,150.00) startOffset 0 endOffset 37 width 341.12: "Rotated Text for testing SVGLocatable" + LayoutSVGText {text} at (100,111) size 301x24 contains 1 chunk(s) + LayoutSVGInlineText {#text} at (0,0) size 301x23 + chunk 1 text run 1 at (100.00,130.00) startOffset 0 endOffset 35 width 300.64: "Some other text with id 'otherText'" + LayoutSVGViewportContainer {svg} at (275,45) size 100x100 + LayoutSVGEllipse {circle} at (275,45) size 100x100 [fill={[type=SOLID] [color=#FF0000]}] [cx=0.00] [cy=0.00] [r=50.00] + LayoutSVGText {text} at (10,188) size 279x15 contains 1 chunk(s) + LayoutSVGInlineText {#text} at (0,0) size 279x15 + chunk 1 text run 1 at (10.00,200.00) startOffset 0 endOffset 50 width 279.00: ".getScreenCTM(): 0.42,0.42,-0.42,0.42,70.00,-60.00" + LayoutSVGText {text} at (10,208) size 240x15 contains 1 chunk(s) + LayoutSVGInlineText {#text} at (0,0) size 240x15 + chunk 1 text run 1 at (10.00,220.00) startOffset 0 endOffset 44 width 240.00: ".getCTM(): 0.42,0.42,-0.42,0.42,70.00,-60.00" + LayoutSVGText {text} at (10,228) size 313x15 contains 1 chunk(s) + LayoutSVGInlineText {#text} at (0,0) size 313x15 + chunk 1 text run 1 at (10.00,240.00) startOffset 0 endOffset 56 width 312.22: ".getTransformToElement(): 0.42,0.42,-0.42,0.42,0.00,0.00" + LayoutSVGText {text} at (10,248) size 336x15 contains 1 chunk(s) + LayoutSVGInlineText {#text} at (0,0) size 336x15 + chunk 1 text run 1 at (10.00,260.00) startOffset 0 endOffset 64 width 336.00: ".getBBox() for 'redCircle': .x=-50,.y=-50,.width=100,.height=100" + LayoutSVGText {text} at (10,268) size 254x15 contains 1 chunk(s) + LayoutSVGInlineText {#text} at (0,0) size 254x15 + chunk 1 text run 1 at (10.00,280.00) startOffset 0 endOffset 46 width 253.78: ".farthestViewportElement of redCircle=svg-root" + LayoutSVGText {text} at (10,288) size 273x15 contains 1 chunk(s) + LayoutSVGInlineText {#text} at (0,0) size 273x15 + chunk 1 text run 1 at (10.00,300.00) startOffset 0 endOffset 46 width 272.78: ".nearestViewportElement of redCircle=nestedSVG" + LayoutSVGText {text} at (10,304) size 261x46 contains 1 chunk(s) + LayoutSVGInlineText {#text} at (0,0) size 261x46 + chunk 1 text run 1 at (10.00,340.00) startOffset 0 endOffset 16 width 261.00: "$Revision: 1.1 $" + LayoutSVGRect {rect} at (0,0) size 480x360 [stroke={[type=SOLID] [color=#000000]}] [x=1.00] [y=1.00] [width=478.00] [height=358.00]
diff --git a/third_party/WebKit/LayoutTests/platform/android/svg/dom/css-transforms-expected.png b/third_party/WebKit/LayoutTests/platform/android/svg/dom/css-transforms-expected.png new file mode 100644 index 0000000..d2d234b --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/android/svg/dom/css-transforms-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/fast/repaint/containing-block-position-change-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/fast/repaint/containing-block-position-change-expected.txt index 504ba60..2338b07 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/fast/repaint/containing-block-position-change-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/linux/fast/repaint/containing-block-position-change-expected.txt
@@ -10,6 +10,7 @@ [100, 74, 50, 50] ], "paintInvalidationClients": [ + "LayoutBlockFlow (positioned) DIV", "LayoutBlockFlow (relative positioned) DIV id='t'", "LayoutBlockFlow (positioned) DIV" ]
diff --git a/third_party/WebKit/LayoutTests/platform/linux/fast/repaint/invalidation-after-opacity-change-subtree-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/fast/repaint/invalidation-after-opacity-change-subtree-expected.txt index 9c38308c..81df00a 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/fast/repaint/invalidation-after-opacity-change-subtree-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/linux/fast/repaint/invalidation-after-opacity-change-subtree-expected.txt
@@ -10,6 +10,7 @@ [8, 2196, 639, 107], [8, 2046, 777, 107], [8, 2046, 766, 107], + [8, 2000, 777, 350], [8, 2000, 777, 350] ], "paintInvalidationClients": [ @@ -23,7 +24,8 @@ "LayoutText #text", "InlineTextBox 'This text should be visible in the'", "InlineTextBox 'output.'", - "LayoutBlockFlow DIV id='container'" + "LayoutBlockFlow DIV id='container'", + "LayoutBlockFlow (positioned) DIV id='absolute'" ] } ]
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.png b/third_party/WebKit/LayoutTests/platform/linux/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.png index c4e74ac..742be23 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.txt index c4cbd77d..53c7594 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/linux/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.txt
@@ -3,8 +3,8 @@ layer at (0,0) size 480x360 LayoutSVGRoot {svg} at (0,0) size 480x360 LayoutSVGHiddenContainer {defs} at (0,0) size 0x0 - LayoutSVGContainer {g} at (10,7) size 365x296 - LayoutSVGContainer {g} at (10,7) size 365x296 + LayoutSVGContainer {g} at (10,7) size 365x276 + LayoutSVGContainer {g} at (10,7) size 365x276 LayoutSVGContainer {g} at (16,7) size 359x157 [transform={m=((1.00,0.00)(0.00,1.00)) t=(70.00,-60.00)}] LayoutSVGText {text} at (30,130) size 342x25 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 342x25 @@ -20,18 +20,15 @@ LayoutSVGText {text} at (10,208) size 240x15 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 240x15 chunk 1 text run 1 at (10.00,220.00) startOffset 0 endOffset 44 width 240.00: ".getCTM(): 0.42,0.42,-0.42,0.42,70.00,-60.00" - LayoutSVGText {text} at (10,228) size 313x15 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 313x15 - chunk 1 text run 1 at (10.00,240.00) startOffset 0 endOffset 56 width 312.22: ".getTransformToElement(): 0.42,0.42,-0.42,0.42,0.00,0.00" - LayoutSVGText {text} at (10,248) size 342x15 contains 1 chunk(s) + LayoutSVGText {text} at (10,228) size 342x15 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 342x15 - chunk 1 text run 1 at (10.00,260.00) startOffset 0 endOffset 65 width 342.00: ".getBBox() for 'blueCircle': .x=-50,.y=-50,.width=100,.height=100" - LayoutSVGText {text} at (10,268) size 260x15 contains 1 chunk(s) + chunk 1 text run 1 at (10.00,240.00) startOffset 0 endOffset 65 width 342.00: ".getBBox() for 'blueCircle': .x=-50,.y=-50,.width=100,.height=100" + LayoutSVGText {text} at (10,248) size 260x15 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 260x15 - chunk 1 text run 1 at (10.00,280.00) startOffset 0 endOffset 47 width 259.78: ".farthestViewportElement of blueCircle=svg-root" - LayoutSVGText {text} at (10,288) size 279x15 contains 1 chunk(s) + chunk 1 text run 1 at (10.00,260.00) startOffset 0 endOffset 47 width 259.78: ".farthestViewportElement of blueCircle=svg-root" + LayoutSVGText {text} at (10,268) size 279x15 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 279x15 - chunk 1 text run 1 at (10.00,300.00) startOffset 0 endOffset 47 width 278.78: ".nearestViewportElement of blueCircle=nestedSVG" + chunk 1 text run 1 at (10.00,280.00) startOffset 0 endOffset 47 width 278.78: ".nearestViewportElement of blueCircle=nestedSVG" LayoutSVGContainer {g} at (10,311) size 228x36 LayoutSVGText {text} at (10,311) size 228x36 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 228x36
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.png b/third_party/WebKit/LayoutTests/platform/linux/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.png index d754fac..53c303cf 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.txt index 4333783..831e37f 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/linux/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.txt
@@ -2,8 +2,8 @@ LayoutView at (0,0) size 480x360 layer at (0,0) size 480x360 LayoutSVGRoot {svg} at (0,0) size 480x360 - LayoutSVGContainer {g} at (10,7) size 365x296 - LayoutSVGContainer {g} at (10,7) size 365x296 + LayoutSVGContainer {g} at (10,7) size 365x276 + LayoutSVGContainer {g} at (10,7) size 365x276 LayoutSVGContainer {g} at (16,7) size 359x157 [transform={m=((1.00,0.00)(0.00,1.00)) t=(70.00,-60.00)}] LayoutSVGText {text} at (30,130) size 342x25 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 342x25 @@ -19,18 +19,15 @@ LayoutSVGText {text} at (10,208) size 240x15 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 240x15 chunk 1 text run 1 at (10.00,220.00) startOffset 0 endOffset 44 width 240.00: ".getCTM(): 0.42,0.42,-0.42,0.42,70.00,-60.00" - LayoutSVGText {text} at (10,228) size 313x15 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 313x15 - chunk 1 text run 1 at (10.00,240.00) startOffset 0 endOffset 56 width 312.22: ".getTransformToElement(): 0.42,0.42,-0.42,0.42,0.00,0.00" - LayoutSVGText {text} at (10,248) size 336x15 contains 1 chunk(s) + LayoutSVGText {text} at (10,228) size 336x15 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 336x15 - chunk 1 text run 1 at (10.00,260.00) startOffset 0 endOffset 64 width 336.00: ".getBBox() for 'redCircle': .x=-50,.y=-50,.width=100,.height=100" - LayoutSVGText {text} at (10,268) size 254x15 contains 1 chunk(s) + chunk 1 text run 1 at (10.00,240.00) startOffset 0 endOffset 64 width 336.00: ".getBBox() for 'redCircle': .x=-50,.y=-50,.width=100,.height=100" + LayoutSVGText {text} at (10,248) size 254x15 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 254x15 - chunk 1 text run 1 at (10.00,280.00) startOffset 0 endOffset 46 width 253.78: ".farthestViewportElement of redCircle=svg-root" - LayoutSVGText {text} at (10,288) size 273x15 contains 1 chunk(s) + chunk 1 text run 1 at (10.00,260.00) startOffset 0 endOffset 46 width 253.78: ".farthestViewportElement of redCircle=svg-root" + LayoutSVGText {text} at (10,268) size 273x15 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 273x15 - chunk 1 text run 1 at (10.00,300.00) startOffset 0 endOffset 46 width 272.78: ".nearestViewportElement of redCircle=nestedSVG" + chunk 1 text run 1 at (10.00,280.00) startOffset 0 endOffset 46 width 272.78: ".nearestViewportElement of redCircle=nestedSVG" LayoutSVGText {text} at (10,304) size 261x46 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 261x46 chunk 1 text run 1 at (10.00,340.00) startOffset 0 endOffset 16 width 261.00: "$Revision: 1.1 $"
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/animations/animate-elem-06-t-drt-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/svg/animations/animate-elem-06-t-drt-expected.txt index be2221d..9d4054c 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/svg/animations/animate-elem-06-t-drt-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/linux/svg/animations/animate-elem-06-t-drt-expected.txt
@@ -7,14 +7,14 @@ On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". -PASS rootSVGElement.getTransformToElement(path).e is -15 -PASS rootSVGElement.getTransformToElement(path).f is -43 -FAIL rootSVGElement.getTransformToElement(path).e should be close to -38.5. Was -38.3656120300293. -PASS rootSVGElement.getTransformToElement(path).f is -30 -PASS rootSVGElement.getTransformToElement(path).e is -65 -PASS rootSVGElement.getTransformToElement(path).f is -33 -PASS rootSVGElement.getTransformToElement(path).e is -65 -PASS rootSVGElement.getTransformToElement(path).f is -33 +PASS getTransformToElement(rootSVGElement, path).e is -15 +PASS getTransformToElement(rootSVGElement, path).f is -43 +FAIL getTransformToElement(rootSVGElement, path).e should be close to -38.5. Was -38.3656120300293. +PASS getTransformToElement(rootSVGElement, path).f is -30 +PASS getTransformToElement(rootSVGElement, path).e is -65 +PASS getTransformToElement(rootSVGElement, path).f is -33 +PASS getTransformToElement(rootSVGElement, path).e is -65 +PASS getTransformToElement(rootSVGElement, path).f is -33 PASS successfullyParsed is true TEST COMPLETE
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/custom/getTransformToElement-expected.png b/third_party/WebKit/LayoutTests/platform/linux/svg/custom/getTransformToElement-expected.png deleted file mode 100644 index 1e5c940..0000000 --- a/third_party/WebKit/LayoutTests/platform/linux/svg/custom/getTransformToElement-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/custom/getTransformToElement-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/svg/custom/getTransformToElement-expected.txt deleted file mode 100644 index bee682b..0000000 --- a/third_party/WebKit/LayoutTests/platform/linux/svg/custom/getTransformToElement-expected.txt +++ /dev/null
@@ -1,11 +0,0 @@ -layer at (0,0) size 800x600 - LayoutView at (0,0) size 800x600 -layer at (0,0) size 800x600 - LayoutSVGRoot {svg} at (20,56) size 101x157 - LayoutSVGContainer {g} at (0,0) size 0x0 [transform={m=((0.00,0.00)(0.00,0.00)) t=(0.00,0.00)}] - LayoutSVGContainer {g} at (20,56) size 40x18 [transform={m=((1.00,0.00)(0.00,1.00)) t=(15.00,15.00)}] - LayoutSVGText {text} at (50,123) size 80x34 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 80x34 - chunk 1 text run 1 at (50.00,150.00) startOffset 0 endOffset 6 width 80.00: "Passed" - LayoutSVGContainer {g} at (49,141) size 72x72 [transform={m=((0.71,0.71)(-0.71,0.71)) t=(0.00,0.00)}] - LayoutSVGRect {rect} at (49,141) size 72x72 [transform={m=((1.00,0.00)(0.00,1.00)) t=(100.00,0.00)}] [x=50.00] [y=50.00] [width=70.00] [height=30.00]
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/dom/css-transforms-expected.png b/third_party/WebKit/LayoutTests/platform/linux/svg/dom/css-transforms-expected.png index d2d234b..4a567c22 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/svg/dom/css-transforms-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/svg/dom/css-transforms-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac-lion/svg/dom/css-transforms-expected.png b/third_party/WebKit/LayoutTests/platform/mac-lion/svg/dom/css-transforms-expected.png index dbc9ce0c..77dd168 100644 --- a/third_party/WebKit/LayoutTests/platform/mac-lion/svg/dom/css-transforms-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac-lion/svg/dom/css-transforms-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac-mavericks/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.png b/third_party/WebKit/LayoutTests/platform/mac-mavericks/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.png index 9ffdd28..ef932178 100644 --- a/third_party/WebKit/LayoutTests/platform/mac-mavericks/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac-mavericks/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac-mavericks/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.png b/third_party/WebKit/LayoutTests/platform/mac-mavericks/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.png index ec43e34..8dd3dd4e 100644 --- a/third_party/WebKit/LayoutTests/platform/mac-mavericks/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac-mavericks/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac-mavericks/svg/dom/css-transforms-expected.png b/third_party/WebKit/LayoutTests/platform/mac-mavericks/svg/dom/css-transforms-expected.png index 32873a7..cb334033 100644 --- a/third_party/WebKit/LayoutTests/platform/mac-mavericks/svg/dom/css-transforms-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac-mavericks/svg/dom/css-transforms-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac-mountainlion/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.png b/third_party/WebKit/LayoutTests/platform/mac-mountainlion/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.png index 0930cd8..e2d54e2 100644 --- a/third_party/WebKit/LayoutTests/platform/mac-mountainlion/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac-mountainlion/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac-snowleopard/svg/dom/css-transforms-expected.png b/third_party/WebKit/LayoutTests/platform/mac-snowleopard/svg/dom/css-transforms-expected.png index 7bde7d8..1fdc0183 100644 --- a/third_party/WebKit/LayoutTests/platform/mac-snowleopard/svg/dom/css-transforms-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac-snowleopard/svg/dom/css-transforms-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac-snowleopard/svg/text/text-selection-ws-02-t-expected.png b/third_party/WebKit/LayoutTests/platform/mac-snowleopard/svg/text/text-selection-ws-02-t-expected.png deleted file mode 100644 index f65d669a..0000000 --- a/third_party/WebKit/LayoutTests/platform/mac-snowleopard/svg/text/text-selection-ws-02-t-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/fast/repaint/invalidation-after-opacity-change-subtree-expected.txt b/third_party/WebKit/LayoutTests/platform/mac/fast/repaint/invalidation-after-opacity-change-subtree-expected.txt index f8def546..fd1af38 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/fast/repaint/invalidation-after-opacity-change-subtree-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/mac/fast/repaint/invalidation-after-opacity-change-subtree-expected.txt
@@ -10,6 +10,7 @@ [8, 2195, 653, 109], [8, 2045, 777, 109], [8, 2045, 774, 109], + [8, 2000, 777, 350], [8, 2000, 777, 350] ], "paintInvalidationClients": [ @@ -23,7 +24,8 @@ "LayoutText #text", "InlineTextBox 'This text should be visible in the'", "InlineTextBox 'output.'", - "LayoutBlockFlow DIV id='container'" + "LayoutBlockFlow DIV id='container'", + "LayoutBlockFlow (positioned) DIV id='absolute'" ] } ]
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.png b/third_party/WebKit/LayoutTests/platform/mac/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.png index c3070ae..12337697 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.txt b/third_party/WebKit/LayoutTests/platform/mac/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.txt index a12ab1d..5cfd2b0 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/mac/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.txt
@@ -3,8 +3,8 @@ layer at (0,0) size 480x360 LayoutSVGRoot {svg} at (0,0) size 480x360 LayoutSVGHiddenContainer {defs} at (0,0) size 0x0 - LayoutSVGContainer {g} at (10,8) size 365x295 - LayoutSVGContainer {g} at (10,8) size 365x295 + LayoutSVGContainer {g} at (10,8) size 365x275 + LayoutSVGContainer {g} at (10,8) size 365x275 LayoutSVGContainer {g} at (16,8) size 359x155 [transform={m=((1.00,0.00)(0.00,1.00)) t=(70.00,-60.00)}] LayoutSVGText {text} at (30,131) size 341x24 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 341x24 @@ -20,18 +20,15 @@ LayoutSVGText {text} at (10,209) size 239x14 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 239x14 chunk 1 text run 1 at (10.00,220.00) startOffset 0 endOffset 44 width 238.81: ".getCTM(): 0.42,0.42,-0.42,0.42,70.00,-60.00" - LayoutSVGText {text} at (10,229) size 307x14 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 307x14 - chunk 1 text run 1 at (10.00,240.00) startOffset 0 endOffset 56 width 306.40: ".getTransformToElement(): 0.42,0.42,-0.42,0.42,0.00,0.00" - LayoutSVGText {text} at (10,249) size 341x14 contains 1 chunk(s) + LayoutSVGText {text} at (10,229) size 341x14 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 341x14 - chunk 1 text run 1 at (10.00,260.00) startOffset 0 endOffset 65 width 340.78: ".getBBox() for 'blueCircle': .x=-50,.y=-50,.width=100,.height=100" - LayoutSVGText {text} at (10,269) size 255x14 contains 1 chunk(s) + chunk 1 text run 1 at (10.00,240.00) startOffset 0 endOffset 65 width 340.78: ".getBBox() for 'blueCircle': .x=-50,.y=-50,.width=100,.height=100" + LayoutSVGText {text} at (10,249) size 255x14 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 255x14 - chunk 1 text run 1 at (10.00,280.00) startOffset 0 endOffset 47 width 254.24: ".farthestViewportElement of blueCircle=svg-root" - LayoutSVGText {text} at (10,289) size 273x14 contains 1 chunk(s) + chunk 1 text run 1 at (10.00,260.00) startOffset 0 endOffset 47 width 254.24: ".farthestViewportElement of blueCircle=svg-root" + LayoutSVGText {text} at (10,269) size 273x14 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 273x14 - chunk 1 text run 1 at (10.00,300.00) startOffset 0 endOffset 47 width 272.27: ".nearestViewportElement of blueCircle=nestedSVG" + chunk 1 text run 1 at (10.00,280.00) startOffset 0 endOffset 47 width 272.27: ".nearestViewportElement of blueCircle=nestedSVG" LayoutSVGContainer {g} at (10,310) size 230x37 LayoutSVGText {text} at (10,310) size 230x37 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 230x37
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.png b/third_party/WebKit/LayoutTests/platform/mac/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.png index 842562e..c93d90d 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.txt b/third_party/WebKit/LayoutTests/platform/mac/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.txt index 25ee08fe..f5a9775f 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/mac/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.txt
@@ -2,8 +2,8 @@ LayoutView at (0,0) size 480x360 layer at (0,0) size 480x360 LayoutSVGRoot {svg} at (0,0) size 480x360 - LayoutSVGContainer {g} at (10,8) size 365x295 - LayoutSVGContainer {g} at (10,8) size 365x295 + LayoutSVGContainer {g} at (10,8) size 365x275 + LayoutSVGContainer {g} at (10,8) size 365x275 LayoutSVGContainer {g} at (16,8) size 359x155 [transform={m=((1.00,0.00)(0.00,1.00)) t=(70.00,-60.00)}] LayoutSVGText {text} at (30,131) size 341x24 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 341x24 @@ -19,18 +19,15 @@ LayoutSVGText {text} at (10,209) size 239x14 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 239x14 chunk 1 text run 1 at (10.00,220.00) startOffset 0 endOffset 44 width 238.81: ".getCTM(): 0.42,0.42,-0.42,0.42,70.00,-60.00" - LayoutSVGText {text} at (10,229) size 307x14 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 307x14 - chunk 1 text run 1 at (10.00,240.00) startOffset 0 endOffset 56 width 306.40: ".getTransformToElement(): 0.42,0.42,-0.42,0.42,0.00,0.00" - LayoutSVGText {text} at (10,249) size 336x14 contains 1 chunk(s) + LayoutSVGText {text} at (10,229) size 336x14 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 336x14 - chunk 1 text run 1 at (10.00,260.00) startOffset 0 endOffset 64 width 335.43: ".getBBox() for 'redCircle': .x=-50,.y=-50,.width=100,.height=100" - LayoutSVGText {text} at (10,269) size 249x14 contains 1 chunk(s) + chunk 1 text run 1 at (10.00,240.00) startOffset 0 endOffset 64 width 335.43: ".getBBox() for 'redCircle': .x=-50,.y=-50,.width=100,.height=100" + LayoutSVGText {text} at (10,249) size 249x14 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 249x14 - chunk 1 text run 1 at (10.00,280.00) startOffset 0 endOffset 46 width 248.89: ".farthestViewportElement of redCircle=svg-root" - LayoutSVGText {text} at (10,289) size 267x14 contains 1 chunk(s) + chunk 1 text run 1 at (10.00,260.00) startOffset 0 endOffset 46 width 248.89: ".farthestViewportElement of redCircle=svg-root" + LayoutSVGText {text} at (10,269) size 267x14 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 267x14 - chunk 1 text run 1 at (10.00,300.00) startOffset 0 endOffset 46 width 266.92: ".nearestViewportElement of redCircle=nestedSVG" + chunk 1 text run 1 at (10.00,280.00) startOffset 0 endOffset 46 width 266.92: ".nearestViewportElement of redCircle=nestedSVG" LayoutSVGText {text} at (10,304) size 264x46 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 264x46 chunk 1 text run 1 at (10.00,340.00) startOffset 0 endOffset 16 width 263.34: "$Revision: 1.1 $"
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/animations/animate-elem-08-t-drt-expected.txt b/third_party/WebKit/LayoutTests/platform/mac/svg/animations/animate-elem-08-t-drt-expected.txt index 9574e44..b222eaf7 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/svg/animations/animate-elem-08-t-drt-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/mac/svg/animations/animate-elem-08-t-drt-expected.txt
@@ -7,54 +7,54 @@ On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". -PASS rootSVGElement.getTransformToElement(path1).a is 0 -PASS rootSVGElement.getTransformToElement(path1).b is 1 -PASS rootSVGElement.getTransformToElement(path1).c is -1 -PASS rootSVGElement.getTransformToElement(path1).d is 0 -PASS rootSVGElement.getTransformToElement(path1).e is 224.9 -FAIL rootSVGElement.getTransformToElement(path1).f should be close to -25.9. Was -25.000000000000014. -PASS rootSVGElement.getTransformToElement(path2).a is 0 -PASS rootSVGElement.getTransformToElement(path2).b is -1 -PASS rootSVGElement.getTransformToElement(path2).c is 1 -PASS rootSVGElement.getTransformToElement(path2).d is 0 -FAIL rootSVGElement.getTransformToElement(path2).e should be close to -223.9. Was -225. -FAIL rootSVGElement.getTransformToElement(path2).f should be close to 275.9. Was 275. -PASS rootSVGElement.getTransformToElement(path1).a is 1 -PASS rootSVGElement.getTransformToElement(path1).b is 0.1 -PASS rootSVGElement.getTransformToElement(path1).c is -0.1 -PASS rootSVGElement.getTransformToElement(path1).d is 1 -FAIL rootSVGElement.getTransformToElement(path1).e should be close to -70.3. Was -70.87814895357428. -FAIL rootSVGElement.getTransformToElement(path1).f should be close to -182.8. Was -182.60109333201257. -PASS rootSVGElement.getTransformToElement(path2).a is -1 -PASS rootSVGElement.getTransformToElement(path2).b is -0.1 -PASS rootSVGElement.getTransformToElement(path2).c is 0.1 -PASS rootSVGElement.getTransformToElement(path2).d is -1 -FAIL rootSVGElement.getTransformToElement(path2).e should be close to 318.6. Was 319.29822182153924. -FAIL rootSVGElement.getTransformToElement(path2).f should be close to 211.6. Was 210.66313575977358. -PASS rootSVGElement.getTransformToElement(path1).a is 0.7 -PASS rootSVGElement.getTransformToElement(path1).b is -0.7 -PASS rootSVGElement.getTransformToElement(path1).c is 0.7 -PASS rootSVGElement.getTransformToElement(path1).d is 0.7 -PASS rootSVGElement.getTransformToElement(path1).e is -265.1 -FAIL rootSVGElement.getTransformToElement(path1).f should be close to -18.9. Was -17.677916691624326. -PASS rootSVGElement.getTransformToElement(path2).a is -0.7 -PASS rootSVGElement.getTransformToElement(path2).b is 0.7 -PASS rootSVGElement.getTransformToElement(path2).c is -0.7 -PASS rootSVGElement.getTransformToElement(path2).d is -0.7 -FAIL rootSVGElement.getTransformToElement(path2).e should be close to 442.7. Was 441.941810617502. -FAIL rootSVGElement.getTransformToElement(path2).f should be close to -156.9. Was -159.09852261339003. -PASS rootSVGElement.getTransformToElement(path1).a is 0.7 -PASS rootSVGElement.getTransformToElement(path1).b is -0.7 -PASS rootSVGElement.getTransformToElement(path1).c is 0.7 -PASS rootSVGElement.getTransformToElement(path1).d is 0.7 -PASS rootSVGElement.getTransformToElement(path1).e is -265.1 -FAIL rootSVGElement.getTransformToElement(path1).f should be close to -18.9. Was -17.677916691624326. -PASS rootSVGElement.getTransformToElement(path2).a is -0.7 -PASS rootSVGElement.getTransformToElement(path2).b is 0.7 -PASS rootSVGElement.getTransformToElement(path2).c is -0.7 -PASS rootSVGElement.getTransformToElement(path2).d is -0.7 -FAIL rootSVGElement.getTransformToElement(path2).e should be close to 442.7. Was 441.941810617502. -FAIL rootSVGElement.getTransformToElement(path2).f should be close to -156.9. Was -159.09852261339003. +PASS getTransformToElement(rootSVGElement, path1).a is 0 +PASS getTransformToElement(rootSVGElement, path1).b is 1 +PASS getTransformToElement(rootSVGElement, path1).c is -1 +PASS getTransformToElement(rootSVGElement, path1).d is 0 +PASS getTransformToElement(rootSVGElement, path1).e is 224.9 +FAIL getTransformToElement(rootSVGElement, path1).f should be close to -25.9. Was -25.000000000000014. +PASS getTransformToElement(rootSVGElement, path2).a is 0 +PASS getTransformToElement(rootSVGElement, path2).b is -1 +PASS getTransformToElement(rootSVGElement, path2).c is 1 +PASS getTransformToElement(rootSVGElement, path2).d is 0 +FAIL getTransformToElement(rootSVGElement, path2).e should be close to -223.9. Was -225. +FAIL getTransformToElement(rootSVGElement, path2).f should be close to 275.9. Was 275. +PASS getTransformToElement(rootSVGElement, path1).a is 1 +PASS getTransformToElement(rootSVGElement, path1).b is 0.1 +PASS getTransformToElement(rootSVGElement, path1).c is -0.1 +PASS getTransformToElement(rootSVGElement, path1).d is 1 +FAIL getTransformToElement(rootSVGElement, path1).e should be close to -70.3. Was -70.87814895357428. +FAIL getTransformToElement(rootSVGElement, path1).f should be close to -182.8. Was -182.60109333201257. +PASS getTransformToElement(rootSVGElement, path2).a is -1 +PASS getTransformToElement(rootSVGElement, path2).b is -0.1 +PASS getTransformToElement(rootSVGElement, path2).c is 0.1 +PASS getTransformToElement(rootSVGElement, path2).d is -1 +FAIL getTransformToElement(rootSVGElement, path2).e should be close to 318.6. Was 319.29822182153924. +FAIL getTransformToElement(rootSVGElement, path2).f should be close to 211.6. Was 210.66313575977358. +PASS getTransformToElement(rootSVGElement, path1).a is 0.7 +PASS getTransformToElement(rootSVGElement, path1).b is -0.7 +PASS getTransformToElement(rootSVGElement, path1).c is 0.7 +PASS getTransformToElement(rootSVGElement, path1).d is 0.7 +PASS getTransformToElement(rootSVGElement, path1).e is -265.1 +FAIL getTransformToElement(rootSVGElement, path1).f should be close to -18.9. Was -17.677916691624326. +PASS getTransformToElement(rootSVGElement, path2).a is -0.7 +PASS getTransformToElement(rootSVGElement, path2).b is 0.7 +PASS getTransformToElement(rootSVGElement, path2).c is -0.7 +PASS getTransformToElement(rootSVGElement, path2).d is -0.7 +FAIL getTransformToElement(rootSVGElement, path2).e should be close to 442.7. Was 441.941810617502. +FAIL getTransformToElement(rootSVGElement, path2).f should be close to -156.9. Was -159.09852261339003. +PASS getTransformToElement(rootSVGElement, path1).a is 0.7 +PASS getTransformToElement(rootSVGElement, path1).b is -0.7 +PASS getTransformToElement(rootSVGElement, path1).c is 0.7 +PASS getTransformToElement(rootSVGElement, path1).d is 0.7 +PASS getTransformToElement(rootSVGElement, path1).e is -265.1 +FAIL getTransformToElement(rootSVGElement, path1).f should be close to -18.9. Was -17.677916691624326. +PASS getTransformToElement(rootSVGElement, path2).a is -0.7 +PASS getTransformToElement(rootSVGElement, path2).b is 0.7 +PASS getTransformToElement(rootSVGElement, path2).c is -0.7 +PASS getTransformToElement(rootSVGElement, path2).d is -0.7 +FAIL getTransformToElement(rootSVGElement, path2).e should be close to 442.7. Was 441.941810617502. +FAIL getTransformToElement(rootSVGElement, path2).f should be close to -156.9. Was -159.09852261339003. PASS successfullyParsed is true TEST COMPLETE
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/custom/getTransformToElement-expected.png b/third_party/WebKit/LayoutTests/platform/mac/svg/custom/getTransformToElement-expected.png deleted file mode 100644 index c7ad916c..0000000 --- a/third_party/WebKit/LayoutTests/platform/mac/svg/custom/getTransformToElement-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/custom/getTransformToElement-expected.txt b/third_party/WebKit/LayoutTests/platform/mac/svg/custom/getTransformToElement-expected.txt deleted file mode 100644 index 4aa66585..0000000 --- a/third_party/WebKit/LayoutTests/platform/mac/svg/custom/getTransformToElement-expected.txt +++ /dev/null
@@ -1,11 +0,0 @@ -layer at (0,0) size 800x600 - LayoutView at (0,0) size 800x600 -layer at (0,0) size 800x600 - LayoutSVGRoot {svg} at (20,56) size 101x157 - LayoutSVGContainer {g} at (0,0) size 0x0 [transform={m=((0.00,0.00)(0.00,0.00)) t=(0.00,0.00)}] - LayoutSVGContainer {g} at (20,56) size 41x18 [transform={m=((1.00,0.00)(0.00,1.00)) t=(15.00,15.00)}] - LayoutSVGText {text} at (50,122) size 82x36 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 82x36 - chunk 1 text run 1 at (50.00,150.00) startOffset 0 endOffset 6 width 81.67: "Passed" - LayoutSVGContainer {g} at (49,141) size 72x72 [transform={m=((0.71,0.71)(-0.71,0.71)) t=(0.00,0.00)}] - LayoutSVGRect {rect} at (49,141) size 72x72 [transform={m=((1.00,0.00)(0.00,1.00)) t=(100.00,0.00)}] [x=50.00] [y=50.00] [width=70.00] [height=30.00]
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/dom/css-transforms-expected.png b/third_party/WebKit/LayoutTests/platform/mac/svg/dom/css-transforms-expected.png index 09ec1ea..dc87defe 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/svg/dom/css-transforms-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/svg/dom/css-transforms-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win-xp/fast/repaint/containing-block-position-change-expected.txt b/third_party/WebKit/LayoutTests/platform/win-xp/fast/repaint/containing-block-position-change-expected.txt index 504ba60..2338b07 100644 --- a/third_party/WebKit/LayoutTests/platform/win-xp/fast/repaint/containing-block-position-change-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/win-xp/fast/repaint/containing-block-position-change-expected.txt
@@ -10,6 +10,7 @@ [100, 74, 50, 50] ], "paintInvalidationClients": [ + "LayoutBlockFlow (positioned) DIV", "LayoutBlockFlow (relative positioned) DIV id='t'", "LayoutBlockFlow (positioned) DIV" ]
diff --git a/third_party/WebKit/LayoutTests/platform/win-xp/fast/repaint/invalidation-after-opacity-change-subtree-expected.txt b/third_party/WebKit/LayoutTests/platform/win-xp/fast/repaint/invalidation-after-opacity-change-subtree-expected.txt index 9c38308c..81df00a 100644 --- a/third_party/WebKit/LayoutTests/platform/win-xp/fast/repaint/invalidation-after-opacity-change-subtree-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/win-xp/fast/repaint/invalidation-after-opacity-change-subtree-expected.txt
@@ -10,6 +10,7 @@ [8, 2196, 639, 107], [8, 2046, 777, 107], [8, 2046, 766, 107], + [8, 2000, 777, 350], [8, 2000, 777, 350] ], "paintInvalidationClients": [ @@ -23,7 +24,8 @@ "LayoutText #text", "InlineTextBox 'This text should be visible in the'", "InlineTextBox 'output.'", - "LayoutBlockFlow DIV id='container'" + "LayoutBlockFlow DIV id='container'", + "LayoutBlockFlow (positioned) DIV id='absolute'" ] } ]
diff --git a/third_party/WebKit/LayoutTests/platform/win-xp/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.txt b/third_party/WebKit/LayoutTests/platform/win-xp/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.txt index 35a5cda..ba7fef54 100644 --- a/third_party/WebKit/LayoutTests/platform/win-xp/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/win-xp/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.txt
@@ -1,39 +1,39 @@ layer at (0,0) size 480x360 - LayoutView at (0,0) size 480x360 + RenderView at (0,0) size 480x360 layer at (0,0) size 480x360 - LayoutSVGRoot {svg} at (0,0) size 480x360 - LayoutSVGHiddenContainer {defs} at (0,0) size 0x0 - LayoutSVGContainer {g} at (10,7) size 365x296 - LayoutSVGContainer {g} at (10,7) size 365x296 - LayoutSVGContainer {g} at (16,7) size 359x158 [transform={m=((1.00,0.00)(0.00,1.00)) t=(70.00,-60.00)}] - LayoutSVGText {text} at (30,130) size 344x25 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 344x25 + RenderSVGRoot {svg} at (0,0) size 480x360 + RenderSVGHiddenContainer {defs} at (0,0) size 0x0 + RenderSVGContainer {g} at (10,7) size 365x296 + RenderSVGContainer {g} at (10,7) size 365x296 + RenderSVGContainer {g} at (16,7) size 359x158 [transform={m=((1.00,0.00)(0.00,1.00)) t=(70.00,-60.00)}] + RenderSVGText {text} at (30,130) size 344x25 contains 1 chunk(s) + RenderSVGInlineText {#text} at (0,0) size 344x25 chunk 1 text run 1 at (30.00,150.00) startOffset 0 endOffset 37 width 343.33: "Rotated Text for testing SVGLocatable" - LayoutSVGText {text} at (100,111) size 303x24 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 303x23 + RenderSVGText {text} at (100,111) size 303x24 contains 1 chunk(s) + RenderSVGInlineText {#text} at (0,0) size 303x23 chunk 1 text run 1 at (100.00,130.00) startOffset 0 endOffset 35 width 302.86: "Some other text with id 'otherText'" - LayoutSVGViewportContainer {svg} at (275,45) size 100x100 - LayoutSVGEllipse {circle} at (275,45) size 100x100 [fill={[type=SOLID] [color=#0000FF]}] [cx=0.00] [cy=0.00] [r=50.00] - LayoutSVGText {text} at (10,188) size 279x15 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 279x15 + RenderSVGViewportContainer {svg} at (275,45) size 100x100 + RenderSVGEllipse {circle} at (275,45) size 100x100 [fill={[type=SOLID] [color=#0000FF]}] [cx=0.00] [cy=0.00] [r=50.00] + RenderSVGText {text} at (10,188) size 279x15 contains 1 chunk(s) + RenderSVGInlineText {#text} at (0,0) size 279x15 chunk 1 text run 1 at (10.00,200.00) startOffset 0 endOffset 50 width 279.00: ".getScreenCTM(): 0.42,0.42,-0.42,0.42,70.00,-60.00" - LayoutSVGText {text} at (10,208) size 240x15 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 240x15 + RenderSVGText {text} at (10,208) size 240x15 contains 1 chunk(s) + RenderSVGInlineText {#text} at (0,0) size 240x15 chunk 1 text run 1 at (10.00,220.00) startOffset 0 endOffset 44 width 240.00: ".getCTM(): 0.42,0.42,-0.42,0.42,70.00,-60.00" - LayoutSVGText {text} at (10,228) size 314x15 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 314x15 + RenderSVGText {text} at (10,228) size 314x15 contains 1 chunk(s) + RenderSVGInlineText {#text} at (0,0) size 314x15 chunk 1 text run 1 at (10.00,240.00) startOffset 0 endOffset 56 width 314.00: ".getTransformToElement(): 0.42,0.42,-0.42,0.42,0.00,0.00" - LayoutSVGText {text} at (10,248) size 342x15 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 342x15 + RenderSVGText {text} at (10,248) size 342x15 contains 1 chunk(s) + RenderSVGInlineText {#text} at (0,0) size 342x15 chunk 1 text run 1 at (10.00,260.00) startOffset 0 endOffset 65 width 342.00: ".getBBox() for 'blueCircle': .x=-50,.y=-50,.width=100,.height=100" - LayoutSVGText {text} at (10,268) size 260x15 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 260x15 + RenderSVGText {text} at (10,268) size 260x15 contains 1 chunk(s) + RenderSVGInlineText {#text} at (0,0) size 260x15 chunk 1 text run 1 at (10.00,280.00) startOffset 0 endOffset 47 width 260.00: ".farthestViewportElement of blueCircle=svg-root" - LayoutSVGText {text} at (10,288) size 279x15 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 279x15 + RenderSVGText {text} at (10,288) size 279x15 contains 1 chunk(s) + RenderSVGInlineText {#text} at (0,0) size 279x15 chunk 1 text run 1 at (10.00,300.00) startOffset 0 endOffset 47 width 279.00: ".nearestViewportElement of blueCircle=nestedSVG" - LayoutSVGContainer {g} at (10,311) size 228x36 - LayoutSVGText {text} at (10,311) size 228x36 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 228x36 + RenderSVGContainer {g} at (10,311) size 228x36 + RenderSVGText {text} at (10,311) size 228x36 contains 1 chunk(s) + RenderSVGInlineText {#text} at (0,0) size 228x36 chunk 1 text run 1 at (10.00,340.00) startOffset 0 endOffset 16 width 228.00: "$Revision: 1.6 $" - LayoutSVGRect {rect} at (0,0) size 480x360 [stroke={[type=SOLID] [color=#000000]}] [x=1.00] [y=1.00] [width=478.00] [height=358.00] + RenderSVGRect {rect} at (0,0) size 480x360 [stroke={[type=SOLID] [color=#000000]}] [x=1.00] [y=1.00] [width=478.00] [height=358.00]
diff --git a/third_party/WebKit/LayoutTests/platform/win-xp/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.txt b/third_party/WebKit/LayoutTests/platform/win-xp/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.txt index 48f1d87..b6751bb 100644 --- a/third_party/WebKit/LayoutTests/platform/win-xp/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/win-xp/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.txt
@@ -1,37 +1,37 @@ layer at (0,0) size 480x360 - LayoutView at (0,0) size 480x360 + RenderView at (0,0) size 480x360 layer at (0,0) size 480x360 - LayoutSVGRoot {svg} at (0,0) size 480x360 - LayoutSVGContainer {g} at (10,7) size 365x296 - LayoutSVGContainer {g} at (10,7) size 365x296 - LayoutSVGContainer {g} at (16,7) size 359x158 [transform={m=((1.00,0.00)(0.00,1.00)) t=(70.00,-60.00)}] - LayoutSVGText {text} at (30,130) size 344x25 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 344x25 + RenderSVGRoot {svg} at (0,0) size 480x360 + RenderSVGContainer {g} at (10,7) size 365x296 + RenderSVGContainer {g} at (10,7) size 365x296 + RenderSVGContainer {g} at (16,7) size 359x158 [transform={m=((1.00,0.00)(0.00,1.00)) t=(70.00,-60.00)}] + RenderSVGText {text} at (30,130) size 344x25 contains 1 chunk(s) + RenderSVGInlineText {#text} at (0,0) size 344x25 chunk 1 text run 1 at (30.00,150.00) startOffset 0 endOffset 37 width 343.33: "Rotated Text for testing SVGLocatable" - LayoutSVGText {text} at (100,111) size 303x24 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 303x23 + RenderSVGText {text} at (100,111) size 303x24 contains 1 chunk(s) + RenderSVGInlineText {#text} at (0,0) size 303x23 chunk 1 text run 1 at (100.00,130.00) startOffset 0 endOffset 35 width 302.86: "Some other text with id 'otherText'" - LayoutSVGViewportContainer {svg} at (275,45) size 100x100 - LayoutSVGEllipse {circle} at (275,45) size 100x100 [fill={[type=SOLID] [color=#FF0000]}] [cx=0.00] [cy=0.00] [r=50.00] - LayoutSVGText {text} at (10,188) size 279x15 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 279x15 + RenderSVGViewportContainer {svg} at (275,45) size 100x100 + RenderSVGEllipse {circle} at (275,45) size 100x100 [fill={[type=SOLID] [color=#FF0000]}] [cx=0.00] [cy=0.00] [r=50.00] + RenderSVGText {text} at (10,188) size 279x15 contains 1 chunk(s) + RenderSVGInlineText {#text} at (0,0) size 279x15 chunk 1 text run 1 at (10.00,200.00) startOffset 0 endOffset 50 width 279.00: ".getScreenCTM(): 0.42,0.42,-0.42,0.42,70.00,-60.00" - LayoutSVGText {text} at (10,208) size 240x15 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 240x15 + RenderSVGText {text} at (10,208) size 240x15 contains 1 chunk(s) + RenderSVGInlineText {#text} at (0,0) size 240x15 chunk 1 text run 1 at (10.00,220.00) startOffset 0 endOffset 44 width 240.00: ".getCTM(): 0.42,0.42,-0.42,0.42,70.00,-60.00" - LayoutSVGText {text} at (10,228) size 314x15 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 314x15 + RenderSVGText {text} at (10,228) size 314x15 contains 1 chunk(s) + RenderSVGInlineText {#text} at (0,0) size 314x15 chunk 1 text run 1 at (10.00,240.00) startOffset 0 endOffset 56 width 314.00: ".getTransformToElement(): 0.42,0.42,-0.42,0.42,0.00,0.00" - LayoutSVGText {text} at (10,248) size 336x15 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 336x15 + RenderSVGText {text} at (10,248) size 336x15 contains 1 chunk(s) + RenderSVGInlineText {#text} at (0,0) size 336x15 chunk 1 text run 1 at (10.00,260.00) startOffset 0 endOffset 64 width 336.00: ".getBBox() for 'redCircle': .x=-50,.y=-50,.width=100,.height=100" - LayoutSVGText {text} at (10,268) size 254x15 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 254x15 + RenderSVGText {text} at (10,268) size 254x15 contains 1 chunk(s) + RenderSVGInlineText {#text} at (0,0) size 254x15 chunk 1 text run 1 at (10.00,280.00) startOffset 0 endOffset 46 width 254.00: ".farthestViewportElement of redCircle=svg-root" - LayoutSVGText {text} at (10,288) size 273x15 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 273x15 + RenderSVGText {text} at (10,288) size 273x15 contains 1 chunk(s) + RenderSVGInlineText {#text} at (0,0) size 273x15 chunk 1 text run 1 at (10.00,300.00) startOffset 0 endOffset 46 width 273.00: ".nearestViewportElement of redCircle=nestedSVG" - LayoutSVGText {text} at (10,304) size 261x46 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 261x46 + RenderSVGText {text} at (10,304) size 261x46 contains 1 chunk(s) + RenderSVGInlineText {#text} at (0,0) size 261x46 chunk 1 text run 1 at (10.00,340.00) startOffset 0 endOffset 16 width 261.00: "$Revision: 1.1 $" - LayoutSVGRect {rect} at (0,0) size 480x360 [stroke={[type=SOLID] [color=#000000]}] [x=1.00] [y=1.00] [width=478.00] [height=358.00] + RenderSVGRect {rect} at (0,0) size 480x360 [stroke={[type=SOLID] [color=#000000]}] [x=1.00] [y=1.00] [width=478.00] [height=358.00]
diff --git a/third_party/WebKit/LayoutTests/platform/win-xp/svg/animations/animate-elem-06-t-drt-expected.txt b/third_party/WebKit/LayoutTests/platform/win-xp/svg/animations/animate-elem-06-t-drt-expected.txt index be2221d..9d4054c 100644 --- a/third_party/WebKit/LayoutTests/platform/win-xp/svg/animations/animate-elem-06-t-drt-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/win-xp/svg/animations/animate-elem-06-t-drt-expected.txt
@@ -7,14 +7,14 @@ On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". -PASS rootSVGElement.getTransformToElement(path).e is -15 -PASS rootSVGElement.getTransformToElement(path).f is -43 -FAIL rootSVGElement.getTransformToElement(path).e should be close to -38.5. Was -38.3656120300293. -PASS rootSVGElement.getTransformToElement(path).f is -30 -PASS rootSVGElement.getTransformToElement(path).e is -65 -PASS rootSVGElement.getTransformToElement(path).f is -33 -PASS rootSVGElement.getTransformToElement(path).e is -65 -PASS rootSVGElement.getTransformToElement(path).f is -33 +PASS getTransformToElement(rootSVGElement, path).e is -15 +PASS getTransformToElement(rootSVGElement, path).f is -43 +FAIL getTransformToElement(rootSVGElement, path).e should be close to -38.5. Was -38.3656120300293. +PASS getTransformToElement(rootSVGElement, path).f is -30 +PASS getTransformToElement(rootSVGElement, path).e is -65 +PASS getTransformToElement(rootSVGElement, path).f is -33 +PASS getTransformToElement(rootSVGElement, path).e is -65 +PASS getTransformToElement(rootSVGElement, path).f is -33 PASS successfullyParsed is true TEST COMPLETE
diff --git a/third_party/WebKit/LayoutTests/platform/win-xp/svg/custom/getTransformToElement-expected.png b/third_party/WebKit/LayoutTests/platform/win-xp/svg/custom/getTransformToElement-expected.png deleted file mode 100644 index 0211d1f..0000000 --- a/third_party/WebKit/LayoutTests/platform/win-xp/svg/custom/getTransformToElement-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win-xp/svg/custom/getTransformToElement-expected.txt b/third_party/WebKit/LayoutTests/platform/win-xp/svg/custom/getTransformToElement-expected.txt deleted file mode 100644 index bee682b..0000000 --- a/third_party/WebKit/LayoutTests/platform/win-xp/svg/custom/getTransformToElement-expected.txt +++ /dev/null
@@ -1,11 +0,0 @@ -layer at (0,0) size 800x600 - LayoutView at (0,0) size 800x600 -layer at (0,0) size 800x600 - LayoutSVGRoot {svg} at (20,56) size 101x157 - LayoutSVGContainer {g} at (0,0) size 0x0 [transform={m=((0.00,0.00)(0.00,0.00)) t=(0.00,0.00)}] - LayoutSVGContainer {g} at (20,56) size 40x18 [transform={m=((1.00,0.00)(0.00,1.00)) t=(15.00,15.00)}] - LayoutSVGText {text} at (50,123) size 80x34 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 80x34 - chunk 1 text run 1 at (50.00,150.00) startOffset 0 endOffset 6 width 80.00: "Passed" - LayoutSVGContainer {g} at (49,141) size 72x72 [transform={m=((0.71,0.71)(-0.71,0.71)) t=(0.00,0.00)}] - LayoutSVGRect {rect} at (49,141) size 72x72 [transform={m=((1.00,0.00)(0.00,1.00)) t=(100.00,0.00)}] [x=50.00] [y=50.00] [width=70.00] [height=30.00]
diff --git a/third_party/WebKit/LayoutTests/platform/win/fast/repaint/invalidation-after-opacity-change-subtree-expected.txt b/third_party/WebKit/LayoutTests/platform/win/fast/repaint/invalidation-after-opacity-change-subtree-expected.txt index c1cac73..3e12513 100644 --- a/third_party/WebKit/LayoutTests/platform/win/fast/repaint/invalidation-after-opacity-change-subtree-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/win/fast/repaint/invalidation-after-opacity-change-subtree-expected.txt
@@ -10,6 +10,7 @@ [8, 2197, 653, 106], [8, 2047, 777, 106], [8, 2047, 774, 106], + [8, 2000, 777, 350], [8, 2000, 777, 350] ], "paintInvalidationClients": [ @@ -23,7 +24,8 @@ "LayoutText #text", "InlineTextBox 'This text should be visible in the'", "InlineTextBox 'output.'", - "LayoutBlockFlow DIV id='container'" + "LayoutBlockFlow DIV id='container'", + "LayoutBlockFlow (positioned) DIV id='absolute'" ] } ]
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.png b/third_party/WebKit/LayoutTests/platform/win/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.png index 8dce6d07..78037a7 100644 --- a/third_party/WebKit/LayoutTests/platform/win/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.txt b/third_party/WebKit/LayoutTests/platform/win/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.txt index 31ad339..5685597 100644 --- a/third_party/WebKit/LayoutTests/platform/win/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/win/svg/W3C-SVG-1.1-SE/types-dom-01-b-expected.txt
@@ -3,8 +3,8 @@ layer at (0,0) size 480x360 LayoutSVGRoot {svg} at (0,0) size 480x360 LayoutSVGHiddenContainer {defs} at (0,0) size 0x0 - LayoutSVGContainer {g} at (10,7) size 365x296 - LayoutSVGContainer {g} at (10,7) size 365x296 + LayoutSVGContainer {g} at (10,7) size 365x276 + LayoutSVGContainer {g} at (10,7) size 365x276 LayoutSVGContainer {g} at (16,7) size 359x157 [transform={m=((1.00,0.00)(0.00,1.00)) t=(70.00,-60.00)}] LayoutSVGText {text} at (30,130) size 342x25 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 342x25 @@ -20,18 +20,15 @@ LayoutSVGText {text} at (10,208) size 240x15 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 240x15 chunk 1 text run 1 at (10.00,220.00) startOffset 0 endOffset 44 width 240.00: ".getCTM(): 0.42,0.42,-0.42,0.42,70.00,-60.00" - LayoutSVGText {text} at (10,228) size 313x15 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 313x15 - chunk 1 text run 1 at (10.00,240.00) startOffset 0 endOffset 56 width 312.22: ".getTransformToElement(): 0.42,0.42,-0.42,0.42,0.00,0.00" - LayoutSVGText {text} at (10,248) size 342x15 contains 1 chunk(s) + LayoutSVGText {text} at (10,228) size 342x15 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 342x15 - chunk 1 text run 1 at (10.00,260.00) startOffset 0 endOffset 65 width 342.00: ".getBBox() for 'blueCircle': .x=-50,.y=-50,.width=100,.height=100" - LayoutSVGText {text} at (10,268) size 260x15 contains 1 chunk(s) + chunk 1 text run 1 at (10.00,240.00) startOffset 0 endOffset 65 width 342.00: ".getBBox() for 'blueCircle': .x=-50,.y=-50,.width=100,.height=100" + LayoutSVGText {text} at (10,248) size 260x15 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 260x15 - chunk 1 text run 1 at (10.00,280.00) startOffset 0 endOffset 47 width 259.78: ".farthestViewportElement of blueCircle=svg-root" - LayoutSVGText {text} at (10,288) size 279x15 contains 1 chunk(s) + chunk 1 text run 1 at (10.00,260.00) startOffset 0 endOffset 47 width 259.78: ".farthestViewportElement of blueCircle=svg-root" + LayoutSVGText {text} at (10,268) size 279x15 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 279x15 - chunk 1 text run 1 at (10.00,300.00) startOffset 0 endOffset 47 width 278.78: ".nearestViewportElement of blueCircle=nestedSVG" + chunk 1 text run 1 at (10.00,280.00) startOffset 0 endOffset 47 width 278.78: ".nearestViewportElement of blueCircle=nestedSVG" LayoutSVGContainer {g} at (10,311) size 230x36 LayoutSVGText {text} at (10,311) size 230x36 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 230x36
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.png b/third_party/WebKit/LayoutTests/platform/win/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.png index f438286..2d4f1bd 100644 --- a/third_party/WebKit/LayoutTests/platform/win/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.txt b/third_party/WebKit/LayoutTests/platform/win/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.txt index 3d7d6b3..17368cb 100644 --- a/third_party/WebKit/LayoutTests/platform/win/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/win/svg/W3C-SVG-1.1/types-basicDOM-01-b-expected.txt
@@ -2,8 +2,8 @@ LayoutView at (0,0) size 480x360 layer at (0,0) size 480x360 LayoutSVGRoot {svg} at (0,0) size 480x360 - LayoutSVGContainer {g} at (10,7) size 365x296 - LayoutSVGContainer {g} at (10,7) size 365x296 + LayoutSVGContainer {g} at (10,7) size 365x276 + LayoutSVGContainer {g} at (10,7) size 365x276 LayoutSVGContainer {g} at (16,7) size 359x157 [transform={m=((1.00,0.00)(0.00,1.00)) t=(70.00,-60.00)}] LayoutSVGText {text} at (30,130) size 342x25 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 342x25 @@ -19,18 +19,15 @@ LayoutSVGText {text} at (10,208) size 240x15 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 240x15 chunk 1 text run 1 at (10.00,220.00) startOffset 0 endOffset 44 width 240.00: ".getCTM(): 0.42,0.42,-0.42,0.42,70.00,-60.00" - LayoutSVGText {text} at (10,228) size 313x15 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 313x15 - chunk 1 text run 1 at (10.00,240.00) startOffset 0 endOffset 56 width 312.22: ".getTransformToElement(): 0.42,0.42,-0.42,0.42,0.00,0.00" - LayoutSVGText {text} at (10,248) size 336x15 contains 1 chunk(s) + LayoutSVGText {text} at (10,228) size 336x15 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 336x15 - chunk 1 text run 1 at (10.00,260.00) startOffset 0 endOffset 64 width 336.00: ".getBBox() for 'redCircle': .x=-50,.y=-50,.width=100,.height=100" - LayoutSVGText {text} at (10,268) size 254x15 contains 1 chunk(s) + chunk 1 text run 1 at (10.00,240.00) startOffset 0 endOffset 64 width 336.00: ".getBBox() for 'redCircle': .x=-50,.y=-50,.width=100,.height=100" + LayoutSVGText {text} at (10,248) size 254x15 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 254x15 - chunk 1 text run 1 at (10.00,280.00) startOffset 0 endOffset 46 width 253.78: ".farthestViewportElement of redCircle=svg-root" - LayoutSVGText {text} at (10,288) size 273x15 contains 1 chunk(s) + chunk 1 text run 1 at (10.00,260.00) startOffset 0 endOffset 46 width 253.78: ".farthestViewportElement of redCircle=svg-root" + LayoutSVGText {text} at (10,268) size 273x15 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 273x15 - chunk 1 text run 1 at (10.00,300.00) startOffset 0 endOffset 46 width 272.78: ".nearestViewportElement of redCircle=nestedSVG" + chunk 1 text run 1 at (10.00,280.00) startOffset 0 endOffset 46 width 272.78: ".nearestViewportElement of redCircle=nestedSVG" LayoutSVGText {text} at (10,304) size 264x45 contains 1 chunk(s) LayoutSVGInlineText {#text} at (0,0) size 264x45 chunk 1 text run 1 at (10.00,340.00) startOffset 0 endOffset 16 width 263.34: "$Revision: 1.1 $"
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/animations/animate-elem-08-t-drt-expected.txt b/third_party/WebKit/LayoutTests/platform/win/svg/animations/animate-elem-08-t-drt-expected.txt index 635976b..f31cc7e 100644 --- a/third_party/WebKit/LayoutTests/platform/win/svg/animations/animate-elem-08-t-drt-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/win/svg/animations/animate-elem-08-t-drt-expected.txt
@@ -7,54 +7,54 @@ On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". -PASS rootSVGElement.getTransformToElement(path1).a is 0 -PASS rootSVGElement.getTransformToElement(path1).b is 1 -PASS rootSVGElement.getTransformToElement(path1).c is -1 -PASS rootSVGElement.getTransformToElement(path1).d is 0 -PASS rootSVGElement.getTransformToElement(path1).e is 224.9 -FAIL rootSVGElement.getTransformToElement(path1).f should be close to -25.9. Was -25.000000000000014. -PASS rootSVGElement.getTransformToElement(path2).a is 0 -PASS rootSVGElement.getTransformToElement(path2).b is -1 -PASS rootSVGElement.getTransformToElement(path2).c is 1 -PASS rootSVGElement.getTransformToElement(path2).d is 0 -FAIL rootSVGElement.getTransformToElement(path2).e should be close to -223.9. Was -225. -FAIL rootSVGElement.getTransformToElement(path2).f should be close to 275.9. Was 275. -PASS rootSVGElement.getTransformToElement(path1).a is 1 -PASS rootSVGElement.getTransformToElement(path1).b is 0.1 -PASS rootSVGElement.getTransformToElement(path1).c is -0.1 -PASS rootSVGElement.getTransformToElement(path1).d is 1 -FAIL rootSVGElement.getTransformToElement(path1).e should be close to -70.3. Was -70.87814895357428. -FAIL rootSVGElement.getTransformToElement(path1).f should be close to -182.8. Was -182.60109333201257. -PASS rootSVGElement.getTransformToElement(path2).a is -1 -PASS rootSVGElement.getTransformToElement(path2).b is -0.1 -PASS rootSVGElement.getTransformToElement(path2).c is 0.1 -PASS rootSVGElement.getTransformToElement(path2).d is -1 -FAIL rootSVGElement.getTransformToElement(path2).e should be close to 318.6. Was 319.29822182153924. -FAIL rootSVGElement.getTransformToElement(path2).f should be close to 211.6. Was 210.66313575977358. -PASS rootSVGElement.getTransformToElement(path1).a is 0.7 -PASS rootSVGElement.getTransformToElement(path1).b is -0.7 -PASS rootSVGElement.getTransformToElement(path1).c is 0.7 -PASS rootSVGElement.getTransformToElement(path1).d is 0.7 -PASS rootSVGElement.getTransformToElement(path1).e is -265.1 -FAIL rootSVGElement.getTransformToElement(path1).f should be close to -18.9. Was -17.677916691624347. -PASS rootSVGElement.getTransformToElement(path2).a is -0.7 -PASS rootSVGElement.getTransformToElement(path2).b is 0.7 -PASS rootSVGElement.getTransformToElement(path2).c is -0.7 -PASS rootSVGElement.getTransformToElement(path2).d is -0.7 -FAIL rootSVGElement.getTransformToElement(path2).e should be close to 442.7. Was 441.941810617502. -FAIL rootSVGElement.getTransformToElement(path2).f should be close to -156.9. Was -159.09852261339003. -PASS rootSVGElement.getTransformToElement(path1).a is 0.7 -PASS rootSVGElement.getTransformToElement(path1).b is -0.7 -PASS rootSVGElement.getTransformToElement(path1).c is 0.7 -PASS rootSVGElement.getTransformToElement(path1).d is 0.7 -PASS rootSVGElement.getTransformToElement(path1).e is -265.1 -FAIL rootSVGElement.getTransformToElement(path1).f should be close to -18.9. Was -17.677916691624347. -PASS rootSVGElement.getTransformToElement(path2).a is -0.7 -PASS rootSVGElement.getTransformToElement(path2).b is 0.7 -PASS rootSVGElement.getTransformToElement(path2).c is -0.7 -PASS rootSVGElement.getTransformToElement(path2).d is -0.7 -FAIL rootSVGElement.getTransformToElement(path2).e should be close to 442.7. Was 441.941810617502. -FAIL rootSVGElement.getTransformToElement(path2).f should be close to -156.9. Was -159.09852261339003. +PASS getTransformToElement(rootSVGElement, path1).a is 0 +PASS getTransformToElement(rootSVGElement, path1).b is 1 +PASS getTransformToElement(rootSVGElement, path1).c is -1 +PASS getTransformToElement(rootSVGElement, path1).d is 0 +PASS getTransformToElement(rootSVGElement, path1).e is 224.9 +FAIL getTransformToElement(rootSVGElement, path1).f should be close to -25.9. Was -25.000000000000014. +PASS getTransformToElement(rootSVGElement, path2).a is 0 +PASS getTransformToElement(rootSVGElement, path2).b is -1 +PASS getTransformToElement(rootSVGElement, path2).c is 1 +PASS getTransformToElement(rootSVGElement, path2).d is 0 +FAIL getTransformToElement(rootSVGElement, path2).e should be close to -223.9. Was -225. +FAIL getTransformToElement(rootSVGElement, path2).f should be close to 275.9. Was 275. +PASS getTransformToElement(rootSVGElement, path1).a is 1 +PASS getTransformToElement(rootSVGElement, path1).b is 0.1 +PASS getTransformToElement(rootSVGElement, path1).c is -0.1 +PASS getTransformToElement(rootSVGElement, path1).d is 1 +FAIL getTransformToElement(rootSVGElement, path1).e should be close to -70.3. Was -70.87814895357428. +FAIL getTransformToElement(rootSVGElement, path1).f should be close to -182.8. Was -182.60109333201257. +PASS getTransformToElement(rootSVGElement, path2).a is -1 +PASS getTransformToElement(rootSVGElement, path2).b is -0.1 +PASS getTransformToElement(rootSVGElement, path2).c is 0.1 +PASS getTransformToElement(rootSVGElement, path2).d is -1 +FAIL getTransformToElement(rootSVGElement, path2).e should be close to 318.6. Was 319.29822182153924. +FAIL getTransformToElement(rootSVGElement, path2).f should be close to 211.6. Was 210.66313575977358. +PASS getTransformToElement(rootSVGElement, path1).a is 0.7 +PASS getTransformToElement(rootSVGElement, path1).b is -0.7 +PASS getTransformToElement(rootSVGElement, path1).c is 0.7 +PASS getTransformToElement(rootSVGElement, path1).d is 0.7 +PASS getTransformToElement(rootSVGElement, path1).e is -265.1 +FAIL getTransformToElement(rootSVGElement, path1).f should be close to -18.9. Was -17.677916691624347. +PASS getTransformToElement(rootSVGElement, path2).a is -0.7 +PASS getTransformToElement(rootSVGElement, path2).b is 0.7 +PASS getTransformToElement(rootSVGElement, path2).c is -0.7 +PASS getTransformToElement(rootSVGElement, path2).d is -0.7 +FAIL getTransformToElement(rootSVGElement, path2).e should be close to 442.7. Was 441.941810617502. +FAIL getTransformToElement(rootSVGElement, path2).f should be close to -156.9. Was -159.09852261339003. +PASS getTransformToElement(rootSVGElement, path1).a is 0.7 +PASS getTransformToElement(rootSVGElement, path1).b is -0.7 +PASS getTransformToElement(rootSVGElement, path1).c is 0.7 +PASS getTransformToElement(rootSVGElement, path1).d is 0.7 +PASS getTransformToElement(rootSVGElement, path1).e is -265.1 +FAIL getTransformToElement(rootSVGElement, path1).f should be close to -18.9. Was -17.677916691624347. +PASS getTransformToElement(rootSVGElement, path2).a is -0.7 +PASS getTransformToElement(rootSVGElement, path2).b is 0.7 +PASS getTransformToElement(rootSVGElement, path2).c is -0.7 +PASS getTransformToElement(rootSVGElement, path2).d is -0.7 +FAIL getTransformToElement(rootSVGElement, path2).e should be close to 442.7. Was 441.941810617502. +FAIL getTransformToElement(rootSVGElement, path2).f should be close to -156.9. Was -159.09852261339003. PASS successfullyParsed is true TEST COMPLETE
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/custom/getTransformToElement-expected.png b/third_party/WebKit/LayoutTests/platform/win/svg/custom/getTransformToElement-expected.png deleted file mode 100644 index 035172f..0000000 --- a/third_party/WebKit/LayoutTests/platform/win/svg/custom/getTransformToElement-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/custom/getTransformToElement-expected.txt b/third_party/WebKit/LayoutTests/platform/win/svg/custom/getTransformToElement-expected.txt deleted file mode 100644 index 9e6af1be..0000000 --- a/third_party/WebKit/LayoutTests/platform/win/svg/custom/getTransformToElement-expected.txt +++ /dev/null
@@ -1,11 +0,0 @@ -layer at (0,0) size 800x600 - LayoutView at (0,0) size 800x600 -layer at (0,0) size 800x600 - LayoutSVGRoot {svg} at (20,56) size 101x157 - LayoutSVGContainer {g} at (0,0) size 0x0 [transform={m=((0.00,0.00)(0.00,0.00)) t=(0.00,0.00)}] - LayoutSVGContainer {g} at (20,56) size 41x17 [transform={m=((1.00,0.00)(0.00,1.00)) t=(15.00,15.00)}] - LayoutSVGText {text} at (50,123) size 82x33 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 82x33 - chunk 1 text run 1 at (50.00,150.00) startOffset 0 endOffset 6 width 81.67: "Passed" - LayoutSVGContainer {g} at (49,141) size 72x72 [transform={m=((0.71,0.71)(-0.71,0.71)) t=(0.00,0.00)}] - LayoutSVGRect {rect} at (49,141) size 72x72 [transform={m=((1.00,0.00)(0.00,1.00)) t=(100.00,0.00)}] [x=50.00] [y=50.00] [width=70.00] [height=30.00]
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/dom/css-transforms-expected.png b/third_party/WebKit/LayoutTests/platform/win/svg/dom/css-transforms-expected.png index 4a1da3c..9adec94 100644 --- a/third_party/WebKit/LayoutTests/platform/win/svg/dom/css-transforms-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/svg/dom/css-transforms-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/W3C-SVG-1.1-SE/types-dom-01-b.svg b/third_party/WebKit/LayoutTests/svg/W3C-SVG-1.1-SE/types-dom-01-b.svg index 8457053b..878d66f 100644 --- a/third_party/WebKit/LayoutTests/svg/W3C-SVG-1.1-SE/types-dom-01-b.svg +++ b/third_party/WebKit/LayoutTests/svg/W3C-SVG-1.1-SE/types-dom-01-b.svg
@@ -19,8 +19,7 @@ Note the use of nested svg elements and testing against different elements in the hierarchy. Note that the values of .getScreenCTM() and .getCTM() can only be tested correctly if they are in the html-based test or the width and height of the root element is explicitly set to 480x360. - The methods .getScreenCTM() and .getCTM() are tested from the rotated text element, the method .getBBox(), - .getTransformToElement() is tested between the rotated text and its parent group, the method .getBBox() and + The methods .getScreenCTM() and .getCTM() are tested from the rotated text element, the method .getBBox() is tested between the rotated text and its parent group, the method .getBBox() and the properties .farthestViewportElement and .nearestViewportElement are tested on the blue circle. </p> </d:testDescription> @@ -40,9 +39,6 @@ .getCTM() for id "rotText": 0.42,0.42,-0.42,0.42,70.00,-60.00 </p> <p> - .getTransformToElement() between id "rotText" and id "parentGroup": 0.42,0.42,-0.42,0.42,0.00,0.00 - </p> - <p> .getBBox() for 'blueCircle': .x=-50,.y=-50,.width=100,.height=100 </p> <p> @@ -70,12 +66,10 @@ document.getElementById("result1").firstChild.nodeValue = ".getScreenCTM(): " + matr.a.toFixed(2) + "," + matr.b.toFixed(2) + "," + matr.c.toFixed(2) + "," + matr.d.toFixed(2) + "," + matr.e.toFixed(2) + "," + matr.f.toFixed(2); var matr = rotText.getCTM(); document.getElementById("result2").firstChild.nodeValue = ".getCTM(): " + matr.a.toFixed(2) + "," + matr.b.toFixed(2) + "," + matr.c.toFixed(2) + "," + matr.d.toFixed(2) + "," + matr.e.toFixed(2) + "," + matr.f.toFixed(2); - var matr = rotText.getTransformToElement(document.getElementById("parentGroup")); - document.getElementById("result3").firstChild.nodeValue = ".getTransformToElement(): " + matr.a.toFixed(2) + "," + matr.b.toFixed(2) + "," + matr.c.toFixed(2) + "," + matr.d.toFixed(2) + "," + matr.e.toFixed(2) + "," + matr.f.toFixed(2); var bbox = blueCircle.getBBox(); - document.getElementById("result4").firstChild.nodeValue = ".getBBox() for 'blueCircle': .x="+bbox.x+",.y="+bbox.y+",.width="+bbox.width+",.height="+bbox.height; - document.getElementById("result5").firstChild.nodeValue = ".farthestViewportElement of blueCircle="+blueCircle.farthestViewportElement.getAttributeNS(null,"id"); - document.getElementById("result6").firstChild.nodeValue = ".nearestViewportElement of blueCircle="+blueCircle.nearestViewportElement.getAttributeNS(null,"id"); + document.getElementById("result3").firstChild.nodeValue = ".getBBox() for 'blueCircle': .x="+bbox.x+",.y="+bbox.y+",.width="+bbox.width+",.height="+bbox.height; + document.getElementById("result4").firstChild.nodeValue = ".farthestViewportElement of blueCircle="+blueCircle.farthestViewportElement.getAttributeNS(null,"id"); + document.getElementById("result5").firstChild.nodeValue = ".nearestViewportElement of blueCircle="+blueCircle.nearestViewportElement.getAttributeNS(null,"id"); } </script> <g font-size="12"> @@ -91,7 +85,6 @@ <text id="result3" x="10" y="240"> </text> <text id="result4" x="10" y="260"> </text> <text id="result5" x="10" y="280"> </text> - <text id="result6" x="10" y="300"> </text> </g> </g> <g font-family="SVGFreeSansASCII,sans-serif" font-size="32">
diff --git a/third_party/WebKit/LayoutTests/svg/W3C-SVG-1.1/types-basicDOM-01-b.svg b/third_party/WebKit/LayoutTests/svg/W3C-SVG-1.1/types-basicDOM-01-b.svg index ecde5a6..34586d0 100644 --- a/third_party/WebKit/LayoutTests/svg/W3C-SVG-1.1/types-basicDOM-01-b.svg +++ b/third_party/WebKit/LayoutTests/svg/W3C-SVG-1.1/types-basicDOM-01-b.svg
@@ -16,7 +16,7 @@ <SVGTestCase xmlns="http://www.w3.org/2000/02/svg/testsuite/description/" reviewer="AE,ED" owner="AN" desc="Tests the interface SVGLocatable" status="accepted" version="$Revision: 1.1 $" testname="$RCSfile: types-basicDOM-01-b.svg,v $"> <OperatorScript> <Paragraph> - This test checks all the methods and properties of the SVGLocatable interface. Note the use of nested svg elements and testing against different elements in the hierarchy. Note that the values of .getScreenCTM() and .getCTM() can only be tested correctly if they are in the html-based test or the width and height of the root element is explicitly set to 480x360. The methods .getScreenCTM() and .getCTM() are tested from the rotated text element, the method .getBBox(), .getTransformToElement() is tested between the rotated text and its parent group, the method .getBBox() and the properties .farthestViewportElement and .nearestViewportElement are tested on the red circle. + This test checks all the methods and properties of the SVGLocatable interface. Note the use of nested svg elements and testing against different elements in the hierarchy. Note that the values of .getScreenCTM() and .getCTM() can only be tested correctly if they are in the html-based test or the width and height of the root element is explicitly set to 480x360. The methods .getScreenCTM() and .getCTM() are tested from the rotated text element, the method .getBBox(), is tested between the rotated text and its parent group, the method .getBBox() and the properties .farthestViewportElement and .nearestViewportElement are tested on the red circle. </Paragraph> <Paragraph> For the test to pass, the values generated by script must match the values provided in the png image. The correct values are: @@ -27,9 +27,6 @@ <Paragraph> .getCTM() for id "rotText": 0.42,0.42,-0.42,0.42,70.00,-60.00 </Paragraph> - <Paragraph> - .getTransformToElement() between id "rotText" and id "parentGroup": 0.42,0.42,-0.42,0.42,0.00,0.00 - </Paragraph> <Paragraph> .getBBox() for 'redCircle': .x=-50,.y=-50,.width=100,.height=100 </Paragraph> @@ -54,12 +51,10 @@ document.getElementById("result1").firstChild.nodeValue = ".getScreenCTM(): " + matr.a.toFixed(2) + "," + matr.b.toFixed(2) + "," + matr.c.toFixed(2) + "," + matr.d.toFixed(2) + "," + matr.e.toFixed(2) + "," + matr.f.toFixed(2); var matr = rotText.getCTM(); document.getElementById("result2").firstChild.nodeValue = ".getCTM(): " + matr.a.toFixed(2) + "," + matr.b.toFixed(2) + "," + matr.c.toFixed(2) + "," + matr.d.toFixed(2) + "," + matr.e.toFixed(2) + "," + matr.f.toFixed(2); - var matr = rotText.getTransformToElement(document.getElementById("parentGroup")); - document.getElementById("result3").firstChild.nodeValue = ".getTransformToElement(): " + matr.a.toFixed(2) + "," + matr.b.toFixed(2) + "," + matr.c.toFixed(2) + "," + matr.d.toFixed(2) + "," + matr.e.toFixed(2) + "," + matr.f.toFixed(2); var bbox = redCircle.getBBox(); - document.getElementById("result4").firstChild.nodeValue = ".getBBox() for 'redCircle': .x="+bbox.x+",.y="+bbox.y+",.width="+bbox.width+",.height="+bbox.height; - document.getElementById("result5").firstChild.nodeValue = ".farthestViewportElement of redCircle="+redCircle.farthestViewportElement.getAttributeNS(null,"id"); - document.getElementById("result6").firstChild.nodeValue = ".nearestViewportElement of redCircle="+redCircle.nearestViewportElement.getAttributeNS(null,"id"); + document.getElementById("result3").firstChild.nodeValue = ".getBBox() for 'redCircle': .x="+bbox.x+",.y="+bbox.y+",.width="+bbox.width+",.height="+bbox.height; + document.getElementById("result4").firstChild.nodeValue = ".farthestViewportElement of redCircle="+redCircle.farthestViewportElement.getAttributeNS(null,"id"); + document.getElementById("result5").firstChild.nodeValue = ".nearestViewportElement of redCircle="+redCircle.nearestViewportElement.getAttributeNS(null,"id"); } ]]></script> <g font-family="sans-serif" font-size="12"> @@ -75,7 +70,6 @@ <text id="result3" x="10" y="240"> </text> <text id="result4" x="10" y="260"> </text> <text id="result5" x="10" y="280"> </text> - <text id="result6" x="10" y="300"> </text> </g> </g> <text id="revision" x="10" y="340" font-size="40" stroke="none" fill="black">$Revision: 1.1 $</text>
diff --git a/third_party/WebKit/LayoutTests/svg/animations/animate-elem-04-t-drt-expected.txt b/third_party/WebKit/LayoutTests/svg/animations/animate-elem-04-t-drt-expected.txt index f1cc948..3b7ce01 100644 --- a/third_party/WebKit/LayoutTests/svg/animations/animate-elem-04-t-drt-expected.txt +++ b/third_party/WebKit/LayoutTests/svg/animations/animate-elem-04-t-drt-expected.txt
@@ -7,14 +7,14 @@ On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". -PASS rootSVGElement.getTransformToElement(path).e is -15 -PASS rootSVGElement.getTransformToElement(path).f is -43 -PASS rootSVGElement.getTransformToElement(path).e is -40 -PASS rootSVGElement.getTransformToElement(path).f is -36.5 -PASS rootSVGElement.getTransformToElement(path).e is -65 -PASS rootSVGElement.getTransformToElement(path).f is -30 -PASS rootSVGElement.getTransformToElement(path).e is -65 -PASS rootSVGElement.getTransformToElement(path).f is -30 +PASS getTransformToElement(rootSVGElement, path).e is -15 +PASS getTransformToElement(rootSVGElement, path).f is -43 +PASS getTransformToElement(rootSVGElement, path).e is -40 +PASS getTransformToElement(rootSVGElement, path).f is -36.5 +PASS getTransformToElement(rootSVGElement, path).e is -65 +PASS getTransformToElement(rootSVGElement, path).f is -30 +PASS getTransformToElement(rootSVGElement, path).e is -65 +PASS getTransformToElement(rootSVGElement, path).f is -30 PASS successfullyParsed is true TEST COMPLETE
diff --git a/third_party/WebKit/LayoutTests/svg/animations/animate-elem-05-t-drt-expected.txt b/third_party/WebKit/LayoutTests/svg/animations/animate-elem-05-t-drt-expected.txt index 086ee0cd..99768c9 100644 --- a/third_party/WebKit/LayoutTests/svg/animations/animate-elem-05-t-drt-expected.txt +++ b/third_party/WebKit/LayoutTests/svg/animations/animate-elem-05-t-drt-expected.txt
@@ -7,14 +7,14 @@ On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". -PASS rootSVGElement.getTransformToElement(path).e is -15 -PASS rootSVGElement.getTransformToElement(path).f is -43 -PASS rootSVGElement.getTransformToElement(path).e is -40 -PASS rootSVGElement.getTransformToElement(path).f is -30 -PASS rootSVGElement.getTransformToElement(path).e is -65 -PASS rootSVGElement.getTransformToElement(path).f is -30 -PASS rootSVGElement.getTransformToElement(path).e is -65 -PASS rootSVGElement.getTransformToElement(path).f is -30 +PASS getTransformToElement(rootSVGElement, path).e is -15 +PASS getTransformToElement(rootSVGElement, path).f is -43 +PASS getTransformToElement(rootSVGElement, path).e is -40 +PASS getTransformToElement(rootSVGElement, path).f is -30 +PASS getTransformToElement(rootSVGElement, path).e is -65 +PASS getTransformToElement(rootSVGElement, path).f is -30 +PASS getTransformToElement(rootSVGElement, path).e is -65 +PASS getTransformToElement(rootSVGElement, path).f is -30 PASS successfullyParsed is true TEST COMPLETE
diff --git a/third_party/WebKit/LayoutTests/svg/animations/animate-elem-06-t-drt-expected.txt b/third_party/WebKit/LayoutTests/svg/animations/animate-elem-06-t-drt-expected.txt index be2221d..9d4054c 100644 --- a/third_party/WebKit/LayoutTests/svg/animations/animate-elem-06-t-drt-expected.txt +++ b/third_party/WebKit/LayoutTests/svg/animations/animate-elem-06-t-drt-expected.txt
@@ -7,14 +7,14 @@ On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". -PASS rootSVGElement.getTransformToElement(path).e is -15 -PASS rootSVGElement.getTransformToElement(path).f is -43 -FAIL rootSVGElement.getTransformToElement(path).e should be close to -38.5. Was -38.3656120300293. -PASS rootSVGElement.getTransformToElement(path).f is -30 -PASS rootSVGElement.getTransformToElement(path).e is -65 -PASS rootSVGElement.getTransformToElement(path).f is -33 -PASS rootSVGElement.getTransformToElement(path).e is -65 -PASS rootSVGElement.getTransformToElement(path).f is -33 +PASS getTransformToElement(rootSVGElement, path).e is -15 +PASS getTransformToElement(rootSVGElement, path).f is -43 +FAIL getTransformToElement(rootSVGElement, path).e should be close to -38.5. Was -38.3656120300293. +PASS getTransformToElement(rootSVGElement, path).f is -30 +PASS getTransformToElement(rootSVGElement, path).e is -65 +PASS getTransformToElement(rootSVGElement, path).f is -33 +PASS getTransformToElement(rootSVGElement, path).e is -65 +PASS getTransformToElement(rootSVGElement, path).f is -33 PASS successfullyParsed is true TEST COMPLETE
diff --git a/third_party/WebKit/LayoutTests/svg/animations/animate-elem-07-t-drt-expected.txt b/third_party/WebKit/LayoutTests/svg/animations/animate-elem-07-t-drt-expected.txt index be2221d..9d4054c 100644 --- a/third_party/WebKit/LayoutTests/svg/animations/animate-elem-07-t-drt-expected.txt +++ b/third_party/WebKit/LayoutTests/svg/animations/animate-elem-07-t-drt-expected.txt
@@ -7,14 +7,14 @@ On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". -PASS rootSVGElement.getTransformToElement(path).e is -15 -PASS rootSVGElement.getTransformToElement(path).f is -43 -FAIL rootSVGElement.getTransformToElement(path).e should be close to -38.5. Was -38.3656120300293. -PASS rootSVGElement.getTransformToElement(path).f is -30 -PASS rootSVGElement.getTransformToElement(path).e is -65 -PASS rootSVGElement.getTransformToElement(path).f is -33 -PASS rootSVGElement.getTransformToElement(path).e is -65 -PASS rootSVGElement.getTransformToElement(path).f is -33 +PASS getTransformToElement(rootSVGElement, path).e is -15 +PASS getTransformToElement(rootSVGElement, path).f is -43 +FAIL getTransformToElement(rootSVGElement, path).e should be close to -38.5. Was -38.3656120300293. +PASS getTransformToElement(rootSVGElement, path).f is -30 +PASS getTransformToElement(rootSVGElement, path).e is -65 +PASS getTransformToElement(rootSVGElement, path).f is -33 +PASS getTransformToElement(rootSVGElement, path).e is -65 +PASS getTransformToElement(rootSVGElement, path).f is -33 PASS successfullyParsed is true TEST COMPLETE
diff --git a/third_party/WebKit/LayoutTests/svg/animations/animate-elem-09-t-drt-expected.txt b/third_party/WebKit/LayoutTests/svg/animations/animate-elem-09-t-drt-expected.txt index 763231d..30d5edda 100644 --- a/third_party/WebKit/LayoutTests/svg/animations/animate-elem-09-t-drt-expected.txt +++ b/third_party/WebKit/LayoutTests/svg/animations/animate-elem-09-t-drt-expected.txt
@@ -9,36 +9,36 @@ PASS rect1.height.animVal.value is 210 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -250 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -250 PASS rect1.height.animVal.value is 177 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -217 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -217 PASS rect1.height.animVal.value is 177 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -217 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -217 PASS rect1.height.animVal.value is 121 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -161 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -161 PASS rect1.height.animVal.value is 121 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -161 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -161 PASS rect1.height.animVal.value is 10 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -50 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -50 PASS rect1.height.animVal.value is 10 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -50 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -50 PASS rect1.height.animVal.value is 10 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -50 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -50 PASS successfullyParsed is true TEST COMPLETE
diff --git a/third_party/WebKit/LayoutTests/svg/animations/animate-elem-10-t-drt-expected.txt b/third_party/WebKit/LayoutTests/svg/animations/animate-elem-10-t-drt-expected.txt index 763231d..30d5edda 100644 --- a/third_party/WebKit/LayoutTests/svg/animations/animate-elem-10-t-drt-expected.txt +++ b/third_party/WebKit/LayoutTests/svg/animations/animate-elem-10-t-drt-expected.txt
@@ -9,36 +9,36 @@ PASS rect1.height.animVal.value is 210 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -250 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -250 PASS rect1.height.animVal.value is 177 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -217 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -217 PASS rect1.height.animVal.value is 177 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -217 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -217 PASS rect1.height.animVal.value is 121 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -161 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -161 PASS rect1.height.animVal.value is 121 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -161 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -161 PASS rect1.height.animVal.value is 10 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -50 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -50 PASS rect1.height.animVal.value is 10 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -50 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -50 PASS rect1.height.animVal.value is 10 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -50 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -50 PASS successfullyParsed is true TEST COMPLETE
diff --git a/third_party/WebKit/LayoutTests/svg/animations/animate-elem-11-t-drt-expected.txt b/third_party/WebKit/LayoutTests/svg/animations/animate-elem-11-t-drt-expected.txt index 9be18b2..d14119b 100644 --- a/third_party/WebKit/LayoutTests/svg/animations/animate-elem-11-t-drt-expected.txt +++ b/third_party/WebKit/LayoutTests/svg/animations/animate-elem-11-t-drt-expected.txt
@@ -9,36 +9,36 @@ PASS rect1.height.animVal.value is 210 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -250 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -250 PASS rect1.height.animVal.value is 143.4 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -183.4 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -183.4 PASS rect1.height.animVal.value is 143.4 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -183.4 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -183.4 PASS rect1.height.animVal.value is 76.7 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -116.7 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -116.7 PASS rect1.height.animVal.value is 76.7 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -116.7 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -116.7 PASS rect1.height.animVal.value is 10 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -50 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -50 PASS rect1.height.animVal.value is 10 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -50 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -50 PASS rect1.height.animVal.value is 10 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -50 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -50 PASS successfullyParsed is true TEST COMPLETE
diff --git a/third_party/WebKit/LayoutTests/svg/animations/animate-elem-12-t-drt-expected.txt b/third_party/WebKit/LayoutTests/svg/animations/animate-elem-12-t-drt-expected.txt index 763231d..30d5edda 100644 --- a/third_party/WebKit/LayoutTests/svg/animations/animate-elem-12-t-drt-expected.txt +++ b/third_party/WebKit/LayoutTests/svg/animations/animate-elem-12-t-drt-expected.txt
@@ -9,36 +9,36 @@ PASS rect1.height.animVal.value is 210 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -250 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -250 PASS rect1.height.animVal.value is 177 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -217 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -217 PASS rect1.height.animVal.value is 177 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -217 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -217 PASS rect1.height.animVal.value is 121 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -161 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -161 PASS rect1.height.animVal.value is 121 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -161 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -161 PASS rect1.height.animVal.value is 10 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -50 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -50 PASS rect1.height.animVal.value is 10 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -50 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -50 PASS rect1.height.animVal.value is 10 PASS rect1.height.baseVal.value is 210 -PASS rootSVGElement.getTransformToElement(rect2).e is -250 -PASS rootSVGElement.getTransformToElement(rect2).f is -50 +PASS getTransformToElement(rootSVGElement, rect2).e is -250 +PASS getTransformToElement(rootSVGElement, rect2).f is -50 PASS successfullyParsed is true TEST COMPLETE
diff --git a/third_party/WebKit/LayoutTests/svg/animations/animateTransform-translate-attributetype-auto-expected.txt b/third_party/WebKit/LayoutTests/svg/animations/animateTransform-translate-attributetype-auto-expected.txt index 411f63a..72a47b74 100644 --- a/third_party/WebKit/LayoutTests/svg/animations/animateTransform-translate-attributetype-auto-expected.txt +++ b/third_party/WebKit/LayoutTests/svg/animations/animateTransform-translate-attributetype-auto-expected.txt
@@ -6,16 +6,16 @@ On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". -PASS rootSVGElement.getTransformToElement(rect).e is 0 -PASS rootSVGElement.getTransformToElement(rect).f is 0 -PASS rootSVGElement.getTransformToElement(rect).e is 0 -PASS rootSVGElement.getTransformToElement(rect).f is 0 -PASS rootSVGElement.getTransformToElement(rect).e is -100 -PASS rootSVGElement.getTransformToElement(rect).f is -100 -PASS rootSVGElement.getTransformToElement(rect).e is -200 -PASS rootSVGElement.getTransformToElement(rect).f is -200 -PASS rootSVGElement.getTransformToElement(rect).e is -200 -PASS rootSVGElement.getTransformToElement(rect).f is -200 +PASS getTransformToElement(rootSVGElement, rect).e is 0 +PASS getTransformToElement(rootSVGElement, rect).f is 0 +PASS getTransformToElement(rootSVGElement, rect).e is 0 +PASS getTransformToElement(rootSVGElement, rect).f is 0 +PASS getTransformToElement(rootSVGElement, rect).e is -100 +PASS getTransformToElement(rootSVGElement, rect).f is -100 +PASS getTransformToElement(rootSVGElement, rect).e is -200 +PASS getTransformToElement(rootSVGElement, rect).f is -200 +PASS getTransformToElement(rootSVGElement, rect).e is -200 +PASS getTransformToElement(rootSVGElement, rect).f is -200 PASS successfullyParsed is true TEST COMPLETE
diff --git a/third_party/WebKit/LayoutTests/svg/animations/animateTransform-translate-invalid-attributetype-expected.txt b/third_party/WebKit/LayoutTests/svg/animations/animateTransform-translate-invalid-attributetype-expected.txt index d3530f3..4d39a8d 100644 --- a/third_party/WebKit/LayoutTests/svg/animations/animateTransform-translate-invalid-attributetype-expected.txt +++ b/third_party/WebKit/LayoutTests/svg/animations/animateTransform-translate-invalid-attributetype-expected.txt
@@ -6,16 +6,16 @@ On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". -PASS rootSVGElement.getTransformToElement(rect).e is 0 -PASS rootSVGElement.getTransformToElement(rect).f is 0 -PASS rootSVGElement.getTransformToElement(rect).e is 0 -PASS rootSVGElement.getTransformToElement(rect).f is 0 -PASS rootSVGElement.getTransformToElement(rect).e is 0 -PASS rootSVGElement.getTransformToElement(rect).f is 0 -PASS rootSVGElement.getTransformToElement(rect).e is 0 -PASS rootSVGElement.getTransformToElement(rect).f is 0 -PASS rootSVGElement.getTransformToElement(rect).e is 0 -PASS rootSVGElement.getTransformToElement(rect).f is 0 +PASS getTransformToElement(rootSVGElement, rect).e is 0 +PASS getTransformToElement(rootSVGElement, rect).f is 0 +PASS getTransformToElement(rootSVGElement, rect).e is 0 +PASS getTransformToElement(rootSVGElement, rect).f is 0 +PASS getTransformToElement(rootSVGElement, rect).e is 0 +PASS getTransformToElement(rootSVGElement, rect).f is 0 +PASS getTransformToElement(rootSVGElement, rect).e is 0 +PASS getTransformToElement(rootSVGElement, rect).f is 0 +PASS getTransformToElement(rootSVGElement, rect).e is 0 +PASS getTransformToElement(rootSVGElement, rect).f is 0 PASS successfullyParsed is true TEST COMPLETE
diff --git a/third_party/WebKit/LayoutTests/svg/animations/resources/SVGAnimationTestCase.js b/third_party/WebKit/LayoutTests/svg/animations/resources/SVGAnimationTestCase.js index bdc2597..590f51eb 100644 --- a/third_party/WebKit/LayoutTests/svg/animations/resources/SVGAnimationTestCase.js +++ b/third_party/WebKit/LayoutTests/svg/animations/resources/SVGAnimationTestCase.js
@@ -43,6 +43,10 @@ shouldBeCloseEnough(actualMatrix + ".f", expectedF, tolerance); } +function getTransformToElement(rootElement, element) { + return element.getCTM().inverse().multiply(rootElement.getCTM()); +} + function expectColor(element, red, green, blue, property) { if (typeof property != "string") color = getComputedStyle(element).getPropertyValue("color");
diff --git a/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-04-t-drt.js b/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-04-t-drt.js index 8fbb528..c6f43e2 100644 --- a/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-04-t-drt.js +++ b/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-04-t-drt.js
@@ -3,15 +3,15 @@ // Setup animation test function sample1() { - expectTranslationMatrix("rootSVGElement.getTransformToElement(path)", "-15", "-43"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, path)", "-15", "-43"); } function sample2() { - expectTranslationMatrix("rootSVGElement.getTransformToElement(path)", "-40", "-36.5"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, path)", "-40", "-36.5"); } function sample3() { - expectTranslationMatrix("rootSVGElement.getTransformToElement(path)", "-65", "-30"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, path)", "-65", "-30"); } function executeTest() {
diff --git a/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-05-t-drt.js b/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-05-t-drt.js index 9aebf6c..4ba8744 100644 --- a/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-05-t-drt.js +++ b/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-05-t-drt.js
@@ -3,15 +3,15 @@ // Setup animation test function sample1() { - expectTranslationMatrix("rootSVGElement.getTransformToElement(path)", "-15", "-43"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, path)","-15","-43"); } function sample2() { - expectTranslationMatrix("rootSVGElement.getTransformToElement(path)", "-40", "-30"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, path)","-40","-30"); } function sample3() { - expectTranslationMatrix("rootSVGElement.getTransformToElement(path)", "-65", "-30"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, path)","-65","-30"); } function executeTest() {
diff --git a/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-06-t-drt.js b/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-06-t-drt.js index 513868c5..6cd9b15 100644 --- a/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-06-t-drt.js +++ b/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-06-t-drt.js
@@ -3,15 +3,15 @@ // Setup animation test function sample1() { - expectTranslationMatrix("rootSVGElement.getTransformToElement(path)", "-15", "-43"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, path)", "-15", "-43"); } function sample2() { - expectTranslationMatrix("rootSVGElement.getTransformToElement(path)", "-38.5", "-30"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, path)", "-38.5", "-30"); } function sample3() { - expectTranslationMatrix("rootSVGElement.getTransformToElement(path)", "-65", "-33"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, path)", "-65", "-33"); } function executeTest() {
diff --git a/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-07-t-drt.js b/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-07-t-drt.js index b093cc2..5841c65 100644 --- a/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-07-t-drt.js +++ b/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-07-t-drt.js
@@ -3,15 +3,15 @@ // Setup animation test function sample1() { - expectTranslationMatrix("rootSVGElement.getTransformToElement(path)", "-15", "-43"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, path)", "-15", "-43"); } function sample2() { - expectTranslationMatrix("rootSVGElement.getTransformToElement(path)", "-38.5", "-30"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, path)", "-38.5", "-30"); } function sample3() { - expectTranslationMatrix("rootSVGElement.getTransformToElement(path)", "-65", "-33"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, path)", "-65", "-33"); } function executeTest() {
diff --git a/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-08-t-drt.js b/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-08-t-drt.js index 18939d8..100489a 100644 --- a/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-08-t-drt.js +++ b/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-08-t-drt.js
@@ -3,18 +3,18 @@ // Setup animation test function sample1() { - expectMatrix("rootSVGElement.getTransformToElement(path1)", "0", "1", "-1", "0", "224.9", "-25.9"); - expectMatrix("rootSVGElement.getTransformToElement(path2)", "0", "-1", "1", "0", "-223.9", "275.9"); + expectMatrix("getTransformToElement(rootSVGElement, path1)", "0", "1", "-1", "0", "224.9", "-25.9"); + expectMatrix("getTransformToElement(rootSVGElement, path2)", "0", "-1", "1", "0", "-223.9", "275.9"); } function sample2() { - expectMatrix("rootSVGElement.getTransformToElement(path1)", "1", "0.1", "-0.1", "1", "-70.3", "-182.8"); - expectMatrix("rootSVGElement.getTransformToElement(path2)", "-1", "-0.1", "0.1", "-1", "318.6", "211.6"); + expectMatrix("getTransformToElement(rootSVGElement, path1)", "1", "0.1", "-0.1", "1", "-70.3", "-182.8"); + expectMatrix("getTransformToElement(rootSVGElement, path2)", "-1", "-0.1", "0.1", "-1", "318.6", "211.6"); } function sample3() { - expectMatrix("rootSVGElement.getTransformToElement(path1)", "0.7", "-0.7", "0.7", "0.7", "-265.1", "-18.9"); - expectMatrix("rootSVGElement.getTransformToElement(path2)", "-0.7", "0.7", "-0.7", "-0.7", "442.7", "-156.9"); + expectMatrix("getTransformToElement(rootSVGElement, path1)", "0.7", "-0.7", "0.7", "0.7", "-265.1", "-18.9"); + expectMatrix("getTransformToElement(rootSVGElement, path2)", "-0.7", "0.7", "-0.7", "-0.7", "442.7", "-156.9"); } function executeTest() {
diff --git a/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-09-t-drt.js b/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-09-t-drt.js index 6f327e0a..8201d0d 100644 --- a/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-09-t-drt.js +++ b/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-09-t-drt.js
@@ -5,25 +5,25 @@ function sample1() { shouldBe("rect1.height.animVal.value", "210"); shouldBe("rect1.height.baseVal.value", "210"); - expectTranslationMatrix("rootSVGElement.getTransformToElement(rect2)", "-250", "-250"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, rect2)", "-250", "-250"); } function sample2() { shouldBe("rect1.height.animVal.value", "177"); shouldBe("rect1.height.baseVal.value", "210"); - expectTranslationMatrix("rootSVGElement.getTransformToElement(rect2)", "-250", "-217"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, rect2)", "-250", "-217"); } function sample3() { shouldBe("rect1.height.animVal.value", "121"); shouldBe("rect1.height.baseVal.value", "210"); - expectTranslationMatrix("rootSVGElement.getTransformToElement(rect2)", "-250", "-161"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, rect2)", "-250", "-161"); } function sample4() { shouldBe("rect1.height.animVal.value", "10"); shouldBe("rect1.height.baseVal.value", "210"); - expectTranslationMatrix("rootSVGElement.getTransformToElement(rect2)", "-250", "-50"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, rect2)", "-250", "-50"); } function executeTest() {
diff --git a/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-10-t-drt.js b/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-10-t-drt.js index bb7c5a9..a348b5f4 100644 --- a/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-10-t-drt.js +++ b/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-10-t-drt.js
@@ -5,25 +5,25 @@ function sample1() { shouldBeCloseEnough("rect1.height.animVal.value", "210"); shouldBe("rect1.height.baseVal.value", "210"); - expectTranslationMatrix("rootSVGElement.getTransformToElement(rect2)", "-250", "-250"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, rect2)", "-250", "-250"); } function sample2() { shouldBeCloseEnough("rect1.height.animVal.value", "177"); shouldBe("rect1.height.baseVal.value", "210"); - expectTranslationMatrix("rootSVGElement.getTransformToElement(rect2)", "-250", "-217"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, rect2)", "-250", "-217"); } function sample3() { shouldBeCloseEnough("rect1.height.animVal.value", "121"); shouldBe("rect1.height.baseVal.value", "210"); - expectTranslationMatrix("rootSVGElement.getTransformToElement(rect2)", "-250", "-161"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, rect2)", "-250", "-161"); } function sample4() { shouldBeCloseEnough("rect1.height.animVal.value", "10"); shouldBe("rect1.height.baseVal.value", "210"); - expectTranslationMatrix("rootSVGElement.getTransformToElement(rect2)", "-250", "-50"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, rect2)", "-250", "-50"); } function executeTest() {
diff --git a/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-11-t-drt.js b/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-11-t-drt.js index f5f4451..0c45c1a03 100644 --- a/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-11-t-drt.js +++ b/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-11-t-drt.js
@@ -5,25 +5,25 @@ function sample1() { shouldBeCloseEnough("rect1.height.animVal.value", "210"); shouldBe("rect1.height.baseVal.value", "210"); - expectTranslationMatrix("rootSVGElement.getTransformToElement(rect2)", "-250", "-250"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, rect2)", "-250", "-250"); } function sample2() { shouldBeCloseEnough("rect1.height.animVal.value", "143.4"); shouldBe("rect1.height.baseVal.value", "210"); - expectTranslationMatrix("rootSVGElement.getTransformToElement(rect2)", "-250", "-183.4"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, rect2)", "-250", "-183.4"); } function sample3() { shouldBeCloseEnough("rect1.height.animVal.value", "76.7"); shouldBe("rect1.height.baseVal.value", "210"); - expectTranslationMatrix("rootSVGElement.getTransformToElement(rect2)", "-250", "-116.7"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, rect2)", "-250", "-116.7"); } function sample4() { shouldBeCloseEnough("rect1.height.animVal.value", "10"); shouldBe("rect1.height.baseVal.value", "210"); - expectTranslationMatrix("rootSVGElement.getTransformToElement(rect2)", "-250", "-50"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, rect2)", "-250", "-50"); } function executeTest() {
diff --git a/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-12-t-drt.js b/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-12-t-drt.js index 79e43e9..4eada699 100644 --- a/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-12-t-drt.js +++ b/third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-elem-12-t-drt.js
@@ -5,25 +5,25 @@ function sample1() { shouldBeCloseEnough("rect1.height.animVal.value", "210"); shouldBe("rect1.height.baseVal.value", "210"); - expectTranslationMatrix("rootSVGElement.getTransformToElement(rect2)", "-250", "-250"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, rect2)", "-250", "-250"); } function sample2() { shouldBeCloseEnough("rect1.height.animVal.value", "177"); shouldBe("rect1.height.baseVal.value", "210"); - expectTranslationMatrix("rootSVGElement.getTransformToElement(rect2)", "-250", "-217"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, rect2)", "-250", "-217"); } function sample3() { shouldBeCloseEnough("rect1.height.animVal.value", "121"); shouldBe("rect1.height.baseVal.value", "210"); - expectTranslationMatrix("rootSVGElement.getTransformToElement(rect2)", "-250", "-161"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, rect2)", "-250", "-161"); } function sample4() { shouldBeCloseEnough("rect1.height.animVal.value", "10"); shouldBe("rect1.height.baseVal.value", "210"); - expectTranslationMatrix("rootSVGElement.getTransformToElement(rect2)", "-250", "-50"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, rect2)", "-250", "-50"); } function executeTest() {
diff --git a/third_party/WebKit/LayoutTests/svg/animations/script-tests/animateTransform-translate-attributetype-auto.js b/third_party/WebKit/LayoutTests/svg/animations/script-tests/animateTransform-translate-attributetype-auto.js index b0d4e822..696d7bf 100644 --- a/third_party/WebKit/LayoutTests/svg/animations/script-tests/animateTransform-translate-attributetype-auto.js +++ b/third_party/WebKit/LayoutTests/svg/animations/script-tests/animateTransform-translate-attributetype-auto.js
@@ -26,13 +26,13 @@ // Setup animation test function sample1() { - expectTranslationMatrix("rootSVGElement.getTransformToElement(rect)", "0", "0"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, rect)", "0", "0"); } function sample2() { - expectTranslationMatrix("rootSVGElement.getTransformToElement(rect)", "-100", "-100"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, rect)", "-100", "-100"); } function sample3() { - expectTranslationMatrix("rootSVGElement.getTransformToElement(rect)", "-200", "-200"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, rect)", "-200", "-200"); } function executeTest() {
diff --git a/third_party/WebKit/LayoutTests/svg/animations/script-tests/animateTransform-translate-invalid-attributetype.js b/third_party/WebKit/LayoutTests/svg/animations/script-tests/animateTransform-translate-invalid-attributetype.js index c26fe5a9..53330bb 100644 --- a/third_party/WebKit/LayoutTests/svg/animations/script-tests/animateTransform-translate-invalid-attributetype.js +++ b/third_party/WebKit/LayoutTests/svg/animations/script-tests/animateTransform-translate-invalid-attributetype.js
@@ -26,7 +26,7 @@ // Setup animation test function sample() { - expectTranslationMatrix("rootSVGElement.getTransformToElement(rect)", "0", "0"); + expectTranslationMatrix("getTransformToElement(rootSVGElement, rect)", "0", "0"); } function executeTest() {
diff --git a/third_party/WebKit/LayoutTests/svg/custom/get-text-element-transform-crash-expected.txt b/third_party/WebKit/LayoutTests/svg/custom/get-text-element-transform-crash-expected.txt deleted file mode 100644 index b027e65..0000000 --- a/third_party/WebKit/LayoutTests/svg/custom/get-text-element-transform-crash-expected.txt +++ /dev/null
@@ -1,3 +0,0 @@ -CONSOLE WARNING: SVG's SMIL animations (<animate>, <set>, etc.) are deprecated and will be removed. Please use CSS animations or Web animations instead. -CONSOLE ERROR: line 5: Uncaught TypeError: Failed to execute 'getTransformToElement' on 'SVGGraphicsElement': 1 argument required, but only 0 present. - PASS
diff --git a/third_party/WebKit/LayoutTests/svg/custom/get-text-element-transform-crash.html b/third_party/WebKit/LayoutTests/svg/custom/get-text-element-transform-crash.html deleted file mode 100644 index 590290b..0000000 --- a/third_party/WebKit/LayoutTests/svg/custom/get-text-element-transform-crash.html +++ /dev/null
@@ -1,23 +0,0 @@ -<html> - <head> - <script type="application/javascript"> - function test() { - document.getElementById("crash").getTransformToElement(); - } - - if (window.testRunner) { - testRunner.dumpAsText(); - } - - </script> - </head> - <body> - <svg xmlns="http://www.w3.org/2000/svg" version="1.1" onload="test()"> - <animateTransform > - <text id="crash"> - </text> - </animateTransform> - </svg> - PASS - </body> -</html>
diff --git a/third_party/WebKit/LayoutTests/svg/custom/getTransformToElement.svg b/third_party/WebKit/LayoutTests/svg/custom/getTransformToElement.svg deleted file mode 100644 index d419e51..0000000 --- a/third_party/WebKit/LayoutTests/svg/custom/getTransformToElement.svg +++ /dev/null
@@ -1,35 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1 Basic//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtd"> -<svg version="1.1" baseProfile="basic" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="svg-root" width="100%" height="100%" onload="runTest()"> - <script type="text/ecmascript"><![CDATA[ - function runTest() { - var referenceElement = document.getElementById("referenceText"); - var ctm = referenceElement.getTransformToElement(document.getElementById("group1")); - if (ctm.a == 0.5 && ctm.b == 0 && ctm.c == 0 && ctm.d == 0.5 && - ctm.e == -20 && ctm.f == -20) { - ctm = referenceElement.getTransformToElement(document.getElementById("group2")); - if (ctm.a.toFixed(3) == 0.354 && ctm.b.toFixed(3) == -0.354 && - ctm.c.toFixed(3) == 0.354 && ctm.d.toFixed(3) == 0.354 && - ctm.e.toFixed(3) == -7.071 && ctm.f.toFixed(8) == 0.0) { - ctm = referenceElement.getTransformToElement(document.getElementById("redRect")); - if (ctm.a.toFixed(3) == 0.354 && ctm.b.toFixed(3) == -0.354 && - ctm.c.toFixed(3) == 0.354 && ctm.d.toFixed(3) == 0.354 && - ctm.e.toFixed(3) == -107.071 && ctm.f.toFixed(8) == 0.0) { - try { - var ctm = referenceElement.getTransformToElement(document.getElementById("group0")); - } catch(e) { - document.getElementById("referenceText").textContent = "Passed"; - } - } - } - } - } - ]]></script> - <g id="group0" transform="scale(0)"/> - <g id="group1" transform="translate(15,15)"> - <text id="referenceText" transform="translate(-20,-20),scale(0.5)" font-size="30" x="50" y="150">Failed</text> - </g> - <g id="group2" transform="rotate(45)"> - <rect id="redRect" transform="translate(100,0)" x="50" y="50" width="70" height="30" fill="none"/> - </g> -</svg>
diff --git a/third_party/WebKit/LayoutTests/svg/dom/css-transforms-expected.txt b/third_party/WebKit/LayoutTests/svg/dom/css-transforms-expected.txt index 19f4f65..8eb7fce 100644 --- a/third_party/WebKit/LayoutTests/svg/dom/css-transforms-expected.txt +++ b/third_party/WebKit/LayoutTests/svg/dom/css-transforms-expected.txt
@@ -19,11 +19,9 @@ PASS dumpMatrix(circle.getCTM()) is "[2.0 0.0 0.0 2.0 20.0 20.0]" PASS dumpMatrix(circle.getScreenCTM()) is "[2.0 0.0 0.0 2.0 28.0 28.0]" PASS dumpRect(circle.getBBox()) is "[0 0 80 80]" -PASS dumpMatrix(circle.getTransformToElement(circle)) is "[1.0 0.0 0.0 1.0 0.0 0.0]" PASS dumpMatrix(rect.getCTM()) is "[0.7 0.7 -0.7 0.7 100.0 0.0]" PASS dumpMatrix(rect.getScreenCTM()) is "[0.7 0.7 -0.7 0.7 312.0 8.0]" PASS dumpRect(rect.getBBox()) is "[40 40 100 100]" -PASS dumpMatrix(rect.getTransformToElement(rect)) is "[1.0 0.0 0.0 1.0 0.0 0.0]" Test CSSMatrix PASS circle.style.webkitTransform is "scale(2, 2) translate(10px, 10px)"
diff --git a/third_party/WebKit/LayoutTests/svg/dom/css-transforms.xhtml b/third_party/WebKit/LayoutTests/svg/dom/css-transforms.xhtml index 377e1ad..fa94baa8 100644 --- a/third_party/WebKit/LayoutTests/svg/dom/css-transforms.xhtml +++ b/third_party/WebKit/LayoutTests/svg/dom/css-transforms.xhtml
@@ -73,13 +73,11 @@ shouldBeEqualToString("dumpMatrix(circle.getCTM())", "[2.0 0.0 0.0 2.0 20.0 20.0]"); shouldBeEqualToString("dumpMatrix(circle.getScreenCTM())", "[2.0 0.0 0.0 2.0 28.0 28.0]"); shouldBeEqualToString("dumpRect(circle.getBBox())", "[0 0 80 80]"); - shouldBeEqualToString("dumpMatrix(circle.getTransformToElement(circle))", "[1.0 0.0 0.0 1.0 0.0 0.0]"); - + shouldBeEqualToString("dumpMatrix(rect.getCTM())", "[0.7 0.7 -0.7 0.7 100.0 0.0]"); shouldBeEqualToString("dumpMatrix(rect.getScreenCTM())", "[0.7 0.7 -0.7 0.7 312.0 8.0]"); shouldBeEqualToString("dumpRect(rect.getBBox())", "[40 40 100 100]"); - shouldBeEqualToString("dumpMatrix(rect.getTransformToElement(rect))", "[1.0 0.0 0.0 1.0 0.0 0.0]"); - + debug(""); debug("Test CSSMatrix"); shouldBeEqualToString("circle.style.webkitTransform", "scale(2, 2) translate(10px, 10px)");
diff --git a/third_party/WebKit/LayoutTests/svg/text/selection-tripleclick.svg b/third_party/WebKit/LayoutTests/svg/text/selection-tripleclick.svg index 401092ea..965de18 100644 --- a/third_party/WebKit/LayoutTests/svg/text/selection-tripleclick.svg +++ b/third_party/WebKit/LayoutTests/svg/text/selection-tripleclick.svg
@@ -4,7 +4,7 @@ <script> var line1 = document.getElementById("line1"); var center = document.rootElement.createSVGPoint(); -var matrix = document.rootElement.getTransformToElement(line1); +var matrix = line1.getCTM().inverse().multiply(document.rootElement.getCTM()) var bbox = line1.getBBox(); center.x = bbox.x + bbox.width/2;
diff --git a/third_party/WebKit/LayoutTests/virtual/gpu/fast/canvas/canvas-imageSmoothingQuality-expected.txt b/third_party/WebKit/LayoutTests/virtual/gpu/fast/canvas/canvas-imageSmoothingQuality-expected.txt new file mode 100644 index 0000000..4bbed49a --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/gpu/fast/canvas/canvas-imageSmoothingQuality-expected.txt
@@ -0,0 +1,68 @@ +CONSOLE WARNING: The provided value '3223' is not a valid enum value of type ImageSmoothingQuality. +CONSOLE WARNING: The provided value 'bad_input' is not a valid enum value of type ImageSmoothingQuality. +CONSOLE WARNING: The provided value 'LOW' is not a valid enum value of type ImageSmoothingQuality. +CONSOLE WARNING: The provided value 'Medium' is not a valid enum value of type ImageSmoothingQuality. +Tests for the imageSmoothingQuality attribute. + +On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". + + +On getting, must return the last value it was set to. +PASS lowContext.imageSmoothingQuality is 'low' +PASS mediumContext.imageSmoothingQuality is 'medium' +PASS highContext.imageSmoothingQuality is 'high' + +FAIL lowData should not be {"0":0,"1":0,"2":0,"3":100}. +FAIL mediumData should not be {"0":0,"1":0,"2":0,"3":100}. +FAIL lowData should not be {"0":0,"1":0,"2":0,"3":100}. + +FAIL sampleAlpha(noFilterData) should be > sampleAlpha(lowData). Was 0 (of type number). +FAIL sampleAlpha(lowData) should be > sampleAlpha(mediumData). Was 100 (of type number). +FAIL sampleAlpha(mediumData) should be > sampleAlpha(highData). Was 100 (of type number). + + +On setting, it must be set to the new value. +highContext.imageSmoothingQuality = 'medium'; +PASS highContext.imageSmoothingQuality is 'medium' +PASS scaleImageData(highCanvas, highCanvas.imageSmoothingQuality); is mediumData +highContext.imageSmoothingQuality = 'high'; +PASS highContext.imageSmoothingQuality is 'high' +PASS scaleImageData(highCanvas, highCanvas.imageSmoothingQuality); is highData + + +When the CanvasRenderingContext2D object is created, the attribute must be set to 'low'. +PASS document.getElementById("default").getContext("2d").imageSmoothingQuality is 'low' + + +ImageSmoothingQuality can be set without real effect when imageSmoothingEnabled is false. +highContext.imageSmoothingEnabled = false; +PASS highContext.imageSmoothingQuality is 'high' +PASS scaleImageData(highCanvas, highCanvas.imageSmoothingQuality) is noFilterData +highContext.imageSmoothingQuality = 'medium' +PASS highContext.imageSmoothingQuality is 'medium' +PASS scaleImageData(highCanvas, highCanvas.imageSmoothingQuality) is noFilterData + + +Invalid Input is not accpeted. +highContext.imageSmoothingEnabled = true; highContext.imageSmoothingQuality = 'high'; +PASS scaleImageData(highCanvas, '3223') did not throw exception. +PASS highContext.imageSmoothingQuality is 'high' +PASS scaleImageData(highCanvas, 'bad_input') did not throw exception. +PASS highContext.imageSmoothingQuality is 'high' +PASS scaleImageData(highCanvas, 'LOW') did not throw exception. +PASS highContext.imageSmoothingQuality is 'high' +PASS scaleImageData(highCanvas, 'Medium') did not throw exception. +PASS highContext.imageSmoothingQuality is 'high' + + +The save() and restore() should work. +highContext.save(); highContext.imageSmoothingQuality = 'medium'; +PASS highContext.imageSmoothingQuality is 'medium' +PASS scaleImageData(highCanvas, highCanvas.imageSmoothingQuality); is mediumData +PASS highContext.restore(); highContext.imageSmoothingQuality is 'high' +PASS scaleImageData(highCanvas, highCanvas.imageSmoothingQuality); is highData + +PASS successfullyParsed is true + +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 8fef1e54..b979841 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
@@ -3984,7 +3984,6 @@ method getBBox method getCTM method getScreenCTM - method getTransformToElement interface SVGImageElement : SVGGraphicsElement getter height getter href
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 e8f44bf..41626fe 100644 --- a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt +++ b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt
@@ -479,6 +479,7 @@ getter globalAlpha getter globalCompositeOperation getter imageSmoothingEnabled + getter imageSmoothingQuality getter lineCap getter lineDashOffset getter lineJoin @@ -546,6 +547,7 @@ setter globalAlpha setter globalCompositeOperation setter imageSmoothingEnabled + setter imageSmoothingQuality setter lineCap setter lineDashOffset setter lineJoin @@ -4522,7 +4524,6 @@ method getBBox method getCTM method getScreenCTM - method getTransformToElement interface SVGImageElement : SVGGraphicsElement getter height getter href
diff --git a/third_party/WebKit/PRESUBMIT.py b/third_party/WebKit/PRESUBMIT.py index d1c0e63..61a1efe1 100644 --- a/third_party/WebKit/PRESUBMIT.py +++ b/third_party/WebKit/PRESUBMIT.py
@@ -78,7 +78,6 @@ results.extend(_CheckForVersionControlConflicts(input_api, output_api)) results.extend(_CheckPatchFiles(input_api, output_api)) results.extend(_CheckTestExpectations(input_api, output_api)) - results.extend(_CheckUnwantedDependencies(input_api, output_api)) results.extend(_CheckChromiumPlatformMacros(input_api, output_api)) results.extend(_CheckWatchlist(input_api, output_api)) results.extend(_CheckFilePermissions(input_api, output_api)) @@ -135,60 +134,6 @@ return results -def _CheckUnwantedDependencies(input_api, output_api): - """Runs checkdeps on #include statements added in this - change. Breaking - rules is an error, breaking ! rules is a - warning. - """ - # We need to wait until we have an input_api object and use this - # roundabout construct to import checkdeps because this file is - # eval-ed and thus doesn't have __file__. - original_sys_path = sys.path - try: - sys.path = sys.path + [input_api.os_path.realpath(input_api.os_path.join( - input_api.PresubmitLocalPath(), '..', '..', 'buildtools', 'checkdeps'))] - import checkdeps - from cpp_checker import CppChecker - from rules import Rule - finally: - # Restore sys.path to what it was before. - sys.path = original_sys_path - - added_includes = [] - for f in input_api.AffectedFiles(): - if not CppChecker.IsCppFile(f.LocalPath()): - continue - - changed_lines = [line for line_num, line in f.ChangedContents()] - added_includes.append([f.LocalPath(), changed_lines]) - - deps_checker = checkdeps.DepsChecker( - input_api.os_path.join(input_api.PresubmitLocalPath())) - - error_descriptions = [] - warning_descriptions = [] - for path, rule_type, rule_description in deps_checker.CheckAddedCppIncludes( - added_includes): - description_with_path = '%s\n %s' % (path, rule_description) - if rule_type == Rule.DISALLOW: - error_descriptions.append(description_with_path) - else: - warning_descriptions.append(description_with_path) - - results = [] - if error_descriptions: - results.append(output_api.PresubmitError( - 'You added one or more #includes that violate checkdeps rules.', - error_descriptions)) - if warning_descriptions: - results.append(output_api.PresubmitPromptOrNotify( - 'You added one or more #includes of files that are temporarily\n' - 'allowed but being removed. Can you avoid introducing the\n' - '#include? See relevant DEPS file(s) for details and contacts.', - warning_descriptions)) - return results - - def _CheckChromiumPlatformMacros(input_api, output_api, source_file_filter=None): """Ensures that Blink code uses WTF's platform macros instead of Chromium's. Using the latter has resulted in at least one subtle
diff --git a/third_party/WebKit/PerformanceTests/Layout/nested-blocks-with-percent-height-and-max-height.html b/third_party/WebKit/PerformanceTests/Layout/nested-blocks-with-percent-height-and-max-height.html new file mode 100644 index 0000000..11e2d3d --- /dev/null +++ b/third_party/WebKit/PerformanceTests/Layout/nested-blocks-with-percent-height-and-max-height.html
@@ -0,0 +1,67 @@ +<!DOCTYPE html> +<style> +html, body { + height: 100%; +} +div { + height: 50%; + max-height: 50%; +} +</style> +<div id="target" style="display: none;"> + <div> + <div> + <div> + <div> + <div> + <div> + <div> + <div> + <div> + <div> + <div> + <div> + <div> + <div> + <div> + <div> + <div> + <div> + <div> + </div> + </div> + </div> + </div> + </div> + </div> + </div> + </div> + </div> + </div> + </div> + </div> + </div> + </div> + </div> + </div> + </div> + </div> + </div> +</div> +<script src="../resources/runner.js"></script> +<script> + var target = document.getElementById("target"); + var style = target.style; + + function test() { + style.display = "block"; + PerfTestRunner.forceLayoutOrFullFrame(); + style.display = "none"; + } + + PerfTestRunner.measureRunsPerSecond({ + description: "Measures performance of nested divs with percent values for height and max-height.", + run: test +}); +</script> +</html>
diff --git a/third_party/WebKit/Source/core/dom/Document.cpp b/third_party/WebKit/Source/core/dom/Document.cpp index 22cb2d7..9726edd 100644 --- a/third_party/WebKit/Source/core/dom/Document.cpp +++ b/third_party/WebKit/Source/core/dom/Document.cpp
@@ -2424,20 +2424,14 @@ void Document::cancelParsing() { - if (!m_parser) - return; - - // We have to clear the parser to avoid possibly triggering - // the onload handler when closing as a side effect of a cancel-style - // change, such as opening a new document or closing the window while - // still parsing. detachParser(); - explicitClose(); + setParsingState(FinishedParsing); + setReadyState(Complete); } PassRefPtrWillBeRawPtr<DocumentParser> Document::implicitOpen(ParserSynchronizationPolicy parserSyncPolicy) { - cancelParsing(); + detachParser(); removeChildren(); ASSERT(!m_focusedElement); @@ -2563,11 +2557,6 @@ if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing()) return; - explicitClose(); -} - -void Document::explicitClose() -{ if (RefPtrWillBeRawPtr<DocumentParser> parser = m_parser) parser->finish();
diff --git a/third_party/WebKit/Source/core/dom/Document.h b/third_party/WebKit/Source/core/dom/Document.h index 552c2da9..f4d0767 100644 --- a/third_party/WebKit/Source/core/dom/Document.h +++ b/third_party/WebKit/Source/core/dom/Document.h
@@ -479,10 +479,6 @@ void close(ExceptionState&); // This is used internally and does not handle exceptions. void close(); - // In some situations (see the code), we ignore document.close(). - // explicitClose() bypass these checks and actually tries to close the - // input stream. - void explicitClose(); // implicitClose() actually does the work of closing the input stream. void implicitClose();
diff --git a/third_party/WebKit/Source/core/frame/FrameView.cpp b/third_party/WebKit/Source/core/frame/FrameView.cpp index 6dc9581..de7808c5 100644 --- a/third_party/WebKit/Source/core/frame/FrameView.cpp +++ b/third_party/WebKit/Source/core/frame/FrameView.cpp
@@ -95,7 +95,7 @@ #include "platform/graphics/paint/CullRect.h" #include "platform/graphics/paint/PaintController.h" #include "platform/scheduler/CancellableTaskFactory.h" -#include "platform/scroll/ScrollAnimator.h" +#include "platform/scroll/ScrollAnimatorBase.h" #include "platform/text/TextStream.h" #include "public/platform/WebDisplayItemList.h" #include "public/platform/WebFrameScheduler.h" @@ -225,13 +225,18 @@ } template <typename Function> -void FrameView::forAllFrameViews(Function function) +void FrameView::forAllNonThrottledFrameViews(Function function) { - for (Frame* frame = m_frame.get(); frame; frame = frame->tree().traverseNext(m_frame.get())) { - if (!frame->isLocalFrame()) + if (shouldThrottleRendering()) + return; + + function(*this); + + for (Frame* child = m_frame->tree().firstChild(); child; child = child->tree().nextSibling()) { + if (!child->isLocalFrame()) continue; - if (FrameView* view = toLocalFrame(frame)->view()) - function(*view); + if (FrameView* childView = toLocalFrame(child)->view()) + childView->forAllNonThrottledFrameViews(function); } } @@ -263,7 +268,7 @@ { RELEASE_ASSERT(!isInPerformLayout()); - if (ScrollAnimator* scrollAnimator = existingScrollAnimator()) + if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator()) scrollAnimator->cancelAnimations(); cancelProgrammaticScrollAnimation(); @@ -1292,9 +1297,7 @@ void FrameView::scrollContentsIfNeededRecursive() { - forAllFrameViews([](FrameView& frameView) { - if (frameView.shouldThrottleRendering()) - return; + forAllNonThrottledFrameViews([](FrameView& frameView) { frameView.scrollContentsIfNeeded(); }); } @@ -1824,7 +1827,7 @@ void FrameView::updateBackgroundRecursively(const Color& backgroundColor, bool transparent) { - forAllFrameViews([backgroundColor, transparent](FrameView& frameView) { + forAllNonThrottledFrameViews([backgroundColor, transparent](FrameView& frameView) { frameView.setTransparent(transparent); frameView.setBaseBackgroundColor(backgroundColor); }); @@ -2457,7 +2460,7 @@ if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) updatePaintProperties(); - if (RuntimeEnabledFeatures::slimmingPaintSynchronizedPaintingEnabled()) { + if (RuntimeEnabledFeatures::slimmingPaintSynchronizedPaintingEnabled() && !m_frame->document()->printing()) { synchronizedPaint(); if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) compositeForSlimmingPaintV2(); @@ -2480,9 +2483,9 @@ { ASSERT(RuntimeEnabledFeatures::slimmingPaintV2Enabled()); - forAllFrameViews([](FrameView& frameView) { frameView.lifecycle().advanceTo(DocumentLifecycle::InUpdatePaintProperties); }); + forAllNonThrottledFrameViews([](FrameView& frameView) { frameView.lifecycle().advanceTo(DocumentLifecycle::InUpdatePaintProperties); }); PaintPropertyTreeBuilder().buildPropertyTrees(*this); - forAllFrameViews([](FrameView& frameView) { frameView.lifecycle().advanceTo(DocumentLifecycle::UpdatePaintPropertiesClean); }); + forAllNonThrottledFrameViews([](FrameView& frameView) { frameView.lifecycle().advanceTo(DocumentLifecycle::UpdatePaintPropertiesClean); }); } void FrameView::synchronizedPaint() @@ -2492,16 +2495,26 @@ LayoutView* view = layoutView(); ASSERT(view); - // TODO(chrishtr): figure out if there can be any GraphicsLayer above this one that draws content. - GraphicsLayer* rootGraphicsLayer = view->layer()->graphicsLayerBacking(); - forAllFrameViews([](FrameView& frameView) { frameView.lifecycle().advanceTo(DocumentLifecycle::InPaint); }); + forAllNonThrottledFrameViews([](FrameView& frameView) { frameView.lifecycle().advanceTo(DocumentLifecycle::InPaint); }); // A null graphics layer can occur for painting of SVG images that are not parented into the main frame tree. - if (rootGraphicsLayer) { - synchronizedPaintRecursively(rootGraphicsLayer); + if (GraphicsLayer* rootGraphicsLayer = view->layer()->graphicsLayerBacking()) { + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { + // TODO(wangxianzhu,chrishtr): What about the extra graphics layers for overflow control, virtual viewport, etc? + GraphicsContext context(*rootGraphicsLayer->paintController()); + rootGraphicsLayer->paint(context, nullptr); + } else { + // Find the real root GraphicsLayer because we also need to paint layers not under the root graphics layer of + // the LayoutView, e.g. scrollbar layers created by PaintLayerCompositor and VisualViewport. + // We could ask PaintLayerCompositor and VisualViewport for the real root GraphicsLayer, but the following loop + // has the least dependency to those things which might change for slimming paint v2. + while (GraphicsLayer* parent = rootGraphicsLayer->parent()) + rootGraphicsLayer = parent; + synchronizedPaintRecursively(rootGraphicsLayer); + } } - forAllFrameViews([](FrameView& frameView) { + forAllNonThrottledFrameViews([](FrameView& frameView) { frameView.lifecycle().advanceTo(DocumentLifecycle::PaintClean); frameView.layoutView()->layer()->clearNeedsRepaintRecursively(); }); @@ -2509,13 +2522,20 @@ void FrameView::synchronizedPaintRecursively(GraphicsLayer* graphicsLayer) { + ASSERT(!RuntimeEnabledFeatures::slimmingPaintV2Enabled()); ASSERT(graphicsLayer->paintController()); GraphicsContext context(*graphicsLayer->paintController()); - graphicsLayer->paint(context, nullptr); + if (GraphicsLayer* maskLayer = graphicsLayer->maskLayer()) + synchronizedPaintRecursively(maskLayer); + if (GraphicsLayer* contentsClippingMaskLayer = graphicsLayer->contentsClippingMaskLayer()) + synchronizedPaintRecursively(contentsClippingMaskLayer); + if (GraphicsLayer* replicaLayer = graphicsLayer->replicaLayer()) + synchronizedPaintRecursively(replicaLayer); - if (!RuntimeEnabledFeatures::slimmingPaintV2Enabled()) - graphicsLayer->paintController()->commitNewDisplayItems(); + // TODO(chrishtr): fix unit tests to not inject one-off interest rects. + graphicsLayer->paint(context, nullptr); + graphicsLayer->paintController()->commitNewDisplayItems(); for (auto& child : graphicsLayer->children()) synchronizedPaintRecursively(child); @@ -2526,13 +2546,12 @@ ASSERT(RuntimeEnabledFeatures::slimmingPaintV2Enabled()); ASSERT(frame() == page()->mainFrame() || (!frame().tree().parent()->isLocalFrame())); - forAllFrameViews([](FrameView& frameView) { frameView.lifecycle().advanceTo(DocumentLifecycle::InCompositingForSlimmingPaintV2); }); + forAllNonThrottledFrameViews([](FrameView& frameView) { frameView.lifecycle().advanceTo(DocumentLifecycle::InCompositingForSlimmingPaintV2); }); - // Detached frames can have no root graphics layer. if (GraphicsLayer* rootGraphicsLayer = layoutView()->layer()->graphicsLayerBacking()) rootGraphicsLayer->paintController()->commitNewDisplayItems(); - forAllFrameViews([](FrameView& frameView) { frameView.lifecycle().advanceTo(DocumentLifecycle::CompositingForSlimmingPaintV2Clean); }); + forAllNonThrottledFrameViews([](FrameView& frameView) { frameView.lifecycle().advanceTo(DocumentLifecycle::CompositingForSlimmingPaintV2Clean); }); } void FrameView::updateFrameTimingRequestsIfNeeded() @@ -2616,7 +2635,8 @@ Vector<LayoutObject*> pendingDelayedPaintInvalidations; PaintInvalidationState rootPaintInvalidationState(*layoutView(), pendingDelayedPaintInvalidations); - invalidateTreeIfNeeded(rootPaintInvalidationState); + if (lifecycle().state() < DocumentLifecycle::PaintInvalidationClean) + invalidateTreeIfNeeded(rootPaintInvalidationState); // Some frames may be not reached during the above invalidateTreeIfNeeded because // - the frame is a detached frame; or @@ -2624,11 +2644,8 @@ // We need to call invalidateTreeIfNeededRecursive() for such frames to finish required // paint invalidation and advance their life cycle state. for (Frame* child = m_frame->tree().firstChild(); child; child = child->tree().nextSibling()) { - if (!child->isLocalFrame()) - continue; - FrameView* childFrameView = toLocalFrame(child)->view(); - if (childFrameView->lifecycle().state() < DocumentLifecycle::PaintInvalidationClean) - childFrameView->invalidateTreeIfNeededRecursive(); + if (child->isLocalFrame()) + toLocalFrame(child)->view()->invalidateTreeIfNeededRecursive(); } // Process objects needing paint invalidation on the next frame. See the definition of PaintInvalidationDelayedFull for more details.
diff --git a/third_party/WebKit/Source/core/frame/FrameView.h b/third_party/WebKit/Source/core/frame/FrameView.h index 19fb36f5..bae313f 100644 --- a/third_party/WebKit/Source/core/frame/FrameView.h +++ b/third_party/WebKit/Source/core/frame/FrameView.h
@@ -737,7 +737,7 @@ void collectFrameTimingRequests(GraphicsLayerFrameTimingRequests&); void collectFrameTimingRequestsRecursive(GraphicsLayerFrameTimingRequests&); - template <typename Function> void forAllFrameViews(Function); + template <typename Function> void forAllNonThrottledFrameViews(Function); void setNeedsUpdateViewportIntersection(); void updateViewportIntersectionsForSubtree();
diff --git a/third_party/WebKit/Source/core/frame/RootFrameViewport.cpp b/third_party/WebKit/Source/core/frame/RootFrameViewport.cpp index fa85bd3d..8c5e302ec 100644 --- a/third_party/WebKit/Source/core/frame/RootFrameViewport.cpp +++ b/third_party/WebKit/Source/core/frame/RootFrameViewport.cpp
@@ -42,7 +42,7 @@ bool RootFrameViewport::shouldUseIntegerScrollOffset() const { - // Fractionals are floored in the ScrollAnimator but it's important that the ScrollAnimators of the + // Fractionals are floored in the ScrollAnimatorBase but it's important that the ScrollAnimators of the // visual and layout viewports get the precise fractional number so never use integer scrolling for // RootFrameViewport, we'll let the truncation happen in the subviewports. return false; @@ -98,7 +98,7 @@ // We want to move the rect into the viewport that excludes the scrollbars so we intersect // the visual viewport with the scrollbar-excluded frameView content rect. However, we don't // use visibleContentRect directly since it floors the scroll position. Instead, we use - // ScrollAnimator::currentPosition and construct a LayoutRect from that. + // ScrollAnimatorBase::currentPosition and construct a LayoutRect from that. LayoutRect frameRectInContent = LayoutRect( layoutViewport().scrollAnimator()->currentPosition(), @@ -132,7 +132,7 @@ void RootFrameViewport::distributeScrollBetweenViewports(const DoublePoint& offset, ScrollType scrollType, ScrollBehavior behavior) { - // Make sure we use the scroll positions as reported by each viewport's ScrollAnimator, since its + // Make sure we use the scroll positions as reported by each viewport's ScrollAnimatorBase, since its // ScrollableArea's position may have the fractional part truncated off. DoublePoint oldPosition = scrollOffsetFromScrollAnimators();
diff --git a/third_party/WebKit/Source/core/frame/VisualViewport.cpp b/third_party/WebKit/Source/core/frame/VisualViewport.cpp index 974675b..78819b9f 100644 --- a/third_party/WebKit/Source/core/frame/VisualViewport.cpp +++ b/third_party/WebKit/Source/core/frame/VisualViewport.cpp
@@ -195,6 +195,9 @@ void VisualViewport::setScaleAndLocation(float scale, const FloatPoint& location) { + if (!mainFrame()) + return; + bool valuesChanged = false; if (scale != m_scale) { @@ -213,8 +216,8 @@ if (ScrollingCoordinator* coordinator = frameHost().page().scrollingCoordinator()) coordinator->scrollableAreaScrollLayerDidChange(this); - Document* document = mainFrame()->document(); - document->enqueueScrollEventForNode(document); + if (Document* document = mainFrame()->document()) + document->enqueueScrollEventForNode(document); mainFrame()->loader().client()->didChangeScrollOffset(); valuesChanged = true;
diff --git a/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp b/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp index b99bb28..aa01bf6 100644 --- a/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp +++ b/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp
@@ -26,8 +26,8 @@ String getSha256String(const String& content) { DigestValue digest; - StringUTF8Adaptor normalizedContent = normalizeSource(content); - bool digestSuccess = computeDigest(HashAlgorithmSha256, normalizedContent.data(), normalizedContent.length(), digest); + StringUTF8Adaptor utf8Content(content); + bool digestSuccess = computeDigest(HashAlgorithmSha256, utf8Content.data(), utf8Content.length(), digest); if (!digestSuccess) { return "sha256-..."; }
diff --git a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp index 85167e0..40fc7273 100644 --- a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp +++ b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp
@@ -430,12 +430,12 @@ if (hashAlgorithmsUsed == ContentSecurityPolicyHashAlgorithmNone) return false; - StringUTF8Adaptor normalizedSource = normalizeSource(source); + StringUTF8Adaptor utf8Source(source); for (const auto& algorithmMap : kAlgorithmMap) { DigestValue digest; if (algorithmMap.cspHashAlgorithm & hashAlgorithmsUsed) { - bool digestSuccess = computeDigest(algorithmMap.algorithm, normalizedSource.data(), normalizedSource.length(), digest); + bool digestSuccess = computeDigest(algorithmMap.algorithm, utf8Source.data(), utf8Source.length(), digest); if (digestSuccess && isAllowedByAllWithHash<allowed>(policies, CSPHashValue(algorithmMap.cspHashAlgorithm, digest))) return true; }
diff --git a/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp b/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp index de7d65b..67c4db6a 100644 --- a/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp
@@ -754,7 +754,7 @@ scheduleEvent(EventTypeNames::emptied); // 4.2 - If a fetching process is in progress for the media element, the user agent should stop it. - m_networkState = NETWORK_EMPTY; + setNetworkState(NETWORK_EMPTY); // 4.3 - Forget the media element's media-resource-specific tracks. forgetResourceSpecificTracks(); @@ -797,7 +797,7 @@ // The resource selection algorithm // 1 - Set the networkState to NETWORK_NO_SOURCE - m_networkState = NETWORK_NO_SOURCE; + setNetworkState(NETWORK_NO_SOURCE); // 2 - Asynchronously await a stable state. @@ -854,7 +854,7 @@ // synchronous section ends. m_loadState = WaitingForSource; setShouldDelayLoadEvent(false); - m_networkState = NETWORK_EMPTY; + setNetworkState(NETWORK_EMPTY); updateDisplayState(); WTF_LOG(Media, "HTMLMediaElement::selectMediaResource(%p), nothing to load", this); @@ -865,7 +865,7 @@ // 4 - Set the media element's delaying-the-load-event flag to true (this delays the load event), // and set its networkState to NETWORK_LOADING. setShouldDelayLoadEvent(true); - m_networkState = NETWORK_LOADING; + setNetworkState(NETWORK_LOADING); // 5 - Queue a task to fire a simple event named loadstart at the media element. scheduleEvent(EventTypeNames::loadstart); @@ -931,7 +931,7 @@ } // The resource fetch algorithm - m_networkState = NETWORK_LOADING; + setNetworkState(NETWORK_LOADING); // Set m_currentSrc *before* changing to the cache url, the fact that we are loading from the app // cache is an internal detail not exposed through the media element API. @@ -1103,7 +1103,7 @@ // delays the load event again, in case it hasn't been fired yet). setShouldDelayLoadEvent(true); // 7. Set the networkState to NETWORK_LOADING. - m_networkState = NETWORK_LOADING; + setNetworkState(NETWORK_LOADING); startProgressEventTimer(); @@ -1238,7 +1238,7 @@ m_loadState = WaitingForSource; // 6.17 - Waiting: Set the element's networkState attribute to the NETWORK_NO_SOURCE value - m_networkState = NETWORK_NO_SOURCE; + setNetworkState(NETWORK_NO_SOURCE); // 6.18 - Set the element's delaying-the-load-event flag to false. This stops delaying the load event. setShouldDelayLoadEvent(false); @@ -1269,7 +1269,7 @@ forgetResourceSpecificTracks(); // 6.3 - Set the element's networkState attribute to the NETWORK_NO_SOURCE value. - m_networkState = NETWORK_NO_SOURCE; + setNetworkState(NETWORK_NO_SOURCE); // 7 - Queue a task to fire a simple event named error at the media element. scheduleEvent(EventTypeNames::error); @@ -1305,7 +1305,7 @@ scheduleEvent(EventTypeNames::error); // 4 - Set the element's networkState attribute to the NETWORK_IDLE value. - m_networkState = NETWORK_IDLE; + setNetworkState(NETWORK_IDLE); // 5 - Set the element's delaying-the-load-event flag to false. This stops delaying the load event. setShouldDelayLoadEvent(false); @@ -1379,7 +1379,7 @@ if (state == WebMediaPlayer::NetworkStateEmpty) { // Just update the cached state and leave, we can't do anything. - m_networkState = NETWORK_EMPTY; + setNetworkState(NETWORK_EMPTY); return; } @@ -1395,14 +1395,14 @@ changeNetworkStateFromLoadingToIdle(); setShouldDelayLoadEvent(false); } else { - m_networkState = NETWORK_IDLE; + setNetworkState(NETWORK_IDLE); } } if (state == WebMediaPlayer::NetworkStateLoading) { if (m_networkState < NETWORK_LOADING || m_networkState == NETWORK_NO_SOURCE) startProgressEventTimer(); - m_networkState = NETWORK_LOADING; + setNetworkState(NETWORK_LOADING); m_completelyLoaded = false; } @@ -1422,7 +1422,7 @@ if (webMediaPlayer() && webMediaPlayer()->didLoadingProgress()) scheduleEvent(EventTypeNames::progress); scheduleEvent(EventTypeNames::suspend); - m_networkState = NETWORK_IDLE; + setNetworkState(NETWORK_IDLE); } void HTMLMediaElement::readyStateChanged() @@ -2659,7 +2659,7 @@ setShouldDelayLoadEvent(true); // 24. Set the networkState back to NETWORK_LOADING. - m_networkState = NETWORK_LOADING; + setNetworkState(NETWORK_LOADING); // 25. Jump back to the find next candidate step above. m_nextChildNodeToConsider = source; @@ -3003,10 +3003,10 @@ // simple event named emptied at the element. Otherwise, set the element's networkState // attribute to the NETWORK_IDLE value. if (readyState == HAVE_NOTHING) { - m_networkState = NETWORK_EMPTY; + setNetworkState(NETWORK_EMPTY); scheduleEvent(EventTypeNames::emptied); } else { - m_networkState = NETWORK_IDLE; + setNetworkState(NETWORK_IDLE); } // 5 - Set the element's delaying-the-load-event flag to false. This stops delaying the load event. @@ -3584,6 +3584,15 @@ m_initialPlayWithoutUserGesture = value; } +void HTMLMediaElement::setNetworkState(NetworkState state) +{ + if (m_networkState != state) { + m_networkState = state; + if (MediaControls* controls = mediaControls()) + controls->networkStateChanged(); + } +} + #if ENABLE(WEB_AUDIO) void HTMLMediaElement::clearWeakMembers(Visitor* visitor) {
diff --git a/third_party/WebKit/Source/core/html/HTMLMediaElement.h b/third_party/WebKit/Source/core/html/HTMLMediaElement.h index bd89bc1..ac28254 100644 --- a/third_party/WebKit/Source/core/html/HTMLMediaElement.h +++ b/third_party/WebKit/Source/core/html/HTMLMediaElement.h
@@ -442,6 +442,8 @@ void removeUserGestureRequirement(); void setInitialPlayWithoutUserGestures(bool); + void setNetworkState(NetworkState); + void audioTracksTimerFired(Timer<HTMLMediaElement>*); Timer<HTMLMediaElement> m_loadTimer;
diff --git a/third_party/WebKit/Source/core/html/HTMLPlugInElement.cpp b/third_party/WebKit/Source/core/html/HTMLPlugInElement.cpp index 68bb358..15d82af2 100644 --- a/third_party/WebKit/Source/core/html/HTMLPlugInElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLPlugInElement.cpp
@@ -114,6 +114,8 @@ #if ENABLE(OILPAN) unregisterAsRenderlessIfNeeded(); registerAsRenderless(widget); + if (m_persistedPluginWidget) + m_persistedPluginWidget->dispose(); #endif m_persistedPluginWidget = widget; } @@ -124,10 +126,6 @@ if (!m_persistedPluginWidget || !m_persistedPluginWidget->isPluginView()) return false; - // If we are in a renderer-less state, keep the registration. - if (!layoutEmbeddedObject()) - return false; - LocalFrame* frame = toPluginView(m_persistedPluginWidget.get())->pluginFrame(); ASSERT(frame); frame->unregisterPluginElement(this); @@ -148,7 +146,9 @@ PassRefPtrWillBeRawPtr<Widget> HTMLPlugInElement::releasePersistedPluginWidget() { #if ENABLE(OILPAN) - unregisterAsRenderlessIfNeeded(); + // If we are in a renderer-less state, keep the registration. + if (layoutEmbeddedObject()) + unregisterAsRenderlessIfNeeded(); #endif return m_persistedPluginWidget.release(); }
diff --git a/third_party/WebKit/Source/core/html/HTMLVideoElement.cpp b/third_party/WebKit/Source/core/html/HTMLVideoElement.cpp index e481ed1..fe517064 100644 --- a/third_party/WebKit/Source/core/html/HTMLVideoElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLVideoElement.cpp
@@ -206,16 +206,13 @@ webMediaPlayer()->paint(canvas, destRect, paint ? paint->getAlpha() : 0xFF, mode); } -bool HTMLVideoElement::copyVideoTextureToPlatformTexture(WebGraphicsContext3D* context, const WebMediaPlayer::CopyVideoTextureParams& params) +bool HTMLVideoElement::copyVideoTextureToPlatformTexture(WebGraphicsContext3D* context, Platform3DObject texture, GLenum internalFormat, GLenum type, bool premultiplyAlpha, bool flipY) { if (!webMediaPlayer()) return false; - ASSERT(Extensions3DUtil::canUseCopyTextureCHROMIUM(params.target, - params.copyType == WebMediaPlayer::CopyVideoTextureParams::SubCopy ? GL_RGBA : params.internalFormat, - params.copyType == WebMediaPlayer::CopyVideoTextureParams::SubCopy ? GL_UNSIGNED_BYTE : params.type, - params.level)); - return webMediaPlayer()->copyVideoTextureToPlatformTexture(context, params); + ASSERT(Extensions3DUtil::canUseCopyTextureCHROMIUM(GL_TEXTURE_2D, internalFormat, type, 0)); + return webMediaPlayer()->copyVideoTextureToPlatformTexture(context, texture, internalFormat, type, premultiplyAlpha, flipY); } bool HTMLVideoElement::hasAvailableVideoFrame() const
diff --git a/third_party/WebKit/Source/core/html/HTMLVideoElement.h b/third_party/WebKit/Source/core/html/HTMLVideoElement.h index d2fc47ac..056e560 100644 --- a/third_party/WebKit/Source/core/html/HTMLVideoElement.h +++ b/third_party/WebKit/Source/core/html/HTMLVideoElement.h
@@ -69,7 +69,7 @@ void paintCurrentFrame(SkCanvas*, const IntRect&, const SkPaint*) const; // Used by WebGL to do GPU-GPU textures copy if possible. - bool copyVideoTextureToPlatformTexture(WebGraphicsContext3D*, const WebMediaPlayer::CopyVideoTextureParams&); + bool copyVideoTextureToPlatformTexture(WebGraphicsContext3D*, Platform3DObject texture, GLenum internalFormat, GLenum type, bool premultiplyAlpha, bool flipY); bool shouldDisplayPosterImage() const { return displayMode() == Poster; }
diff --git a/third_party/WebKit/Source/core/html/imports/HTMLImportLoader.cpp b/third_party/WebKit/Source/core/html/imports/HTMLImportLoader.cpp index 9b91418..a31d1c17 100644 --- a/third_party/WebKit/Source/core/html/imports/HTMLImportLoader.cpp +++ b/third_party/WebKit/Source/core/html/imports/HTMLImportLoader.cpp
@@ -65,7 +65,6 @@ if (m_document->parser()) m_document->parser()->removeClient(this); m_document->setImportsController(nullptr); - m_document->cancelParsing(); m_document.clear(); } }
diff --git a/third_party/WebKit/Source/core/html/parser/HTMLConstructionSite.cpp b/third_party/WebKit/Source/core/html/parser/HTMLConstructionSite.cpp index d2807787..b8b8cba6 100644 --- a/third_party/WebKit/Source/core/html/parser/HTMLConstructionSite.cpp +++ b/third_party/WebKit/Source/core/html/parser/HTMLConstructionSite.cpp
@@ -603,8 +603,8 @@ RefPtrWillBeRawPtr<HTMLElement> body = createHTMLElement(token); attachLater(currentNode(), body); m_openElements.pushHTMLBodyElement(HTMLStackItem::create(body.release(), token)); - if (LocalFrame* frame = m_document->frame()) - frame->loader().client()->dispatchWillInsertBody(); + if (m_document && m_document->frame()) + m_document->frame()->loader().client()->dispatchWillInsertBody(); } void HTMLConstructionSite::insertHTMLFormElement(AtomicHTMLToken* token, bool isDemoted)
diff --git a/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.cpp b/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.cpp index 0f10986..cca7640d 100644 --- a/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.cpp +++ b/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.cpp
@@ -489,6 +489,9 @@ if (isStopped()) break; } + // XSSAuditorDelegate can detach the parser if it decides to block the entire current document. + if (isDetached()) + return elementTokenCount; for (Vector<CompactHTMLToken>::const_iterator it = tokens->begin(); it != tokens->end(); ++it) { ASSERT(!isWaitingForScripts());
diff --git a/third_party/WebKit/Source/core/html/shadow/MediaControls.cpp b/third_party/WebKit/Source/core/html/shadow/MediaControls.cpp index ab6d148..5ae1bf1 100644 --- a/third_party/WebKit/Source/core/html/shadow/MediaControls.cpp +++ b/third_party/WebKit/Source/core/html/shadow/MediaControls.cpp
@@ -414,8 +414,7 @@ { m_muteButton->updateDisplayType(); // Invalidate the mute button because it paints differently according to volume. - if (LayoutObject* layoutObject = m_muteButton->layoutObject()) - layoutObject->setShouldDoFullPaintInvalidation(); + invalidate(m_muteButton); if (mediaElement().muted()) m_volumeSlider->setVolume(0); @@ -441,8 +440,7 @@ } // Invalidate the volume slider because it paints differently according to volume. - if (LayoutObject* layoutObject = m_volumeSlider->layoutObject()) - layoutObject->setShouldDoFullPaintInvalidation(); + invalidate(m_volumeSlider); } void MediaControls::changedClosedCaptionsVisibility() @@ -708,6 +706,25 @@ updateVolume(); } +void MediaControls::invalidate(Element* element) +{ + if (!element) + return; + + if (LayoutObject* layoutObject = element->layoutObject()) + layoutObject->setShouldDoFullPaintInvalidation(); +} + +void MediaControls::networkStateChanged() +{ + invalidate(m_playButton); + invalidate(m_overlayPlayButton); + invalidate(m_muteButton); + invalidate(m_fullScreenButton); + invalidate(m_timeline); + invalidate(m_volumeSlider); +} + DEFINE_TRACE(MediaControls) { visitor->trace(m_mediaElement);
diff --git a/third_party/WebKit/Source/core/html/shadow/MediaControls.h b/third_party/WebKit/Source/core/html/shadow/MediaControls.h index 2d4fb968..8ff1320d 100644 --- a/third_party/WebKit/Source/core/html/shadow/MediaControls.h +++ b/third_party/WebKit/Source/core/html/shadow/MediaControls.h
@@ -82,9 +82,14 @@ // Notify us that our controls enclosure has changed width. void notifyPanelWidthChanged(const LayoutUnit& newWidth); + // Notify us that the media element's network state has changed. + void networkStateChanged(); + DECLARE_VIRTUAL_TRACE(); private: + void invalidate(Element*); + class BatchedControlUpdate; explicit MediaControls(HTMLMediaElement&);
diff --git a/third_party/WebKit/Source/core/input/EventHandler.cpp b/third_party/WebKit/Source/core/input/EventHandler.cpp index 4f97d79..1e4b1d43 100644 --- a/third_party/WebKit/Source/core/input/EventHandler.cpp +++ b/third_party/WebKit/Source/core/input/EventHandler.cpp
@@ -92,7 +92,7 @@ #include "platform/geometry/FloatPoint.h" #include "platform/graphics/Image.h" #include "platform/heap/Handle.h" -#include "platform/scroll/ScrollAnimator.h" +#include "platform/scroll/ScrollAnimatorBase.h" #include "platform/scroll/Scrollbar.h" #include "wtf/Assertions.h" #include "wtf/CurrentTime.h" @@ -1910,13 +1910,13 @@ FrameView* view = m_frame->view(); if (!view) return false; - if (ScrollAnimator* scrollAnimator = view->existingScrollAnimator()) + if (ScrollAnimatorBase* scrollAnimator = view->existingScrollAnimator()) scrollAnimator->cancelAnimations(); const FrameView::ScrollableAreaSet* areas = view->scrollableAreas(); if (!areas) return false; for (const ScrollableArea* scrollableArea : *areas) { - ScrollAnimator* animator = scrollableArea->existingScrollAnimator(); + ScrollAnimatorBase* animator = scrollableArea->existingScrollAnimator(); if (animator) animator->cancelAnimations(); }
diff --git a/third_party/WebKit/Source/core/inspector/DevToolsHost.cpp b/third_party/WebKit/Source/core/inspector/DevToolsHost.cpp index 6753bec..d879b0a 100644 --- a/third_party/WebKit/Source/core/inspector/DevToolsHost.cpp +++ b/third_party/WebKit/Source/core/inspector/DevToolsHost.cpp
@@ -195,12 +195,6 @@ return dst.toString(); } -void DevToolsHost::sendMessageToBackend(const String& message) -{ - if (m_client) - m_client->sendMessageToBackend(escapeUnicodeNonCharacters(message)); -} - void DevToolsHost::sendMessageToEmbedder(const String& message) { if (m_client)
diff --git a/third_party/WebKit/Source/core/inspector/DevToolsHost.h b/third_party/WebKit/Source/core/inspector/DevToolsHost.h index 45aa94c..1c03b8a7 100644 --- a/third_party/WebKit/Source/core/inspector/DevToolsHost.h +++ b/third_party/WebKit/Source/core/inspector/DevToolsHost.h
@@ -64,7 +64,6 @@ // Called from [Custom] implementations. void showContextMenu(Event*, const Vector<ContextMenuItem>& items); void showContextMenu(LocalFrame* targetFrame, float x, float y, const Vector<ContextMenuItem>& items); - void sendMessageToBackend(const String& message); void sendMessageToEmbedder(const String& message); String getSelectionBackgroundColor();
diff --git a/third_party/WebKit/Source/core/inspector/DevToolsHost.idl b/third_party/WebKit/Source/core/inspector/DevToolsHost.idl index d20abb5e..ddddb8e 100644 --- a/third_party/WebKit/Source/core/inspector/DevToolsHost.idl +++ b/third_party/WebKit/Source/core/inspector/DevToolsHost.idl
@@ -44,7 +44,6 @@ // FIXME: showContextMenu is here only for old frontends. Remove in M43. [Custom] void showContextMenu(MouseEvent event, any items); [Custom] void showContextMenuAtPoint(float x, float y, any items, optional Document document); - void sendMessageToBackend(DOMString message); void sendMessageToEmbedder(DOMString message); DOMString getSelectionBackgroundColor();
diff --git a/third_party/WebKit/Source/core/inspector/InspectorFrontendClient.h b/third_party/WebKit/Source/core/inspector/InspectorFrontendClient.h index 31f84aec..3f11b9e4 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorFrontendClient.h +++ b/third_party/WebKit/Source/core/inspector/InspectorFrontendClient.h
@@ -43,8 +43,6 @@ public: virtual ~InspectorFrontendClient() { } - virtual void sendMessageToBackend(const String&) = 0; - virtual void sendMessageToEmbedder(const String&) = 0; virtual bool isUnderTest() = 0;
diff --git a/third_party/WebKit/Source/core/layout/LayoutBlock.cpp b/third_party/WebKit/Source/core/layout/LayoutBlock.cpp index 4629844..0cea0eb 100644 --- a/third_party/WebKit/Source/core/layout/LayoutBlock.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutBlock.cpp
@@ -235,15 +235,21 @@ bool oldStyleIsContainer = oldStyle->position() != StaticPosition || oldHasTransformRelatedProperty; if (oldStyleIsContainer && (newStyle.position() == StaticPosition || (oldHasTransformRelatedProperty && !newHasTransformRelatedProperty))) { - // Clear our positioned objects list. Our absolutely positioned descendants will be + // Clear our positioned objects list. Our absolute and fixed positioned descendants will be // inserted into our containing block's positioned objects list during layout. - removePositionedObjects(0, NewContainingBlock); + removePositionedObjects(nullptr, NewContainingBlock); } else if (!oldStyleIsContainer && (newStyle.position() != StaticPosition || newHasTransformRelatedProperty)) { // Remove our absolutely positioned descendants from their current containing block. // They will be inserted into our positioned objects list during layout. if (LayoutBlock* cb = containingBlockForAbsolutePosition()) cb->removePositionedObjects(this, NewContainingBlock); } + if (!oldHasTransformRelatedProperty && newHasTransformRelatedProperty) { + // Remove our fixed positioned descendants from their current containing block. + // They will be inserted into our positioned objects list during layout. + if (LayoutBlock* cb = containerForFixedPosition()) + cb->removePositionedObjects(this, NewContainingBlock); + } } LayoutBox::styleWillChange(diff, newStyle); @@ -281,7 +287,7 @@ if (oldStyle && parent()) { if (oldStyle->position() != newStyle.position() && newStyle.position() != StaticPosition) { - // Remove our absolutely positioned descendants from their new containing block, + // Remove our absolute and fixed positioned descendants from their new containing block, // in case containingBlock() changes by the change to the position property. // See styleWillChange() for other cases. if (LayoutBlock* cb = containingBlock()) @@ -1466,11 +1472,20 @@ Vector<LayoutBox*, 16> deadObjects; for (auto* positionedObject : *positionedDescendants) { - if (!o || positionedObject->isDescendantOf(o)) { + if (!o || (positionedObject->isDescendantOf(o) && o != positionedObject)) { if (containingBlockState == NewContainingBlock) { positionedObject->setChildNeedsLayout(MarkOnlyThis); if (positionedObject->needsPreferredWidthsRecalculation()) positionedObject->setPreferredLogicalWidthsDirty(MarkOnlyThis); + + // The positioned object changing containing block may change paint invalidation container. + // Invalidate it (including non-compositing descendants) on its original paint invalidation container. + if (!RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { + // This valid because we need to invalidate based on the current status. + DisableCompositingQueryAsserts compositingDisabler; + if (!positionedObject->isPaintInvalidationContainer()) + positionedObject->invalidatePaintIncludingNonCompositingDescendants(); + } } // It is parent blocks job to add positioned child to positioned objects list of its containing block
diff --git a/third_party/WebKit/Source/core/layout/LayoutGeometryMap.cpp b/third_party/WebKit/Source/core/layout/LayoutGeometryMap.cpp index 2f40991..ca3bd92 100644 --- a/third_party/WebKit/Source/core/layout/LayoutGeometryMap.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutGeometryMap.cpp
@@ -104,37 +104,6 @@ transformState.flatten(); } -FloatPoint LayoutGeometryMap::mapToContainer(const FloatPoint& p, const LayoutBoxModelObject* container) const -{ - FloatPoint result; - - if (!hasFixedPositionStep() && !hasTransformStep() && !hasNonUniformStep() && (!container || (m_mapping.size() && container == m_mapping[0].m_layoutObject))) { - result = p + m_accumulatedOffset; - } else { - TransformState transformState(TransformState::ApplyTransformDirection, p); - mapToContainer(transformState, container); - result = transformState.lastPlanarPoint(); - } - -#if ENABLE(ASSERT) - if (m_mapping.size() > 0) { - const LayoutObject* lastLayoutObject = m_mapping.last().m_layoutObject; - const PaintLayer* layer = lastLayoutObject->enclosingLayer(); - - // Bounds for invisible layers are intentionally not calculated, and are - // therefore not necessarily expected to be correct here. This is ok, - // because they will be recomputed if the layer becomes visible. - if (!layer || !layer->subtreeIsInvisible()) { - FloatPoint layoutObjectMappedResult = lastLayoutObject->localToContainerPoint(p, container, m_mapCoordinatesFlags); - - ASSERT(roundedIntPoint(layoutObjectMappedResult) == roundedIntPoint(result)); - } - } -#endif - - return result; -} - #ifndef NDEBUG // Handy function to call from gdb while debugging mismatched point/rect errors. void LayoutGeometryMap::dumpSteps() const
diff --git a/third_party/WebKit/Source/core/layout/LayoutGeometryMap.h b/third_party/WebKit/Source/core/layout/LayoutGeometryMap.h index 7c35202..4fe2cc5 100644 --- a/third_party/WebKit/Source/core/layout/LayoutGeometryMap.h +++ b/third_party/WebKit/Source/core/layout/LayoutGeometryMap.h
@@ -61,14 +61,12 @@ // Map to a container. Will assert that the container has been pushed onto this map. // A null container maps through the LayoutView (including its scale transform, if any). // If the container is the LayoutView, the scroll offset is applied, but not the scale. - FloatPoint mapToContainer(const FloatPoint&, const LayoutBoxModelObject*) const; FloatQuad mapToContainer(const FloatRect&, const LayoutBoxModelObject*) const; // Called by code walking the layout or layer trees. void pushMappingsToAncestor(const PaintLayer*, const PaintLayer* ancestorLayer); void popMappingsToAncestor(const PaintLayer*); void pushMappingsToAncestor(const LayoutObject*, const LayoutBoxModelObject* ancestorLayoutObject); - void popMappingsToAncestor(const LayoutBoxModelObject*); // The following methods should only be called by layoutObjects inside a call to pushMappingsToAncestor(). @@ -78,6 +76,7 @@ void push(const LayoutObject*, const TransformationMatrix&, bool accumulatingTransform = false, bool isNonUniform = false, bool isFixedPosition = false, bool hasTransform = false, LayoutSize offsetForFixedPosition = LayoutSize()); private: + void popMappingsToAncestor(const LayoutBoxModelObject*); void mapToContainer(TransformState&, const LayoutBoxModelObject* container = nullptr) const; void stepInserted(const LayoutGeometryMapStep&);
diff --git a/third_party/WebKit/Source/core/layout/LayoutObject.cpp b/third_party/WebKit/Source/core/layout/LayoutObject.cpp index 21ccab9d..336f2fa 100644 --- a/third_party/WebKit/Source/core/layout/LayoutObject.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutObject.cpp
@@ -887,7 +887,6 @@ { ASSERT(!paintInvalidationContainerSkipped || !*paintInvalidationContainerSkipped); ASSERT(!isText()); - ASSERT(style()->position() == FixedPosition); LayoutObject* ancestor = parent(); for (; ancestor && !ancestor->canContainFixedPositionObjects(); ancestor = ancestor->parent()) { @@ -3391,7 +3390,7 @@ traverseNonCompositingDescendants(const_cast<LayoutObject&>(object), Functor(paintInvalidationContainer)); } -void LayoutObject::invalidatePaintOfPreviousPaintInvalidationRect(const LayoutBoxModelObject& paintInvalidationContainer, PaintInvalidationReason reason) const +void LayoutObject::invalidatePaintOfPreviousPaintInvalidationRect(const LayoutBoxModelObject& paintInvalidationContainer, PaintInvalidationReason reason) { // These disablers are valid because we want to use the current compositing/invalidation status. DisablePaintInvalidationStateAsserts invalidationDisabler; @@ -3404,6 +3403,12 @@ // The PaintController may have changed. Pass the previous paint invalidation rect to the new PaintController. // The rect will be updated if it changes during the next paint invalidation. invalidateDisplayItemClients(paintInvalidationContainer, PaintInvalidationLayer, &invalidationRect); + + // This method may be used to invalidate paint of an object changing paint invalidation container. + // Clear previous paint invalidation rect on the original paint invalidation container to avoid + // under-invalidation if the new paint invalidation rect on the new paint invalidation container + // happens to be the same as the old one. + setPreviousPaintInvalidationRect(LayoutRect()); } void LayoutObject::invalidatePaintIncludingNonCompositingDescendants() @@ -3467,12 +3472,10 @@ return objectPaintPropertiesMap().get(this); } -ObjectPaintProperties& LayoutObject::ensureObjectPaintProperties() +void LayoutObject::setObjectPaintProperties(PassOwnPtr<ObjectPaintProperties> paintProperties) { ASSERT(RuntimeEnabledFeatures::slimmingPaintV2Enabled()); - if (ObjectPaintProperties* properties = objectPaintProperties()) - return *properties; - return *objectPaintPropertiesMap().set(this, ObjectPaintProperties::create()).storedValue->value.get(); + objectPaintPropertiesMap().set(this, paintProperties); } void LayoutObject::clearObjectPaintProperties()
diff --git a/third_party/WebKit/Source/core/layout/LayoutObject.h b/third_party/WebKit/Source/core/layout/LayoutObject.h index c6697f7..ce34329 100644 --- a/third_party/WebKit/Source/core/layout/LayoutObject.h +++ b/third_party/WebKit/Source/core/layout/LayoutObject.h
@@ -383,7 +383,7 @@ // The property nodes are only updated during InUpdatePaintProperties phase // of the document lifecycle and shall remain immutable during other phases. ObjectPaintProperties* objectPaintProperties() const; - ObjectPaintProperties& ensureObjectPaintProperties(); + void setObjectPaintProperties(PassOwnPtr<ObjectPaintProperties>); void clearObjectPaintProperties(); private: @@ -770,7 +770,9 @@ // the layoutObject returned is an ancestor of |paintInvalidationContainer|. LayoutObject* container(const LayoutBoxModelObject* paintInvalidationContainer = nullptr, bool* paintInvalidationContainerSkipped = nullptr) const; LayoutObject* containerCrossingFrameBoundaries() const; + // Finds the container as if this object is fixed-position. LayoutBlock* containerForFixedPosition(const LayoutBoxModelObject* paintInvalidationContainer = nullptr, bool* paintInvalidationContainerSkipped = nullptr) const; + // Finds the containing block as if this object is absolute-position. LayoutBlock* containingBlockForAbsolutePosition() const; virtual LayoutObject* hoverAncestor() const { return parent(); } @@ -1504,7 +1506,7 @@ inline void invalidateContainerPreferredLogicalWidths(); - void invalidatePaintOfPreviousPaintInvalidationRect(const LayoutBoxModelObject& paintInvalidationContainer, PaintInvalidationReason) const; + void invalidatePaintOfPreviousPaintInvalidationRect(const LayoutBoxModelObject& paintInvalidationContainer, PaintInvalidationReason); LayoutRect previousSelectionRectForPaintInvalidation() const; void setPreviousSelectionRectForPaintInvalidation(const LayoutRect&);
diff --git a/third_party/WebKit/Source/core/layout/LayoutObjectChildList.cpp b/third_party/WebKit/Source/core/layout/LayoutObjectChildList.cpp index 0dae1bd..5ff94c0 100644 --- a/third_party/WebKit/Source/core/layout/LayoutObjectChildList.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutObjectChildList.cpp
@@ -178,7 +178,7 @@ cache->childrenChanged(owner); } -void LayoutObjectChildList::invalidatePaintOnRemoval(const LayoutObject& oldChild) +void LayoutObjectChildList::invalidatePaintOnRemoval(LayoutObject& oldChild) { if (!oldChild.isRooted()) return;
diff --git a/third_party/WebKit/Source/core/layout/LayoutObjectChildList.h b/third_party/WebKit/Source/core/layout/LayoutObjectChildList.h index 4745639a..a8fd0f5 100644 --- a/third_party/WebKit/Source/core/layout/LayoutObjectChildList.h +++ b/third_party/WebKit/Source/core/layout/LayoutObjectChildList.h
@@ -60,7 +60,7 @@ } private: - void invalidatePaintOnRemoval(const LayoutObject& oldChild); + void invalidatePaintOnRemoval(LayoutObject& oldChild); LayoutObject* m_firstChild; LayoutObject* m_lastChild;
diff --git a/third_party/WebKit/Source/core/layout/api/LineLayoutSVGInlineText.h b/third_party/WebKit/Source/core/layout/api/LineLayoutSVGInlineText.h index d979bc8..204cd21 100644 --- a/third_party/WebKit/Source/core/layout/api/LineLayoutSVGInlineText.h +++ b/third_party/WebKit/Source/core/layout/api/LineLayoutSVGInlineText.h
@@ -58,6 +58,59 @@ } }; +class SVGInlineTextMetricsIterator { + DISALLOW_NEW(); +public: + SVGInlineTextMetricsIterator() { reset(nullptr); } + + void advanceToTextStart(LineLayoutSVGInlineText* textLineLayout, unsigned startCharacterOffset) + { + ASSERT(textLineLayout); + if (m_textLineLayout != textLineLayout) { + reset(textLineLayout); + ASSERT(!metricsList().isEmpty()); + } + + if (m_characterOffset == startCharacterOffset) + return; + + // TODO(fs): We could walk backwards through the metrics list in these cases. + if (m_characterOffset > startCharacterOffset) + reset(textLineLayout); + + while (m_characterOffset < startCharacterOffset) + next(); + } + + void next() + { + m_characterOffset += metrics().length(); + ++m_metricsListOffset; + } + + const SVGTextMetrics& metrics() const + { + ASSERT(m_textLineLayout && m_metricsListOffset < metricsList().size()); + return metricsList()[m_metricsListOffset]; + } + const Vector<SVGTextMetrics>& metricsList() const { return m_textLineLayout->layoutAttributes()->textMetricsValues(); } + unsigned metricsListOffset() const { return m_metricsListOffset; } + unsigned characterOffset() const { return m_characterOffset; } + bool isAtEnd() const { return m_metricsListOffset == metricsList().size(); } + +private: + void reset(LineLayoutSVGInlineText* textLineLayout) + { + m_textLineLayout = textLineLayout; + m_characterOffset = 0; + m_metricsListOffset = 0; + } + + LineLayoutSVGInlineText* m_textLineLayout; + unsigned m_metricsListOffset; + unsigned m_characterOffset; +}; + } // namespace blink #endif // LineLayoutSVGInlineText_h
diff --git a/third_party/WebKit/Source/core/layout/api/LineLayoutText.h b/third_party/WebKit/Source/core/layout/api/LineLayoutText.h index b4468698..31b63ff4 100644 --- a/third_party/WebKit/Source/core/layout/api/LineLayoutText.h +++ b/third_party/WebKit/Source/core/layout/api/LineLayoutText.h
@@ -67,6 +67,11 @@ return toText()->uncheckedCharacterAt(offset); } + UChar32 codepointAt(unsigned offset) const + { + return toText()->codepointAt(offset); + } + bool is8Bit() const { return toText()->is8Bit();
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGInlineText.h b/third_party/WebKit/Source/core/layout/svg/LayoutSVGInlineText.h index 5bdb876d..0825c8e 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGInlineText.h +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGInlineText.h
@@ -69,59 +69,6 @@ DEFINE_LAYOUT_OBJECT_TYPE_CASTS(LayoutSVGInlineText, isSVGInlineText()); -class SVGInlineTextMetricsIterator { - DISALLOW_NEW(); -public: - SVGInlineTextMetricsIterator() { reset(nullptr); } - - void advanceToTextStart(const LayoutSVGInlineText* textLayoutObject, unsigned startCharacterOffset) - { - ASSERT(textLayoutObject); - if (m_textLayoutObject != textLayoutObject) { - reset(textLayoutObject); - ASSERT(!metricsList().isEmpty()); - } - - if (m_characterOffset == startCharacterOffset) - return; - - // TODO(fs): We could walk backwards through the metrics list in these cases. - if (m_characterOffset > startCharacterOffset) - reset(textLayoutObject); - - while (m_characterOffset < startCharacterOffset) - next(); - } - - void next() - { - m_characterOffset += metrics().length(); - ++m_metricsListOffset; - } - - const SVGTextMetrics& metrics() const - { - ASSERT(m_textLayoutObject && m_metricsListOffset < metricsList().size()); - return metricsList()[m_metricsListOffset]; - } - const Vector<SVGTextMetrics>& metricsList() const { return m_textLayoutObject->layoutAttributes()->textMetricsValues(); } - unsigned metricsListOffset() const { return m_metricsListOffset; } - unsigned characterOffset() const { return m_characterOffset; } - bool isAtEnd() const { return m_metricsListOffset == metricsList().size(); } - -private: - void reset(const LayoutSVGInlineText* textLayoutObject) - { - m_textLayoutObject = textLayoutObject; - m_characterOffset = 0; - m_metricsListOffset = 0; - } - - const LayoutSVGInlineText* m_textLayoutObject; - unsigned m_metricsListOffset; - unsigned m_characterOffset; -}; - } #endif // LayoutSVGInlineText_h
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGShape.h b/third_party/WebKit/Source/core/layout/svg/LayoutSVGShape.h index 1fbb1e49..678b2a2e 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGShape.h +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGShape.h
@@ -130,6 +130,9 @@ private: OwnPtr<AffineTransform> m_localTransform; + // TODO(fmalita): the Path is now cached in SVGPath; while this additional cache is just a + // shallow copy, it certainly has a complexity/state management cost (plus allocation & storage + // overhead) - so we should look into removing it. OwnPtr<Path> m_path; mutable OwnPtr<LayoutSVGShapeRareData> m_rareData;
diff --git a/third_party/WebKit/Source/core/layout/svg/SVGTextLayoutEngine.cpp b/third_party/WebKit/Source/core/layout/svg/SVGTextLayoutEngine.cpp index 74f1ccb..5f949b8 100644 --- a/third_party/WebKit/Source/core/layout/svg/SVGTextLayoutEngine.cpp +++ b/third_party/WebKit/Source/core/layout/svg/SVGTextLayoutEngine.cpp
@@ -207,16 +207,16 @@ { ASSERT(textBox); - LayoutSVGInlineText& text = toLayoutSVGInlineText(textBox->layoutObject()); - ASSERT(text.parent()); - ASSERT(text.parent()->node()); - ASSERT(text.parent()->node()->isSVGElement()); + LineLayoutSVGInlineText textLineLayout = LineLayoutSVGInlineText(textBox->lineLayoutItem()); + ASSERT(textLineLayout.parent()); + ASSERT(textLineLayout.parent().node()); + ASSERT(textLineLayout.parent().node()->isSVGElement()); - const ComputedStyle& style = text.styleRef(); + const ComputedStyle& style = textLineLayout.styleRef(); textBox->clearTextFragments(); m_isVerticalText = !style.isHorizontalWritingMode(); - layoutTextOnLineOrPath(textBox, text, style); + layoutTextOnLineOrPath(textBox, textLineLayout, style); if (m_inPathLayout) return; @@ -329,13 +329,13 @@ m_logicalCharacterOffset += logicalMetrics.length(); } -void SVGTextLayoutEngine::layoutTextOnLineOrPath(SVGInlineTextBox* textBox, const LayoutSVGInlineText& text, const ComputedStyle& style) +void SVGTextLayoutEngine::layoutTextOnLineOrPath(SVGInlineTextBox* textBox, LineLayoutSVGInlineText textLineLayout, const ComputedStyle& style) { if (m_inPathLayout && !m_textPathCalculator) return; // Find the start of the current text box in the metrics list. - m_visualMetricsIterator.advanceToTextStart(&text, textBox->start()); + m_visualMetricsIterator.advanceToTextStart(&textLineLayout, textBox->start()); const Font& font = style.font(); @@ -347,7 +347,7 @@ float lastAngle = 0; float baselineShift = baselineLayout.calculateBaselineShift(style); - baselineShift -= baselineLayout.calculateAlignmentBaselineShift(m_isVerticalText, &text); + baselineShift -= baselineLayout.calculateAlignmentBaselineShift(m_isVerticalText, textLineLayout); // Main layout algorithm. const unsigned boxEndOffset = textBox->start() + textBox->len(); @@ -386,7 +386,7 @@ // Calculate glyph orientation angle. // Font::width() calculates the resolved FontOrientation for each character, // but is not exposed today to avoid the API complexity. - UChar32 currentCharacter = text.codepointAt(m_visualMetricsIterator.characterOffset()); + UChar32 currentCharacter = textLineLayout.codepointAt(m_visualMetricsIterator.characterOffset()); FontOrientation fontOrientation = font.fontDescription().orientation(); fontOrientation = adjustOrientationForCharacterInMixedVertical(fontOrientation, currentCharacter);
diff --git a/third_party/WebKit/Source/core/layout/svg/SVGTextLayoutEngine.h b/third_party/WebKit/Source/core/layout/svg/SVGTextLayoutEngine.h index 7a48151..bb5ab735 100644 --- a/third_party/WebKit/Source/core/layout/svg/SVGTextLayoutEngine.h +++ b/third_party/WebKit/Source/core/layout/svg/SVGTextLayoutEngine.h
@@ -20,6 +20,7 @@ #ifndef SVGTextLayoutEngine_h #define SVGTextLayoutEngine_h +#include "core/layout/api/LineLayoutSVGInlineText.h" #include "core/layout/svg/LayoutSVGInlineText.h" #include "core/layout/svg/SVGTextFragment.h" #include "core/layout/svg/SVGTextLayoutAttributes.h" @@ -66,7 +67,7 @@ void endTextPathLayout(); void layoutInlineTextBox(SVGInlineTextBox*); - void layoutTextOnLineOrPath(SVGInlineTextBox*, const LayoutSVGInlineText&, const ComputedStyle&); + void layoutTextOnLineOrPath(SVGInlineTextBox*, LineLayoutSVGInlineText, const ComputedStyle&); bool currentLogicalCharacterAttributes(SVGTextLayoutAttributes*&); bool currentLogicalCharacterMetrics(SVGTextLayoutAttributes*&, SVGTextMetrics&);
diff --git a/third_party/WebKit/Source/core/layout/svg/SVGTextLayoutEngineBaseline.cpp b/third_party/WebKit/Source/core/layout/svg/SVGTextLayoutEngineBaseline.cpp index cc298e98..150a522 100644 --- a/third_party/WebKit/Source/core/layout/svg/SVGTextLayoutEngineBaseline.cpp +++ b/third_party/WebKit/Source/core/layout/svg/SVGTextLayoutEngineBaseline.cpp
@@ -53,12 +53,12 @@ } } -EAlignmentBaseline SVGTextLayoutEngineBaseline::dominantBaselineToAlignmentBaseline(bool isVerticalText, const LayoutObject* textLayoutObject) const +EAlignmentBaseline SVGTextLayoutEngineBaseline::dominantBaselineToAlignmentBaseline(bool isVerticalText, LineLayoutItem textLineLayout) const { - ASSERT(textLayoutObject); - ASSERT(textLayoutObject->style()); + ASSERT(textLineLayout); + ASSERT(textLineLayout.style()); - const SVGComputedStyle& style = textLayoutObject->style()->svgStyle(); + const SVGComputedStyle& style = textLineLayout.style()->svgStyle(); EDominantBaseline baseline = style.dominantBaseline(); if (baseline == DB_AUTO) { @@ -75,11 +75,11 @@ // content. return AB_ALPHABETIC; case DB_NO_CHANGE: - ASSERT(textLayoutObject->parent()); - return dominantBaselineToAlignmentBaseline(isVerticalText, textLayoutObject->parent()); + ASSERT(textLineLayout.parent()); + return dominantBaselineToAlignmentBaseline(isVerticalText, textLineLayout.parent()); case DB_RESET_SIZE: - ASSERT(textLayoutObject->parent()); - return dominantBaselineToAlignmentBaseline(isVerticalText, textLayoutObject->parent()); + ASSERT(textLineLayout.parent()); + return dominantBaselineToAlignmentBaseline(isVerticalText, textLineLayout.parent()); case DB_IDEOGRAPHIC: return AB_IDEOGRAPHIC; case DB_ALPHABETIC: @@ -102,18 +102,18 @@ } } -float SVGTextLayoutEngineBaseline::calculateAlignmentBaselineShift(bool isVerticalText, const LayoutObject* textLayoutObject) const +float SVGTextLayoutEngineBaseline::calculateAlignmentBaselineShift(bool isVerticalText, LineLayoutItem textLineLayout) const { - ASSERT(textLayoutObject); - ASSERT(textLayoutObject->style()); - ASSERT(textLayoutObject->parent()); + ASSERT(textLineLayout); + ASSERT(textLineLayout.style()); + ASSERT(textLineLayout.parent()); - const LayoutObject* textLayoutObjectParent = textLayoutObject->parent(); - ASSERT(textLayoutObjectParent); + LineLayoutItem textLineLayoutParent = textLineLayout.parent(); + ASSERT(textLineLayoutParent); - EAlignmentBaseline baseline = textLayoutObject->style()->svgStyle().alignmentBaseline(); + EAlignmentBaseline baseline = textLineLayout.style()->svgStyle().alignmentBaseline(); if (baseline == AB_AUTO || baseline == AB_BASELINE) { - baseline = dominantBaselineToAlignmentBaseline(isVerticalText, textLayoutObjectParent); + baseline = dominantBaselineToAlignmentBaseline(isVerticalText, textLineLayoutParent); ASSERT(baseline != AB_AUTO && baseline != AB_BASELINE); }
diff --git a/third_party/WebKit/Source/core/layout/svg/SVGTextLayoutEngineBaseline.h b/third_party/WebKit/Source/core/layout/svg/SVGTextLayoutEngineBaseline.h index 432776d..945d6b2 100644 --- a/third_party/WebKit/Source/core/layout/svg/SVGTextLayoutEngineBaseline.h +++ b/third_party/WebKit/Source/core/layout/svg/SVGTextLayoutEngineBaseline.h
@@ -20,6 +20,7 @@ #ifndef SVGTextLayoutEngineBaseline_h #define SVGTextLayoutEngineBaseline_h +#include "core/layout/api/LineLayoutItem.h" #include "core/style/SVGComputedStyleDefs.h" #include "wtf/Allocator.h" #include "wtf/Noncopyable.h" @@ -41,10 +42,10 @@ SVGTextLayoutEngineBaseline(const Font&, float effectiveZoom); float calculateBaselineShift(const ComputedStyle&) const; - float calculateAlignmentBaselineShift(bool isVerticalText, const LayoutObject* textLayoutObject) const; + float calculateAlignmentBaselineShift(bool isVerticalText, LineLayoutItem) const; private: - EAlignmentBaseline dominantBaselineToAlignmentBaseline(bool isVerticalText, const LayoutObject* textLayoutObject) const; + EAlignmentBaseline dominantBaselineToAlignmentBaseline(bool isVerticalText, LineLayoutItem) const; const Font& m_font;
diff --git a/third_party/WebKit/Source/core/layout/svg/SVGTextQuery.cpp b/third_party/WebKit/Source/core/layout/svg/SVGTextQuery.cpp index 4abf49a..476e677 100644 --- a/third_party/WebKit/Source/core/layout/svg/SVGTextQuery.cpp +++ b/third_party/WebKit/Source/core/layout/svg/SVGTextQuery.cpp
@@ -105,9 +105,9 @@ static bool queryTextBox(QueryData* queryData, const SVGInlineTextBox* textBox, ProcessTextFragmentCallback fragmentCallback) { queryData->textBox = textBox; - queryData->textLineLayout = LineLayoutSVGInlineText(&toLayoutSVGInlineText(textBox->layoutObject())); + queryData->textLineLayout = LineLayoutSVGInlineText(textBox->lineLayoutItem()); - queryData->isVerticalText = !textBox->layoutObject().style()->isHorizontalWritingMode(); + queryData->isVerticalText = !queryData->textLineLayout.style()->isHorizontalWritingMode(); // Loop over all text fragments in this text box, firing a callback for each. for (const SVGTextFragment& fragment : textBox->textFragments()) {
diff --git a/third_party/WebKit/Source/core/loader/DocumentLoader.cpp b/third_party/WebKit/Source/core/loader/DocumentLoader.cpp index a5fbff0..cb3e39a1 100644 --- a/third_party/WebKit/Source/core/loader/DocumentLoader.cpp +++ b/third_party/WebKit/Source/core/loader/DocumentLoader.cpp
@@ -184,8 +184,9 @@ void DocumentLoader::didChangePerformanceTiming() { - if (frameLoader()) + if (frame() && frame()->isMainFrame() && m_state >= Committed) { frameLoader()->client()->didChangePerformanceTiming(); + } } void DocumentLoader::updateForSameDocumentNavigation(const KURL& newURL, SameDocumentNavigationSource sameDocumentNavigationSource)
diff --git a/third_party/WebKit/Source/core/loader/FrameLoader.cpp b/third_party/WebKit/Source/core/loader/FrameLoader.cpp index c228a93..c89cbf27 100644 --- a/third_party/WebKit/Source/core/loader/FrameLoader.cpp +++ b/third_party/WebKit/Source/core/loader/FrameLoader.cpp
@@ -85,7 +85,7 @@ #include "platform/UserGestureIndicator.h" #include "platform/network/HTTPParsers.h" #include "platform/network/ResourceRequest.h" -#include "platform/scroll/ScrollAnimator.h" +#include "platform/scroll/ScrollAnimatorBase.h" #include "platform/weborigin/SecurityOrigin.h" #include "platform/weborigin/SecurityPolicy.h" #include "public/platform/WebURLRequest.h" @@ -290,7 +290,6 @@ return; m_frame->editor().clear(); - m_frame->document()->cancelParsing(); m_frame->document()->removeFocusedElementOfSubtree(m_frame->document()); m_frame->selection().prepareForDestruction(); m_frame->eventHandler().clear(); @@ -976,17 +975,11 @@ } m_frame->document()->suppressLoadEvent(); - // FIXME: This is an odd set of steps to shut down parsing and it's unclear why it works. - // It's also unclear why other steps don't work. - if (m_frame->document()->parsing()) { - finishedParsing(); - m_frame->document()->setParsingState(Document::FinishedParsing); - } - m_frame->document()->setReadyState(Document::Complete); if (m_provisionalDocumentLoader) m_provisionalDocumentLoader->stopLoading(); if (m_documentLoader) m_documentLoader->stopLoading(); + m_frame->document()->cancelParsing(); detachDocumentLoader(m_provisionalDocumentLoader); @@ -1355,13 +1348,7 @@ if (!shouldClose(navigationType == NavigationTypeReload)) return; - // FIXME: This is an odd set of steps to shut down parsing and it's unclear why it works. - // It's also unclear why other steps don't work. - if (m_frame->document()->parsing()) { - finishedParsing(); - m_frame->document()->setParsingState(Document::FinishedParsing); - } - m_frame->document()->setReadyState(Document::Complete); + m_frame->document()->cancelParsing(); // In certain circumstances on pages with multiple frames, stopAllLoaders() or firing readystatechanged // might detach the current FrameLoader, in which case we should bail on this newly defunct load.
diff --git a/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp b/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp index 0cf28c5..151fa5c 100644 --- a/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp +++ b/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp
@@ -53,7 +53,7 @@ #if OS(MACOSX) #include "platform/mac/ScrollAnimatorMac.h" #endif -#include "platform/scroll/ScrollAnimator.h" +#include "platform/scroll/ScrollAnimatorBase.h" #include "platform/scroll/ScrollbarTheme.h" #include "public/platform/Platform.h" #include "public/platform/WebCompositorAnimationTimeline.h"
diff --git a/third_party/WebKit/Source/core/paint/LayerClipRecorderTest.cpp b/third_party/WebKit/Source/core/paint/LayerClipRecorderTest.cpp index 5f07cd0..6f8c1aa 100644 --- a/third_party/WebKit/Source/core/paint/LayerClipRecorderTest.cpp +++ b/third_party/WebKit/Source/core/paint/LayerClipRecorderTest.cpp
@@ -60,6 +60,7 @@ TEST_F(LayerClipRecorderTest, Single) { + rootPaintController().invalidateAll(); GraphicsContext context(rootPaintController()); LayoutRect bound = layoutView().viewRect(); EXPECT_EQ((size_t)0, rootPaintController().displayItemList().size()); @@ -74,6 +75,7 @@ TEST_F(LayerClipRecorderTest, Empty) { + rootPaintController().invalidateAll(); GraphicsContext context(rootPaintController()); EXPECT_EQ((size_t)0, rootPaintController().displayItemList().size());
diff --git a/third_party/WebKit/Source/core/paint/LayoutObjectDrawingRecorderTest.cpp b/third_party/WebKit/Source/core/paint/LayoutObjectDrawingRecorderTest.cpp index 9f41d0ff..1743803 100644 --- a/third_party/WebKit/Source/core/paint/LayoutObjectDrawingRecorderTest.cpp +++ b/third_party/WebKit/Source/core/paint/LayoutObjectDrawingRecorderTest.cpp
@@ -18,7 +18,6 @@ namespace blink { using LayoutObjectDrawingRecorderTest = PaintControllerPaintTest; -using LayoutObjectDrawingRecorderTestForSlimmingPaintV2 = PaintControllerPaintTestForSlimmingPaintV2; namespace { @@ -41,10 +40,9 @@ TEST_F(LayoutObjectDrawingRecorderTest, Nothing) { + rootPaintController().invalidateAll(); GraphicsContext context(rootPaintController()); LayoutRect bound = layoutView().viewRect(); - EXPECT_EQ((size_t)0, rootPaintController().displayItemList().size()); - drawNothing(context, layoutView(), PaintPhaseForeground, bound); rootPaintController().commitNewDisplayItems(); EXPECT_DISPLAY_LIST(rootPaintController().displayItemList(), 1, @@ -54,6 +52,7 @@ TEST_F(LayoutObjectDrawingRecorderTest, Rect) { + rootPaintController().invalidateAll(); GraphicsContext context(rootPaintController()); LayoutRect bound = layoutView().viewRect(); drawRect(context, layoutView(), PaintPhaseForeground, bound); @@ -64,6 +63,7 @@ TEST_F(LayoutObjectDrawingRecorderTest, Cached) { + rootPaintController().invalidateAll(); GraphicsContext context(rootPaintController()); LayoutRect bound = layoutView().viewRect(); drawNothing(context, layoutView(), PaintPhaseBlockBackground, bound);
diff --git a/third_party/WebKit/Source/core/paint/ObjectPaintProperties.h b/third_party/WebKit/Source/core/paint/ObjectPaintProperties.h index 2f04415..cf8b631 100644 --- a/third_party/WebKit/Source/core/paint/ObjectPaintProperties.h +++ b/third_party/WebKit/Source/core/paint/ObjectPaintProperties.h
@@ -24,9 +24,13 @@ WTF_MAKE_NONCOPYABLE(ObjectPaintProperties); USING_FAST_MALLOC(ObjectPaintProperties); public: - static PassOwnPtr<ObjectPaintProperties> create() + static PassOwnPtr<ObjectPaintProperties> create( + PassRefPtr<TransformPaintPropertyNode> paintOffsetTranslation, + PassRefPtr<TransformPaintPropertyNode> transform, + PassRefPtr<TransformPaintPropertyNode> perspective, + PassRefPtr<TransformPaintPropertyNode> scrollTranslation) { - return adoptPtr(new ObjectPaintProperties()); + return adoptPtr(new ObjectPaintProperties(paintOffsetTranslation, transform, perspective, scrollTranslation)); } // The hierarchy of transform subtree created by a LayoutObject. @@ -35,20 +39,21 @@ // +---[ transform ] The space created by CSS transform. // +---[ perspective ] The space created by CSS perspective. // +---[ scrollTranslation ] The space created by overflow clip. - void setPaintOffsetTranslation(PassRefPtr<TransformPaintPropertyNode> paintOffsetTranslation) { m_paintOffsetTranslation = paintOffsetTranslation; } const TransformPaintPropertyNode* paintOffsetTranslation() const { return m_paintOffsetTranslation.get(); } - - void setTransform(PassRefPtr<TransformPaintPropertyNode> transform) { m_transform = transform; } const TransformPaintPropertyNode* transform() const { return m_transform.get(); } - - void setPerspective(PassRefPtr<TransformPaintPropertyNode> perspective) { m_perspective = perspective; } const TransformPaintPropertyNode* perspective() const { return m_perspective.get(); } - - void setScrollTranslation(PassRefPtr<TransformPaintPropertyNode> scrollTranslation) { m_scrollTranslation = scrollTranslation; } const TransformPaintPropertyNode* scrollTranslation() const { return m_scrollTranslation.get(); } private: - ObjectPaintProperties() { } + ObjectPaintProperties( + PassRefPtr<TransformPaintPropertyNode> paintOffsetTranslation, + PassRefPtr<TransformPaintPropertyNode> transform, + PassRefPtr<TransformPaintPropertyNode> perspective, + PassRefPtr<TransformPaintPropertyNode> scrollTranslation) + : m_paintOffsetTranslation(paintOffsetTranslation) + , m_transform(transform) + , m_perspective(perspective) + , m_scrollTranslation(scrollTranslation) { } RefPtr<TransformPaintPropertyNode> m_paintOffsetTranslation; RefPtr<TransformPaintPropertyNode> m_transform;
diff --git a/third_party/WebKit/Source/core/paint/PaintControllerPaintTest.cpp b/third_party/WebKit/Source/core/paint/PaintControllerPaintTest.cpp index 48187b1..143a3c7 100644 --- a/third_party/WebKit/Source/core/paint/PaintControllerPaintTest.cpp +++ b/third_party/WebKit/Source/core/paint/PaintControllerPaintTest.cpp
@@ -15,7 +15,9 @@ namespace blink { -TEST_F(PaintControllerPaintTest, FullDocumentPaintingWithCaret) +INSTANTIATE_TEST_CASE_P(All, PaintControllerPaintTestForSlimmingPaintV1AndV2, ::testing::Bool()); + +TEST_P(PaintControllerPaintTestForSlimmingPaintV1AndV2, FullDocumentPaintingWithCaret) { setBodyInnerHTML("<div id='div' contentEditable='true' style='outline:none'>XYZ</div>"); document().page()->focusController().setActive(true); @@ -25,96 +27,47 @@ LayoutObject& divLayoutObject = *document().body()->firstChild()->layoutObject(); InlineTextBox& textInlineBox = *toLayoutText(div.firstChild()->layoutObject())->firstTextBox(); - GraphicsContext context(rootPaintController()); - PaintLayerPaintingInfo paintingInfo(&rootLayer, LayoutRect(0, 0, 800, 600), GlobalPaintNormalPhase, LayoutSize()); - PaintLayerPainter(rootLayer).paintLayerContents(&context, paintingInfo, PaintLayerPaintingCompositingAllPhases); - rootPaintController().commitNewDisplayItems(); + if (RuntimeEnabledFeatures::slimmingPaintSynchronizedPaintingEnabled()) { + EXPECT_DISPLAY_LIST(rootPaintController().displayItemList(), 4, + TestDisplayItem(layoutView(), backgroundType), + TestDisplayItem(rootLayer, subsequenceType), + TestDisplayItem(textInlineBox, foregroundType), + TestDisplayItem(rootLayer, endSubsequenceType)); + } else { + GraphicsContext context(rootPaintController()); + PaintLayerPaintingInfo paintingInfo(&rootLayer, LayoutRect(0, 0, 800, 600), GlobalPaintNormalPhase, LayoutSize()); + PaintLayerPainter(rootLayer).paintLayerContents(&context, paintingInfo, PaintLayerPaintingCompositingAllPhases); + rootPaintController().commitNewDisplayItems(); - EXPECT_DISPLAY_LIST(rootPaintController().displayItemList(), 2, - TestDisplayItem(layoutView(), backgroundType), - TestDisplayItem(textInlineBox, foregroundType)); - - div.focus(); - document().view()->updateAllLifecyclePhases(); - EXPECT_TRUE(rootPaintController().clientCacheIsValid(layoutView().displayItemClient())); - EXPECT_FALSE(rootPaintController().clientCacheIsValid(divLayoutObject.displayItemClient())); - EXPECT_TRUE(rootPaintController().clientCacheIsValid(textInlineBox.displayItemClient())); - PaintLayerPainter(rootLayer).paintLayerContents(&context, paintingInfo, PaintLayerPaintingCompositingAllPhases); - rootPaintController().commitNewDisplayItems(); - - EXPECT_DISPLAY_LIST(rootPaintController().displayItemList(), 3, - TestDisplayItem(layoutView(), backgroundType), - TestDisplayItem(textInlineBox, foregroundType), - TestDisplayItem(divLayoutObject, DisplayItem::Caret)); // New! -} - -TEST_F(PaintControllerPaintTest, InlineRelayout) -{ - setBodyInnerHTML("<div id='div' style='width:100px; height: 200px'>AAAAAAAAAA BBBBBBBBBB</div>"); - PaintLayer& rootLayer = *layoutView().layer(); - Element& div = *toElement(document().body()->firstChild()); - LayoutBlock& divBlock = *toLayoutBlock(document().body()->firstChild()->layoutObject()); - LayoutText& text = *toLayoutText(divBlock.firstChild()); - InlineTextBox& firstTextBox = *text.firstTextBox(); - DisplayItemClient firstTextBoxDisplayItemClient = firstTextBox.displayItemClient(); - - GraphicsContext context(rootPaintController()); - PaintLayerPaintingInfo paintingInfo(&rootLayer, LayoutRect(0, 0, 800, 600), GlobalPaintNormalPhase, LayoutSize()); - PaintLayerPainter(rootLayer).paintLayerContents(&context, paintingInfo, PaintLayerPaintingCompositingAllPhases); - rootPaintController().commitNewDisplayItems(); - - EXPECT_DISPLAY_LIST(rootPaintController().displayItemList(), 2, - TestDisplayItem(layoutView(), backgroundType), - TestDisplayItem(firstTextBox, foregroundType)); - - div.setAttribute(HTMLNames::styleAttr, "width: 10px; height: 200px"); - document().view()->updateAllLifecyclePhases(); - EXPECT_TRUE(rootPaintController().clientCacheIsValid(layoutView().displayItemClient())); - EXPECT_FALSE(rootPaintController().clientCacheIsValid(divBlock.displayItemClient())); - EXPECT_FALSE(rootPaintController().clientCacheIsValid(firstTextBoxDisplayItemClient)); - PaintLayerPainter(rootLayer).paintLayerContents(&context, paintingInfo, PaintLayerPaintingCompositingAllPhases); - rootPaintController().commitNewDisplayItems(); - - LayoutText& newText = *toLayoutText(divBlock.firstChild()); - InlineTextBox& newFirstTextBox = *newText.firstTextBox(); - InlineTextBox& secondTextBox = *newText.firstTextBox()->nextTextBox(); - - EXPECT_DISPLAY_LIST(rootPaintController().displayItemList(), 3, - TestDisplayItem(layoutView(), backgroundType), - TestDisplayItem(newFirstTextBox, foregroundType), - TestDisplayItem(secondTextBox, foregroundType)); -} - -TEST_F(PaintControllerPaintTestForSlimmingPaintV2, FullDocumentPaintingWithCaret) -{ - setBodyInnerHTML("<div id='div' contentEditable='true' style='outline:none'>XYZ</div>"); - document().page()->focusController().setActive(true); - document().page()->focusController().setFocused(true); - PaintLayer& rootLayer = *layoutView().layer(); - Element& div = *toElement(document().body()->firstChild()); - LayoutObject& divLayoutObject = *document().body()->firstChild()->layoutObject(); - InlineTextBox& textInlineBox = *toLayoutText(div.firstChild()->layoutObject())->firstTextBox(); - - document().view()->updateAllLifecyclePhases(); - - EXPECT_DISPLAY_LIST(rootPaintController().displayItemList(), 4, - TestDisplayItem(layoutView(), backgroundType), - TestDisplayItem(rootLayer, subsequenceType), - TestDisplayItem(textInlineBox, foregroundType), - TestDisplayItem(rootLayer, endSubsequenceType)); + EXPECT_DISPLAY_LIST(rootPaintController().displayItemList(), 2, + TestDisplayItem(layoutView(), backgroundType), + TestDisplayItem(textInlineBox, foregroundType)); + } div.focus(); document().view()->updateAllLifecyclePhases(); - EXPECT_DISPLAY_LIST(rootPaintController().displayItemList(), 5, - TestDisplayItem(layoutView(), backgroundType), - TestDisplayItem(rootLayer, subsequenceType), - TestDisplayItem(textInlineBox, foregroundType), - TestDisplayItem(divLayoutObject, DisplayItem::Caret), // New! - TestDisplayItem(rootLayer, endSubsequenceType)); + if (RuntimeEnabledFeatures::slimmingPaintSynchronizedPaintingEnabled()) { + EXPECT_DISPLAY_LIST(rootPaintController().displayItemList(), 5, + TestDisplayItem(layoutView(), backgroundType), + TestDisplayItem(rootLayer, subsequenceType), + TestDisplayItem(textInlineBox, foregroundType), + TestDisplayItem(divLayoutObject, DisplayItem::Caret), // New! + TestDisplayItem(rootLayer, endSubsequenceType)); + } else { + GraphicsContext context(rootPaintController()); + PaintLayerPaintingInfo paintingInfo(&rootLayer, LayoutRect(0, 0, 800, 600), GlobalPaintNormalPhase, LayoutSize()); + PaintLayerPainter(rootLayer).paintLayerContents(&context, paintingInfo, PaintLayerPaintingCompositingAllPhases); + rootPaintController().commitNewDisplayItems(); + + EXPECT_DISPLAY_LIST(rootPaintController().displayItemList(), 3, + TestDisplayItem(layoutView(), backgroundType), + TestDisplayItem(textInlineBox, foregroundType), + TestDisplayItem(divLayoutObject, DisplayItem::Caret)); // New! + } } -TEST_F(PaintControllerPaintTestForSlimmingPaintV2, InlineRelayout) +TEST_P(PaintControllerPaintTestForSlimmingPaintV1AndV2, InlineRelayout) { setBodyInnerHTML("<div id='div' style='width:100px; height: 200px'>AAAAAAAAAA BBBBBBBBBB</div>"); PaintLayer& rootLayer = *layoutView().layer(); @@ -123,13 +76,22 @@ LayoutText& text = *toLayoutText(divBlock.firstChild()); InlineTextBox& firstTextBox = *text.firstTextBox(); - document().view()->updateAllLifecyclePhases(); + if (RuntimeEnabledFeatures::slimmingPaintSynchronizedPaintingEnabled()) { + EXPECT_DISPLAY_LIST(rootPaintController().displayItemList(), 4, + TestDisplayItem(layoutView(), backgroundType), + TestDisplayItem(rootLayer, subsequenceType), + TestDisplayItem(firstTextBox, foregroundType), + TestDisplayItem(rootLayer, endSubsequenceType)); + } else { + GraphicsContext context(rootPaintController()); + PaintLayerPaintingInfo paintingInfo(&rootLayer, LayoutRect(0, 0, 800, 600), GlobalPaintNormalPhase, LayoutSize()); + PaintLayerPainter(rootLayer).paintLayerContents(&context, paintingInfo, PaintLayerPaintingCompositingAllPhases); + rootPaintController().commitNewDisplayItems(); - EXPECT_DISPLAY_LIST(rootPaintController().displayItemList(), 4, - TestDisplayItem(layoutView(), backgroundType), - TestDisplayItem(rootLayer, subsequenceType), - TestDisplayItem(firstTextBox, foregroundType), - TestDisplayItem(rootLayer, endSubsequenceType)); + EXPECT_DISPLAY_LIST(rootPaintController().displayItemList(), 2, + TestDisplayItem(layoutView(), backgroundType), + TestDisplayItem(firstTextBox, foregroundType)); + } div.setAttribute(HTMLNames::styleAttr, "width: 10px; height: 200px"); document().view()->updateAllLifecyclePhases(); @@ -138,12 +100,24 @@ InlineTextBox& newFirstTextBox = *newText.firstTextBox(); InlineTextBox& secondTextBox = *newText.firstTextBox()->nextTextBox(); - EXPECT_DISPLAY_LIST(rootPaintController().displayItemList(), 5, - TestDisplayItem(layoutView(), backgroundType), - TestDisplayItem(rootLayer, subsequenceType), - TestDisplayItem(newFirstTextBox, foregroundType), - TestDisplayItem(secondTextBox, foregroundType), - TestDisplayItem(rootLayer, endSubsequenceType)); + if (RuntimeEnabledFeatures::slimmingPaintSynchronizedPaintingEnabled()) { + EXPECT_DISPLAY_LIST(rootPaintController().displayItemList(), 5, + TestDisplayItem(layoutView(), backgroundType), + TestDisplayItem(rootLayer, subsequenceType), + TestDisplayItem(newFirstTextBox, foregroundType), + TestDisplayItem(secondTextBox, foregroundType), + TestDisplayItem(rootLayer, endSubsequenceType)); + } else { + GraphicsContext context(rootPaintController()); + PaintLayerPaintingInfo paintingInfo(&rootLayer, LayoutRect(0, 0, 800, 600), GlobalPaintNormalPhase, LayoutSize()); + PaintLayerPainter(rootLayer).paintLayerContents(&context, paintingInfo, PaintLayerPaintingCompositingAllPhases); + rootPaintController().commitNewDisplayItems(); + + EXPECT_DISPLAY_LIST(rootPaintController().displayItemList(), 3, + TestDisplayItem(layoutView(), backgroundType), + TestDisplayItem(newFirstTextBox, foregroundType), + TestDisplayItem(secondTextBox, foregroundType)); + } } } // namespace blink
diff --git a/third_party/WebKit/Source/core/paint/PaintLayer.cpp b/third_party/WebKit/Source/core/paint/PaintLayer.cpp index 15b0c80..ac1ff2d 100644 --- a/third_party/WebKit/Source/core/paint/PaintLayer.cpp +++ b/third_party/WebKit/Source/core/paint/PaintLayer.cpp
@@ -269,7 +269,7 @@ // FIXME(400589): We would like to do this in PaintLayerScrollableArea::updateAfterLayout, // but it depends on the size computed by updateLayerPosition. if (m_scrollableArea) { - if (ScrollAnimator* scrollAnimator = m_scrollableArea->existingScrollAnimator()) + if (ScrollAnimatorBase* scrollAnimator = m_scrollableArea->existingScrollAnimator()) scrollAnimator->updateAfterLayout(); }
diff --git a/third_party/WebKit/Source/core/paint/PaintLayerClipper.h b/third_party/WebKit/Source/core/paint/PaintLayerClipper.h index e7ef075..e8339b2 100644 --- a/third_party/WebKit/Source/core/paint/PaintLayerClipper.h +++ b/third_party/WebKit/Source/core/paint/PaintLayerClipper.h
@@ -90,11 +90,6 @@ return m_cacheSlot; } - bool isComputingPaintingRect() const - { - return m_cacheSlot == PaintingClipRectsIgnoringOverflowClip || m_cacheSlot == PaintingClipRects; - } - const PaintLayer* rootLayer; const OverlayScrollbarSizeRelevancy scrollbarRelevancy; @@ -164,8 +159,6 @@ LayoutRect childrenClipRect() const; // Returns the foreground clip rect of the layer in the document's coordinate space. LayoutRect localClipRect() const; // Returns the background clip rect of the layer in the local coordinate space. - ClipRects* getClipRects(const ClipRectsContext&) const; - ClipRect backgroundClipRect(const ClipRectsContext&) const; // This method figures out our layerBounds in coordinates relative to @@ -175,6 +168,8 @@ void calculateRects(const ClipRectsContext&, const LayoutRect& paintDirtyRect, LayoutRect& layerBounds, ClipRect& backgroundRect, ClipRect& foregroundRect, const LayoutPoint* offsetFromRoot = 0) const; private: + ClipRects* getClipRects(const ClipRectsContext&) const; + void calculateClipRects(const ClipRectsContext&, ClipRects&) const; ClipRects* clipRectsIfCached(const ClipRectsContext&) const; ClipRects* storeClipRectsInCache(const ClipRectsContext&, ClipRects* parentClipRects, const ClipRects&) const;
diff --git a/third_party/WebKit/Source/core/paint/PaintLayerPainterTest.cpp b/third_party/WebKit/Source/core/paint/PaintLayerPainterTest.cpp index 88cf58d..65b2c8d8 100644 --- a/third_party/WebKit/Source/core/paint/PaintLayerPainterTest.cpp +++ b/third_party/WebKit/Source/core/paint/PaintLayerPainterTest.cpp
@@ -18,8 +18,6 @@ FrameSettingOverrideFunction settingOverrider() const override { return GetParam(); } }; -using PaintLayerPainterTestForSlimmingPaintV2 = PaintControllerPaintTestForSlimmingPaintV2; - INSTANTIATE_TEST_CASE_P(All, PaintLayerPainterTest, ::testing::Values( nullptr, RootLayerScrollsFrameSettingOverride));
diff --git a/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.cpp b/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.cpp index c49a397..b7ea489 100644 --- a/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.cpp +++ b/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.cpp
@@ -72,7 +72,7 @@ #include "platform/PlatformMouseEvent.h" #include "platform/graphics/GraphicsLayer.h" #include "platform/graphics/paint/DrawingRecorder.h" -#include "platform/scroll/ScrollAnimator.h" +#include "platform/scroll/ScrollAnimatorBase.h" #include "platform/scroll/ScrollbarTheme.h" #include "public/platform/Platform.h"
diff --git a/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilder.cpp b/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilder.cpp index 35e4e56..4898686 100644 --- a/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilder.cpp +++ b/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilder.cpp
@@ -214,11 +214,12 @@ updateOutOfFlowContext(object, localContext); if (newTransformNodeForPaintOffsetTranslation || newTransformNodeForTransform || newTransformNodeForPerspective || newTransformNodeForScrollTranslation) { - ObjectPaintProperties& properties = object.ensureObjectPaintProperties(); - properties.setPaintOffsetTranslation(newTransformNodeForPaintOffsetTranslation.release()); - properties.setTransform(newTransformNodeForTransform.release()); - properties.setPerspective(newTransformNodeForPerspective.release()); - properties.setScrollTranslation(newTransformNodeForScrollTranslation.release()); + OwnPtr<ObjectPaintProperties> updatedPaintProperties = ObjectPaintProperties::create( + newTransformNodeForPaintOffsetTranslation.release(), + newTransformNodeForTransform.release(), + newTransformNodeForPerspective.release(), + newTransformNodeForScrollTranslation.release()); + object.setObjectPaintProperties(updatedPaintProperties.release()); } else { object.clearObjectPaintProperties(); }
diff --git a/third_party/WebKit/Source/core/paint/TableCellPainterTest.cpp b/third_party/WebKit/Source/core/paint/TableCellPainterTest.cpp index dca1f90..724cbf1 100644 --- a/third_party/WebKit/Source/core/paint/TableCellPainterTest.cpp +++ b/third_party/WebKit/Source/core/paint/TableCellPainterTest.cpp
@@ -11,7 +11,6 @@ using TableCellPainterTest = PaintControllerPaintTest; -// TODO(wangxianzhu): Create a version for slimming paint v2 when it supports interest rect TEST_F(TableCellPainterTest, TableCellBackgroundInterestRect) { RuntimeEnabledFeatures::setSlimmingPaintSynchronizedPaintingEnabled(true);
diff --git a/third_party/WebKit/Source/core/svg/SVGElement.cpp b/third_party/WebKit/Source/core/svg/SVGElement.cpp index 42d8e37..5024d32 100644 --- a/third_party/WebKit/Source/core/svg/SVGElement.cpp +++ b/third_party/WebKit/Source/core/svg/SVGElement.cpp
@@ -542,7 +542,7 @@ } #endif -SVGElement* SVGElement::correspondingElement() +SVGElement* SVGElement::correspondingElement() const { ASSERT(!hasSVGRareData() || !svgRareData()->correspondingElement() || containingShadowRoot()); return hasSVGRareData() ? svgRareData()->correspondingElement() : 0;
diff --git a/third_party/WebKit/Source/core/svg/SVGElement.h b/third_party/WebKit/Source/core/svg/SVGElement.h index 04ce2a3..3a9f8f9 100644 --- a/third_party/WebKit/Source/core/svg/SVGElement.h +++ b/third_party/WebKit/Source/core/svg/SVGElement.h
@@ -124,7 +124,7 @@ void cursorImageValueRemoved(); #endif - SVGElement* correspondingElement(); + SVGElement* correspondingElement() const; void setCorrespondingElement(SVGElement*); SVGUseElement* correspondingUseElement() const;
diff --git a/third_party/WebKit/Source/core/svg/SVGElementRareData.h b/third_party/WebKit/Source/core/svg/SVGElementRareData.h index a1db7db..8c3a1ac 100644 --- a/third_party/WebKit/Source/core/svg/SVGElementRareData.h +++ b/third_party/WebKit/Source/core/svg/SVGElementRareData.h
@@ -63,7 +63,7 @@ SVGCursorElement* cursorElement() const { return m_cursorElement; } void setCursorElement(SVGCursorElement* cursorElement) { m_cursorElement = cursorElement; } - SVGElement* correspondingElement() { return m_correspondingElement.get(); } + SVGElement* correspondingElement() const { return m_correspondingElement.get(); } void setCorrespondingElement(SVGElement* correspondingElement) { m_correspondingElement = correspondingElement; } CSSCursorImageValue* cursorImageValue() const { return m_cursorImageValue; }
diff --git a/third_party/WebKit/Source/core/svg/SVGGraphicsElement.cpp b/third_party/WebKit/Source/core/svg/SVGGraphicsElement.cpp index e403da2d..79da429 100644 --- a/third_party/WebKit/Source/core/svg/SVGGraphicsElement.cpp +++ b/third_party/WebKit/Source/core/svg/SVGGraphicsElement.cpp
@@ -50,22 +50,6 @@ SVGTests::trace(visitor); } -PassRefPtrWillBeRawPtr<SVGMatrixTearOff> SVGGraphicsElement::getTransformToElement(SVGElement* target, ExceptionState& exceptionState) -{ - AffineTransform ctm = getCTM(AllowStyleUpdate); - - if (target && target->isSVGGraphicsElement()) { - AffineTransform targetCTM = toSVGGraphicsElement(target)->getCTM(AllowStyleUpdate); - if (!targetCTM.isInvertible()) { - exceptionState.throwDOMException(InvalidStateError, "The target transformation is not invertable."); - return nullptr; - } - ctm = targetCTM.inverse() * ctm; - } - - return SVGMatrixTearOff::create(ctm); -} - static bool isViewportElement(const Element& element) { return (isSVGSVGElement(element)
diff --git a/third_party/WebKit/Source/core/svg/SVGGraphicsElement.h b/third_party/WebKit/Source/core/svg/SVGGraphicsElement.h index 88b763d2..a107e9a1 100644 --- a/third_party/WebKit/Source/core/svg/SVGGraphicsElement.h +++ b/third_party/WebKit/Source/core/svg/SVGGraphicsElement.h
@@ -48,8 +48,6 @@ PassRefPtrWillBeRawPtr<SVGMatrixTearOff> getCTMFromJavascript(); PassRefPtrWillBeRawPtr<SVGMatrixTearOff> getScreenCTMFromJavascript(); - PassRefPtrWillBeRawPtr<SVGMatrixTearOff> getTransformToElement(SVGElement*, ExceptionState&); - SVGElement* nearestViewportElement() const; SVGElement* farthestViewportElement() const;
diff --git a/third_party/WebKit/Source/core/svg/SVGGraphicsElement.idl b/third_party/WebKit/Source/core/svg/SVGGraphicsElement.idl index 7af9e22..3c34964 100644 --- a/third_party/WebKit/Source/core/svg/SVGGraphicsElement.idl +++ b/third_party/WebKit/Source/core/svg/SVGGraphicsElement.idl
@@ -41,7 +41,6 @@ [ImplementedAs=getBBoxFromJavascript] SVGRect getBBox(); [ImplementedAs=getCTMFromJavascript] SVGMatrix getCTM(); [ImplementedAs=getScreenCTMFromJavascript] SVGMatrix getScreenCTM(); - [RaisesException, MeasureAs=SVGGraphicsElementGetTransformToElement] SVGMatrix getTransformToElement(SVGElement element); }; SVGGraphicsElement implements SVGTests;
diff --git a/third_party/WebKit/Source/core/svg/SVGPath.cpp b/third_party/WebKit/Source/core/svg/SVGPath.cpp index eb28e52..bbc275c 100644 --- a/third_party/WebKit/Source/core/svg/SVGPath.cpp +++ b/third_party/WebKit/Source/core/svg/SVGPath.cpp
@@ -32,6 +32,7 @@ #include "core/svg/SVGPathByteStreamSource.h" #include "core/svg/SVGPathParser.h" #include "core/svg/SVGPathUtilities.h" +#include "platform/graphics/Path.h" namespace blink { @@ -50,6 +51,16 @@ { } +const Path& SVGPath::path() const +{ + if (!m_cachedPath) { + m_cachedPath = adoptPtr(new Path); + buildPathFromByteStream(byteStream(), *m_cachedPath); + } + + return *m_cachedPath; +} + PassRefPtrWillBeRawPtr<SVGPath> SVGPath::clone() const { return adoptRefWillBeNoop(new SVGPath(byteStream().copy())); @@ -62,16 +73,28 @@ return svgPath; } +SVGPathByteStream& SVGPath::ensureByteStream() +{ + if (!m_byteStream) + m_byteStream = SVGPathByteStream::create(); + + return *m_byteStream.get(); +} + +void SVGPath::byteStreamWillChange() +{ + m_cachedPath.clear(); +} + const SVGPathByteStream& SVGPath::byteStream() const { - return const_cast<SVGPath*>(this)->mutableByteStream(); + return const_cast<SVGPath*>(this)->ensureByteStream(); } SVGPathByteStream& SVGPath::mutableByteStream() { - if (!m_byteStream) - m_byteStream = SVGPathByteStream::create(); - return *m_byteStream.get(); + byteStreamWillChange(); + return ensureByteStream(); } String SVGPath::valueAsString() const @@ -118,6 +141,8 @@ fromStream = copy.get(); } + byteStreamWillChange(); + // If the 'from' value is given and it's length doesn't match the 'to' value list length, fallback to a discrete animation. if (fromStream->size() != toStream.size() && fromStream->size()) { if (percentage < 0.5) {
diff --git a/third_party/WebKit/Source/core/svg/SVGPath.h b/third_party/WebKit/Source/core/svg/SVGPath.h index 5ca84a9..0f9ac5b 100644 --- a/third_party/WebKit/Source/core/svg/SVGPath.h +++ b/third_party/WebKit/Source/core/svg/SVGPath.h
@@ -36,6 +36,7 @@ namespace blink { class ExceptionState; +class Path; class SVGPathByteStream; class SVGPath : public SVGPropertyBase { @@ -49,6 +50,8 @@ ~SVGPath() override; + const Path& path() const; + const SVGPathByteStream& byteStream() const; SVGPathByteStream& mutableByteStream(); @@ -68,7 +71,11 @@ SVGPath(); explicit SVGPath(PassOwnPtr<SVGPathByteStream>); + SVGPathByteStream& ensureByteStream(); + void byteStreamWillChange(); + OwnPtr<SVGPathByteStream> m_byteStream; + mutable OwnPtr<Path> m_cachedPath; }; inline PassRefPtrWillBeRawPtr<SVGPath> toSVGPath(PassRefPtrWillBeRawPtr<SVGPropertyBase> passBase)
diff --git a/third_party/WebKit/Source/core/svg/SVGPathElement.cpp b/third_party/WebKit/Source/core/svg/SVGPathElement.cpp index 8a26824..94b22165 100644 --- a/third_party/WebKit/Source/core/svg/SVGPathElement.cpp +++ b/third_party/WebKit/Source/core/svg/SVGPathElement.cpp
@@ -72,9 +72,11 @@ Path SVGPathElement::asPath() const { - Path path; - buildPathFromByteStream(pathByteStream(), path); - return path; + // If this is a <use> instance, return the referenced path to maximize geometry sharing. + if (const SVGElement* element = correspondingElement()) + return toSVGPathElement(element)->asPath(); + + return m_path->currentValue()->path(); } float SVGPathElement::getTotalLength()
diff --git a/third_party/WebKit/Source/core/testing/Internals.cpp b/third_party/WebKit/Source/core/testing/Internals.cpp index d124861..3677823 100644 --- a/third_party/WebKit/Source/core/testing/Internals.cpp +++ b/third_party/WebKit/Source/core/testing/Internals.cpp
@@ -2538,7 +2538,7 @@ ScrollableArea* scrollableArea = layer->scrollableArea(); if (!scrollableArea) return false; - ScrollAnimator* animator = layer->scrollableArea()->scrollAnimator(); + ScrollAnimatorBase* animator = layer->scrollableArea()->scrollAnimator(); if (!animator) return false; @@ -2561,4 +2561,12 @@ return document->loader()->timing().monotonicTimeToZeroBasedDocumentTime(platformTime); } +void Internals::setMediaElementNetworkState(HTMLMediaElement* mediaElement, int32_t state) +{ + ASSERT(mediaElement); + ASSERT(state >= HTMLMediaElement::NetworkState::NETWORK_EMPTY); + ASSERT(state <= HTMLMediaElement::NetworkState::NETWORK_NO_SOURCE); + mediaElement->setNetworkState(static_cast<WebMediaPlayer::NetworkState>(state)); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/core/testing/Internals.h b/third_party/WebKit/Source/core/testing/Internals.h index 7133f56..f65d7dab 100644 --- a/third_party/WebKit/Source/core/testing/Internals.h +++ b/third_party/WebKit/Source/core/testing/Internals.h
@@ -395,6 +395,9 @@ // Translate given platform monotonic time in seconds to high resolution // document time in seconds double monotonicTimeToZeroBasedDocumentTime(double, ExceptionState&); + + void setMediaElementNetworkState(HTMLMediaElement*, int32_t state); + private: explicit Internals(ScriptState*); Document* contextDocument() const;
diff --git a/third_party/WebKit/Source/core/testing/Internals.idl b/third_party/WebKit/Source/core/testing/Internals.idl index dd44d9b..cf78ae8d 100644 --- a/third_party/WebKit/Source/core/testing/Internals.idl +++ b/third_party/WebKit/Source/core/testing/Internals.idl
@@ -357,4 +357,6 @@ void forceRestrictIFramePermissions(); [RaisesException] double monotonicTimeToZeroBasedDocumentTime(double platformTime); + + [TypeChecking=Interface] void setMediaElementNetworkState(HTMLMediaElement element, long state); };
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 44dae03..30aef63 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
@@ -30,14 +30,14 @@ /** * @constructor - * @extends {WebInspector.VBox} + * @extends {WebInspector.DataGridContainerWidget} * @param {boolean} expandable * @param {function()=} refreshCallback * @param {function()=} selectedCallback */ WebInspector.CookiesTable = function(expandable, refreshCallback, selectedCallback) { - WebInspector.VBox.call(this); + WebInspector.DataGridContainerWidget.call(this); var readOnly = expandable; this._refreshCallback = refreshCallback; @@ -67,7 +67,7 @@ this._nextSelectedCookie = /** @type {?WebInspector.Cookie} */ (null); - this._dataGrid.show(this.element); + this.appendDataGrid(this._dataGrid); this._data = []; } @@ -285,5 +285,5 @@ this._refreshCallback(); }, - __proto__: WebInspector.VBox.prototype + __proto__: WebInspector.DataGridContainerWidget.prototype }
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 d8962c0..8d710bf6 100644 --- a/third_party/WebKit/Source/devtools/front_end/console/ConsoleViewMessage.js +++ b/third_party/WebKit/Source/devtools/front_end/console/ConsoleViewMessage.js
@@ -91,7 +91,7 @@ for (var i = 0; this._dataGrids && i < this._dataGrids.length; ++i) { var dataGrid = this._dataGrids[i]; var parentElement = this._dataGridParents.get(dataGrid) || null; - dataGrid.show(parentElement); + parentElement.appendChild(dataGrid.element); dataGrid.updateWidths(); } }, @@ -112,7 +112,7 @@ for (var i = 0; this._dataGrids && i < this._dataGrids.length; ++i) { var dataGrid = this._dataGrids[i]; this._dataGridParents.set(dataGrid, dataGrid.element.parentElement); - dataGrid.detach(); + dataGrid.element.remove(); } },
diff --git a/third_party/WebKit/Source/devtools/front_end/devtools.js b/third_party/WebKit/Source/devtools/front_end/devtools.js index bf9234aa..671aac0f 100644 --- a/third_party/WebKit/Source/devtools/front_end/devtools.js +++ b/third_party/WebKit/Source/devtools/front_end/devtools.js
@@ -507,7 +507,7 @@ */ sendMessageToBackend: function(message) { - DevToolsHost.sendMessageToBackend(message); + DevToolsAPI.sendMessageToEmbedder("dispatchProtocolMessage", [message], null); }, /**
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 17b703fd..942e9ba 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/ComputedStyleWidget.js +++ b/third_party/WebKit/Source/devtools/front_end/elements/ComputedStyleWidget.js
@@ -138,14 +138,15 @@ uniqueProperties.sort(propertySorter); var propertyTraces = this._computePropertyTraces(cascades.matched); + var inhertiedProperties = this._computeInheritedProperties(cascades.matched); var showInherited = this._showInheritedComputedStylePropertiesSetting.get(); for (var i = 0; i < uniqueProperties.length; ++i) { var propertyName = uniqueProperties[i]; var propertyValue = nodeStyle.computedStyle.get(propertyName); - var inherited = this._isPropertyInherited(cascades.matched, propertyName); + var canonicalName = WebInspector.CSSMetadata.canonicalPropertyName(propertyName); + var inherited = !inhertiedProperties.has(canonicalName); if (!showInherited && inherited && !(propertyName in this._alwaysShowComputedProperties)) continue; - var canonicalName = WebInspector.CSSMetadata.canonicalPropertyName(propertyName); if (propertyName !== canonicalName && propertyValue === nodeStyle.computedStyle.get(canonicalName)) continue; @@ -174,7 +175,7 @@ var trace = propertyTraces.get(propertyName); if (trace) { - this._renderPropertyTrace(cssModel, nodeStyle.node, treeElement, trace); + this._renderPropertyTrace(cssModel, cascades.matched, nodeStyle.node, treeElement, trace); treeElement.listItemElement.addEventListener("mousedown", consumeEvent, false); treeElement.listItemElement.addEventListener("dblclick", consumeEvent, false); treeElement.listItemElement.addEventListener("click", handleClick.bind(null, treeElement), false); @@ -212,25 +213,26 @@ /** * @param {!WebInspector.CSSStyleModel} cssModel + * @param {!WebInspector.SectionCascade} matchedCascade * @param {!WebInspector.DOMNode} node * @param {!TreeElement} rootTreeElement - * @param {!Array.<!{property: !WebInspector.CSSProperty, overloaded: boolean}>} tracedProperties + * @param {!Array<!WebInspector.CSSProperty>} tracedProperties */ - _renderPropertyTrace: function(cssModel, node, rootTreeElement, tracedProperties) + _renderPropertyTrace: function(cssModel, matchedCascade, node, rootTreeElement, tracedProperties) { - for (var propertyInfo of tracedProperties) { + for (var property of tracedProperties) { var trace = createElement("div"); trace.classList.add("property-trace"); - if (propertyInfo.overloaded) + if (matchedCascade.propertyState(property) === WebInspector.SectionCascade.PropertyState.Overloaded) trace.classList.add("property-trace-inactive"); - var renderer = new WebInspector.StylesSidebarPropertyRenderer(null, node, propertyInfo.property.name, /** @type {string} */(propertyInfo.property.value)); + var renderer = new WebInspector.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"); trace.appendChild(valueElement); - var rule = propertyInfo.property.ownerStyle.parentRule; + var rule = property.ownerStyle.parentRule; if (rule) { var linkSpan = trace.createChild("span", "trace-link"); linkSpan.appendChild(WebInspector.StylePropertiesSection.createRuleOriginNode(cssModel, this._linkifier, rule)); @@ -249,7 +251,7 @@ /** * @param {!WebInspector.SectionCascade} matchedCascade - * @return {!Map.<string, !Array.<!{property: !WebInspector.CSSProperty, overloaded: boolean}>>} + * @return {!Map<string, !Array<!WebInspector.CSSProperty>>} */ _computePropertyTraces: function(matchedCascade) { @@ -258,14 +260,11 @@ for (var model of models) { var allProperties = model.style().allProperties; for (var property of allProperties) { - if (!property.activeInStyle() || !model.isPropertyInCascade(property.name)) + if (!property.activeInStyle() || !matchedCascade.propertyState(property)) continue; if (!result.has(property.name)) result.set(property.name, []); - result.get(property.name).push({ - property: property, - overloaded: model.isPropertyOverloaded(property.name) - }); + result.get(property.name).push(property); } } return result; @@ -273,12 +272,19 @@ /** * @param {!WebInspector.SectionCascade} matchedCascade - * @param {string} propertyName + * @return {!Set<string>} */ - _isPropertyInherited: function(matchedCascade, propertyName) + _computeInheritedProperties: function(matchedCascade) { - var canonicalName = WebInspector.CSSMetadata.canonicalPropertyName(propertyName); - return !matchedCascade.allUsedProperties().has(canonicalName); + var result = new Set(); + for (var model of matchedCascade.sectionModels()) { + for (var property of model.style().allProperties) { + if (!matchedCascade.propertyState(property)) + continue; + result.add(WebInspector.CSSMetadata.canonicalPropertyName(property.name)); + } + } + return result; }, /**
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/StylesSectionModel.js b/third_party/WebKit/Source/devtools/front_end/elements/StylesSectionModel.js index 153fcbae..3389f71 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/StylesSectionModel.js +++ b/third_party/WebKit/Source/devtools/front_end/elements/StylesSectionModel.js
@@ -119,32 +119,6 @@ resetCachedData: function() { this._cascade._resetUsedProperties(); - }, - - /** - * @param {string} propertyName - * @return {boolean} - */ - isPropertyInCascade: function(propertyName) - { - if (!this.hasMatchingSelectors()) - return false; - if (this.inherited() && !WebInspector.CSSMetadata.isPropertyInherited(propertyName)) - return false; - return true; - }, - - /** - * @param {string} propertyName - * @return {boolean} - */ - isPropertyOverloaded: function(propertyName) - { - if (!this.isPropertyInCascade(propertyName)) - return false; - var usedProperties = this._cascade._usedPropertiesForModel(this); - var canonicalName = WebInspector.CSSMetadata.canonicalPropertyName(propertyName); - return !usedProperties.has(canonicalName); } } @@ -188,15 +162,6 @@ }, /** - * @return {!Set.<string>} - */ - allUsedProperties: function() - { - this._recomputeUsedPropertiesIfNeeded(); - return this._allUsedProperties; - }, - - /** * @param {!WebInspector.StylesSectionModel} model * @param {!WebInspector.StylesSectionModel=} insertAfter * @return {!WebInspector.StylesSectionModel} @@ -214,73 +179,70 @@ return model; }, - _recomputeUsedPropertiesIfNeeded: function() + /** + * @param {!WebInspector.CSSProperty} property + * @return {?WebInspector.SectionCascade.PropertyState} + */ + propertyState: function(property) { - if (this._usedPropertiesPerModel.size > 0) - return; - var usedProperties = WebInspector.SectionCascade._computeUsedProperties(this._models, this._allUsedProperties); - for (var i = 0; i < usedProperties.length; ++i) - this._usedPropertiesPerModel.set(this._models[i], usedProperties[i]); + if (this._propertiesState.size === 0) + this._propertiesState = WebInspector.SectionCascade._computeUsedProperties(this._models); + return this._propertiesState.get(property) || null; }, _resetUsedProperties: function() { - /** @type {!Set.<string>} */ - this._allUsedProperties = new Set(); - /** @type {!Map.<!WebInspector.StylesSectionModel, !Set.<string>>} */ - this._usedPropertiesPerModel = new Map(); - }, - - /** - * @param {!WebInspector.StylesSectionModel} model - * @return {!Set.<string>} - */ - _usedPropertiesForModel: function(model) - { - this._recomputeUsedPropertiesIfNeeded(); - return /**@type {!Set.<string>}*/ (this._usedPropertiesPerModel.get(model)); + /** @type {!Map<!WebInspector.CSSProperty, !WebInspector.SectionCascade.PropertyState>} */ + this._propertiesState = new Map(); } } /** * @param {!Array.<!WebInspector.StylesSectionModel>} styleRules - * @param {!Set.<string>} allUsedProperties - * @return {!Array.<!Set.<string>>} + * @return {!Map<!WebInspector.CSSProperty, !WebInspector.SectionCascade.PropertyState>} */ -WebInspector.SectionCascade._computeUsedProperties = function(styleRules, allUsedProperties) +WebInspector.SectionCascade._computeUsedProperties = function(styleRules) { /** @type {!Set.<string>} */ var foundImportantProperties = new Set(); - /** @type {!Map.<string, !Set.<string>>} */ + /** @type {!Map.<string, !Map<string, !WebInspector.CSSProperty>>} */ var propertyToEffectiveRule = new Map(); /** @type {!Map.<string, !WebInspector.DOMNode>} */ var inheritedPropertyToNode = new Map(); - var stylesUsedProperties = []; + /** @type {!Set<string>} */ + var allUsedProperties = new Set(); + var result = new Map(); for (var i = 0; i < styleRules.length; ++i) { var styleRule = styleRules[i]; - /** @type {!Set.<string>} */ - var styleRuleUsedProperties = new Set(); - stylesUsedProperties.push(styleRuleUsedProperties); if (!styleRule.hasMatchingSelectors()) continue; + /** @type {!Map<string, !WebInspector.CSSProperty>} */ + var styleActiveProperties = new Map(); var style = styleRule.style(); var allProperties = style.allProperties; for (var j = 0; j < allProperties.length; ++j) { var property = allProperties[j]; - if (!property.activeInStyle()) - continue; // Do not pick non-inherited properties from inherited styles. if (styleRule.inherited() && !WebInspector.CSSMetadata.isPropertyInherited(property.name)) continue; - var canonicalName = WebInspector.CSSMetadata.canonicalPropertyName(property.name); - if (foundImportantProperties.has(canonicalName)) + if (!property.activeInStyle()) { + result.set(property, WebInspector.SectionCascade.PropertyState.Overloaded); continue; + } - if (!property.important && allUsedProperties.has(canonicalName)) + var canonicalName = WebInspector.CSSMetadata.canonicalPropertyName(property.name); + if (foundImportantProperties.has(canonicalName)) { + result.set(property, WebInspector.SectionCascade.PropertyState.Overloaded); continue; + } + + if (!property.important && allUsedProperties.has(canonicalName)) { + result.set(property, WebInspector.SectionCascade.PropertyState.Overloaded); + continue; + } var isKnownProperty = propertyToEffectiveRule.has(canonicalName); var parentNode = styleRule.parentNode(); @@ -288,23 +250,29 @@ inheritedPropertyToNode.set(canonicalName, parentNode); if (property.important) { - if (styleRule.inherited() && isKnownProperty && styleRule.parentNode() !== inheritedPropertyToNode.get(canonicalName)) + if (styleRule.inherited() && isKnownProperty && styleRule.parentNode() !== inheritedPropertyToNode.get(canonicalName)) { + result.set(property, WebInspector.SectionCascade.PropertyState.Overloaded); continue; + } foundImportantProperties.add(canonicalName); - if (isKnownProperty) + if (isKnownProperty) { + var overloaded = propertyToEffectiveRule.get(canonicalName).get(canonicalName); + result.set(overloaded, WebInspector.SectionCascade.PropertyState.Overloaded); propertyToEffectiveRule.get(canonicalName).delete(canonicalName); + } } - styleRuleUsedProperties.add(canonicalName); + styleActiveProperties.set(canonicalName, property); allUsedProperties.add(canonicalName); - propertyToEffectiveRule.set(canonicalName, styleRuleUsedProperties); + propertyToEffectiveRule.set(canonicalName, styleActiveProperties); + result.set(property, WebInspector.SectionCascade.PropertyState.Active); } // If every longhand of the shorthand is not active, then the shorthand is not active too. for (var property of style.leadingProperties()) { var canonicalName = WebInspector.CSSMetadata.canonicalPropertyName(property.name); - if (!styleRuleUsedProperties.has(canonicalName)) + if (!styleActiveProperties.has(canonicalName)) continue; var longhands = style.longhandProperties(property.name); if (!longhands.length) @@ -312,13 +280,20 @@ var notUsed = true; for (var longhand of longhands) { var longhandCanonicalName = WebInspector.CSSMetadata.canonicalPropertyName(longhand.name); - notUsed = notUsed && !styleRuleUsedProperties.has(longhandCanonicalName); + notUsed = notUsed && !styleActiveProperties.has(longhandCanonicalName); } if (!notUsed) continue; - styleRuleUsedProperties.delete(canonicalName); + styleActiveProperties.delete(canonicalName); allUsedProperties.delete(canonicalName); + result.set(property, WebInspector.SectionCascade.PropertyState.Overloaded); } } - return stylesUsedProperties; + return result; } + +/** @enum {string} */ +WebInspector.SectionCascade.PropertyState = { + Active: "Active", + Overloaded: "Overloaded" +} \ No newline at end of file
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 e2e0a101e..7c7a1008 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/StylesSidebarPane.js +++ b/third_party/WebKit/Source/devtools/front_end/elements/StylesSidebarPane.js
@@ -1099,7 +1099,8 @@ } else { var child = this.propertiesTreeOutline.firstChild(); while (child) { - child.setOverloaded(this.styleRule.isPropertyOverloaded(child.name)); + var overloaded = this.styleRule.cascade().propertyState(child.property) === WebInspector.SectionCascade.PropertyState.Overloaded; + child.setOverloaded(overloaded); child = child.traverseNextTreeElement(false, null, true); } } @@ -1125,7 +1126,7 @@ for (var property of style.leadingProperties()) { var isShorthand = !!WebInspector.CSSMetadata.cssPropertiesMetainfo.longhands(property.name); var inherited = this.isPropertyInherited(property.name); - var overloaded = this.styleRule.isPropertyOverloaded(property.name); + var overloaded = this.styleRule.cascade().propertyState(property) === WebInspector.SectionCascade.PropertyState.Overloaded; var item = new WebInspector.StylePropertyTreeElement(this._parentPane, this.styleRule, property, isShorthand, inherited, overloaded); this.propertiesTreeOutline.appendChild(item); } @@ -2013,7 +2014,7 @@ var section = this.section(); if (section) { inherited = section.isPropertyInherited(name); - overloaded = section.styleRule.isPropertyOverloaded(name); + overloaded = section.styleRule.cascade().propertyState(longhandProperties[i]) === WebInspector.SectionCascade.PropertyState.Overloaded; } var item = new WebInspector.StylePropertyTreeElement(this._parentPane, this._styleRule, longhandProperties[i], false, inherited, overloaded);
diff --git a/third_party/WebKit/Source/devtools/front_end/externs.js b/third_party/WebKit/Source/devtools/front_end/externs.js index 58c518d0..f060059 100644 --- a/third_party/WebKit/Source/devtools/front_end/externs.js +++ b/third_party/WebKit/Source/devtools/front_end/externs.js
@@ -226,11 +226,6 @@ /** * @param {string} message */ -DevToolsHost.sendMessageToBackend = function(message) { } - -/** - * @param {string} message - */ DevToolsHost.sendMessageToEmbedder = function(message) { } /**
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 79a5d21..0830a7c 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/EventSourceMessagesView.js +++ b/third_party/WebKit/Source/devtools/front_end/network/EventSourceMessagesView.js
@@ -4,12 +4,12 @@ /** * @constructor - * @extends {WebInspector.VBox} + * @extends {WebInspector.DataGridContainerWidget} * @param {!WebInspector.NetworkRequest} request */ WebInspector.EventSourceMessagesView = function(request) { - WebInspector.VBox.call(this); + WebInspector.DataGridContainerWidget.call(this); this.registerRequiredCSS("network/eventSourceMessagesView.css"); this.element.classList.add("event-source-messages-view"); this._request = request; @@ -28,7 +28,7 @@ this._dataGrid.addEventListener(WebInspector.DataGrid.Events.SortingChanged, this._sortItems, this); this._dataGrid.setName("EventSourceMessagesView"); - this._dataGrid.show(this.element); + this.appendDataGrid(this._dataGrid); } WebInspector.EventSourceMessagesView.prototype = { @@ -67,7 +67,7 @@ this._dataGrid.sortNodes(comparator, !this._dataGrid.isSortOrderAscending()); }, - __proto__: WebInspector.VBox.prototype + __proto__: WebInspector.DataGridContainerWidget.prototype } /**
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 70b50ae..21811c2 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/NetworkLogView.js +++ b/third_party/WebKit/Source/devtools/front_end/network/NetworkLogView.js
@@ -30,16 +30,16 @@ /** * @constructor + * @extends {WebInspector.DataGridContainerWidget} * @implements {WebInspector.Searchable} * @implements {WebInspector.TargetManager.Observer} - * @extends {WebInspector.VBox} * @param {!WebInspector.FilterBar} filterBar * @param {!Element} progressBarContainer * @param {!WebInspector.Setting} networkLogLargeRowsSetting */ WebInspector.NetworkLogView = function(filterBar, progressBarContainer, networkLogLargeRowsSetting) { - WebInspector.VBox.call(this); + WebInspector.DataGridContainerWidget.call(this); this.setMinimumSize(50, 64); this.registerRequiredCSS("network/networkLogView.css"); this.registerRequiredCSS("ui/filter.css"); @@ -485,7 +485,7 @@ this._dataGrid.element.addEventListener("mousedown", this._dataGridMouseDown.bind(this), true); this._dataGrid.element.addEventListener("mousemove", this._dataGridMouseMove.bind(this), true); this._dataGrid.element.addEventListener("mouseleave", this._highlightInitiatorChain.bind(this, null), true); - this._dataGrid.show(this.element); + this.appendDataGrid(this._dataGrid); // Event listeners need to be added _after_ we attach to the document, so that owner document is properly update. this._dataGrid.addEventListener(WebInspector.DataGrid.Events.SortingChanged, this._sortItems, this); @@ -1927,7 +1927,7 @@ return command.join(" "); }, - __proto__: WebInspector.VBox.prototype + __proto__: WebInspector.DataGridContainerWidget.prototype } /** @typedef {function(!WebInspector.NetworkRequest): boolean} */
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 95ef4ca..63105e2 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/ResourceWebSocketFrameView.js +++ b/third_party/WebKit/Source/devtools/front_end/network/ResourceWebSocketFrameView.js
@@ -47,7 +47,9 @@ this._dataGrid.setName("ResourceWebSocketFrameView"); this._dataGrid.addEventListener(WebInspector.DataGrid.Events.SelectedNode, this._onFrameSelected, this); - this._splitWidget.setMainWidget(this._dataGrid); + var dataGridWidget = new WebInspector.DataGridContainerWidget(); + dataGridWidget.appendDataGrid(this._dataGrid); + this._splitWidget.setMainWidget(dataGridWidget); this._messageView = new WebInspector.EmptyWidget("Select frame to browse its content."); this._splitWidget.setSidebarWidget(this._messageView);
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 faab86b..2be3dd5 100644 --- a/third_party/WebKit/Source/devtools/front_end/profiler/CPUProfileView.js +++ b/third_party/WebKit/Source/devtools/front_end/profiler/CPUProfileView.js
@@ -48,6 +48,8 @@ this.dataGrid = new WebInspector.DataGrid(columns); this.dataGrid.addEventListener(WebInspector.DataGrid.Events.SortingChanged, this._sortProfile, this); + this._dataGridContainer = new WebInspector.DataGridContainerWidget(); + this._dataGridContainer.appendDataGrid(this.dataGrid); this.viewSelectComboBox = new WebInspector.ToolbarComboBox(this._changeView.bind(this)); @@ -307,13 +309,13 @@ case WebInspector.CPUProfileView._TypeTree: this.profileDataGridTree = this._getTopDownProfileDataGridTree(); this._sortProfile(); - this._visibleView = this.dataGrid; + this._visibleView = this._dataGridContainer; this._searchableElement = this.profileDataGridTree; break; case WebInspector.CPUProfileView._TypeHeavy: this.profileDataGridTree = this._getBottomUpProfileDataGridTree(); this._sortProfile(); - this._visibleView = this.dataGrid; + this._visibleView = this._dataGridContainer; this._searchableElement = this.profileDataGridTree; break; }
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 89c1fa3..b363ca10 100644 --- a/third_party/WebKit/Source/devtools/front_end/profiler/HeapSnapshotView.js +++ b/third_party/WebKit/Source/devtools/front_end/profiler/HeapSnapshotView.js
@@ -59,34 +59,33 @@ this._splitWidget = new WebInspector.SplitWidget(false, true, "heapSnapshotSplitViewState", 200, 200); this._splitWidget.show(this._searchableView.element); - this._containmentWidget = new WebInspector.VBox(); + this._containmentWidget = new WebInspector.DataGridContainerWidget(); this._containmentWidget.setMinimumSize(50, 25); this._containmentDataGrid = new WebInspector.HeapSnapshotContainmentDataGrid(this); - this._containmentDataGrid.show(this._containmentWidget.element); this._containmentDataGrid.addEventListener(WebInspector.DataGrid.Events.SelectedNode, this._selectionChanged, this); + this._containmentWidget.appendDataGrid(this._containmentDataGrid); this._statisticsView = new WebInspector.HeapSnapshotStatisticsView(); - this._constructorsWidget = new WebInspector.VBox(); + this._constructorsWidget = new WebInspector.DataGridContainerWidget(); this._constructorsWidget.setMinimumSize(50, 25); this._constructorsDataGrid = new WebInspector.HeapSnapshotConstructorsDataGrid(this); - this._constructorsDataGrid.show(this._constructorsWidget.element); this._constructorsDataGrid.addEventListener(WebInspector.DataGrid.Events.SelectedNode, this._selectionChanged, this); + this._constructorsWidget.appendDataGrid(this._constructorsDataGrid); - this._diffWidget = new WebInspector.VBox(); + this._diffWidget = new WebInspector.DataGridContainerWidget(); this._diffWidget.setMinimumSize(50, 25); - this._diffDataGrid = new WebInspector.HeapSnapshotDiffDataGrid(this); - this._diffDataGrid.show(this._diffWidget.element); this._diffDataGrid.addEventListener(WebInspector.DataGrid.Events.SelectedNode, this._selectionChanged, this); + this._diffWidget.appendDataGrid(this._diffDataGrid); if (isHeapTimeline && WebInspector.moduleSetting("recordAllocationStacks").get()) { - this._allocationWidget = new WebInspector.VBox(); + this._allocationWidget = new WebInspector.DataGridContainerWidget(); this._allocationWidget.setMinimumSize(50, 25); this._allocationDataGrid = new WebInspector.AllocationDataGrid(profile.target() , this); this._allocationDataGrid.addEventListener(WebInspector.DataGrid.Events.SelectedNode, this._onSelectAllocationNode, this); - this._allocationDataGrid.show(this._allocationWidget.element); + this._allocationWidget.appendDataGrid(this._allocationDataGrid); this._allocationStackView = new WebInspector.HeapAllocationStackView(profile.target()); this._allocationStackView.setMinimumSize(50, 25); @@ -95,7 +94,7 @@ this._tabbedPane.headerElement().classList.add("heap-object-details-header"); } - this._retainmentWidget = new WebInspector.VBox(); + this._retainmentWidget = new WebInspector.DataGridContainerWidget(); this._retainmentWidget.setMinimumSize(50, 21); this._retainmentWidget.element.classList.add("retaining-paths-view"); @@ -123,7 +122,7 @@ this._splitWidget.installResizer(splitWidgetResizer); this._retainmentDataGrid = new WebInspector.HeapSnapshotRetainmentDataGrid(this); - this._retainmentDataGrid.show(this._retainmentWidget.element); + this._retainmentWidget.appendDataGrid(this._retainmentDataGrid); this._retainmentDataGrid.addEventListener(WebInspector.DataGrid.Events.SelectedNode, this._inspectedObjectChanged, this); this._retainmentDataGrid.reset();
diff --git a/third_party/WebKit/Source/devtools/front_end/promises/PromisePane.js b/third_party/WebKit/Source/devtools/front_end/promises/PromisePane.js index 63ff4f8..2f97efb 100644 --- a/third_party/WebKit/Source/devtools/front_end/promises/PromisePane.js +++ b/third_party/WebKit/Source/devtools/front_end/promises/PromisePane.js
@@ -48,7 +48,7 @@ resetFiltersLink.textContent = WebInspector.UIString("Show all promises."); resetFiltersLink.addEventListener("click", this._resetFilters.bind(this), true); - this._dataGridContainer = new WebInspector.VBox(); + this._dataGridContainer = new WebInspector.DataGridContainerWidget(); this._dataGridContainer.show(this.element); // FIXME: Make "status" column width fixed to ~16px. var columns = [ @@ -60,7 +60,7 @@ ]; this._dataGrid = new WebInspector.ViewportDataGrid(columns, undefined, undefined, undefined, this._onContextMenu.bind(this)); this._dataGrid.setStickToBottom(true); - this._dataGrid.show(this._dataGridContainer.element); + this._dataGridContainer.appendDataGrid(this._dataGrid); this._linkifier = new WebInspector.Linkifier();
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 0e61829d7..83921fc 100644 --- a/third_party/WebKit/Source/devtools/front_end/resources/ApplicationCacheItemsView.js +++ b/third_party/WebKit/Source/devtools/front_end/resources/ApplicationCacheItemsView.js
@@ -25,11 +25,11 @@ /** * @constructor - * @extends {WebInspector.VBox} + * @extends {WebInspector.DataGridContainerWidget} */ WebInspector.ApplicationCacheItemsView = function(model, frameId) { - WebInspector.VBox.call(this); + WebInspector.DataGridContainerWidget.call(this); this._model = model; @@ -191,7 +191,7 @@ {title: WebInspector.UIString("Size"), align: WebInspector.DataGrid.Align.Right, sortable: true} ]; this._dataGrid = new WebInspector.DataGrid(columns); - this._dataGrid.show(this.element); + this.appendDataGrid(this._dataGrid); this._dataGrid.addEventListener(WebInspector.DataGrid.Events.SortingChanged, this._populateDataGrid, this); }, @@ -257,6 +257,6 @@ // this._update(); }, - __proto__: WebInspector.VBox.prototype + __proto__: WebInspector.DataGridContainerWidget.prototype }
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 fd0622b..34df4dd 100644 --- a/third_party/WebKit/Source/devtools/front_end/resources/DOMStorageItemsView.js +++ b/third_party/WebKit/Source/devtools/front_end/resources/DOMStorageItemsView.js
@@ -26,11 +26,11 @@ /** * @constructor - * @extends {WebInspector.VBox} + * @extends {WebInspector.DataGridContainerWidget} */ WebInspector.DOMStorageItemsView = function(domStorage) { - WebInspector.VBox.call(this); + WebInspector.DataGridContainerWidget.call(this); this.domStorage = domStorage; @@ -175,7 +175,7 @@ return; this._dataGrid = this._dataGridForDOMStorageItems(items); - this._dataGrid.show(this.element); + this.appendDataGrid(this._dataGrid); this.deleteButton.setVisible(this._dataGrid.rootNode().children.length > 1); }, @@ -259,5 +259,5 @@ this.domStorage.removeItem(node.data.key); }, - __proto__: WebInspector.VBox.prototype + __proto__: WebInspector.DataGridContainerWidget.prototype }
diff --git a/third_party/WebKit/Source/devtools/front_end/resources/DatabaseQueryView.js b/third_party/WebKit/Source/devtools/front_end/resources/DatabaseQueryView.js index 00fc611..3ae995e 100644 --- a/third_party/WebKit/Source/devtools/front_end/resources/DatabaseQueryView.js +++ b/third_party/WebKit/Source/devtools/front_end/resources/DatabaseQueryView.js
@@ -154,7 +154,9 @@ if (dataGrid) { dataGrid.renderInline(); - this._appendViewQueryResult(trimmedQuery, dataGrid); + var dataGridContainer = new WebInspector.DataGridContainerWidget(); + dataGridContainer.appendDataGrid(dataGrid); + this._appendViewQueryResult(trimmedQuery, dataGridContainer); dataGrid.autoSizeColumns(5); } @@ -175,7 +177,6 @@ { var resultElement = this._appendQueryResult(query); view.show(resultElement); - this._promptElement.scrollIntoView(false); },
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 85af9e30..2ceff7fa 100644 --- a/third_party/WebKit/Source/devtools/front_end/resources/DatabaseTableView.js +++ b/third_party/WebKit/Source/devtools/front_end/resources/DatabaseTableView.js
@@ -25,11 +25,11 @@ /** * @constructor - * @extends {WebInspector.VBox} + * @extends {WebInspector.DataGridContainerWidget} */ WebInspector.DatabaseTableView = function(database, tableName) { - WebInspector.VBox.call(this); + WebInspector.DataGridContainerWidget.call(this); this.database = database; this.tableName = tableName; @@ -84,7 +84,7 @@ this._emptyWidget.show(this.element); return; } - this._dataGrid.show(this.element); + this.appendDataGrid(this._dataGrid); this._dataGrid.autoSizeColumns(5); this._columnsMap = new Map(); @@ -142,5 +142,5 @@ this.update(); }, - __proto__: WebInspector.VBox.prototype + __proto__: WebInspector.DataGridContainerWidget.prototype }
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 cf8c12a..be2c4a74 100644 --- a/third_party/WebKit/Source/devtools/front_end/resources/IndexedDBViews.js +++ b/third_party/WebKit/Source/devtools/front_end/resources/IndexedDBViews.js
@@ -110,7 +110,7 @@ /** * @constructor - * @extends {WebInspector.VBox} + * @extends {WebInspector.DataGridContainerWidget} * @param {!WebInspector.IndexedDBModel} model * @param {!WebInspector.IndexedDBModel.DatabaseId} databaseId * @param {!WebInspector.IndexedDBModel.ObjectStore} objectStore @@ -118,7 +118,7 @@ */ WebInspector.IDBDataView = function(model, databaseId, objectStore, index) { - WebInspector.VBox.call(this); + WebInspector.DataGridContainerWidget.call(this); this.registerRequiredCSS("resources/indexedDBViews.css"); this._model = model; @@ -253,9 +253,9 @@ this._index = index; if (this._dataGrid) - this._dataGrid.detach(); + this.removeDataGrid(this._dataGrid); this._dataGrid = this._createDataGrid(); - this._dataGrid.show(this.element); + this.appendDataGrid(this._dataGrid); this._skipCount = 0; this._updateData(true); @@ -361,7 +361,7 @@ this._entries = []; }, - __proto__: WebInspector.VBox.prototype + __proto__: WebInspector.DataGridContainerWidget.prototype } /**
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 0828d9a..7768ce4 100644 --- a/third_party/WebKit/Source/devtools/front_end/resources/ServiceWorkerCacheViews.js +++ b/third_party/WebKit/Source/devtools/front_end/resources/ServiceWorkerCacheViews.js
@@ -4,13 +4,13 @@ /** * @constructor - * @extends {WebInspector.VBox} + * @extends {WebInspector.DataGridContainerWidget} * @param {!WebInspector.ServiceWorkerCacheModel} model * @param {!WebInspector.ServiceWorkerCacheModel.Cache} cache */ WebInspector.ServiceWorkerCacheView = function(model, cache) { - WebInspector.VBox.call(this); + WebInspector.DataGridContainerWidget.call(this); this.registerRequiredCSS("resources/serviceWorkerCacheViews.css"); this._model = model; @@ -88,9 +88,9 @@ this._cache = cache; if (this._dataGrid) - this._dataGrid.detach(); + this.removeDataGrid(this._dataGrid); this._dataGrid = this._createDataGrid(); - this._dataGrid.show(this.element); + this.appendDataGrid(this._dataGrid); this._skipCount = 0; this._updateData(true); @@ -160,5 +160,5 @@ this._entries = []; }, - __proto__: WebInspector.VBox.prototype + __proto__: WebInspector.DataGridContainerWidget.prototype }
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 307131b..e2aa265 100644 --- a/third_party/WebKit/Source/devtools/front_end/security/SecurityPanel.js +++ b/third_party/WebKit/Source/devtools/front_end/security/SecurityPanel.js
@@ -712,9 +712,8 @@ originState.certificateDetailsPromise.then(displayCertificateDetails.bind(this), displayCertificateDetailsUnavailable); var noteSection = this.element.createChild("div", "origin-view-section"); - noteSection.createChild("div", "origin-view-section-title").textContent = WebInspector.UIString("Development Note"); // TODO(lgarron): Fix the issue and then remove this section. See comment in SecurityPanel._processRequest(). - noteSection.createChild("div").textContent = WebInspector.UIString("At the moment, this view only shows security details from the first connection made to %s", origin); + noteSection.createChild("div").textContent = WebInspector.UIString("The security details above are from the first inspected response."); } else { var notSecureSection = this.element.createChild("div", "origin-view-section"); notSecureSection.createChild("div", "origin-view-section-title").textContent = WebInspector.UIString("Not Secure");
diff --git a/third_party/WebKit/Source/devtools/front_end/security/originView.css b/third_party/WebKit/Source/devtools/front_end/security/originView.css index b69034a..aeb26f6b 100644 --- a/third_party/WebKit/Source/devtools/front_end/security/originView.css +++ b/third_party/WebKit/Source/devtools/front_end/security/originView.css
@@ -11,7 +11,7 @@ } .security-origin-view .origin-view-section { - padding: 0.5em 1.5em 1.5em; + padding: 1.5em 1.5em 1.5em; border-bottom: 1px solid rgb(230, 230, 230); } @@ -34,7 +34,6 @@ .security-origin-view .origin-view-section-title { font-weight: bold; font-size: 1em; - margin-top: 0.5em; margin-bottom: 0.25em; }
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 49ae48f..b095db2 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline/TimelinePanel.js +++ b/third_party/WebKit/Source/devtools/front_end/timeline/TimelinePanel.js
@@ -111,7 +111,8 @@ this._tabbedPane = new WebInspector.TabbedPane(); this._tabbedPane.appendTab(WebInspector.TimelinePanel.ViewMode.FlameChart, WebInspector.UIString("Flame Chart"), new WebInspector.VBox()); this._tabbedPane.appendTab(WebInspector.TimelinePanel.ViewMode.Waterfall, WebInspector.UIString("Waterfall"), new WebInspector.VBox()); - this._tabbedPane.appendTab(WebInspector.TimelinePanel.ViewMode.TreeView, WebInspector.UIString("Tree View"), new WebInspector.VBox()); + this._tabbedPane.appendTab(WebInspector.TimelinePanel.ViewMode.CallTree, WebInspector.UIString("Call Tree"), new WebInspector.VBox()); + this._tabbedPane.appendTab(WebInspector.TimelinePanel.ViewMode.BottomUp, WebInspector.UIString("Bottom-Up"), new WebInspector.VBox()); this._tabbedPane.addEventListener(WebInspector.TabbedPane.EventTypes.TabSelected, this._onMainViewChanged.bind(this)); this._tabbedPane.show(this._searchableView.element); } else { @@ -131,7 +132,8 @@ WebInspector.TimelinePanel.ViewMode = { Waterfall: "Waterfall", FlameChart: "FlameChart", - TreeView: "TreeView" + CallTree: "CallTree", + BottomUp: "BottomUp", } /** @@ -139,7 +141,8 @@ */ WebInspector.TimelinePanel.DetailsTab = { Details: "Details", - BottomUpTree: "BottomUpTree", + CallTree: "CallTree", + BottomUp: "BottomUp", PaintProfiler: "PaintProfiler", LayerViewer: "LayerViewer" } @@ -617,14 +620,15 @@ var timelineView = new WebInspector.TimelineView(this, this._model); this._addModeView(timelineView); timelineView.setFrameModel(this._frameModel); - } else if (viewMode === WebInspector.TimelinePanel.ViewMode.TreeView) { + } else if (viewMode === WebInspector.TimelinePanel.ViewMode.CallTree || viewMode === WebInspector.TimelinePanel.ViewMode.BottomUp) { this._filterBar.filterButton().setEnabled(false); this._filterBar.filtersElement().classList.toggle("hidden", true); - var treeView = new WebInspector.TimelineTreeModeView(this, this._model); + var innerView = viewMode === WebInspector.TimelinePanel.ViewMode.BottomUp ? new WebInspector.BottomUpTimelineTreeView(this._model) : new WebInspector.CallTreeTimelineTreeView(this._model); + var treeView = new WebInspector.TimelineTreeModeView(this, innerView); this._addModeView(treeView); } - if (this._captureMemorySetting.get() && viewMode !== WebInspector.TimelinePanel.ViewMode.TreeView) + if (this._captureMemorySetting.get() && viewMode !== WebInspector.TimelinePanel.ViewMode.CallTree && viewMode !== WebInspector.TimelinePanel.ViewMode.BottomUp) this._addModeView(new WebInspector.MemoryCountersGraph(this, this._model)); this.doResize(); @@ -1219,12 +1223,12 @@ * @extends {WebInspector.VBox} * @implements {WebInspector.TimelineModeView} * @param {!WebInspector.TimelineModeViewDelegate} delegate - * @param {!WebInspector.TimelineModel} model + * @param {!WebInspector.TimelineTreeView} innerTreeView */ -WebInspector.TimelineTreeModeView = function(delegate, model) +WebInspector.TimelineTreeModeView = function(delegate, innerTreeView) { WebInspector.VBox.call(this); - this._treeView = new WebInspector.TimelineTreeView(model); + this._treeView = innerTreeView; this._treeView.show(this.element); } @@ -1310,13 +1314,16 @@ this.setPreferredTab(WebInspector.TimelinePanel.DetailsTab.Details); if (!Runtime.experiments.isEnabled("multipleTimelineViews")) { - this._heavyTreeView = new WebInspector.TimelineTreeView(timelineModel); - this.appendTab(WebInspector.TimelinePanel.DetailsTab.BottomUpTree, WebInspector.UIString("Aggregated Details"), this._heavyTreeView); + this._callTreeView = new WebInspector.CallTreeTimelineTreeView(timelineModel); + this.appendTab(WebInspector.TimelinePanel.DetailsTab.CallTree, WebInspector.UIString("Call Tree"), this._callTreeView); + this._bottomUpView = new WebInspector.BottomUpTimelineTreeView(timelineModel); + this.appendTab(WebInspector.TimelinePanel.DetailsTab.BottomUp, WebInspector.UIString("Bottom-Up"), this._bottomUpView); } this._staticTabs = new Set([ WebInspector.TimelinePanel.DetailsTab.Details, - WebInspector.TimelinePanel.DetailsTab.BottomUpTree + WebInspector.TimelinePanel.DetailsTab.CallTree, + WebInspector.TimelinePanel.DetailsTab.BottomUp, ]); this.addEventListener(WebInspector.TabbedPane.EventTypes.TabSelected, this._tabSelected, this); @@ -1343,8 +1350,10 @@ updateContents: function(selection) { this._selection = selection; - if (this.selectedTabId === WebInspector.TimelinePanel.DetailsTab.BottomUpTree && this._heavyTreeView) - this._heavyTreeView.updateContents(selection); + if (this.selectedTabId === WebInspector.TimelinePanel.DetailsTab.CallTree && this._callTreeView) + this._callTreeView.updateContents(selection); + if (this.selectedTabId === WebInspector.TimelinePanel.DetailsTab.BottomUp && this._bottomUpView) + this._bottomUpView.updateContents(selection); }, /**
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 b5e9bc7..50f6295 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline/TimelineTreeView.js +++ b/third_party/WebKit/Source/devtools/front_end/timeline/TimelineTreeView.js
@@ -4,12 +4,12 @@ /** * @constructor - * @extends {WebInspector.VBox} + * @extends {WebInspector.DataGridContainerWidget} * @param {!WebInspector.TimelineModel} model */ WebInspector.TimelineTreeView = function(model) { - WebInspector.VBox.call(this); + WebInspector.DataGridContainerWidget.call(this); this.element.classList.add("timeline-tree-view"); this._model = model; @@ -37,15 +37,7 @@ this._createToolbar(); - this.dataGrid.show(this.element); -} - -/** - * @enum {string} - */ -WebInspector.TimelineTreeView.Mode = { - TopDown: "TopDown", - BottomUp: "BottomUp" + this.appendDataGrid(this.dataGrid); } /** @@ -82,13 +74,6 @@ _createToolbar: function() { var panelToolbar = new WebInspector.Toolbar(this.element); - panelToolbar.appendToolbarItem(new WebInspector.ToolbarText(WebInspector.UIString("View"))); - - this._modeCombobox = new WebInspector.ToolbarComboBox(this._onTreeModeChanged.bind(this)); - this._modeCombobox.addOption(this._modeCombobox.createOption(WebInspector.UIString("Costly Functions"), "", WebInspector.TimelineTreeView.Mode.BottomUp)); - this._modeCombobox.addOption(this._modeCombobox.createOption(WebInspector.UIString("Call Tree"), "", WebInspector.TimelineTreeView.Mode.TopDown)); - panelToolbar.appendToolbarItem(this._modeCombobox); - this._groupByCombobox = new WebInspector.ToolbarComboBox(this._onGroupByChanged.bind(this)); /** * @param {string} name @@ -122,11 +107,6 @@ return this._linkifier.linkifyScriptLocation(this._model.target(), scriptId, url, lineNumber, columnNumber); }, - _onTreeModeChanged: function() - { - this._refreshTree(); - }, - _onGroupByChanged: function() { this._groupBySetting.set(this._groupByCombobox.selectedOption().value); @@ -137,11 +117,7 @@ { this._linkifier.reset(); this.dataGrid.rootNode().removeChildren(); - var topDown = WebInspector.TimelineModel.buildTopDownTree( - this._model.mainThreadEvents(), this._startTime, this._endTime, this._filters, WebInspector.TimelineTreeView.eventId); - var isTopDown = this._modeCombobox.selectedOption().value === WebInspector.TimelineTreeView.Mode.TopDown; - var tree = isTopDown ? this._preformTopDownTreeGrouping(topDown) : this._buildBottomUpTree(topDown); - this.dataGrid.markColumnAsSortedBy(isTopDown ? "total" : "self", WebInspector.DataGrid.Order.Descending); + var tree = this._buildTree(); var maxSelfTime = 0; var maxTotalTime = 0; for (var child of tree.children.values()) { @@ -150,46 +126,18 @@ } for (var child of tree.children.values()) { // Exclude the idle time off the total calculation. - var gridNode = new WebInspector.TimelineTreeView.GridNode(child, topDown.totalTime, maxSelfTime, maxTotalTime, this); + var gridNode = new WebInspector.TimelineTreeView.GridNode(child, tree.totalTime, maxSelfTime, maxTotalTime, this); this.dataGrid.insertChild(gridNode); } this._sortingChanged(); }, /** - * @param {!WebInspector.TimelineModel.ProfileTreeNode} topDownTree * @return {!WebInspector.TimelineModel.ProfileTreeNode} */ - _preformTopDownTreeGrouping: function(topDownTree) + _buildTree: function() { - var nodeToGroupId = this._nodeToGroupIdFunction(); - if (nodeToGroupId) { - this._groupNodes = new Map(); - for (var node of topDownTree.children.values()) { - var groupNode = this._nodeToGroupNode(nodeToGroupId, node); - groupNode.selfTime += node.selfTime; - groupNode.totalTime += node.totalTime; - groupNode.children.set(node.id, node); - } - topDownTree.children = this._groupNodes; - this._groupNodes = null; - } - return topDownTree; - }, - - /** - * @param {!WebInspector.TimelineModel.ProfileTreeNode} topDownTree - * @return {!WebInspector.TimelineModel.ProfileTreeNode} - */ - _buildBottomUpTree: function(topDownTree) - { - this._groupNodes = new Map(); - var nodeToGroupId = this._nodeToGroupIdFunction(); - var nodeToGroupNode = nodeToGroupId ? this._nodeToGroupNode.bind(this, nodeToGroupId) : null; - var bottomUpRoot = WebInspector.TimelineModel.buildBottomUpTree(topDownTree, nodeToGroupNode); - for (var group of this._groupNodes) - bottomUpRoot.children.set(group[0], group[1]); - return bottomUpRoot; + throw new Error("Not Implemented"); }, /** @@ -321,7 +269,7 @@ this.dataGrid.sortNodes(compareField.bind(null, field), !this.dataGrid.isSortOrderAscending()); }, - __proto__: WebInspector.VBox.prototype + __proto__: WebInspector.DataGridContainerWidget.prototype } /** @@ -497,3 +445,89 @@ __proto__: WebInspector.SortableDataGridNode.prototype } + +/** + * @constructor + * @extends {WebInspector.TimelineTreeView} + * @param {!WebInspector.TimelineModel} model + */ +WebInspector.CallTreeTimelineTreeView = function(model) +{ + WebInspector.TimelineTreeView.call(this, model); + this.dataGrid.markColumnAsSortedBy("total", WebInspector.DataGrid.Order.Descending); +} + +WebInspector.CallTreeTimelineTreeView.prototype = { + /** + * @override + * @return {!WebInspector.TimelineModel.ProfileTreeNode} + */ + _buildTree: function() + { + var topDown = WebInspector.TimelineModel.buildTopDownTree(this._model.mainThreadEvents(), this._startTime, this._endTime, this._filters, WebInspector.TimelineTreeView.eventId); + return this._performTopDownTreeGrouping(topDown); + }, + + /** + * @param {!WebInspector.TimelineModel.ProfileTreeNode} topDownTree + * @return {!WebInspector.TimelineModel.ProfileTreeNode} + */ + _performTopDownTreeGrouping: function(topDownTree) + { + var nodeToGroupId = this._nodeToGroupIdFunction(); + if (nodeToGroupId) { + this._groupNodes = new Map(); + for (var node of topDownTree.children.values()) { + var groupNode = this._nodeToGroupNode(nodeToGroupId, node); + groupNode.selfTime += node.selfTime; + groupNode.totalTime += node.totalTime; + groupNode.children.set(node.id, node); + } + topDownTree.children = this._groupNodes; + this._groupNodes = null; + } + return topDownTree; + }, + + __proto__: WebInspector.TimelineTreeView.prototype +}; + +/** + * @constructor + * @extends {WebInspector.TimelineTreeView} + * @param {!WebInspector.TimelineModel} model + */ +WebInspector.BottomUpTimelineTreeView = function(model) +{ + WebInspector.TimelineTreeView.call(this, model); + this.dataGrid.markColumnAsSortedBy("self", WebInspector.DataGrid.Order.Descending); +} + +WebInspector.BottomUpTimelineTreeView.prototype = { + /** + * @override + * @return {!WebInspector.TimelineModel.ProfileTreeNode} + */ + _buildTree: function() + { + var topDown = WebInspector.TimelineModel.buildTopDownTree(this._model.mainThreadEvents(), this._startTime, this._endTime, this._filters, WebInspector.TimelineTreeView.eventId); + return this._buildBottomUpTree(topDown); + }, + + /** + * @param {!WebInspector.TimelineModel.ProfileTreeNode} topDownTree + * @return {!WebInspector.TimelineModel.ProfileTreeNode} + */ + _buildBottomUpTree: function(topDownTree) + { + this._groupNodes = new Map(); + var nodeToGroupId = this._nodeToGroupIdFunction(); + var nodeToGroupNode = nodeToGroupId ? this._nodeToGroupNode.bind(this, nodeToGroupId) : null; + var bottomUpRoot = WebInspector.TimelineModel.buildBottomUpTree(topDownTree, nodeToGroupNode); + for (var group of this._groupNodes) + bottomUpRoot.children.set(group[0], group[1]); + return bottomUpRoot; + }, + + __proto__: WebInspector.TimelineTreeView.prototype +};
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 1538fab..53376a6b 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
@@ -25,7 +25,7 @@ /** * @constructor - * @extends {WebInspector.Widget} + * @extends {WebInspector.Object} * @param {!Array.<!WebInspector.DataGrid.ColumnDescriptor>} columnsArray * @param {function(!WebInspector.DataGridNode, string, string, string)=} editCallback * @param {function(!WebInspector.DataGridNode)=} deleteCallback @@ -34,10 +34,8 @@ */ WebInspector.DataGrid = function(columnsArray, editCallback, deleteCallback, refreshCallback, contextMenuCallback) { - WebInspector.Widget.call(this); - this.registerRequiredCSS("ui_lazy/dataGrid.css"); - - this.element.className = "data-grid"; // Override + this.element = createElementWithClass("div", "data-grid"); + this.element.appendChild(WebInspector.Widget.createStyleElement("ui_lazy/dataGrid.css")); this.element.tabIndex = 0; this.element.addEventListener("keydown", this._keyDown.bind(this), false); @@ -646,7 +644,11 @@ wasShown: function() { - this._loadColumnWeights(); + this._loadColumnWeights(); + }, + + willHide: function() + { }, _applyColumnWeights: function() @@ -698,15 +700,6 @@ return this._scrollContainer; }, - /** - * @override - * @return {!Array.<!Element>} - */ - elementsToRestoreScrollPositionsFor: function() - { - return this._inline ? [] : [this._scrollContainer]; - }, - _positionResizers: function() { var headerTableColumns = this._headerTableColumnGroup.children; @@ -1083,7 +1076,7 @@ CenterResizerOverBorderAdjustment: 3, - __proto__: WebInspector.Widget.prototype + __proto__: WebInspector.Object.prototype } /** @enum {string} */ @@ -1801,3 +1794,76 @@ __proto__: WebInspector.DataGridNode.prototype } + +/** + * @constructor + * @extends {WebInspector.VBox} + */ +WebInspector.DataGridContainerWidget = function() +{ + WebInspector.VBox.call(this); + this._dataGrids = []; +} + +WebInspector.DataGridContainerWidget.prototype = { + /** + * @param {!WebInspector.DataGrid} dataGrid + */ + appendDataGrid: function(dataGrid) + { + this._dataGrids.push(dataGrid); + this.element.appendChild(dataGrid.element); + }, + + /** + * @param {!WebInspector.DataGrid} dataGrid + */ + removeDataGrid: function(dataGrid) + { + this._dataGrids.remove(dataGrid); + this.element.removeChild(dataGrid.element); + }, + + /** + * @override + */ + wasShown: function() + { + for (var dataGrid of this._dataGrids) + dataGrid.wasShown(); + }, + + /** + * @override + */ + willHide: function() + { + for (var dataGrid of this._dataGrids) + dataGrid.willHide(); + }, + + /** + * @override + */ + onResize: function() + { + for (var dataGrid of this._dataGrids) + dataGrid.onResize(); + }, + + /** + * @override + * @return {!Array.<!Element>} + */ + elementsToRestoreScrollPositionsFor: function() + { + var result = []; + for (var dataGrid of this._dataGrids) { + if (!dataGrid._inline) + result.push(dataGrid._scrollContainer); + } + return result; + }, + + __proto__: WebInspector.VBox.prototype +}
diff --git a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.cpp b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.cpp index 7675cd2..c39c19b 100644 --- a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.cpp +++ b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.cpp
@@ -2107,6 +2107,19 @@ modifiableState().setImageSmoothingEnabled(enabled); } +String CanvasRenderingContext2D::imageSmoothingQuality() const +{ + return state().imageSmoothingQuality(); +} + +void CanvasRenderingContext2D::setImageSmoothingQuality(const String& quality) +{ + if (quality == state().imageSmoothingQuality()) + return; + + modifiableState().setImageSmoothingQuality(quality); +} + void CanvasRenderingContext2D::getContextAttributes(Canvas2DContextAttributes& attrs) const { attrs.setAlpha(m_hasAlpha);
diff --git a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.h b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.h index 7972002..d884aaa 100644 --- a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.h +++ b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.h
@@ -201,6 +201,8 @@ bool imageSmoothingEnabled() const; void setImageSmoothingEnabled(bool); + String imageSmoothingQuality() const; + void setImageSmoothingQuality(const String&); void getContextAttributes(Canvas2DContextAttributes&) const;
diff --git a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.idl b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.idl index d366967..b830fb9 100644 --- a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.idl +++ b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.idl
@@ -33,6 +33,7 @@ ImageBitmap) CanvasImageSource; enum CanvasFillRule { "nonzero", "evenodd" }; +enum ImageSmoothingQuality {"low", "medium", "high"}; [ SetWrapperReferenceFrom=canvas, @@ -62,7 +63,8 @@ // image smoothing [ImplementedAs=imageSmoothingEnabled, DeprecateAs=PrefixedImageSmoothingEnabled] attribute boolean webkitImageSmoothingEnabled; - [MeasureAs=UnprefixedImageSmoothingEnabled] attribute boolean imageSmoothingEnabled; + [MeasureAs=UnprefixedImageSmoothingEnabled] attribute boolean imageSmoothingEnabled; // (default True) + [RuntimeEnabled=ExperimentalCanvasFeatures] attribute ImageSmoothingQuality imageSmoothingQuality; // (default "low") // colors and styles (see also the CanvasDrawingStyles interface) attribute (DOMString or CanvasGradient or CanvasPattern) strokeStyle; // (default black)
diff --git a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DState.cpp b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DState.cpp index 510e4df9..e532787 100644 --- a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DState.cpp +++ b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DState.cpp
@@ -46,6 +46,7 @@ , m_fillStyleDirty(true) , m_strokeStyleDirty(true) , m_lineDashDirty(false) + , m_imageSmoothingQuality(kLow_SkFilterQuality) { m_fillPaint.setStyle(SkPaint::kFill_Style); m_fillPaint.setAntiAlias(true); @@ -97,6 +98,8 @@ , m_fillStyleDirty(other.m_fillStyleDirty) , m_strokeStyleDirty(other.m_strokeStyleDirty) , m_lineDashDirty(other.m_lineDashDirty) + , m_imageSmoothingEnabled(other.m_imageSmoothingEnabled) + , m_imageSmoothingQuality(other.m_imageSmoothingQuality) { if (mode == CopyClipList) { m_clipList = other.m_clipList; @@ -148,6 +151,8 @@ m_strokeStyleDirty = other.m_strokeStyleDirty; m_lineDashDirty = other.m_lineDashDirty; m_clipList = other.m_clipList; + m_imageSmoothingEnabled = other.m_imageSmoothingEnabled; + m_imageSmoothingQuality = other.m_imageSmoothingQuality; if (m_realizedFont) static_cast<CSSFontSelector*>(m_font.fontSelector())->registerForInvalidationCallbacks(this); @@ -468,16 +473,60 @@ void CanvasRenderingContext2DState::setImageSmoothingEnabled(bool enabled) { - SkFilterQuality filterQuality = enabled ? kLow_SkFilterQuality : kNone_SkFilterQuality; + m_imageSmoothingEnabled = enabled; + updateFilterQuality(); +} + +bool CanvasRenderingContext2DState::imageSmoothingEnabled() const +{ + return m_imageSmoothingEnabled; +} + +void CanvasRenderingContext2DState::setImageSmoothingQuality(const String& qualityString) +{ + if (qualityString == "low") { + m_imageSmoothingQuality = kLow_SkFilterQuality; + } else if (qualityString == "medium") { + m_imageSmoothingQuality = kMedium_SkFilterQuality; + } else if (qualityString == "high") { + m_imageSmoothingQuality = kHigh_SkFilterQuality; + } else { + return; + } + updateFilterQuality(); +} + +String CanvasRenderingContext2DState::imageSmoothingQuality() const +{ + switch (m_imageSmoothingQuality) { + case kLow_SkFilterQuality: + return "low"; + case kMedium_SkFilterQuality: + return "medium"; + case kHigh_SkFilterQuality: + return "high"; + default: + ASSERT_NOT_REACHED(); + return "low"; + } +} + +void CanvasRenderingContext2DState::updateFilterQuality() const +{ + if (!m_imageSmoothingEnabled) { + updateFilterQualityWithSkFilterQuality(kNone_SkFilterQuality); + } else { + updateFilterQualityWithSkFilterQuality(m_imageSmoothingQuality); + } +} + +void CanvasRenderingContext2DState::updateFilterQualityWithSkFilterQuality(const SkFilterQuality& filterQuality) const +{ m_strokePaint.setFilterQuality(filterQuality); m_fillPaint.setFilterQuality(filterQuality); m_imagePaint.setFilterQuality(filterQuality); } -bool CanvasRenderingContext2DState::imageSmoothingEnabled() const -{ - return m_imagePaint.getFilterQuality() == kLow_SkFilterQuality; -} bool CanvasRenderingContext2DState::shouldDrawShadows() const {
diff --git a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DState.h b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DState.h index 5c5f8ef..6073c20 100644 --- a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DState.h +++ b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DState.h
@@ -140,6 +140,8 @@ void setImageSmoothingEnabled(bool); bool imageSmoothingEnabled() const; + void setImageSmoothingQuality(const String&); + String imageSmoothingQuality() const; void setUnparsedStrokeColor(const String& color) { m_unparsedStrokeColor = color; } const String& unparsedStrokeColor() const { return m_unparsedStrokeColor; } @@ -165,6 +167,8 @@ void updateLineDash() const; void updateStrokeStyle() const; void updateFillStyle() const; + void updateFilterQuality() const; + void updateFilterQualityWithSkFilterQuality(const SkFilterQuality&) const; void shadowParameterChanged(); SkDrawLooper* emptyDrawLooper() const; SkDrawLooper* shadowOnlyDrawLooper() const; @@ -217,6 +221,9 @@ mutable bool m_strokeStyleDirty : 1; mutable bool m_lineDashDirty : 1; + bool m_imageSmoothingEnabled; + SkFilterQuality m_imageSmoothingQuality; + ClipList m_clipList; };
diff --git a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp index 5dcfc465..bd0e611 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp +++ b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp
@@ -4390,7 +4390,7 @@ if (!canvas->is3D()) { ImageBuffer* buffer = canvas->buffer(); - if (!buffer->copyToPlatformTexture(webContext(), GL_TEXTURE_2D, targetTexture, targetInternalformat, targetType, + if (!buffer->copyToPlatformTexture(webContext(), targetTexture, targetInternalformat, targetType, targetLevel, m_unpackPremultiplyAlpha, m_unpackFlipY)) { ASSERT_NOT_REACHED(); } @@ -4422,51 +4422,6 @@ } } -bool WebGLRenderingContextBase::texImage2DVideoByGPU(TexImageFunctionType functionType, WebGLTexture* texture, GLenum target, - GLint level, GLenum internalformat, GLenum type, GLint xoffset, GLint yoffset, HTMLVideoElement* video) -{ - typedef WebMediaPlayer::CopyVideoTextureParams CopyParams; - if (video->copyVideoTextureToPlatformTexture(webContext(), - CopyParams( - functionType == NotTexSubImage2D ? CopyParams::FullCopy : CopyParams::SubCopy, - target, texture->object(), internalformat, type, level, xoffset, - yoffset, m_unpackPremultiplyAlpha, m_unpackFlipY))) { - if (functionType == NotTexSubImage2D) - texture->setLevelInfo(target, level, internalformat, video->videoWidth(), video->videoHeight(), 1, type); - return true; - } - - // Try using an accelerated image buffer, this allows YUV conversion to be done on the GPU. - OwnPtr<ImageBufferSurface> surface = adoptPtr(new AcceleratedImageBufferSurface(IntSize(video->videoWidth(), video->videoHeight()))); - if (surface->isValid()) { - OwnPtr<ImageBuffer> imageBuffer(ImageBuffer::create(surface.release())); - if (imageBuffer) { - // The video element paints an RGBA frame into our surface here. By using an AcceleratedImageBufferSurface, - // we enable the WebMediaPlayer implementation to do any necessary color space conversion on the GPU (though it - // may still do a CPU conversion and upload the results). - video->paintCurrentFrame(imageBuffer->canvas(), IntRect(0, 0, video->videoWidth(), video->videoHeight()), nullptr); - - // This is a straight GPU-GPU copy, any necessary color space conversion was handled in the paintCurrentFrameInContext() call. - switch (functionType) { - case NotTexSubImage2D: - if (imageBuffer->copyToPlatformTexture(webContext(), target, texture->object(), internalformat, type, - level, m_unpackPremultiplyAlpha, m_unpackFlipY)) { - texture->setLevelInfo(target, level, internalformat, video->videoWidth(), video->videoHeight(), 1, type); - return true; - } - break; - case TexSubImage2D: - if (imageBuffer->copySubToPlatformTexture(webContext(), target, texture->object(), level, - xoffset, yoffset, video->videoWidth(), video->videoHeight(), m_unpackPremultiplyAlpha, m_unpackFlipY)) { - return true; - } - break; - } - } - } - return false; -} - void WebGLRenderingContextBase::texImage2D(GLenum target, GLint level, GLenum internalformat, GLenum format, GLenum type, HTMLCanvasElement* canvas, ExceptionState& exceptionState) { @@ -4513,9 +4468,31 @@ // Otherwise, it will fall back to the normal SW path. WebGLTexture* texture = validateTextureBinding("texImage2D", target, true); ASSERT(texture); - if (Extensions3DUtil::canUseCopyTextureCHROMIUM(target, internalformat, type, level)) { - if (texImage2DVideoByGPU(NotTexSubImage2D, texture, target, level, internalformat, type, 0, 0, video)) + if (GL_TEXTURE_2D == target) { + if (Extensions3DUtil::canUseCopyTextureCHROMIUM(target, internalformat, type, level) + && video->copyVideoTextureToPlatformTexture(webContext(), texture->object(), internalformat, type, m_unpackPremultiplyAlpha, m_unpackFlipY)) { + texture->setLevelInfo(target, level, internalformat, video->videoWidth(), video->videoHeight(), 1, type); return; + } + + // Try using an accelerated image buffer, this allows YUV conversion to be done on the GPU. + OwnPtr<ImageBufferSurface> surface = adoptPtr(new AcceleratedImageBufferSurface(IntSize(video->videoWidth(), video->videoHeight()))); + if (surface->isValid()) { + OwnPtr<ImageBuffer> imageBuffer(ImageBuffer::create(surface.release())); + if (imageBuffer) { + // The video element paints an RGBA frame into our surface here. By using an AcceleratedImageBufferSurface, + // we enable the WebMediaPlayer implementation to do any necessary color space conversion on the GPU (though it + // may still do a CPU conversion and upload the results). + video->paintCurrentFrame(imageBuffer->canvas(), IntRect(0, 0, video->videoWidth(), video->videoHeight()), nullptr); + + // This is a straight GPU-GPU copy, any necessary color space conversion was handled in the paintCurrentFrameInContext() call. + if (imageBuffer->copyToPlatformTexture(webContext(), texture->object(), internalformat, type, + level, m_unpackPremultiplyAlpha, m_unpackFlipY)) { + texture->setLevelInfo(target, level, internalformat, video->videoWidth(), video->videoHeight(), 1, type); + return; + } + } + } } // Normal pure SW path. @@ -4731,16 +4708,6 @@ || !validateTexFunc("texSubImage2D", TexSubImage2D, SourceHTMLVideoElement, target, level, 0, video->videoWidth(), video->videoHeight(), 0, format, type, xoffset, yoffset)) return; - // Go through the fast path doing a GPU-GPU textures copy without a readback to system memory if possible. - // Otherwise, it will fall back to the normal SW path. - WebGLTexture* texture = validateTextureBinding("texSubImage2D", target, true); - ASSERT(texture); - if (Extensions3DUtil::canUseCopyTextureCHROMIUM(target, GL_RGBA, type, level)) { - if (texImage2DVideoByGPU(TexSubImage2D, texture, target, level, GL_FALSE, - GL_FALSE, xoffset, yoffset, video)) - return; - } - RefPtr<Image> image = videoFrameToImage(video); if (!image) return;
diff --git a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.h b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.h index 55ae7629..a5fb75a 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.h +++ b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.h
@@ -840,9 +840,6 @@ GLenum internalformat, GLenum type, GLint xoffset, GLint yoffset, GLint zoffset, HTMLCanvasElement*); bool canUseTexImageCanvasByGPU(GLenum internalformat, GLenum type); - bool texImage2DVideoByGPU(TexImageFunctionType, WebGLTexture*, GLenum target, GLint level, - GLenum internalformat, GLenum type, GLint xoffset, GLint yoffset, HTMLVideoElement*); - void handleTextureCompleteness(const char*, bool); void createFallbackBlackTextures1x1();
diff --git a/third_party/WebKit/Source/platform/BUILD.gn b/third_party/WebKit/Source/platform/BUILD.gn index f041e51..d904269 100644 --- a/third_party/WebKit/Source/platform/BUILD.gn +++ b/third_party/WebKit/Source/platform/BUILD.gn
@@ -220,8 +220,8 @@ # Uses KillRingMac.mm instead. "KillRingNone.cpp", "fonts/skia/FontCacheSkia.cpp", - "scroll/ScrollAnimatorNone.cpp", - "scroll/ScrollAnimatorNone.h", + "scroll/ScrollAnimator.cpp", + "scroll/ScrollAnimator.h", # Mac uses only ScrollAnimatorMac. "scroll/ScrollbarThemeNonMacCommon.cpp",
diff --git a/third_party/WebKit/Source/platform/blink_platform.gyp b/third_party/WebKit/Source/platform/blink_platform.gyp index 395079e..701bded1d 100644 --- a/third_party/WebKit/Source/platform/blink_platform.gyp +++ b/third_party/WebKit/Source/platform/blink_platform.gyp
@@ -322,8 +322,8 @@ # Mac uses only ScrollAnimatorMac. ['exclude', 'scroll/ScrollbarThemeNonMacCommon\\.(cpp|h)$'], - ['exclude', 'scroll/ScrollAnimatorNone\\.cpp$'], - ['exclude', 'scroll/ScrollAnimatorNone\\.h$'], + ['exclude', 'scroll/ScrollAnimator\\.cpp$'], + ['exclude', 'scroll/ScrollAnimator\\.h$'], ['exclude', 'fonts/skia/FontCacheSkia\\.cpp$'],
diff --git a/third_party/WebKit/Source/platform/blink_platform.gypi b/third_party/WebKit/Source/platform/blink_platform.gypi index 037557c..6b9c357a 100644 --- a/third_party/WebKit/Source/platform/blink_platform.gypi +++ b/third_party/WebKit/Source/platform/blink_platform.gypi
@@ -819,10 +819,10 @@ 'scheduler/CancellableTaskFactory.h', 'scroll/ProgrammaticScrollAnimator.cpp', 'scroll/ProgrammaticScrollAnimator.h', + 'scroll/ScrollAnimatorBase.cpp', + 'scroll/ScrollAnimatorBase.h', 'scroll/ScrollAnimator.cpp', 'scroll/ScrollAnimator.h', - 'scroll/ScrollAnimatorNone.cpp', - 'scroll/ScrollAnimatorNone.h', 'scroll/ScrollTypes.h', 'scroll/ScrollableArea.cpp', 'scroll/ScrollableArea.h',
diff --git a/third_party/WebKit/Source/platform/fonts/ScriptRunIteratorTest.cpp b/third_party/WebKit/Source/platform/fonts/ScriptRunIteratorTest.cpp index eb92ed6..9cb7b56f 100644 --- a/third_party/WebKit/Source/platform/fonts/ScriptRunIteratorTest.cpp +++ b/third_party/WebKit/Source/platform/fonts/ScriptRunIteratorTest.cpp
@@ -728,7 +728,14 @@ CHECK_RUNS({ { "ç̈", USCRIPT_LATIN } }); } +TEST_F(ScriptRunIteratorTest, CommonMalayalam) +{ + CHECK_RUNS({ { "100-ാം", USCRIPT_MALAYALAM } }); +} + + class ScriptRunIteratorICUDataTest : public testing::Test { + public: ScriptRunIteratorICUDataTest() : m_maxExtensions(0)
diff --git a/third_party/WebKit/Source/platform/graphics/ImageBuffer.cpp b/third_party/WebKit/Source/platform/graphics/ImageBuffer.cpp index 042495b..51465ee0 100644 --- a/third_party/WebKit/Source/platform/graphics/ImageBuffer.cpp +++ b/third_party/WebKit/Source/platform/graphics/ImageBuffer.cpp
@@ -178,25 +178,9 @@ return m_surface->layer(); } -bool ImageBuffer::copyToPlatformTexture(WebGraphicsContext3D* context, GLenum target, Platform3DObject texture, - GLenum internalFormat, GLenum destType, GLint level, bool premultiplyAlpha, bool flipY) +bool ImageBuffer::copyToPlatformTexture(WebGraphicsContext3D* context, Platform3DObject texture, GLenum internalFormat, GLenum destType, GLint level, bool premultiplyAlpha, bool flipY) { - return copyToPlatformTextureInternal(true, context, target, texture, internalFormat, - destType, level, 0, 0, 0, 0, premultiplyAlpha, flipY); -} - -bool ImageBuffer::copySubToPlatformTexture(WebGraphicsContext3D* context, GLenum target, Platform3DObject texture, - GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, bool premultiplyAlpha, bool flipY) -{ - return copyToPlatformTextureInternal(false, context, target, texture, GL_FALSE, GL_FALSE, level, - xoffset, yoffset, width, height, premultiplyAlpha, flipY); -} - -bool ImageBuffer::copyToPlatformTextureInternal(bool isFullCopy, WebGraphicsContext3D* context, GLenum target, - Platform3DObject texture, GLenum internalFormat, GLenum destType, GLint level, GLint xoffset, GLint yoffset, - GLsizei width, GLsizei height, bool premultiplyAlpha, bool flipY) -{ - if (!Extensions3DUtil::canUseCopyTextureCHROMIUM(target, internalFormat, destType, level)) + if (!Extensions3DUtil::canUseCopyTextureCHROMIUM(GL_TEXTURE_2D, internalFormat, destType, level)) return false; if (!isSurfaceValid()) @@ -235,16 +219,9 @@ context->waitSyncPoint(mailbox->syncPoint); Platform3DObject sourceTexture = context->createAndConsumeTextureCHROMIUM(GL_TEXTURE_2D, mailbox->name); - WGC3Dboolean glFlipY = flipY ? GL_FALSE : GL_TRUE; - WGC3Dboolean glPremultiplyAlpha = premultiplyAlpha ? GL_FALSE : GL_TRUE; - // The canvas is stored in a premultiplied format, so unpremultiply if necessary. // The canvas is stored in an inverted position, so the flip semantics are reversed. - if (isFullCopy) { - context->copyTextureCHROMIUM(target, sourceTexture, texture, internalFormat, destType, glFlipY, GL_FALSE, glPremultiplyAlpha); - } else { - context->copySubTextureCHROMIUM(target, sourceTexture, texture, xoffset, yoffset, 0, 0, width, height, glFlipY, GL_FALSE, glPremultiplyAlpha); - } + context->copyTextureCHROMIUM(GL_TEXTURE_2D, sourceTexture, texture, internalFormat, destType, flipY ? GL_FALSE : GL_TRUE, GL_FALSE, premultiplyAlpha ? GL_FALSE : GL_TRUE); context->deleteTexture(sourceTexture);
diff --git a/third_party/WebKit/Source/platform/graphics/ImageBuffer.h b/third_party/WebKit/Source/platform/graphics/ImageBuffer.h index 651e8c9..d41b5b9 100644 --- a/third_party/WebKit/Source/platform/graphics/ImageBuffer.h +++ b/third_party/WebKit/Source/platform/graphics/ImageBuffer.h
@@ -122,9 +122,7 @@ // with textures that are RGB or RGBA format, UNSIGNED_BYTE type and level 0, as specified in // Extensions3D::canUseCopyTextureCHROMIUM(). // Destroys the TEXTURE_2D binding for the active texture unit of the passed context - bool copyToPlatformTexture(WebGraphicsContext3D*, GLenum, Platform3DObject, GLenum, GLenum, GLint, bool, bool); - bool copySubToPlatformTexture(WebGraphicsContext3D*, GLenum, Platform3DObject, GLint, GLint xoffset, - GLint yoffset, GLsizei width, GLsizei height, bool, bool); + bool copyToPlatformTexture(WebGraphicsContext3D*, Platform3DObject, GLenum, GLenum, GLint, bool, bool); bool copyRenderingResultsFromDrawingBuffer(DrawingBuffer*, SourceDrawingBuffer); @@ -150,10 +148,6 @@ DrawnToAfterSnapshot, }; mutable SnapshotState m_snapshotState; - - bool copyToPlatformTextureInternal(bool isFullCopy, WebGraphicsContext3D*, GLenum, Platform3DObject, GLenum, GLenum, - GLint, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, bool, bool); - OwnPtr<ImageBufferSurface> m_surface; ImageBufferClient* m_client; };
diff --git a/third_party/WebKit/Source/platform/graphics/gpu/Extensions3DUtil.cpp b/third_party/WebKit/Source/platform/graphics/gpu/Extensions3DUtil.cpp index e63df142..950b8fa5 100644 --- a/third_party/WebKit/Source/platform/graphics/gpu/Extensions3DUtil.cpp +++ b/third_party/WebKit/Source/platform/graphics/gpu/Extensions3DUtil.cpp
@@ -83,24 +83,9 @@ bool Extensions3DUtil::canUseCopyTextureCHROMIUM(GLenum destTarget, GLenum destFormat, GLenum destType, GLint level) { - switch (destTarget) { - case GL_TEXTURE_2D: - break; - // TODO(dshwang): support cube map. crbug.com/517548 - case GL_TEXTURE_CUBE_MAP_POSITIVE_X: - case GL_TEXTURE_CUBE_MAP_NEGATIVE_X: - case GL_TEXTURE_CUBE_MAP_POSITIVE_Y: - case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y: - case GL_TEXTURE_CUBE_MAP_POSITIVE_Z: - case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z: - return false; - default: - ASSERT_NOT_REACHED(); - return false; - } - // TODO(dshwang): restriction of (RGB || RGBA)/UNSIGNED_BYTE/(Level 0) should be lifted when + // FIXME: restriction of (RGB || RGBA)/UNSIGNED_BYTE/(Level 0) should be lifted when // WebGraphicsContext3D::copyTextureCHROMIUM(...) are fully functional. - if ((destFormat == GL_RGB || destFormat == GL_RGBA) + if (destTarget == GL_TEXTURE_2D && (destFormat == GL_RGB || destFormat == GL_RGBA) && destType == GL_UNSIGNED_BYTE && !level) return true;
diff --git a/third_party/WebKit/Source/platform/graphics/paint/PaintController.cpp b/third_party/WebKit/Source/platform/graphics/paint/PaintController.cpp index fc2e069..51bbe10 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/PaintController.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/PaintController.cpp
@@ -124,7 +124,9 @@ void PaintController::invalidateClient(const DisplayItemClientWrapper& client) { #if ENABLE(ASSERT) - m_invalidations.append(client.debugName()); + // Slimming paint v1 CompositedLayerMapping may invalidate client on extra layers. + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled() || clientCacheIsValid(client.displayItemClient())) + m_invalidations.append(client.debugName()); #endif invalidateUntracked(client.displayItemClient());
diff --git a/third_party/WebKit/Source/platform/mac/ScrollAnimatorMac.h b/third_party/WebKit/Source/platform/mac/ScrollAnimatorMac.h index 997b548..e324f1b 100644 --- a/third_party/WebKit/Source/platform/mac/ScrollAnimatorMac.h +++ b/third_party/WebKit/Source/platform/mac/ScrollAnimatorMac.h
@@ -30,7 +30,7 @@ #include "platform/geometry/FloatPoint.h" #include "platform/geometry/FloatSize.h" #include "platform/geometry/IntRect.h" -#include "platform/scroll/ScrollAnimator.h" +#include "platform/scroll/ScrollAnimatorBase.h" #include "wtf/RetainPtr.h" OBJC_CLASS WebScrollAnimationHelperDelegate; @@ -43,7 +43,7 @@ class Scrollbar; -class PLATFORM_EXPORT ScrollAnimatorMac : public ScrollAnimator { +class PLATFORM_EXPORT ScrollAnimatorMac : public ScrollAnimatorBase { public: ScrollAnimatorMac(ScrollableArea*);
diff --git a/third_party/WebKit/Source/platform/mac/ScrollAnimatorMac.mm b/third_party/WebKit/Source/platform/mac/ScrollAnimatorMac.mm index 287279d..5ff50a382 100644 --- a/third_party/WebKit/Source/platform/mac/ScrollAnimatorMac.mm +++ b/third_party/WebKit/Source/platform/mac/ScrollAnimatorMac.mm
@@ -659,13 +659,13 @@ namespace blink { -PassOwnPtr<ScrollAnimator> ScrollAnimator::create(ScrollableArea* scrollableArea) +PassOwnPtr<ScrollAnimatorBase> ScrollAnimatorBase::create(ScrollableArea* scrollableArea) { return adoptPtr(new ScrollAnimatorMac(scrollableArea)); } ScrollAnimatorMac::ScrollAnimatorMac(ScrollableArea* scrollableArea) - : ScrollAnimator(scrollableArea) + : ScrollAnimatorBase(scrollableArea) , m_initialScrollbarPaintTimer(this, &ScrollAnimatorMac::initialScrollbarPaintTimerFired) , m_sendContentAreaScrolledTimer(this, &ScrollAnimatorMac::sendContentAreaScrolledTimerFired) , m_haveScrolledSincePageLoad(false) @@ -703,10 +703,10 @@ m_haveScrolledSincePageLoad = true; if (!scrollAnimationEnabledForSystem || !m_scrollableArea->scrollAnimatorEnabled()) - return ScrollAnimator::userScroll(orientation, granularity, step, delta); + return ScrollAnimatorBase::userScroll(orientation, granularity, step, delta); if (granularity == ScrollByPixel || granularity == ScrollByPrecisePixel) - return ScrollAnimator::userScroll(orientation, granularity, step, delta); + return ScrollAnimatorBase::userScroll(orientation, granularity, step, delta); float currentPos = orientation == HorizontalScrollbar ? m_currentPosX : m_currentPosY; float newPos = std::max<float>(std::min<float>(currentPos + (step * delta), m_scrollableArea->maximumScrollPosition(orientation)), m_scrollableArea->minimumScrollPosition(orientation));
diff --git a/third_party/WebKit/Source/platform/network/ContentSecurityPolicyParsers.cpp b/third_party/WebKit/Source/platform/network/ContentSecurityPolicyParsers.cpp index 52c991e..fd334ec 100644 --- a/third_party/WebKit/Source/platform/network/ContentSecurityPolicyParsers.cpp +++ b/third_party/WebKit/Source/platform/network/ContentSecurityPolicyParsers.cpp
@@ -67,9 +67,4 @@ return !isASCIISpace(c) && c != '/'; } -WTF::StringUTF8Adaptor normalizeSource(const String& source) -{ - return WTF::StringUTF8Adaptor(source, WTF::StringUTF8Adaptor::Normalize, WTF::EntitiesForUnencodables); -} - } // namespace
diff --git a/third_party/WebKit/Source/platform/network/ContentSecurityPolicyParsers.h b/third_party/WebKit/Source/platform/network/ContentSecurityPolicyParsers.h index 9538d80..3784603 100644 --- a/third_party/WebKit/Source/platform/network/ContentSecurityPolicyParsers.h +++ b/third_party/WebKit/Source/platform/network/ContentSecurityPolicyParsers.h
@@ -52,9 +52,6 @@ // positional and may only appear at the end of a Base64 encoded string. PLATFORM_EXPORT bool isBase64EncodedCharacter(UChar); -// Normalize script or style source for script hash use. -PLATFORM_EXPORT WTF::StringUTF8Adaptor normalizeSource(const String& source); - } // namespace blink #endif
diff --git a/third_party/WebKit/Source/platform/scroll/ScrollAnimator.cpp b/third_party/WebKit/Source/platform/scroll/ScrollAnimator.cpp index 75cdc5a..dc8b043 100644 --- a/third_party/WebKit/Source/platform/scroll/ScrollAnimator.cpp +++ b/third_party/WebKit/Source/platform/scroll/ScrollAnimator.cpp
@@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, Google Inc. All rights reserved. + * Copyright (c) 2011, 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 @@ -31,68 +31,504 @@ #include "config.h" #include "platform/scroll/ScrollAnimator.h" -#include "platform/RuntimeEnabledFeatures.h" -#include "platform/geometry/FloatPoint.h" +#include "platform/TraceEvent.h" #include "platform/scroll/ScrollableArea.h" -#include "wtf/PassOwnPtr.h" +#include "wtf/CurrentTime.h" +#include "wtf/PassRefPtr.h" #include <algorithm> namespace blink { +const double kFrameRate = 60; +const double kTickTime = 1 / kFrameRate; +const double kMinimumTimerInterval = .001; + +PassOwnPtr<ScrollAnimatorBase> ScrollAnimatorBase::create(ScrollableArea* scrollableArea) +{ + if (scrollableArea && scrollableArea->scrollAnimatorEnabled()) + return adoptPtr(new ScrollAnimator(scrollableArea)); + return adoptPtr(new ScrollAnimatorBase(scrollableArea)); +} + +ScrollAnimator::Parameters::Parameters() + : m_isEnabled(false) +{ +} + +ScrollAnimator::Parameters::Parameters(bool isEnabled, double animationTime, double repeatMinimumSustainTime, Curve attackCurve, double attackTime, Curve releaseCurve, double releaseTime, Curve coastTimeCurve, double maximumCoastTime) + : m_isEnabled(isEnabled) + , m_animationTime(animationTime) + , m_repeatMinimumSustainTime(repeatMinimumSustainTime) + , m_attackCurve(attackCurve) + , m_attackTime(attackTime) + , m_releaseCurve(releaseCurve) + , m_releaseTime(releaseTime) + , m_coastTimeCurve(coastTimeCurve) + , m_maximumCoastTime(maximumCoastTime) +{ +} + +double ScrollAnimator::PerAxisData::curveAt(Curve curve, double t) +{ + switch (curve) { + case Linear: + return t; + case Quadratic: + return t * t; + case Cubic: + return t * t * t; + case Quartic: + return t * t * t * t; + case Bounce: + // Time base is chosen to keep the bounce points simpler: + // 1 (half bounce coming in) + 1 + .5 + .25 + const double kTimeBase = 2.75; + const double kTimeBaseSquared = kTimeBase * kTimeBase; + if (t < 1 / kTimeBase) + return kTimeBaseSquared * t * t; + if (t < 2 / kTimeBase) { + // Invert a [-.5,.5] quadratic parabola, center it in [1,2]. + double t1 = t - 1.5 / kTimeBase; + const double kParabolaAtEdge = 1 - .5 * .5; + return kTimeBaseSquared * t1 * t1 + kParabolaAtEdge; + } + if (t < 2.5 / kTimeBase) { + // Invert a [-.25,.25] quadratic parabola, center it in [2,2.5]. + double t2 = t - 2.25 / kTimeBase; + const double kParabolaAtEdge = 1 - .25 * .25; + return kTimeBaseSquared * t2 * t2 + kParabolaAtEdge; + } + // Invert a [-.125,.125] quadratic parabola, center it in [2.5,2.75]. + const double kParabolaAtEdge = 1 - .125 * .125; + t -= 2.625 / kTimeBase; + return kTimeBaseSquared * t * t + kParabolaAtEdge; + } + ASSERT_NOT_REACHED(); + return 0; +} + +double ScrollAnimator::PerAxisData::attackCurve(Curve curve, double deltaTime, double curveT, double startPosition, double attackPosition) +{ + double t = deltaTime / curveT; + double positionFactor = curveAt(curve, t); + return startPosition + positionFactor * (attackPosition - startPosition); +} + +double ScrollAnimator::PerAxisData::releaseCurve(Curve curve, double deltaTime, double curveT, double releasePosition, double desiredPosition) +{ + double t = deltaTime / curveT; + double positionFactor = 1 - curveAt(curve, 1 - t); + return releasePosition + (positionFactor * (desiredPosition - releasePosition)); +} + +double ScrollAnimator::PerAxisData::coastCurve(Curve curve, double factor) +{ + return 1 - curveAt(curve, 1 - factor); +} + +double ScrollAnimator::PerAxisData::curveIntegralAt(Curve curve, double t) +{ + switch (curve) { + case Linear: + return t * t / 2; + case Quadratic: + return t * t * t / 3; + case Cubic: + return t * t * t * t / 4; + case Quartic: + return t * t * t * t * t / 5; + case Bounce: + const double kTimeBase = 2.75; + const double kTimeBaseSquared = kTimeBase * kTimeBase; + const double kTimeBaseSquaredOverThree = kTimeBaseSquared / 3; + double area; + double t1 = std::min(t, 1 / kTimeBase); + area = kTimeBaseSquaredOverThree * t1 * t1 * t1; + if (t < 1 / kTimeBase) + return area; + + t1 = std::min(t - 1 / kTimeBase, 1 / kTimeBase); + // The integral of kTimeBaseSquared * (t1 - .5 / kTimeBase) * (t1 - .5 / kTimeBase) + kParabolaAtEdge + const double kSecondInnerOffset = kTimeBaseSquared * .5 / kTimeBase; + double bounceArea = t1 * (t1 * (kTimeBaseSquaredOverThree * t1 - kSecondInnerOffset) + 1); + area += bounceArea; + if (t < 2 / kTimeBase) + return area; + + t1 = std::min(t - 2 / kTimeBase, 0.5 / kTimeBase); + // The integral of kTimeBaseSquared * (t1 - .25 / kTimeBase) * (t1 - .25 / kTimeBase) + kParabolaAtEdge + const double kThirdInnerOffset = kTimeBaseSquared * .25 / kTimeBase; + bounceArea = t1 * (t1 * (kTimeBaseSquaredOverThree * t1 - kThirdInnerOffset) + 1); + area += bounceArea; + if (t < 2.5 / kTimeBase) + return area; + + t1 = t - 2.5 / kTimeBase; + // The integral of kTimeBaseSquared * (t1 - .125 / kTimeBase) * (t1 - .125 / kTimeBase) + kParabolaAtEdge + const double kFourthInnerOffset = kTimeBaseSquared * .125 / kTimeBase; + bounceArea = t1 * (t1 * (kTimeBaseSquaredOverThree * t1 - kFourthInnerOffset) + 1); + area += bounceArea; + return area; + } + ASSERT_NOT_REACHED(); + return 0; +} + +double ScrollAnimator::PerAxisData::attackArea(Curve curve, double startT, double endT) +{ + double startValue = curveIntegralAt(curve, startT); + double endValue = curveIntegralAt(curve, endT); + return endValue - startValue; +} + +double ScrollAnimator::PerAxisData::releaseArea(Curve curve, double startT, double endT) +{ + double startValue = curveIntegralAt(curve, 1 - endT); + double endValue = curveIntegralAt(curve, 1 - startT); + return endValue - startValue; +} + +ScrollAnimator::PerAxisData::PerAxisData(float* currentPosition, int visibleLength) + : m_currentPosition(currentPosition) + , m_visibleLength(visibleLength) +{ + reset(); +} + +void ScrollAnimator::PerAxisData::reset() +{ + m_currentVelocity = 0; + + m_desiredPosition = 0; + m_desiredVelocity = 0; + + m_startPosition = 0; + m_startTime = 0; + m_startVelocity = 0; + + m_animationTime = 0; + m_lastAnimationTime = 0; + + m_attackPosition = 0; + m_attackTime = 0; + m_attackCurve = Quadratic; + + m_releasePosition = 0; + m_releaseTime = 0; + m_releaseCurve = Quadratic; +} + + +bool ScrollAnimator::PerAxisData::updateDataFromParameters(float step, float delta, float scrollableSize, double currentTime, Parameters* parameters) +{ + float pixelDelta = step * delta; + if (!m_startTime || !pixelDelta || (pixelDelta < 0) != (m_desiredPosition - *m_currentPosition < 0)) { + m_desiredPosition = *m_currentPosition; + m_startTime = 0; + } + float newPosition = m_desiredPosition + pixelDelta; + + if (newPosition < 0 || newPosition > scrollableSize) + newPosition = std::max(std::min(newPosition, scrollableSize), 0.0f); + + if (newPosition == m_desiredPosition) + return false; + + m_desiredPosition = newPosition; + + if (!m_startTime) { + m_attackTime = parameters->m_attackTime; + m_attackCurve = parameters->m_attackCurve; + } + m_animationTime = parameters->m_animationTime; + m_releaseTime = parameters->m_releaseTime; + m_releaseCurve = parameters->m_releaseCurve; + + // Prioritize our way out of over constraint. + if (m_attackTime + m_releaseTime > m_animationTime) { + if (m_releaseTime > m_animationTime) + m_releaseTime = m_animationTime; + m_attackTime = m_animationTime - m_releaseTime; + } + + if (!m_startTime) { + // FIXME: This should be the time from the event that got us here. + m_startTime = currentTime - kTickTime / 2; + m_startPosition = *m_currentPosition; + m_lastAnimationTime = m_startTime; + } + m_startVelocity = m_currentVelocity; + + double remainingDelta = m_desiredPosition - *m_currentPosition; + + double attackAreaLeft = 0; + + double deltaTime = m_lastAnimationTime - m_startTime; + double attackTimeLeft = std::max(0., m_attackTime - deltaTime); + double timeLeft = m_animationTime - deltaTime; + double minTimeLeft = m_releaseTime + std::min(parameters->m_repeatMinimumSustainTime, m_animationTime - m_releaseTime - attackTimeLeft); + if (timeLeft < minTimeLeft) { + m_animationTime = deltaTime + minTimeLeft; + timeLeft = minTimeLeft; + } + + if (parameters->m_maximumCoastTime > (parameters->m_repeatMinimumSustainTime + parameters->m_releaseTime)) { + double targetMaxCoastVelocity = m_visibleLength * .25 * kFrameRate; + // This needs to be as minimal as possible while not being intrusive to page up/down. + double minCoastDelta = m_visibleLength; + + if (fabs(remainingDelta) > minCoastDelta) { + double maxCoastDelta = parameters->m_maximumCoastTime * targetMaxCoastVelocity; + double coastFactor = std::min(1., (fabs(remainingDelta) - minCoastDelta) / (maxCoastDelta - minCoastDelta)); + + // We could play with the curve here - linear seems a little soft. Initial testing makes me want to feed into the sustain time more aggressively. + double coastMinTimeLeft = std::min(parameters->m_maximumCoastTime, minTimeLeft + coastCurve(parameters->m_coastTimeCurve, coastFactor) * (parameters->m_maximumCoastTime - minTimeLeft)); + + double additionalTime = std::max(0., coastMinTimeLeft - minTimeLeft); + if (additionalTime) { + double additionalReleaseTime = std::min(additionalTime, parameters->m_releaseTime / (parameters->m_releaseTime + parameters->m_repeatMinimumSustainTime) * additionalTime); + m_releaseTime = parameters->m_releaseTime + additionalReleaseTime; + m_animationTime = deltaTime + coastMinTimeLeft; + timeLeft = coastMinTimeLeft; + } + } + } + + double releaseTimeLeft = std::min(timeLeft, m_releaseTime); + double sustainTimeLeft = std::max(0., timeLeft - releaseTimeLeft - attackTimeLeft); + + if (attackTimeLeft) { + double attackSpot = deltaTime / m_attackTime; + attackAreaLeft = attackArea(m_attackCurve, attackSpot, 1) * m_attackTime; + } + + double releaseSpot = (m_releaseTime - releaseTimeLeft) / m_releaseTime; + double releaseAreaLeft = releaseArea(m_releaseCurve, releaseSpot, 1) * m_releaseTime; + + m_desiredVelocity = remainingDelta / (attackAreaLeft + sustainTimeLeft + releaseAreaLeft); + m_releasePosition = m_desiredPosition - m_desiredVelocity * releaseAreaLeft; + if (attackAreaLeft) + m_attackPosition = m_startPosition + m_desiredVelocity * attackAreaLeft; + else + m_attackPosition = m_releasePosition - (m_animationTime - m_releaseTime - m_attackTime) * m_desiredVelocity; + + if (sustainTimeLeft) { + double roundOff = m_releasePosition - ((attackAreaLeft ? m_attackPosition : *m_currentPosition) + m_desiredVelocity * sustainTimeLeft); + m_desiredVelocity += roundOff / sustainTimeLeft; + } + + return true; +} + +inline double ScrollAnimator::PerAxisData::newScrollAnimationPosition(double deltaTime) +{ + if (deltaTime < m_attackTime) + return attackCurve(m_attackCurve, deltaTime, m_attackTime, m_startPosition, m_attackPosition); + if (deltaTime < (m_animationTime - m_releaseTime)) + return m_attackPosition + (deltaTime - m_attackTime) * m_desiredVelocity; + // release is based on targeting the exact final position. + double releaseDeltaT = deltaTime - (m_animationTime - m_releaseTime); + return releaseCurve(m_releaseCurve, releaseDeltaT, m_releaseTime, m_releasePosition, m_desiredPosition); +} + +// FIXME: Add in jank detection trace events into this function. +bool ScrollAnimator::PerAxisData::animateScroll(double currentTime) +{ + double lastScrollInterval = currentTime - m_lastAnimationTime; + if (lastScrollInterval < kMinimumTimerInterval) + return true; + + m_lastAnimationTime = currentTime; + + double deltaTime = currentTime - m_startTime; + + if (deltaTime > m_animationTime) { + *m_currentPosition = m_desiredPosition; + reset(); + return false; + } + double newPosition = newScrollAnimationPosition(deltaTime); + // Normalize velocity to a per second amount. Could be used to check for jank. + if (lastScrollInterval > 0) + m_currentVelocity = (newPosition - *m_currentPosition) / lastScrollInterval; + *m_currentPosition = newPosition; + + return true; +} + +void ScrollAnimator::PerAxisData::updateVisibleLength(int visibleLength) +{ + m_visibleLength = visibleLength; +} + ScrollAnimator::ScrollAnimator(ScrollableArea* scrollableArea) - : m_scrollableArea(scrollableArea) - , m_currentPosX(0) - , m_currentPosY(0) + : ScrollAnimatorBase(scrollableArea) + , m_horizontalData(&m_currentPosX, scrollableArea->visibleWidth()) + , m_verticalData(&m_currentPosY, scrollableArea->visibleHeight()) + , m_startTime(0) + , m_animationActive(false) { } ScrollAnimator::~ScrollAnimator() { + stopAnimationTimerIfNeeded(); } -ScrollResultOneDimensional ScrollAnimator::userScroll(ScrollbarOrientation orientation, ScrollGranularity, float step, float delta) +ScrollAnimator::Parameters ScrollAnimator::parametersForScrollGranularity(ScrollGranularity granularity) const { - float& currentPos = (orientation == HorizontalScrollbar) ? m_currentPosX : m_currentPosY; - float newPos = clampScrollPosition(orientation, currentPos + step * delta); - if (currentPos == newPos) - return ScrollResultOneDimensional(false, delta); + switch (granularity) { + case ScrollByDocument: + return Parameters(true, 20 * kTickTime, 10 * kTickTime, Cubic, 10 * kTickTime, Cubic, 10 * kTickTime, Linear, 1); + case ScrollByLine: + return Parameters(true, 10 * kTickTime, 7 * kTickTime, Cubic, 3 * kTickTime, Cubic, 3 * kTickTime, Linear, 1); + case ScrollByPage: + return Parameters(true, 15 * kTickTime, 10 * kTickTime, Cubic, 5 * kTickTime, Cubic, 5 * kTickTime, Linear, 1); + case ScrollByPixel: + return Parameters(true, 11 * kTickTime, 2 * kTickTime, Cubic, 3 * kTickTime, Cubic, 3 * kTickTime, Quadratic, 1.25); + default: + ASSERT_NOT_REACHED(); + } + return Parameters(); +} - float usedDelta = (newPos - currentPos) / step; - currentPos = newPos; +ScrollResultOneDimensional ScrollAnimator::userScroll(ScrollbarOrientation orientation, ScrollGranularity granularity, float step, float delta) +{ + if (!m_scrollableArea->scrollAnimatorEnabled()) + return ScrollAnimatorBase::userScroll(orientation, granularity, step, delta); - notifyPositionChanged(); + TRACE_EVENT0("blink", "ScrollAnimator::scroll"); - return ScrollResultOneDimensional(true, delta - usedDelta); + // FIXME: get the type passed in. MouseWheel could also be by line, but should still have different + // animation parameters than the keyboard. + Parameters parameters; + switch (granularity) { + case ScrollByDocument: + case ScrollByLine: + case ScrollByPage: + case ScrollByPixel: + parameters = parametersForScrollGranularity(granularity); + break; + case ScrollByPrecisePixel: + return ScrollAnimatorBase::userScroll(orientation, granularity, step, delta); + } + + // If the individual input setting is disabled, bail. + if (!parameters.m_isEnabled) + return ScrollAnimatorBase::userScroll(orientation, granularity, step, delta); + + // This is an animatable scroll. Set the animation in motion using the appropriate parameters. + float scrollableSize = static_cast<float>(m_scrollableArea->scrollSize(orientation)); + + PerAxisData& data = (orientation == VerticalScrollbar) ? m_verticalData : m_horizontalData; + bool needToScroll = data.updateDataFromParameters(step, delta, scrollableSize, WTF::monotonicallyIncreasingTime(), ¶meters); + float unusedDelta = needToScroll ? delta - (data.m_desiredPosition - *data.m_currentPosition) : delta; + if (needToScroll && !animationTimerActive()) { + m_startTime = data.m_startTime; + animationWillStart(); + animationTimerFired(); + scrollableArea()->registerForAnimation(); + } + return ScrollResultOneDimensional(needToScroll, unusedDelta); } void ScrollAnimator::scrollToOffsetWithoutAnimation(const FloatPoint& offset) { m_currentPosX = offset.x(); m_currentPosY = offset.y(); + + // Must be called after setting the position since canceling the animation resets + // the desired position to the current. + cancelAnimations(); notifyPositionChanged(); } -void ScrollAnimator::setCurrentPosition(const FloatPoint& position) +void ScrollAnimator::cancelAnimations() { - m_currentPosX = position.x(); - m_currentPosY = position.y(); + m_animationActive = false; + + m_horizontalData.reset(); + m_verticalData.reset(); + m_horizontalData.m_desiredPosition = m_currentPosX; + m_verticalData.m_desiredPosition = m_currentPosY; } -FloatPoint ScrollAnimator::currentPosition() const +void ScrollAnimator::serviceScrollAnimations() { - return FloatPoint(m_currentPosX, m_currentPosY); + if (m_animationActive) + animationTimerFired(); } -void ScrollAnimator::notifyPositionChanged() +bool ScrollAnimator::hasRunningAnimation() const { - m_scrollableArea->scrollPositionChanged(DoublePoint(m_currentPosX, m_currentPosY), UserScroll); + return m_animationActive; } -float ScrollAnimator::clampScrollPosition(ScrollbarOrientation orientation, float pos) +void ScrollAnimator::updateAfterLayout() { - float maxScrollPos = m_scrollableArea->maximumScrollPosition(orientation); - float minScrollPos = m_scrollableArea->minimumScrollPosition(orientation); - return std::max(std::min(pos, maxScrollPos), minScrollPos); + updateVisibleLengths(); +} + +void ScrollAnimator::willEndLiveResize() +{ + updateVisibleLengths(); +} + +void ScrollAnimator::didAddVerticalScrollbar(Scrollbar*) +{ + updateVisibleLengths(); +} + +void ScrollAnimator::didAddHorizontalScrollbar(Scrollbar*) +{ + updateVisibleLengths(); +} + +void ScrollAnimator::updateVisibleLengths() +{ + m_horizontalData.updateVisibleLength(scrollableArea()->visibleWidth()); + m_verticalData.updateVisibleLength(scrollableArea()->visibleHeight()); +} + +void ScrollAnimator::animationTimerFired() +{ + TRACE_EVENT0("blink", "ScrollAnimator::animationTimerFired"); + + double currentTime = WTF::monotonicallyIncreasingTime(); + + bool continueAnimation = false; + if (m_horizontalData.m_startTime && m_horizontalData.animateScroll(currentTime)) + continueAnimation = true; + if (m_verticalData.m_startTime && m_verticalData.animateScroll(currentTime)) + continueAnimation = true; + + if (continueAnimation) + startNextTimer(); + else + m_animationActive = false; + + TRACE_EVENT0("blink", "ScrollAnimator::notifyPositionChanged"); + notifyPositionChanged(); + + if (!continueAnimation) + animationDidFinish(); +} + +void ScrollAnimator::startNextTimer() +{ + if (scrollableArea()->scheduleAnimation()) + m_animationActive = true; +} + +bool ScrollAnimator::animationTimerActive() +{ + return m_animationActive; +} + +void ScrollAnimator::stopAnimationTimerIfNeeded() +{ + if (animationTimerActive()) + m_animationActive = false; } } // namespace blink
diff --git a/third_party/WebKit/Source/platform/scroll/ScrollAnimator.h b/third_party/WebKit/Source/platform/scroll/ScrollAnimator.h index dc603cd8..ed898006 100644 --- a/third_party/WebKit/Source/platform/scroll/ScrollAnimator.h +++ b/third_party/WebKit/Source/platform/scroll/ScrollAnimator.h
@@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, Google Inc. All rights reserved. + * Copyright (c) 2011, 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 @@ -31,84 +31,122 @@ #ifndef ScrollAnimator_h #define ScrollAnimator_h -#include "platform/PlatformExport.h" -#include "platform/PlatformWheelEvent.h" -#include "platform/geometry/FloatSize.h" -#include "platform/scroll/ScrollTypes.h" -#include "wtf/Forward.h" +#include "platform/Timer.h" +#include "platform/geometry/FloatPoint.h" +#include "platform/scroll/ScrollAnimatorBase.h" namespace blink { -class FloatPoint; -class ScrollableArea; -class Scrollbar; +class ScrollAnimatorTest; -class PLATFORM_EXPORT ScrollAnimator { +class PLATFORM_EXPORT ScrollAnimator : public ScrollAnimatorBase { public: - static PassOwnPtr<ScrollAnimator> create(ScrollableArea*); - - virtual ~ScrollAnimator(); - - // Computes a scroll destination for the given parameters. The returned - // ScrollResultOneDimensional will have didScroll set to false if already at - // the destination. Otherwise, starts scrolling towards the destination and - // didScroll is true. Scrolling may be immediate or animated. The base - // class implementation always scrolls immediately, never animates. - virtual ScrollResultOneDimensional userScroll(ScrollbarOrientation, ScrollGranularity, float step, float delta); - - virtual void scrollToOffsetWithoutAnimation(const FloatPoint&); - - ScrollableArea* scrollableArea() const { return m_scrollableArea; } - - virtual void setIsActive() { } - -#if OS(MACOSX) - virtual void handleWheelEventPhase(PlatformWheelEventPhase) { } -#endif - - void setCurrentPosition(const FloatPoint&); - FloatPoint currentPosition() const; - - virtual void cancelAnimations() { } - virtual void serviceScrollAnimations() { } - virtual bool hasRunningAnimation() const { return false; } - - virtual void contentAreaWillPaint() const { } - virtual void mouseEnteredContentArea() const { } - virtual void mouseExitedContentArea() const { } - virtual void mouseMovedInContentArea() const { } - virtual void mouseEnteredScrollbar(Scrollbar*) const { } - virtual void mouseExitedScrollbar(Scrollbar*) const { } - virtual void willStartLiveResize() { } - virtual void updateAfterLayout() { } - virtual void contentsResized() const { } - virtual void willEndLiveResize() { } - virtual void contentAreaDidShow() const { } - virtual void contentAreaDidHide() const { } - - virtual void finishCurrentScrollAnimations() { } - - virtual void didAddVerticalScrollbar(Scrollbar*) { } - virtual void willRemoveVerticalScrollbar(Scrollbar*) { } - virtual void didAddHorizontalScrollbar(Scrollbar*) { } - virtual void willRemoveHorizontalScrollbar(Scrollbar*) { } - - virtual bool shouldScrollbarParticipateInHitTesting(Scrollbar*) { return true; } - - virtual void notifyContentAreaScrolled(const FloatSize&) { } - - virtual bool setScrollbarsVisibleForTesting(bool) { return false; } -protected: explicit ScrollAnimator(ScrollableArea*); + ~ScrollAnimator() override; - virtual void notifyPositionChanged(); + ScrollResultOneDimensional userScroll(ScrollbarOrientation, ScrollGranularity, float step, float delta) override; + void scrollToOffsetWithoutAnimation(const FloatPoint&) override; - ScrollableArea* m_scrollableArea; - float m_currentPosX; // We avoid using a FloatPoint in order to reduce - float m_currentPosY; // subclass code complexity. + void cancelAnimations() override; + void serviceScrollAnimations() override; + bool hasRunningAnimation() const override; -private: - float clampScrollPosition(ScrollbarOrientation, float); + void updateAfterLayout() override; + void willEndLiveResize() override; + void didAddVerticalScrollbar(Scrollbar*) override; + void didAddHorizontalScrollbar(Scrollbar*) override; + + enum Curve { + Linear, + Quadratic, + Cubic, + Quartic, + Bounce + }; + + struct PLATFORM_EXPORT Parameters { + Parameters(); + Parameters(bool isEnabled, double animationTime, double repeatMinimumSustainTime, Curve attackCurve, double attackTime, Curve releaseCurve, double releaseTime, Curve coastTimeCurve, double maximumCoastTime); + + // Note that the times can be overspecified such that releaseTime or releaseTime and attackTime are greater + // than animationTime. animationTime takes priority over releaseTime, capping it. attackTime is capped at + // whatever time remains, or zero if none. + bool m_isEnabled; + double m_animationTime; + double m_repeatMinimumSustainTime; + + Curve m_attackCurve; + double m_attackTime; + + Curve m_releaseCurve; + double m_releaseTime; + + Curve m_coastTimeCurve; + double m_maximumCoastTime; + }; + +protected: + virtual void animationWillStart() { } + virtual void animationDidFinish() { } + + Parameters parametersForScrollGranularity(ScrollGranularity) const; + + friend class ScrollAnimatorTest; + + struct PLATFORM_EXPORT PerAxisData { + PerAxisData(float* currentPos, int visibleLength); + void reset(); + bool updateDataFromParameters(float step, float delta, float scrollableSize, double currentTime, Parameters*); + bool animateScroll(double currentTime); + void updateVisibleLength(int visibleLength); + + static double curveAt(Curve, double t); + static double attackCurve(Curve, double deltaT, double curveT, double startPos, double attackPos); + static double releaseCurve(Curve, double deltaT, double curveT, double releasePos, double desiredPos); + static double coastCurve(Curve, double factor); + + static double curveIntegralAt(Curve, double t); + static double attackArea(Curve, double startT, double endT); + static double releaseArea(Curve, double startT, double endT); + + double newScrollAnimationPosition(double deltaTime); + + float* m_currentPosition; + double m_currentVelocity; + + double m_desiredPosition; + double m_desiredVelocity; + + double m_startPosition; + double m_startTime; + double m_startVelocity; + + double m_animationTime; + double m_lastAnimationTime; + + double m_attackPosition; + double m_attackTime; + Curve m_attackCurve; + + double m_releasePosition; + double m_releaseTime; + Curve m_releaseCurve; + + int m_visibleLength; + }; + + void startNextTimer(); + void animationTimerFired(); + + void stopAnimationTimerIfNeeded(); + bool animationTimerActive(); + void updateVisibleLengths(); + + PerAxisData m_horizontalData; + PerAxisData m_verticalData; + + double m_startTime; + bool m_animationActive; }; } // namespace blink
diff --git a/third_party/WebKit/Source/platform/scroll/ScrollAnimatorBase.cpp b/third_party/WebKit/Source/platform/scroll/ScrollAnimatorBase.cpp new file mode 100644 index 0000000..8971694d --- /dev/null +++ b/third_party/WebKit/Source/platform/scroll/ScrollAnimatorBase.cpp
@@ -0,0 +1,98 @@ +/* + * Copyright (c) 2010, 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. + */ + +#include "config.h" +#include "platform/scroll/ScrollAnimatorBase.h" + +#include "platform/RuntimeEnabledFeatures.h" +#include "platform/geometry/FloatPoint.h" +#include "platform/scroll/ScrollableArea.h" +#include "wtf/PassOwnPtr.h" +#include <algorithm> + +namespace blink { + +ScrollAnimatorBase::ScrollAnimatorBase(ScrollableArea* scrollableArea) + : m_scrollableArea(scrollableArea) + , m_currentPosX(0) + , m_currentPosY(0) +{ +} + +ScrollAnimatorBase::~ScrollAnimatorBase() +{ +} + +ScrollResultOneDimensional ScrollAnimatorBase::userScroll(ScrollbarOrientation orientation, ScrollGranularity, float step, float delta) +{ + float& currentPos = (orientation == HorizontalScrollbar) ? m_currentPosX : m_currentPosY; + float newPos = clampScrollPosition(orientation, currentPos + step * delta); + if (currentPos == newPos) + return ScrollResultOneDimensional(false, delta); + + float usedDelta = (newPos - currentPos) / step; + currentPos = newPos; + + notifyPositionChanged(); + + return ScrollResultOneDimensional(true, delta - usedDelta); +} + +void ScrollAnimatorBase::scrollToOffsetWithoutAnimation(const FloatPoint& offset) +{ + m_currentPosX = offset.x(); + m_currentPosY = offset.y(); + notifyPositionChanged(); +} + +void ScrollAnimatorBase::setCurrentPosition(const FloatPoint& position) +{ + m_currentPosX = position.x(); + m_currentPosY = position.y(); +} + +FloatPoint ScrollAnimatorBase::currentPosition() const +{ + return FloatPoint(m_currentPosX, m_currentPosY); +} + +void ScrollAnimatorBase::notifyPositionChanged() +{ + m_scrollableArea->scrollPositionChanged(DoublePoint(m_currentPosX, m_currentPosY), UserScroll); +} + +float ScrollAnimatorBase::clampScrollPosition(ScrollbarOrientation orientation, float pos) +{ + float maxScrollPos = m_scrollableArea->maximumScrollPosition(orientation); + float minScrollPos = m_scrollableArea->minimumScrollPosition(orientation); + return std::max(std::min(pos, maxScrollPos), minScrollPos); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/platform/scroll/ScrollAnimatorBase.h b/third_party/WebKit/Source/platform/scroll/ScrollAnimatorBase.h new file mode 100644 index 0000000..e1ab6121 --- /dev/null +++ b/third_party/WebKit/Source/platform/scroll/ScrollAnimatorBase.h
@@ -0,0 +1,116 @@ +/* + * Copyright (c) 2010, 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. + */ + +#ifndef ScrollAnimatorBase_h +#define ScrollAnimatorBase_h + +#include "platform/PlatformExport.h" +#include "platform/PlatformWheelEvent.h" +#include "platform/geometry/FloatSize.h" +#include "platform/scroll/ScrollTypes.h" +#include "wtf/Forward.h" + +namespace blink { + +class FloatPoint; +class ScrollableArea; +class Scrollbar; + +class PLATFORM_EXPORT ScrollAnimatorBase { +public: + static PassOwnPtr<ScrollAnimatorBase> create(ScrollableArea*); + + virtual ~ScrollAnimatorBase(); + + // Computes a scroll destination for the given parameters. The returned + // ScrollResultOneDimensional will have didScroll set to false if already at + // the destination. Otherwise, starts scrolling towards the destination and + // didScroll is true. Scrolling may be immediate or animated. The base + // class implementation always scrolls immediately, never animates. + virtual ScrollResultOneDimensional userScroll(ScrollbarOrientation, ScrollGranularity, float step, float delta); + + virtual void scrollToOffsetWithoutAnimation(const FloatPoint&); + + ScrollableArea* scrollableArea() const { return m_scrollableArea; } + + virtual void setIsActive() { } + +#if OS(MACOSX) + virtual void handleWheelEventPhase(PlatformWheelEventPhase) { } +#endif + + void setCurrentPosition(const FloatPoint&); + FloatPoint currentPosition() const; + + virtual void cancelAnimations() { } + virtual void serviceScrollAnimations() { } + virtual bool hasRunningAnimation() const { return false; } + + virtual void contentAreaWillPaint() const { } + virtual void mouseEnteredContentArea() const { } + virtual void mouseExitedContentArea() const { } + virtual void mouseMovedInContentArea() const { } + virtual void mouseEnteredScrollbar(Scrollbar*) const { } + virtual void mouseExitedScrollbar(Scrollbar*) const { } + virtual void willStartLiveResize() { } + virtual void updateAfterLayout() { } + virtual void contentsResized() const { } + virtual void willEndLiveResize() { } + virtual void contentAreaDidShow() const { } + virtual void contentAreaDidHide() const { } + + virtual void finishCurrentScrollAnimations() { } + + virtual void didAddVerticalScrollbar(Scrollbar*) { } + virtual void willRemoveVerticalScrollbar(Scrollbar*) { } + virtual void didAddHorizontalScrollbar(Scrollbar*) { } + virtual void willRemoveHorizontalScrollbar(Scrollbar*) { } + + virtual bool shouldScrollbarParticipateInHitTesting(Scrollbar*) { return true; } + + virtual void notifyContentAreaScrolled(const FloatSize&) { } + + virtual bool setScrollbarsVisibleForTesting(bool) { return false; } +protected: + explicit ScrollAnimatorBase(ScrollableArea*); + + virtual void notifyPositionChanged(); + + ScrollableArea* m_scrollableArea; + float m_currentPosX; // We avoid using a FloatPoint in order to reduce + float m_currentPosY; // subclass code complexity. + +private: + float clampScrollPosition(ScrollbarOrientation, float); +}; + +} // namespace blink + +#endif // ScrollAnimatorBase_h
diff --git a/third_party/WebKit/Source/platform/scroll/ScrollAnimatorNone.cpp b/third_party/WebKit/Source/platform/scroll/ScrollAnimatorNone.cpp deleted file mode 100644 index 5aa4e19..0000000 --- a/third_party/WebKit/Source/platform/scroll/ScrollAnimatorNone.cpp +++ /dev/null
@@ -1,536 +0,0 @@ -/* - * Copyright (c) 2011, 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. - */ - -#include "config.h" - -#include "platform/scroll/ScrollAnimatorNone.h" - -#include <algorithm> -#include "platform/scroll/ScrollableArea.h" -#include "wtf/CurrentTime.h" -#include "wtf/PassRefPtr.h" - -#include "platform/TraceEvent.h" - -namespace blink { - -const double kFrameRate = 60; -const double kTickTime = 1 / kFrameRate; -const double kMinimumTimerInterval = .001; - -PassOwnPtr<ScrollAnimator> ScrollAnimator::create(ScrollableArea* scrollableArea) -{ - if (scrollableArea && scrollableArea->scrollAnimatorEnabled()) - return adoptPtr(new ScrollAnimatorNone(scrollableArea)); - return adoptPtr(new ScrollAnimator(scrollableArea)); -} - -ScrollAnimatorNone::Parameters::Parameters() - : m_isEnabled(false) -{ -} - -ScrollAnimatorNone::Parameters::Parameters(bool isEnabled, double animationTime, double repeatMinimumSustainTime, Curve attackCurve, double attackTime, Curve releaseCurve, double releaseTime, Curve coastTimeCurve, double maximumCoastTime) - : m_isEnabled(isEnabled) - , m_animationTime(animationTime) - , m_repeatMinimumSustainTime(repeatMinimumSustainTime) - , m_attackCurve(attackCurve) - , m_attackTime(attackTime) - , m_releaseCurve(releaseCurve) - , m_releaseTime(releaseTime) - , m_coastTimeCurve(coastTimeCurve) - , m_maximumCoastTime(maximumCoastTime) -{ -} - -double ScrollAnimatorNone::PerAxisData::curveAt(Curve curve, double t) -{ - switch (curve) { - case Linear: - return t; - case Quadratic: - return t * t; - case Cubic: - return t * t * t; - case Quartic: - return t * t * t * t; - case Bounce: - // Time base is chosen to keep the bounce points simpler: - // 1 (half bounce coming in) + 1 + .5 + .25 - const double kTimeBase = 2.75; - const double kTimeBaseSquared = kTimeBase * kTimeBase; - if (t < 1 / kTimeBase) - return kTimeBaseSquared * t * t; - if (t < 2 / kTimeBase) { - // Invert a [-.5,.5] quadratic parabola, center it in [1,2]. - double t1 = t - 1.5 / kTimeBase; - const double kParabolaAtEdge = 1 - .5 * .5; - return kTimeBaseSquared * t1 * t1 + kParabolaAtEdge; - } - if (t < 2.5 / kTimeBase) { - // Invert a [-.25,.25] quadratic parabola, center it in [2,2.5]. - double t2 = t - 2.25 / kTimeBase; - const double kParabolaAtEdge = 1 - .25 * .25; - return kTimeBaseSquared * t2 * t2 + kParabolaAtEdge; - } - // Invert a [-.125,.125] quadratic parabola, center it in [2.5,2.75]. - const double kParabolaAtEdge = 1 - .125 * .125; - t -= 2.625 / kTimeBase; - return kTimeBaseSquared * t * t + kParabolaAtEdge; - } - ASSERT_NOT_REACHED(); - return 0; -} - -double ScrollAnimatorNone::PerAxisData::attackCurve(Curve curve, double deltaTime, double curveT, double startPosition, double attackPosition) -{ - double t = deltaTime / curveT; - double positionFactor = curveAt(curve, t); - return startPosition + positionFactor * (attackPosition - startPosition); -} - -double ScrollAnimatorNone::PerAxisData::releaseCurve(Curve curve, double deltaTime, double curveT, double releasePosition, double desiredPosition) -{ - double t = deltaTime / curveT; - double positionFactor = 1 - curveAt(curve, 1 - t); - return releasePosition + (positionFactor * (desiredPosition - releasePosition)); -} - -double ScrollAnimatorNone::PerAxisData::coastCurve(Curve curve, double factor) -{ - return 1 - curveAt(curve, 1 - factor); -} - -double ScrollAnimatorNone::PerAxisData::curveIntegralAt(Curve curve, double t) -{ - switch (curve) { - case Linear: - return t * t / 2; - case Quadratic: - return t * t * t / 3; - case Cubic: - return t * t * t * t / 4; - case Quartic: - return t * t * t * t * t / 5; - case Bounce: - const double kTimeBase = 2.75; - const double kTimeBaseSquared = kTimeBase * kTimeBase; - const double kTimeBaseSquaredOverThree = kTimeBaseSquared / 3; - double area; - double t1 = std::min(t, 1 / kTimeBase); - area = kTimeBaseSquaredOverThree * t1 * t1 * t1; - if (t < 1 / kTimeBase) - return area; - - t1 = std::min(t - 1 / kTimeBase, 1 / kTimeBase); - // The integral of kTimeBaseSquared * (t1 - .5 / kTimeBase) * (t1 - .5 / kTimeBase) + kParabolaAtEdge - const double kSecondInnerOffset = kTimeBaseSquared * .5 / kTimeBase; - double bounceArea = t1 * (t1 * (kTimeBaseSquaredOverThree * t1 - kSecondInnerOffset) + 1); - area += bounceArea; - if (t < 2 / kTimeBase) - return area; - - t1 = std::min(t - 2 / kTimeBase, 0.5 / kTimeBase); - // The integral of kTimeBaseSquared * (t1 - .25 / kTimeBase) * (t1 - .25 / kTimeBase) + kParabolaAtEdge - const double kThirdInnerOffset = kTimeBaseSquared * .25 / kTimeBase; - bounceArea = t1 * (t1 * (kTimeBaseSquaredOverThree * t1 - kThirdInnerOffset) + 1); - area += bounceArea; - if (t < 2.5 / kTimeBase) - return area; - - t1 = t - 2.5 / kTimeBase; - // The integral of kTimeBaseSquared * (t1 - .125 / kTimeBase) * (t1 - .125 / kTimeBase) + kParabolaAtEdge - const double kFourthInnerOffset = kTimeBaseSquared * .125 / kTimeBase; - bounceArea = t1 * (t1 * (kTimeBaseSquaredOverThree * t1 - kFourthInnerOffset) + 1); - area += bounceArea; - return area; - } - ASSERT_NOT_REACHED(); - return 0; -} - -double ScrollAnimatorNone::PerAxisData::attackArea(Curve curve, double startT, double endT) -{ - double startValue = curveIntegralAt(curve, startT); - double endValue = curveIntegralAt(curve, endT); - return endValue - startValue; -} - -double ScrollAnimatorNone::PerAxisData::releaseArea(Curve curve, double startT, double endT) -{ - double startValue = curveIntegralAt(curve, 1 - endT); - double endValue = curveIntegralAt(curve, 1 - startT); - return endValue - startValue; -} - -ScrollAnimatorNone::PerAxisData::PerAxisData(float* currentPosition, int visibleLength) - : m_currentPosition(currentPosition) - , m_visibleLength(visibleLength) -{ - reset(); -} - -void ScrollAnimatorNone::PerAxisData::reset() -{ - m_currentVelocity = 0; - - m_desiredPosition = 0; - m_desiredVelocity = 0; - - m_startPosition = 0; - m_startTime = 0; - m_startVelocity = 0; - - m_animationTime = 0; - m_lastAnimationTime = 0; - - m_attackPosition = 0; - m_attackTime = 0; - m_attackCurve = Quadratic; - - m_releasePosition = 0; - m_releaseTime = 0; - m_releaseCurve = Quadratic; -} - - -bool ScrollAnimatorNone::PerAxisData::updateDataFromParameters(float step, float delta, float scrollableSize, double currentTime, Parameters* parameters) -{ - float pixelDelta = step * delta; - if (!m_startTime || !pixelDelta || (pixelDelta < 0) != (m_desiredPosition - *m_currentPosition < 0)) { - m_desiredPosition = *m_currentPosition; - m_startTime = 0; - } - float newPosition = m_desiredPosition + pixelDelta; - - if (newPosition < 0 || newPosition > scrollableSize) - newPosition = std::max(std::min(newPosition, scrollableSize), 0.0f); - - if (newPosition == m_desiredPosition) - return false; - - m_desiredPosition = newPosition; - - if (!m_startTime) { - m_attackTime = parameters->m_attackTime; - m_attackCurve = parameters->m_attackCurve; - } - m_animationTime = parameters->m_animationTime; - m_releaseTime = parameters->m_releaseTime; - m_releaseCurve = parameters->m_releaseCurve; - - // Prioritize our way out of over constraint. - if (m_attackTime + m_releaseTime > m_animationTime) { - if (m_releaseTime > m_animationTime) - m_releaseTime = m_animationTime; - m_attackTime = m_animationTime - m_releaseTime; - } - - if (!m_startTime) { - // FIXME: This should be the time from the event that got us here. - m_startTime = currentTime - kTickTime / 2; - m_startPosition = *m_currentPosition; - m_lastAnimationTime = m_startTime; - } - m_startVelocity = m_currentVelocity; - - double remainingDelta = m_desiredPosition - *m_currentPosition; - - double attackAreaLeft = 0; - - double deltaTime = m_lastAnimationTime - m_startTime; - double attackTimeLeft = std::max(0., m_attackTime - deltaTime); - double timeLeft = m_animationTime - deltaTime; - double minTimeLeft = m_releaseTime + std::min(parameters->m_repeatMinimumSustainTime, m_animationTime - m_releaseTime - attackTimeLeft); - if (timeLeft < minTimeLeft) { - m_animationTime = deltaTime + minTimeLeft; - timeLeft = minTimeLeft; - } - - if (parameters->m_maximumCoastTime > (parameters->m_repeatMinimumSustainTime + parameters->m_releaseTime)) { - double targetMaxCoastVelocity = m_visibleLength * .25 * kFrameRate; - // This needs to be as minimal as possible while not being intrusive to page up/down. - double minCoastDelta = m_visibleLength; - - if (fabs(remainingDelta) > minCoastDelta) { - double maxCoastDelta = parameters->m_maximumCoastTime * targetMaxCoastVelocity; - double coastFactor = std::min(1., (fabs(remainingDelta) - minCoastDelta) / (maxCoastDelta - minCoastDelta)); - - // We could play with the curve here - linear seems a little soft. Initial testing makes me want to feed into the sustain time more aggressively. - double coastMinTimeLeft = std::min(parameters->m_maximumCoastTime, minTimeLeft + coastCurve(parameters->m_coastTimeCurve, coastFactor) * (parameters->m_maximumCoastTime - minTimeLeft)); - - double additionalTime = std::max(0., coastMinTimeLeft - minTimeLeft); - if (additionalTime) { - double additionalReleaseTime = std::min(additionalTime, parameters->m_releaseTime / (parameters->m_releaseTime + parameters->m_repeatMinimumSustainTime) * additionalTime); - m_releaseTime = parameters->m_releaseTime + additionalReleaseTime; - m_animationTime = deltaTime + coastMinTimeLeft; - timeLeft = coastMinTimeLeft; - } - } - } - - double releaseTimeLeft = std::min(timeLeft, m_releaseTime); - double sustainTimeLeft = std::max(0., timeLeft - releaseTimeLeft - attackTimeLeft); - - if (attackTimeLeft) { - double attackSpot = deltaTime / m_attackTime; - attackAreaLeft = attackArea(m_attackCurve, attackSpot, 1) * m_attackTime; - } - - double releaseSpot = (m_releaseTime - releaseTimeLeft) / m_releaseTime; - double releaseAreaLeft = releaseArea(m_releaseCurve, releaseSpot, 1) * m_releaseTime; - - m_desiredVelocity = remainingDelta / (attackAreaLeft + sustainTimeLeft + releaseAreaLeft); - m_releasePosition = m_desiredPosition - m_desiredVelocity * releaseAreaLeft; - if (attackAreaLeft) - m_attackPosition = m_startPosition + m_desiredVelocity * attackAreaLeft; - else - m_attackPosition = m_releasePosition - (m_animationTime - m_releaseTime - m_attackTime) * m_desiredVelocity; - - if (sustainTimeLeft) { - double roundOff = m_releasePosition - ((attackAreaLeft ? m_attackPosition : *m_currentPosition) + m_desiredVelocity * sustainTimeLeft); - m_desiredVelocity += roundOff / sustainTimeLeft; - } - - return true; -} - -inline double ScrollAnimatorNone::PerAxisData::newScrollAnimationPosition(double deltaTime) -{ - if (deltaTime < m_attackTime) - return attackCurve(m_attackCurve, deltaTime, m_attackTime, m_startPosition, m_attackPosition); - if (deltaTime < (m_animationTime - m_releaseTime)) - return m_attackPosition + (deltaTime - m_attackTime) * m_desiredVelocity; - // release is based on targeting the exact final position. - double releaseDeltaT = deltaTime - (m_animationTime - m_releaseTime); - return releaseCurve(m_releaseCurve, releaseDeltaT, m_releaseTime, m_releasePosition, m_desiredPosition); -} - -// FIXME: Add in jank detection trace events into this function. -bool ScrollAnimatorNone::PerAxisData::animateScroll(double currentTime) -{ - double lastScrollInterval = currentTime - m_lastAnimationTime; - if (lastScrollInterval < kMinimumTimerInterval) - return true; - - m_lastAnimationTime = currentTime; - - double deltaTime = currentTime - m_startTime; - - if (deltaTime > m_animationTime) { - *m_currentPosition = m_desiredPosition; - reset(); - return false; - } - double newPosition = newScrollAnimationPosition(deltaTime); - // Normalize velocity to a per second amount. Could be used to check for jank. - if (lastScrollInterval > 0) - m_currentVelocity = (newPosition - *m_currentPosition) / lastScrollInterval; - *m_currentPosition = newPosition; - - return true; -} - -void ScrollAnimatorNone::PerAxisData::updateVisibleLength(int visibleLength) -{ - m_visibleLength = visibleLength; -} - -ScrollAnimatorNone::ScrollAnimatorNone(ScrollableArea* scrollableArea) - : ScrollAnimator(scrollableArea) - , m_horizontalData(&m_currentPosX, scrollableArea->visibleWidth()) - , m_verticalData(&m_currentPosY, scrollableArea->visibleHeight()) - , m_startTime(0) - , m_animationActive(false) -{ -} - -ScrollAnimatorNone::~ScrollAnimatorNone() -{ - stopAnimationTimerIfNeeded(); -} - -ScrollAnimatorNone::Parameters ScrollAnimatorNone::parametersForScrollGranularity(ScrollGranularity granularity) const -{ - switch (granularity) { - case ScrollByDocument: - return Parameters(true, 20 * kTickTime, 10 * kTickTime, Cubic, 10 * kTickTime, Cubic, 10 * kTickTime, Linear, 1); - case ScrollByLine: - return Parameters(true, 10 * kTickTime, 7 * kTickTime, Cubic, 3 * kTickTime, Cubic, 3 * kTickTime, Linear, 1); - case ScrollByPage: - return Parameters(true, 15 * kTickTime, 10 * kTickTime, Cubic, 5 * kTickTime, Cubic, 5 * kTickTime, Linear, 1); - case ScrollByPixel: - return Parameters(true, 11 * kTickTime, 2 * kTickTime, Cubic, 3 * kTickTime, Cubic, 3 * kTickTime, Quadratic, 1.25); - default: - ASSERT_NOT_REACHED(); - } - return Parameters(); -} - -ScrollResultOneDimensional ScrollAnimatorNone::userScroll(ScrollbarOrientation orientation, ScrollGranularity granularity, float step, float delta) -{ - if (!m_scrollableArea->scrollAnimatorEnabled()) - return ScrollAnimator::userScroll(orientation, granularity, step, delta); - - TRACE_EVENT0("blink", "ScrollAnimatorNone::scroll"); - - // FIXME: get the type passed in. MouseWheel could also be by line, but should still have different - // animation parameters than the keyboard. - Parameters parameters; - switch (granularity) { - case ScrollByDocument: - case ScrollByLine: - case ScrollByPage: - case ScrollByPixel: - parameters = parametersForScrollGranularity(granularity); - break; - case ScrollByPrecisePixel: - return ScrollAnimator::userScroll(orientation, granularity, step, delta); - } - - // If the individual input setting is disabled, bail. - if (!parameters.m_isEnabled) - return ScrollAnimator::userScroll(orientation, granularity, step, delta); - - // This is an animatable scroll. Set the animation in motion using the appropriate parameters. - float scrollableSize = static_cast<float>(m_scrollableArea->scrollSize(orientation)); - - PerAxisData& data = (orientation == VerticalScrollbar) ? m_verticalData : m_horizontalData; - bool needToScroll = data.updateDataFromParameters(step, delta, scrollableSize, WTF::monotonicallyIncreasingTime(), ¶meters); - float unusedDelta = needToScroll ? delta - (data.m_desiredPosition - *data.m_currentPosition) : delta; - if (needToScroll && !animationTimerActive()) { - m_startTime = data.m_startTime; - animationWillStart(); - animationTimerFired(); - scrollableArea()->registerForAnimation(); - } - return ScrollResultOneDimensional(needToScroll, unusedDelta); -} - -void ScrollAnimatorNone::scrollToOffsetWithoutAnimation(const FloatPoint& offset) -{ - m_currentPosX = offset.x(); - m_currentPosY = offset.y(); - - // Must be called after setting the position since canceling the animation resets - // the desired position to the current. - cancelAnimations(); - notifyPositionChanged(); -} - -void ScrollAnimatorNone::cancelAnimations() -{ - m_animationActive = false; - - m_horizontalData.reset(); - m_verticalData.reset(); - m_horizontalData.m_desiredPosition = m_currentPosX; - m_verticalData.m_desiredPosition = m_currentPosY; -} - -void ScrollAnimatorNone::serviceScrollAnimations() -{ - if (m_animationActive) - animationTimerFired(); -} - -bool ScrollAnimatorNone::hasRunningAnimation() const -{ - return m_animationActive; -} - -void ScrollAnimatorNone::updateAfterLayout() -{ - updateVisibleLengths(); -} - -void ScrollAnimatorNone::willEndLiveResize() -{ - updateVisibleLengths(); -} - -void ScrollAnimatorNone::didAddVerticalScrollbar(Scrollbar*) -{ - updateVisibleLengths(); -} - -void ScrollAnimatorNone::didAddHorizontalScrollbar(Scrollbar*) -{ - updateVisibleLengths(); -} - -void ScrollAnimatorNone::updateVisibleLengths() -{ - m_horizontalData.updateVisibleLength(scrollableArea()->visibleWidth()); - m_verticalData.updateVisibleLength(scrollableArea()->visibleHeight()); -} - -void ScrollAnimatorNone::animationTimerFired() -{ - TRACE_EVENT0("blink", "ScrollAnimatorNone::animationTimerFired"); - - double currentTime = WTF::monotonicallyIncreasingTime(); - - bool continueAnimation = false; - if (m_horizontalData.m_startTime && m_horizontalData.animateScroll(currentTime)) - continueAnimation = true; - if (m_verticalData.m_startTime && m_verticalData.animateScroll(currentTime)) - continueAnimation = true; - - if (continueAnimation) - startNextTimer(); - else - m_animationActive = false; - - TRACE_EVENT0("blink", "ScrollAnimatorNone::notifyPositionChanged"); - notifyPositionChanged(); - - if (!continueAnimation) - animationDidFinish(); -} - -void ScrollAnimatorNone::startNextTimer() -{ - if (scrollableArea()->scheduleAnimation()) - m_animationActive = true; -} - -bool ScrollAnimatorNone::animationTimerActive() -{ - return m_animationActive; -} - -void ScrollAnimatorNone::stopAnimationTimerIfNeeded() -{ - if (animationTimerActive()) - m_animationActive = false; -} - -} // namespace blink
diff --git a/third_party/WebKit/Source/platform/scroll/ScrollAnimatorNone.h b/third_party/WebKit/Source/platform/scroll/ScrollAnimatorNone.h deleted file mode 100644 index e5ca5c7..0000000 --- a/third_party/WebKit/Source/platform/scroll/ScrollAnimatorNone.h +++ /dev/null
@@ -1,154 +0,0 @@ -/* - * Copyright (c) 2011, 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. - */ - -#ifndef ScrollAnimatorNone_h -#define ScrollAnimatorNone_h - -#include "platform/Timer.h" -#include "platform/geometry/FloatPoint.h" -#include "platform/scroll/ScrollAnimator.h" - -namespace blink { - -class ScrollAnimatorNoneTest; - -class PLATFORM_EXPORT ScrollAnimatorNone : public ScrollAnimator { -public: - explicit ScrollAnimatorNone(ScrollableArea*); - ~ScrollAnimatorNone() override; - - ScrollResultOneDimensional userScroll(ScrollbarOrientation, ScrollGranularity, float step, float delta) override; - void scrollToOffsetWithoutAnimation(const FloatPoint&) override; - - void cancelAnimations() override; - void serviceScrollAnimations() override; - bool hasRunningAnimation() const override; - - void updateAfterLayout() override; - void willEndLiveResize() override; - void didAddVerticalScrollbar(Scrollbar*) override; - void didAddHorizontalScrollbar(Scrollbar*) override; - - enum Curve { - Linear, - Quadratic, - Cubic, - Quartic, - Bounce - }; - - struct PLATFORM_EXPORT Parameters { - Parameters(); - Parameters(bool isEnabled, double animationTime, double repeatMinimumSustainTime, Curve attackCurve, double attackTime, Curve releaseCurve, double releaseTime, Curve coastTimeCurve, double maximumCoastTime); - - // Note that the times can be overspecified such that releaseTime or releaseTime and attackTime are greater - // than animationTime. animationTime takes priority over releaseTime, capping it. attackTime is capped at - // whatever time remains, or zero if none. - bool m_isEnabled; - double m_animationTime; - double m_repeatMinimumSustainTime; - - Curve m_attackCurve; - double m_attackTime; - - Curve m_releaseCurve; - double m_releaseTime; - - Curve m_coastTimeCurve; - double m_maximumCoastTime; - }; - -protected: - virtual void animationWillStart() { } - virtual void animationDidFinish() { } - - Parameters parametersForScrollGranularity(ScrollGranularity) const; - - friend class ScrollAnimatorNoneTest; - - struct PLATFORM_EXPORT PerAxisData { - PerAxisData(float* currentPos, int visibleLength); - void reset(); - bool updateDataFromParameters(float step, float delta, float scrollableSize, double currentTime, Parameters*); - bool animateScroll(double currentTime); - void updateVisibleLength(int visibleLength); - - static double curveAt(Curve, double t); - static double attackCurve(Curve, double deltaT, double curveT, double startPos, double attackPos); - static double releaseCurve(Curve, double deltaT, double curveT, double releasePos, double desiredPos); - static double coastCurve(Curve, double factor); - - static double curveIntegralAt(Curve, double t); - static double attackArea(Curve, double startT, double endT); - static double releaseArea(Curve, double startT, double endT); - - double newScrollAnimationPosition(double deltaTime); - - float* m_currentPosition; - double m_currentVelocity; - - double m_desiredPosition; - double m_desiredVelocity; - - double m_startPosition; - double m_startTime; - double m_startVelocity; - - double m_animationTime; - double m_lastAnimationTime; - - double m_attackPosition; - double m_attackTime; - Curve m_attackCurve; - - double m_releasePosition; - double m_releaseTime; - Curve m_releaseCurve; - - int m_visibleLength; - }; - - void startNextTimer(); - void animationTimerFired(); - - void stopAnimationTimerIfNeeded(); - bool animationTimerActive(); - void updateVisibleLengths(); - - PerAxisData m_horizontalData; - PerAxisData m_verticalData; - - double m_startTime; - bool m_animationActive; -}; - -} // namespace blink - -#endif // ScrollAnimatorNone_h
diff --git a/third_party/WebKit/Source/platform/scroll/ScrollableArea.cpp b/third_party/WebKit/Source/platform/scroll/ScrollableArea.cpp index 692405b..f23801b 100644 --- a/third_party/WebKit/Source/platform/scroll/ScrollableArea.cpp +++ b/third_party/WebKit/Source/platform/scroll/ScrollableArea.cpp
@@ -94,13 +94,13 @@ m_animators.clear(); } -ScrollAnimator* ScrollableArea::scrollAnimator() const +ScrollAnimatorBase* ScrollableArea::scrollAnimator() const { if (!m_animators) m_animators = adoptPtr(new ScrollableAreaAnimators); if (!m_animators->scrollAnimator) - m_animators->scrollAnimator = ScrollAnimator::create(const_cast<ScrollableArea*>(this)); + m_animators->scrollAnimator = ScrollAnimatorBase::create(const_cast<ScrollableArea*>(this)); return m_animators->scrollAnimator.get(); } @@ -218,7 +218,7 @@ // Smooth user scrolls (keyboard, wheel clicks) are handled via the userScroll method. // TODO(bokan): The userScroll method should probably be modified to call this method - // and ScrollAnimator to have a simpler animateToOffset method like the + // and ScrollAnimatorBase to have a simpler animateToOffset method like the // ProgrammaticScrollAnimator. ASSERT(scrollBehavior == ScrollBehaviorInstant); scrollAnimator()->scrollToOffsetWithoutAnimation(FloatPoint(x, y)); @@ -297,7 +297,7 @@ if (m_inLiveResize) return; m_inLiveResize = true; - if (ScrollAnimator* scrollAnimator = existingScrollAnimator()) + if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator()) scrollAnimator->willStartLiveResize(); } @@ -306,31 +306,31 @@ if (!m_inLiveResize) return; m_inLiveResize = false; - if (ScrollAnimator* scrollAnimator = existingScrollAnimator()) + if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator()) scrollAnimator->willEndLiveResize(); } void ScrollableArea::contentAreaWillPaint() const { - if (ScrollAnimator* scrollAnimator = existingScrollAnimator()) + if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator()) scrollAnimator->contentAreaWillPaint(); } void ScrollableArea::mouseEnteredContentArea() const { - if (ScrollAnimator* scrollAnimator = existingScrollAnimator()) + if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator()) scrollAnimator->mouseEnteredContentArea(); } void ScrollableArea::mouseExitedContentArea() const { - if (ScrollAnimator* scrollAnimator = existingScrollAnimator()) + if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator()) scrollAnimator->mouseEnteredContentArea(); } void ScrollableArea::mouseMovedInContentArea() const { - if (ScrollAnimator* scrollAnimator = existingScrollAnimator()) + if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator()) scrollAnimator->mouseMovedInContentArea(); } @@ -346,19 +346,19 @@ void ScrollableArea::contentAreaDidShow() const { - if (ScrollAnimator* scrollAnimator = existingScrollAnimator()) + if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator()) scrollAnimator->contentAreaDidShow(); } void ScrollableArea::contentAreaDidHide() const { - if (ScrollAnimator* scrollAnimator = existingScrollAnimator()) + if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator()) scrollAnimator->contentAreaDidHide(); } void ScrollableArea::finishCurrentScrollAnimations() const { - if (ScrollAnimator* scrollAnimator = existingScrollAnimator()) + if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator()) scrollAnimator->finishCurrentScrollAnimations(); } @@ -383,7 +383,7 @@ void ScrollableArea::contentsResized() { - if (ScrollAnimator* scrollAnimator = existingScrollAnimator()) + if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator()) scrollAnimator->contentsResized(); } @@ -477,7 +477,7 @@ void ScrollableArea::serviceScrollAnimations(double monotonicTime) { bool requiresAnimationService = false; - if (ScrollAnimator* scrollAnimator = existingScrollAnimator()) { + if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator()) { scrollAnimator->serviceScrollAnimations(); if (scrollAnimator->hasRunningAnimation()) requiresAnimationService = true; @@ -505,7 +505,7 @@ void ScrollableArea::cancelScrollAnimation() { - if (ScrollAnimator* scrollAnimator = existingScrollAnimator()) + if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator()) scrollAnimator->cancelAnimations(); }
diff --git a/third_party/WebKit/Source/platform/scroll/ScrollableArea.h b/third_party/WebKit/Source/platform/scroll/ScrollableArea.h index 84c5eb45..26b8fb9 100644 --- a/third_party/WebKit/Source/platform/scroll/ScrollableArea.h +++ b/third_party/WebKit/Source/platform/scroll/ScrollableArea.h
@@ -30,7 +30,7 @@ #include "platform/RuntimeEnabledFeatures.h" #include "platform/geometry/DoublePoint.h" #include "platform/heap/Handle.h" -#include "platform/scroll/ScrollAnimator.h" +#include "platform/scroll/ScrollAnimatorBase.h" #include "platform/scroll/ScrollTypes.h" #include "platform/scroll/Scrollbar.h" #include "wtf/Noncopyable.h" @@ -45,7 +45,7 @@ class PlatformWheelEvent; class ProgrammaticScrollAnimator; struct ScrollAlignment; -class ScrollAnimator; +class ScrollAnimatorBase; class WebCompositorAnimationTimeline; enum ScrollBehavior { @@ -122,11 +122,11 @@ void setScrollbarOverlayStyle(ScrollbarOverlayStyle); ScrollbarOverlayStyle scrollbarOverlayStyle() const { return static_cast<ScrollbarOverlayStyle>(m_scrollbarOverlayStyle); } - // This getter will create a ScrollAnimator if it doesn't already exist. - ScrollAnimator* scrollAnimator() const; + // This getter will create a ScrollAnimatorBase if it doesn't already exist. + ScrollAnimatorBase* scrollAnimator() const; - // This getter will return null if the ScrollAnimator hasn't been created yet. - ScrollAnimator* existingScrollAnimator() const { return m_animators ? m_animators->scrollAnimator.get() : 0; } + // This getter will return null if the ScrollAnimatorBase hasn't been created yet. + ScrollAnimatorBase* existingScrollAnimator() const { return m_animators ? m_animators->scrollAnimator.get() : 0; } ProgrammaticScrollAnimator* programmaticScrollAnimator() const; ProgrammaticScrollAnimator* existingProgrammaticScrollAnimator() const @@ -306,7 +306,7 @@ void resetScrollOriginChanged() { m_scrollOriginChanged = false; } // Needed to let the animators call scrollPositionChanged. - friend class ScrollAnimator; + friend class ScrollAnimatorBase; friend class ProgrammaticScrollAnimator; void scrollPositionChanged(const DoublePoint&, ScrollType); @@ -339,7 +339,7 @@ IntRect m_verticalBarDamage; struct ScrollableAreaAnimators { - OwnPtr<ScrollAnimator> scrollAnimator; + OwnPtr<ScrollAnimatorBase> scrollAnimator; OwnPtr<ProgrammaticScrollAnimator> programmaticScrollAnimator; };
diff --git a/third_party/WebKit/Source/platform/scroll/Scrollbar.cpp b/third_party/WebKit/Source/platform/scroll/Scrollbar.cpp index 7672bf9a..e549491b 100644 --- a/third_party/WebKit/Source/platform/scroll/Scrollbar.cpp +++ b/third_party/WebKit/Source/platform/scroll/Scrollbar.cpp
@@ -30,7 +30,7 @@ #include "platform/PlatformGestureEvent.h" #include "platform/PlatformMouseEvent.h" #include "platform/graphics/paint/CullRect.h" -#include "platform/scroll/ScrollAnimator.h" +#include "platform/scroll/ScrollAnimatorBase.h" #include "platform/scroll/ScrollableArea.h" #include "platform/scroll/ScrollbarTheme.h"
diff --git a/third_party/WebKit/Source/platform/scroll/Scrollbar.h b/third_party/WebKit/Source/platform/scroll/Scrollbar.h index cfb5131..4f6596d 100644 --- a/third_party/WebKit/Source/platform/scroll/Scrollbar.h +++ b/third_party/WebKit/Source/platform/scroll/Scrollbar.h
@@ -41,7 +41,7 @@ class IntRect; class PlatformGestureEvent; class PlatformMouseEvent; -class ScrollAnimator; +class ScrollAnimatorBase; class ScrollableArea; class ScrollbarTheme;
diff --git a/third_party/WebKit/Source/web/BUILD.gn b/third_party/WebKit/Source/web/BUILD.gn index 960394b..02da39f 100644 --- a/third_party/WebKit/Source/web/BUILD.gn +++ b/third_party/WebKit/Source/web/BUILD.gn
@@ -17,7 +17,7 @@ [ "web.gypi" ]) web_unittest_files = web_gypi.web_unittest_files if (!is_mac) { - web_unittest_files += [ "tests/ScrollAnimatorNoneTest.cpp" ] + web_unittest_files += [ "tests/ScrollAnimatorTest.cpp" ] } component("web") {
diff --git a/third_party/WebKit/Source/web/InspectorOverlay.cpp b/third_party/WebKit/Source/web/InspectorOverlay.cpp index 5914390..d73cd21 100644 --- a/third_party/WebKit/Source/web/InspectorOverlay.cpp +++ b/third_party/WebKit/Source/web/InspectorOverlay.cpp
@@ -51,10 +51,10 @@ #include "platform/ScriptForbiddenScope.h" #include "platform/graphics/GraphicsContext.h" #include "platform/graphics/paint/CullRect.h" +#include "platform/graphics/paint/DisplayItemCacheSkipper.h" #include "public/platform/Platform.h" #include "public/platform/WebData.h" #include "web/PageOverlay.h" -#include "web/WebGraphicsContextImpl.h" #include "web/WebInputEventConversion.h" #include "web/WebLocalFrameImpl.h" #include "web/WebViewImpl.h" @@ -109,12 +109,13 @@ PageOverlay::Delegate::trace(visitor); } - void paintPageOverlay(WebGraphicsContext* context, const WebSize& webViewSize) const override + void paintPageOverlay(const PageOverlay&, GraphicsContext& graphicsContext, const WebSize& webViewSize) const override { if (m_overlay->isEmpty()) return; - GraphicsContext& graphicsContext = toWebGraphicsContextImpl(context)->graphicsContext(); + // Skip cache because the following paint may conflict with the view's real painting. + DisplayItemCacheSkipper cacheSkipper(graphicsContext); FrameView* view = m_overlay->overlayMainFrame()->view(); ASSERT(!view->needsLayout()); view->paint(&graphicsContext, CullRect(IntRect(0, 0, view->width(), view->height())));
diff --git a/third_party/WebKit/Source/web/PageOverlay.cpp b/third_party/WebKit/Source/web/PageOverlay.cpp index f39c3bc..86ae847 100644 --- a/third_party/WebKit/Source/web/PageOverlay.cpp +++ b/third_party/WebKit/Source/web/PageOverlay.cpp
@@ -38,7 +38,6 @@ #include "public/platform/WebLayer.h" #include "public/web/WebViewClient.h" #include "web/WebDevToolsAgentImpl.h" -#include "web/WebGraphicsContextImpl.h" #include "web/WebViewImpl.h" namespace blink { @@ -100,8 +99,7 @@ void PageOverlay::paintContents(const GraphicsLayer* graphicsLayer, GraphicsContext& gc, GraphicsLayerPaintingPhase phase, const IntRect* inClip) const { ASSERT(m_layer); - WebGraphicsContextImpl contextWrapper(gc, *this, DisplayItem::PageOverlay); - m_delegate->paintPageOverlay(&contextWrapper, expandedIntSize(m_layer->size())); + m_delegate->paintPageOverlay(*this, gc, expandedIntSize(m_layer->size())); } String PageOverlay::debugName(const GraphicsLayer*)
diff --git a/third_party/WebKit/Source/web/PageOverlay.h b/third_party/WebKit/Source/web/PageOverlay.h index bf99b2fe..305fe2d 100644 --- a/third_party/WebKit/Source/web/PageOverlay.h +++ b/third_party/WebKit/Source/web/PageOverlay.h
@@ -41,7 +41,6 @@ class GraphicsContext; class WebPageOverlay; class WebViewImpl; -class WebGraphicsContext; // Manages a layer that is overlaid on a WebView's content. // Clients can paint by implementing WebPageOverlay. @@ -55,7 +54,7 @@ DEFINE_INLINE_VIRTUAL_TRACE() { } // Paints page overlay contents. - virtual void paintPageOverlay(WebGraphicsContext*, const WebSize& webViewSize) const = 0; + virtual void paintPageOverlay(const PageOverlay&, GraphicsContext&, const WebSize& webViewSize) const = 0; virtual ~Delegate() { } };
diff --git a/third_party/WebKit/Source/web/PageOverlayTest.cpp b/third_party/WebKit/Source/web/PageOverlayTest.cpp index 441b6b5..4b13417 100644 --- a/third_party/WebKit/Source/web/PageOverlayTest.cpp +++ b/third_party/WebKit/Source/web/PageOverlayTest.cpp
@@ -19,7 +19,6 @@ #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkColor.h" #include "third_party/skia/include/core/SkPaint.h" -#include "web/WebGraphicsContextImpl.h" #include "web/WebLocalFrameImpl.h" #include "web/WebViewImpl.h" #include "web/tests/FrameTestHelpers.h" @@ -71,45 +70,20 @@ FrameTestHelpers::WebViewHelper m_helper; }; -// PageOverlay that uses a WebCanvas to draw a solid color. -class SimpleCanvasOverlay : public PageOverlay::Delegate { +// PageOverlay that paints a solid color. +class SolidColorOverlay : public PageOverlay::Delegate { public: - SimpleCanvasOverlay(SkColor color) : m_color(color) { } + SolidColorOverlay(Color color) : m_color(color) { } - void paintPageOverlay(WebGraphicsContext* context, const WebSize& size) const override + void paintPageOverlay(const PageOverlay& pageOverlay, GraphicsContext& graphicsContext, const WebSize& size) const override { - WebFloatRect rect(0, 0, size.width, size.height); - WebCanvas* canvas = context->beginDrawing(rect); - SkPaint paint; - paint.setColor(m_color); - paint.setStyle(SkPaint::kFill_Style); - canvas->drawRectCoords(0, 0, size.width, size.height, paint); - context->endDrawing(); - } - -private: - SkColor m_color; -}; - -// PageOverlay that uses the underlying blink::GraphicsContext to paint a -// solid color. -class PrivateGraphicsContextOverlay : public PageOverlay::Delegate { -public: - PrivateGraphicsContextOverlay(Color color) : m_color(color) { } - - void paintPageOverlay(WebGraphicsContext* context, const WebSize& size) const override - { - GraphicsContext& graphicsContext = toWebGraphicsContextImpl(context)->graphicsContext(); - if (DrawingRecorder::useCachedDrawingIfPossible(graphicsContext, *this, DisplayItem::PageOverlay)) + if (DrawingRecorder::useCachedDrawingIfPossible(graphicsContext, pageOverlay, DisplayItem::PageOverlay)) return; FloatRect rect(0, 0, size.width, size.height); - DrawingRecorder drawingRecorder(graphicsContext, *this, DisplayItem::PageOverlay, rect); + DrawingRecorder drawingRecorder(graphicsContext, pageOverlay, DisplayItem::PageOverlay, rect); graphicsContext.fillRect(rect, m_color); } - DisplayItemClient displayItemClient() const { return toDisplayItemClient(this); } - String debugName() const { return "PrivateGraphicsContextOverlay"; } - private: Color m_color; }; @@ -129,13 +103,12 @@ MOCK_METHOD2(onDrawRect, void(const SkRect&, const SkPaint&)); }; -template <typename OverlayType> -void PageOverlayTest::runPageOverlayTestWithAcceleratedCompositing() +TEST_F(PageOverlayTest, PageOverlay_AcceleratedCompositing) { initialize(AcceleratedCompositing); webViewImpl()->layerTreeView()->setViewportSize(WebSize(viewportWidth, viewportHeight)); - OwnPtr<PageOverlay> pageOverlay = PageOverlay::create(webViewImpl(), new OverlayType(SK_ColorYELLOW)); + OwnPtr<PageOverlay> pageOverlay = PageOverlay::create(webViewImpl(), new SolidColorOverlay(SK_ColorYELLOW)); pageOverlay->update(); webViewImpl()->layout(); @@ -164,15 +137,5 @@ graphicsContext.endRecording()->playback(&canvas); } -TEST_F(PageOverlayTest, SimpleCanvasOverlay_AcceleratedCompositing) -{ - runPageOverlayTestWithAcceleratedCompositing<SimpleCanvasOverlay>(); -} - -TEST_F(PageOverlayTest, PrivateGraphicsContextOverlay_AcceleratedCompositing) -{ - runPageOverlayTestWithAcceleratedCompositing<PrivateGraphicsContextOverlay>(); -} - } // namespace } // namespace blink
diff --git a/third_party/WebKit/Source/web/WebDevToolsFrontendImpl.cpp b/third_party/WebKit/Source/web/WebDevToolsFrontendImpl.cpp index b917a46..c11ebd9 100644 --- a/third_party/WebKit/Source/web/WebDevToolsFrontendImpl.cpp +++ b/third_party/WebKit/Source/web/WebDevToolsFrontendImpl.cpp
@@ -104,12 +104,6 @@ frame->frame()->script().executeScriptInMainWorld(scriptWithId.toString()); } -void WebDevToolsFrontendImpl::sendMessageToBackend(const String& message) -{ - if (m_client) - m_client->sendMessageToBackend(message); -} - void WebDevToolsFrontendImpl::sendMessageToEmbedder(const String& message) { if (m_client)
diff --git a/third_party/WebKit/Source/web/WebDevToolsFrontendImpl.h b/third_party/WebKit/Source/web/WebDevToolsFrontendImpl.h index ceceb67e..2825ab4 100644 --- a/third_party/WebKit/Source/web/WebDevToolsFrontendImpl.h +++ b/third_party/WebKit/Source/web/WebDevToolsFrontendImpl.h
@@ -51,8 +51,6 @@ void didClearWindowObject(WebLocalFrameImpl*); - void sendMessageToBackend(const WTF::String&) override; - void sendMessageToEmbedder(const WTF::String&) override; bool isUnderTest() override;
diff --git a/third_party/WebKit/Source/web/WebGraphicsContextImpl.cpp b/third_party/WebKit/Source/web/WebGraphicsContextImpl.cpp deleted file mode 100644 index d40c99f..0000000 --- a/third_party/WebKit/Source/web/WebGraphicsContextImpl.cpp +++ /dev/null
@@ -1,46 +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 "config.h" -#include "web/WebGraphicsContextImpl.h" - -#include "platform/graphics/GraphicsContext.h" -#include "platform/graphics/paint/DrawingRecorder.h" - -namespace blink { - -WebGraphicsContextImpl::WebGraphicsContextImpl(GraphicsContext& graphicsContext, const DisplayItemClientWrapper& client, DisplayItem::Type type) - : m_graphicsContext(graphicsContext) - , m_client(client) - , m_type(type) -#ifndef NDEBUG - , m_hasBegunDrawing(false) -#endif -{ -} - -WebGraphicsContextImpl::~WebGraphicsContextImpl() -{ -} - -WebCanvas* WebGraphicsContextImpl::beginDrawing(const WebFloatRect& bounds) -{ -#ifndef NDEBUG - ASSERT(!m_hasBegunDrawing); - m_hasBegunDrawing = true; -#endif - ASSERT(!DrawingRecorder::useCachedDrawingIfPossible(m_graphicsContext, m_client, m_type)); - m_drawingRecorder = adoptPtr(new DrawingRecorder(m_graphicsContext, m_client, m_type, bounds)); - WebCanvas* canvas = m_graphicsContext.canvas(); - ASSERT(canvas); - return canvas; -} - -void WebGraphicsContextImpl::endDrawing() -{ - ASSERT(m_drawingRecorder); - m_drawingRecorder.clear(); -} - -} // namespace blink
diff --git a/third_party/WebKit/Source/web/WebGraphicsContextImpl.h b/third_party/WebKit/Source/web/WebGraphicsContextImpl.h deleted file mode 100644 index 9541076..0000000 --- a/third_party/WebKit/Source/web/WebGraphicsContextImpl.h +++ /dev/null
@@ -1,46 +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 WebGraphicsContextImpl_h -#define WebGraphicsContextImpl_h - -#include "platform/graphics/paint/DisplayItem.h" -#include "platform/graphics/paint/DisplayItemClient.h" -#include "public/web/WebGraphicsContext.h" -#include "wtf/OwnPtr.h" - -namespace blink { - -class DrawingRecorder; -class GraphicsContext; - -// Wraps a blink::GraphicsContext. -// Internal consumers can extract the underlying context (via WebGraphicsContextImpl). -// External consumers can make a single drawing using a WebCanvas. -class WebGraphicsContextImpl : public WebGraphicsContext { -public: - WebGraphicsContextImpl(GraphicsContext&, const DisplayItemClientWrapper&, DisplayItem::Type); - ~WebGraphicsContextImpl(); - GraphicsContext& graphicsContext() { return m_graphicsContext; } - - // blink::WebGraphicsContext - WebCanvas* beginDrawing(const WebFloatRect& bounds) override; - void endDrawing() override; - -private: - GraphicsContext& m_graphicsContext; - DisplayItemClientWrapper m_client; - DisplayItem::Type m_type; - OwnPtr<DrawingRecorder> m_drawingRecorder; -#ifndef NDEBUG - bool m_hasBegunDrawing; -#endif -}; - -// Source/web/ assumes that WebGraphicsContextImpl is the only implementation. -DEFINE_TYPE_CASTS(WebGraphicsContextImpl, WebGraphicsContext, webGraphicsContext, true, true); - -} // namespace blink - -#endif
diff --git a/third_party/WebKit/Source/web/WebPagePopupImpl.cpp b/third_party/WebKit/Source/web/WebPagePopupImpl.cpp index 208acec..1c463b9 100644 --- a/third_party/WebKit/Source/web/WebPagePopupImpl.cpp +++ b/third_party/WebKit/Source/web/WebPagePopupImpl.cpp
@@ -345,7 +345,7 @@ if (m_layerTreeView) { m_layerTreeView->setVisible(true); m_isAcceleratedCompositingActive = true; - m_layerTreeView->setDeviceScaleFactor(m_widgetClient->deviceScaleFactor()); + m_layerTreeView->setDeviceScaleFactor(m_webView->deviceScaleFactor()); } else { m_isAcceleratedCompositingActive = false; }
diff --git a/third_party/WebKit/Source/web/WebPluginContainerImpl.cpp b/third_party/WebKit/Source/web/WebPluginContainerImpl.cpp index 6890882..7be53ac 100644 --- a/third_party/WebKit/Source/web/WebPluginContainerImpl.cpp +++ b/third_party/WebKit/Source/web/WebPluginContainerImpl.cpp
@@ -70,7 +70,7 @@ #include "platform/graphics/GraphicsContext.h" #include "platform/graphics/GraphicsLayer.h" #include "platform/graphics/paint/CullRect.h" -#include "platform/scroll/ScrollAnimator.h" +#include "platform/scroll/ScrollAnimatorBase.h" #include "platform/scroll/ScrollbarTheme.h" #include "public/platform/Platform.h" #include "public/platform/WebClipboard.h"
diff --git a/third_party/WebKit/Source/web/WebViewImpl.cpp b/third_party/WebKit/Source/web/WebViewImpl.cpp index 6e6f742..afbc5c3 100644 --- a/third_party/WebKit/Source/web/WebViewImpl.cpp +++ b/third_party/WebKit/Source/web/WebViewImpl.cpp
@@ -113,9 +113,11 @@ #include "platform/fonts/FontCache.h" #include "platform/graphics/Color.h" #include "platform/graphics/FirstPaintInvalidationTracking.h" +#include "platform/graphics/GraphicsContext.h" #include "platform/graphics/Image.h" #include "platform/graphics/ImageBuffer.h" #include "platform/graphics/gpu/DrawingBuffer.h" +#include "platform/graphics/paint/DrawingRecorder.h" #include "platform/scroll/ScrollbarTheme.h" #include "platform/weborigin/SchemeRegistry.h" #include "public/platform/Platform.h" @@ -134,7 +136,6 @@ #include "public/web/WebElement.h" #include "public/web/WebFrame.h" #include "public/web/WebFrameClient.h" -#include "public/web/WebGraphicsContext.h" #include "public/web/WebHitTestResult.h" #include "public/web/WebInputElement.h" #include "public/web/WebMeaningfulLayout.h" @@ -309,15 +310,13 @@ } private: - void paintPageOverlay(WebGraphicsContext* context, const WebSize& size) const override + void paintPageOverlay(const PageOverlay& pageOverlay, GraphicsContext& graphicsContext, const WebSize& size) const override { - WebFloatRect rect(0, 0, size.width, size.height); - WebCanvas* canvas = context->beginDrawing(rect); - SkPaint paint; - paint.setColor(m_color); - paint.setStyle(SkPaint::kFill_Style); - canvas->drawRectCoords(0, 0, size.width, size.height, paint); - context->endDrawing(); + if (DrawingRecorder::useCachedDrawingIfPossible(graphicsContext, pageOverlay, DisplayItem::PageOverlay)) + return; + FloatRect rect(0, 0, size.width, size.height); + DrawingRecorder drawingRecorder(graphicsContext, pageOverlay, DisplayItem::PageOverlay, rect); + graphicsContext.fillRect(rect, m_color); } WebColor m_color; @@ -412,6 +411,7 @@ , m_zoomLevel(0) , m_minimumZoomLevel(zoomFactorToZoomLevel(minTextSizeMultiplier)) , m_maximumZoomLevel(zoomFactorToZoomLevel(maxTextSizeMultiplier)) + , m_zoomFactorForDeviceScaleFactor(1.f) , m_maximumLegibleScale(1) , m_doubleTapZoomPageScaleFactor(0) , m_doubleTapZoomPending(false) @@ -2958,6 +2958,7 @@ LocalFrame* frame = mainFrameImpl()->frame(); if (!WebLocalFrameImpl::pluginContainerFromFrame(frame)) { float zoomFactor = m_zoomFactorOverride ? m_zoomFactorOverride : static_cast<float>(zoomLevelToZoomFactor(m_zoomLevel)); + zoomFactor *= m_zoomFactorForDeviceScaleFactor; frame->setPageZoomFactor(zoomFactor); } @@ -3103,6 +3104,14 @@ updateLayerTreeDeviceScaleFactor(); } +void WebViewImpl::setZoomFactorForDeviceScaleFactor(float zoomFactorForDeviceScaleFactor) +{ + m_zoomFactorForDeviceScaleFactor = zoomFactorForDeviceScaleFactor; + if (!m_layerTreeView) + return; + setZoomLevel(m_zoomLevel); +} + void WebViewImpl::setDeviceColorProfile(const WebVector<char>& colorProfile) { if (!page())
diff --git a/third_party/WebKit/Source/web/WebViewImpl.h b/third_party/WebKit/Source/web/WebViewImpl.h index cbf00be..eab0ba9f 100644 --- a/third_party/WebKit/Source/web/WebViewImpl.h +++ b/third_party/WebKit/Source/web/WebViewImpl.h
@@ -210,6 +210,8 @@ float deviceScaleFactor() const override; void setDeviceScaleFactor(float) override; + void setZoomFactorForDeviceScaleFactor(float) override; + void setDeviceColorProfile(const WebVector<char>&) override; void resetDeviceColorProfile() override; @@ -652,6 +654,9 @@ double m_maximumZoomLevel; + // Additional zoom factor used to scale the content by device scale factor. + double m_zoomFactorForDeviceScaleFactor; + // This value, when multiplied by the font scale factor, gives the maximum // page scale that can result from automatic zooms. float m_maximumLegibleScale;
diff --git a/third_party/WebKit/Source/web/tests/FrameThrottlingTest.cpp b/third_party/WebKit/Source/web/tests/FrameThrottlingTest.cpp index a45d5df5..dd09b2d 100644 --- a/third_party/WebKit/Source/web/tests/FrameThrottlingTest.cpp +++ b/third_party/WebKit/Source/web/tests/FrameThrottlingTest.cpp
@@ -152,7 +152,10 @@ frameElement->setAttribute(styleAttr, "transform: translateY(480px)"); compositeFrame(); EXPECT_TRUE(frameDocument->view()->canThrottleRendering()); - EXPECT_EQ(DocumentLifecycle::PaintInvalidationClean, frameDocument->lifecycle().state()); + if (RuntimeEnabledFeatures::slimmingPaintSynchronizedPaintingEnabled()) + EXPECT_EQ(DocumentLifecycle::PaintClean, frameDocument->lifecycle().state()); + else + EXPECT_EQ(DocumentLifecycle::PaintInvalidationClean, frameDocument->lifecycle().state()); // Mutating the throttled frame followed by a beginFrame will not result in // a complete lifecycle update.
diff --git a/third_party/WebKit/Source/web/tests/LayoutGeometryMapTest.cpp b/third_party/WebKit/Source/web/tests/LayoutGeometryMapTest.cpp index c1c7bee2..c734170 100644 --- a/third_party/WebKit/Source/web/tests/LayoutGeometryMapTest.cpp +++ b/third_party/WebKit/Source/web/tests/LayoutGeometryMapTest.cpp
@@ -142,27 +142,20 @@ // differently LayoutGeometryMap rgm; rgm.pushMappingsToAncestor(getLayoutBox(webView, "InitialDiv"), 0); - FloatPoint point; FloatRect rect(0.0f, 0.0f, 1.0f, 2.0f); - EXPECT_EQ(FloatPoint(8.0f, 8.0f), rgm.mapToContainer(point, nullptr)); EXPECT_EQ(FloatQuad(FloatRect(8.0f, 8.0f, 1.0f, 2.0f)), rgm.mapToContainer(rect, nullptr)); rgm.popMappingsToAncestor(static_cast<PaintLayer*>(nullptr)); - EXPECT_EQ(FloatPoint(0.0f, 0.0f), rgm.mapToContainer(point, nullptr)); EXPECT_EQ(FloatQuad(FloatRect(0.0f, 0.0f, 1.0f, 2.0f)), rgm.mapToContainer(rect, nullptr)); rgm.pushMappingsToAncestor(getLayoutBox(webView, "InnerDiv"), 0); - EXPECT_EQ(FloatPoint(21.0f, 6.0f), rgm.mapToContainer(point, getLayoutBox(webView, "CenterDiv"))); EXPECT_EQ(FloatQuad(FloatRect(21.0f, 6.0f, 1.0f, 2.0f)), rgm.mapToContainer(rect, getLayoutBox(webView, "CenterDiv"))); rgm.pushMappingsToAncestor(getLayoutBox(webView, "OtherDiv"), getLayoutBox(webView, "InnerDiv")); - EXPECT_EQ(FloatPoint(22.0f, 12.0f), rgm.mapToContainer(point, getLayoutBox(webView, "CenterDiv"))); EXPECT_EQ(FloatQuad(FloatRect(22.0f, 12.0f, 1.0f, 2.0f)), rgm.mapToContainer(rect, getLayoutBox(webView, "CenterDiv"))); - EXPECT_EQ(FloatPoint(1.0f, 6.0f), rgm.mapToContainer(point, getLayoutBox(webView, "InnerDiv"))); EXPECT_EQ(FloatQuad(FloatRect(1.0f, 6.0f, 1.0f, 2.0f)), rgm.mapToContainer(rect, getLayoutBox(webView, "InnerDiv"))); - EXPECT_EQ(FloatPoint(50.0f, 44.0f), rgm.mapToContainer(point, nullptr)); EXPECT_EQ(FloatQuad(FloatRect(50.0f, 44.0f, 1.0f, 2.0f)), rgm.mapToContainer(rect, nullptr)); } @@ -182,41 +175,30 @@ LayoutGeometryMap rgm; rgm.pushMappingsToAncestor(getLayoutBox(webView, "InitialDiv"), 0); - FloatPoint point; const float rectWidth = 15.0f; const float scaleWidth = 2.0f; const float scaleHeight = 3.0f; FloatRect rect(0.0f, 0.0f, 15.0f, 25.0f); - EXPECT_EQ(FloatPoint(8.0f, 8.0f), rgm.mapToContainer(point, nullptr)); EXPECT_EQ(FloatQuad(FloatRect(8.0f, 8.0f, 15.0f, 25.0f)), rgm.mapToContainer(rect, nullptr)); rgm.popMappingsToAncestor(static_cast<PaintLayer*>(nullptr)); - EXPECT_EQ(FloatPoint(0.0f, 0.0f), rgm.mapToContainer(point, nullptr)); EXPECT_EQ(FloatQuad(FloatRect(0.0f, 0.0f, 15.0f, 25.0f)).boundingBox(), rgm.mapToContainer(rect, nullptr).boundingBox()); rgm.pushMappingsToAncestor(getLayoutBox(webView, "InnerDiv"), 0); - EXPECT_EQ(FloatPoint(523.0f, 6.0f), rgm.mapToContainer(point, getLayoutBox(webView, "CenterDiv"))); EXPECT_EQ(FloatQuad(FloatRect(523.0f - rectWidth, 6.0f, 15.0f, 25.0f)).boundingBox(), rgm.mapToContainer(rect, getLayoutBox(webView, "CenterDiv")).boundingBox()); rgm.pushMappingsToAncestor(getLayoutBox(webView, "OtherDiv"), getLayoutBox(webView, "InnerDiv")); - EXPECT_EQ(FloatPoint(522.0f, 12.0f), rgm.mapToContainer(point, getLayoutBox(webView, "CenterDiv"))); EXPECT_EQ(FloatQuad(FloatRect(522.0f - rectWidth, 12.0f, 15.0f, 25.0f)).boundingBox(), rgm.mapToContainer(rect, getLayoutBox(webView, "CenterDiv")).boundingBox()); - EXPECT_EQ(FloatPoint(1.0f, 6.0f), rgm.mapToContainer(point, getLayoutBox(webView, "InnerDiv"))); EXPECT_EQ(FloatQuad(FloatRect(1.0f, 6.0f, 15.0f, 25.0f)).boundingBox(), rgm.mapToContainer(rect, getLayoutBox(webView, "InnerDiv")).boundingBox()); - EXPECT_EQ(FloatPoint(821.0f, 31.0f), rgm.mapToContainer(point, nullptr)); EXPECT_EQ(FloatQuad(FloatRect(821.0f - rectWidth * scaleWidth, 31.0f, 15.0f * scaleWidth, 25.0f * scaleHeight)).boundingBox(), rgm.mapToContainer(rect, nullptr).boundingBox()); - point = FloatPoint(10.0f, 25.0f); rect = FloatRect(10.0f, 25.0f, 15.0f, 25.0f); - EXPECT_EQ(FloatPoint(512.0f, 37.0f), rgm.mapToContainer(point, getLayoutBox(webView, "CenterDiv"))); EXPECT_EQ(FloatQuad(FloatRect(512.0f - rectWidth, 37.0f, 15.0f, 25.0f)).boundingBox(), rgm.mapToContainer(rect, getLayoutBox(webView, "CenterDiv")).boundingBox()); - EXPECT_EQ(FloatPoint(11.0f, 31.0f), rgm.mapToContainer(point, getLayoutBox(webView, "InnerDiv"))); EXPECT_EQ(FloatQuad(FloatRect(11.0f, 31.0f, 15.0f, 25.0f)).boundingBox(), rgm.mapToContainer(rect, getLayoutBox(webView, "InnerDiv")).boundingBox()); - EXPECT_EQ(FloatPoint(801.0f, 106.0f), rgm.mapToContainer(point, nullptr)); EXPECT_EQ(FloatQuad(FloatRect(801.0f - rectWidth * scaleWidth, 106.0f, 15.0f * scaleWidth, 25.0f * scaleHeight)).boundingBox(), rgm.mapToContainer(rect, nullptr).boundingBox()); } @@ -230,34 +212,23 @@ LayoutGeometryMap rgm; rgm.pushMappingsToAncestor(getLayoutBox(webView, "InitialDiv"), 0); - FloatPoint point; FloatRect rect(0.0f, 0.0f, 15.0f, 25.0f); - EXPECT_EQ(FloatPoint(8.0f, 8.0f), rgm.mapToContainer(point, nullptr)); EXPECT_EQ(FloatQuad(FloatRect(8.0f, 8.0f, 15.0f, 25.0f)), rgm.mapToContainer(rect, nullptr)); rgm.popMappingsToAncestor(static_cast<PaintLayer*>(nullptr)); - EXPECT_EQ(FloatPoint(0.0f, 0.0f), rgm.mapToContainer(point, nullptr)); EXPECT_EQ(FloatQuad(FloatRect(0.0f, 0.0f, 15.0f, 25.0f)), rgm.mapToContainer(rect, nullptr)); rgm.pushMappingsToAncestor(getLayoutBox(webView, "InnerDiv"), 0); - EXPECT_EQ(FloatPoint(20.0f, 14.0f), rgm.mapToContainer(point, getLayoutContainer(webView, "CenterDiv"))); EXPECT_EQ(FloatQuad(FloatRect(20.0f, 14.0f, 15.0f, 25.0f)), rgm.mapToContainer(rect, nullptr)); rgm.pushMappingsToAncestor(getLayoutBox(webView, "OtherDiv"), getLayoutBox(webView, "InnerDiv")); - EXPECT_EQ(FloatPoint(21.0f, 20.0f), rgm.mapToContainer(point, getLayoutContainer(webView, "CenterDiv"))); EXPECT_EQ(FloatQuad(FloatRect(21.0f, 20.0f, 15.0f, 25.0f)), rgm.mapToContainer(rect, getLayoutContainer(webView, "CenterDiv"))); - EXPECT_EQ(FloatPoint(21.0f, 20.0f), rgm.mapToContainer(point, getLayoutContainer(webView, "InnerDiv"))); - EXPECT_EQ(FloatPoint(21.0f, 20.0f), rgm.mapToContainer(point, nullptr)); - - point = FloatPoint(10.0f, 25.0f); rect = FloatRect(22.0f, 15.2f, 15.3f, 0.0f); EXPECT_EQ(FloatQuad(FloatRect(43.0f, 35.2f, 15.3f, 0.0f)), rgm.mapToContainer(rect, getLayoutContainer(webView, "CenterDiv"))); - EXPECT_EQ(FloatPoint(31.0f, 45.0f), rgm.mapToContainer(point, getLayoutContainer(webView, "InnerDiv"))); EXPECT_EQ(FloatQuad(FloatRect(43.0f, 35.2f, 15.3f, 0.0f)), rgm.mapToContainer(rect, getLayoutContainer(webView, "InnerDiv"))); - EXPECT_EQ(FloatPoint(31.0f, 45.0f), rgm.mapToContainer(point, nullptr)); EXPECT_EQ(FloatQuad(FloatRect(43.0f, 35.2f, 15.3f, 0.0f)), rgm.mapToContainer(rect, nullptr)); } @@ -275,10 +246,8 @@ rgmNoFrame.pushMappingsToAncestor(getFrameElement("test_frame", webView, "InitialDiv"), 0); rgm.pushMappingsToAncestor(getFrameElement("test_frame", webView, "InitialDiv"), 0); - FloatPoint point; FloatRect rect(0.0f, 0.0f, 1.0f, 2.0f); - EXPECT_EQ(FloatPoint(8.0f, 8.0f), rgmNoFrame.mapToContainer(point, nullptr)); EXPECT_EQ(FloatQuad(FloatRect(8.0f, 8.0f, 1.0f, 2.0f)), rgmNoFrame.mapToContainer(rect, nullptr)); // Our initial rect looks like: (0, 0, 1, 2) @@ -298,8 +267,6 @@ // That maximum x should likewise be p0.x + cos(30deg) = p0.x + 0.866. // And the maximum y should be p0.x + sin(30deg) + 2*cos(30deg) // = p0.y + 2.232. - EXPECT_NEAR(70.5244f, rgm.mapToContainer(point, nullptr).x(), 0.0001f); - EXPECT_NEAR(-44.0237f, rgm.mapToContainer(point, nullptr).y(), 0.0001f); EXPECT_NEAR(69.5244f, rectFromQuad(rgm.mapToContainer(rect, nullptr)).x(), 0.0001f); EXPECT_NEAR(-44.0237, rectFromQuad(rgm.mapToContainer(rect, nullptr)).y(), 0.0001f); EXPECT_NEAR(1.866, rectFromQuad(rgm.mapToContainer(rect, nullptr)).width(), 0.0001f); @@ -307,36 +274,25 @@ rgm.popMappingsToAncestor(static_cast<PaintLayer*>(nullptr)); rgmNoFrame.popMappingsToAncestor(static_cast<PaintLayer*>(nullptr)); - EXPECT_EQ(FloatPoint(0.0f, 0.0f), rgm.mapToContainer(point, nullptr)); - EXPECT_EQ(FloatPoint(0.0f, 0.0f), rgmNoFrame.mapToContainer(point, nullptr)); rgm.pushMappingsToAncestor(getFrameElement("test_frame", webView, "InnerDiv"), 0); rgmNoFrame.pushMappingsToAncestor(getFrameElement("test_frame", webView, "InnerDiv"), 0); - EXPECT_EQ(FloatPoint(21.0f, 6.0f), rgm.mapToContainer(point, getFrameLayoutContainer("test_frame", webView, "CenterDiv"))); EXPECT_EQ(FloatQuad(FloatRect(21.0f, 6.0f, 1.0f, 2.0f)), rgm.mapToContainer(rect, getFrameLayoutContainer("test_frame", webView, "CenterDiv"))); - EXPECT_EQ(FloatPoint(21.0f, 6.0f), rgmNoFrame.mapToContainer(point, getFrameLayoutContainer("test_frame", webView, "CenterDiv"))); EXPECT_EQ(FloatQuad(FloatRect(21.0f, 6.0f, 1.0f, 2.0f)), rgmNoFrame.mapToContainer(rect, getFrameLayoutContainer("test_frame", webView, "CenterDiv"))); rgm.pushMappingsToAncestor(getFrameElement("test_frame", webView, "OtherDiv"), getFrameLayoutContainer("test_frame", webView, "InnerDiv")); rgmNoFrame.pushMappingsToAncestor(getFrameElement("test_frame", webView, "OtherDiv"), getFrameLayoutContainer("test_frame", webView, "InnerDiv")); - EXPECT_EQ(FloatPoint(22.0f, 12.0f), rgm.mapToContainer(point, getFrameLayoutContainer("test_frame", webView, "CenterDiv"))); EXPECT_EQ(FloatQuad(FloatRect(22.0f, 12.0f, 1.0f, 2.0f)), rgm.mapToContainer(rect, getFrameLayoutContainer("test_frame", webView, "CenterDiv"))); - EXPECT_EQ(FloatPoint(22.0f, 12.0f), rgmNoFrame.mapToContainer(point, getFrameLayoutContainer("test_frame", webView, "CenterDiv"))); EXPECT_EQ(FloatQuad(FloatRect(22.0f, 12.0f, 1.0f, 2.0f)), rgmNoFrame.mapToContainer(rect, getFrameLayoutContainer("test_frame", webView, "CenterDiv"))); - EXPECT_EQ(FloatPoint(1.0f, 6.0f), rgm.mapToContainer(point, getFrameLayoutContainer("test_frame", webView, "InnerDiv"))); EXPECT_EQ(FloatQuad(FloatRect(1.0f, 6.0f, 1.0f, 2.0f)), rgm.mapToContainer(rect, getFrameLayoutContainer("test_frame", webView, "InnerDiv"))); - EXPECT_EQ(FloatPoint(1.0f, 6.0f), rgmNoFrame.mapToContainer(point, getFrameLayoutContainer("test_frame", webView, "InnerDiv"))); EXPECT_EQ(FloatQuad(FloatRect(1.0f, 6.0f, 1.0f, 2.0f)), rgmNoFrame.mapToContainer(rect, getFrameLayoutContainer("test_frame", webView, "InnerDiv"))); - EXPECT_NEAR(88.8975f, rgm.mapToContainer(point, nullptr).x(), 0.0001f); - EXPECT_NEAR(8.1532f, rgm.mapToContainer(point, nullptr).y(), 0.0001f); EXPECT_NEAR(87.8975f, rectFromQuad(rgm.mapToContainer(rect, nullptr)).x(), 0.0001f); EXPECT_NEAR(8.1532f, rectFromQuad(rgm.mapToContainer(rect, nullptr)).y(), 0.0001f); EXPECT_NEAR(1.866, rectFromQuad(rgm.mapToContainer(rect, nullptr)).width(), 0.0001f); EXPECT_NEAR(2.232, rectFromQuad(rgm.mapToContainer(rect, nullptr)).height(), 0.0001f); - EXPECT_EQ(FloatPoint(50.0f, 44.0f), rgmNoFrame.mapToContainer(point, nullptr)); EXPECT_EQ(FloatQuad(FloatRect(50.0f, 44.0f, 1.0f, 2.0f)), rgmNoFrame.mapToContainer(rect, nullptr)); } @@ -361,21 +317,16 @@ FloatPoint point; FloatRect rect(0.0f, 0.0f, 5.0f, 3.0f); - EXPECT_EQ(FloatPoint(8.0f, 8.0f), rgm.mapToContainer(point, nullptr)); EXPECT_EQ(FloatQuad(FloatRect(8.0f, 8.0f, 5.0f, 3.0f)), rgm.mapToContainer(rect, nullptr)); rgm.popMappingsToAncestor(static_cast<PaintLayer*>(nullptr)); - EXPECT_EQ(FloatPoint(0.0f, 0.0f), rgm.mapToContainer(point, nullptr)); EXPECT_EQ(FloatQuad(FloatRect(0.0f, 0.0f, 5.0f, 3.0f)), rgm.mapToContainer(rect, nullptr)); rgm.pushMappingsToAncestor(getLayoutBox(webView, "Col1"), 0); - EXPECT_EQ(FloatPoint(8.0f, 8.0f), rgm.mapToContainer(point, nullptr)); EXPECT_EQ(FloatQuad(FloatRect(8.0f, 8.0f, 5.0f, 3.0f)), rgm.mapToContainer(rect, nullptr)); rgm.popMappingsToAncestor(static_cast<PaintLayer*>(nullptr)); rgm.pushMappingsToAncestor(getLayoutBox(webView, "Col2"), nullptr); - EXPECT_NEAR(8.0f + offset, rgm.mapToContainer(point, nullptr).x(), 0.1f); - EXPECT_NEAR(8.0f, rgm.mapToContainer(point, nullptr).y(), 0.1f); EXPECT_NEAR(8.0f + offset, rectFromQuad(rgm.mapToContainer(rect, nullptr)).x(), 0.1f); EXPECT_NEAR(8.0f, rectFromQuad(rgm.mapToContainer(rect, nullptr)).y(), 0.1f); EXPECT_EQ(5.0f, rectFromQuad(rgm.mapToContainer(rect, nullptr)).width()); @@ -383,8 +334,6 @@ rgm.popMappingsToAncestor(static_cast<PaintLayer*>(nullptr)); rgm.pushMappingsToAncestor(getLayoutBox(webView, "Col3"), nullptr); - EXPECT_NEAR(8.0f + offset * 2.0f, rgm.mapToContainer(point, nullptr).x(), 0.1f); - EXPECT_NEAR(8.0f, rgm.mapToContainer(point, nullptr).y(), 0.1f); EXPECT_NEAR(8.0f + offset * 2.0f, rectFromQuad(rgm.mapToContainer(rect, nullptr)).x(), 0.1f); EXPECT_NEAR(8.0f, rectFromQuad(rgm.mapToContainer(rect, nullptr)).y(), 0.1f); EXPECT_EQ(5.0f, rectFromQuad(rgm.mapToContainer(rect, nullptr)).width());
diff --git a/third_party/WebKit/Source/web/tests/ScrollAnimatorNoneTest.cpp b/third_party/WebKit/Source/web/tests/ScrollAnimatorTest.cpp similarity index 75% rename from third_party/WebKit/Source/web/tests/ScrollAnimatorNoneTest.cpp rename to third_party/WebKit/Source/web/tests/ScrollAnimatorTest.cpp index ce99426..192702f 100644 --- a/third_party/WebKit/Source/web/tests/ScrollAnimatorNoneTest.cpp +++ b/third_party/WebKit/Source/web/tests/ScrollAnimatorTest.cpp
@@ -23,15 +23,15 @@ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -// Tests for the ScrollAnimatorNone class. +// Tests for the ScrollAnimator class. #include "config.h" -#include "platform/scroll/ScrollAnimatorNone.h" +#include "platform/scroll/ScrollAnimator.h" #include "platform/Logging.h" #include "platform/geometry/FloatPoint.h" #include "platform/geometry/IntRect.h" -#include "platform/scroll/ScrollAnimator.h" +#include "platform/scroll/ScrollAnimatorBase.h" #include "platform/scroll/ScrollableArea.h" #include <gmock/gmock.h> #include <gtest/gtest.h> @@ -86,7 +86,7 @@ bool m_scrollAnimatorEnabled; }; -class MockScrollAnimatorNone : public ScrollAnimatorNone { +class MockScrollAnimatorNone : public ScrollAnimator { public: static PassOwnPtr<MockScrollAnimatorNone> create(ScrollableArea* scrollableArea) { @@ -118,7 +118,7 @@ private: explicit MockScrollAnimatorNone(ScrollableArea* scrollableArea) - : ScrollAnimatorNone(scrollableArea) { } + : ScrollAnimator(scrollableArea) { } }; @@ -187,11 +187,11 @@ scrollAnimatorNone->reset(); } -class ScrollAnimatorNoneTest : public testing::Test { +class ScrollAnimatorTest : public testing::Test { public: - struct SavePerAxisData : public ScrollAnimatorNone::PerAxisData { - SavePerAxisData(const ScrollAnimatorNone::PerAxisData& data) - : ScrollAnimatorNone::PerAxisData(0, 768) + struct SavePerAxisData : public ScrollAnimator::PerAxisData { + SavePerAxisData(const ScrollAnimator::PerAxisData& data) + : ScrollAnimator::PerAxisData(0, 768) , m_mockScrollableArea(MockScrollableArea::create(true)) , m_mockScrollAnimatorNone(MockScrollAnimatorNone::create(m_mockScrollableArea.get())) { @@ -219,7 +219,7 @@ OwnPtr<MockScrollAnimatorNone> m_mockScrollAnimatorNone; }; - ScrollAnimatorNoneTest() + ScrollAnimatorTest() : m_mockScrollableArea(MockScrollableArea::create(true)) , m_mockScrollAnimatorNone(MockScrollAnimatorNone::create(m_mockScrollableArea.get())) { @@ -228,7 +228,7 @@ void SetUp() override { m_currentPosition = 100; - m_data = new ScrollAnimatorNone::PerAxisData(&m_currentPosition, 768); + m_data = new ScrollAnimator::PerAxisData(&m_currentPosition, 768); } void TearDown() override { @@ -236,17 +236,17 @@ } void reset(); - bool updateDataFromParameters(float step, float multiplier, float scrollableSize, double currentTime, ScrollAnimatorNone::Parameters*); + bool updateDataFromParameters(float step, float multiplier, float scrollableSize, double currentTime, ScrollAnimator::Parameters*); bool animateScroll(double currentTime); - double attackArea(ScrollAnimatorNone::Curve, double startT, double endT); - double releaseArea(ScrollAnimatorNone::Curve, double startT, double endT); - double attackCurve(ScrollAnimatorNone::Curve, double deltaT, double curveT, double startPosition, double attackPosition); - double releaseCurve(ScrollAnimatorNone::Curve, double deltaT, double curveT, double releasePosition, double desiredPosition); - double coastCurve(ScrollAnimatorNone::Curve, double factor); + double attackArea(ScrollAnimator::Curve, double startT, double endT); + double releaseArea(ScrollAnimator::Curve, double startT, double endT); + double attackCurve(ScrollAnimator::Curve, double deltaT, double curveT, double startPosition, double attackPosition); + double releaseCurve(ScrollAnimator::Curve, double deltaT, double curveT, double releasePosition, double desiredPosition); + double coastCurve(ScrollAnimator::Curve, double factor); - void curveTestInner(ScrollAnimatorNone::Curve, double step, double time); - void curveTest(ScrollAnimatorNone::Curve); + void curveTestInner(ScrollAnimator::Curve, double step, double time); + void curveTest(ScrollAnimator::Curve); void checkDesiredPosition(float expectedPosition); void checkSoftLanding(float expectedPosition); @@ -259,21 +259,21 @@ OwnPtrWillBePersistent<MockScrollableArea> m_mockScrollableArea; OwnPtr<MockScrollAnimatorNone> m_mockScrollAnimatorNone; bool m_scrollingDown; - ScrollAnimatorNone::PerAxisData* m_data; + ScrollAnimator::PerAxisData* m_data; }; -double ScrollAnimatorNoneTest::kTickTime = 1 / 60.0; -double ScrollAnimatorNoneTest::kAnimationTime = 0.01; -double ScrollAnimatorNoneTest::kStartTime = 10.0; -double ScrollAnimatorNoneTest::kEndTime = 20.0; +double ScrollAnimatorTest::kTickTime = 1 / 60.0; +double ScrollAnimatorTest::kAnimationTime = 0.01; +double ScrollAnimatorTest::kStartTime = 10.0; +double ScrollAnimatorTest::kEndTime = 20.0; -void ScrollAnimatorNoneTest::reset() +void ScrollAnimatorTest::reset() { m_data->reset(); m_scrollingDown = true; } -bool ScrollAnimatorNoneTest::updateDataFromParameters(float step, float multiplier, float scrollableSize, double currentTime, ScrollAnimatorNone::Parameters* parameters) +bool ScrollAnimatorTest::updateDataFromParameters(float step, float multiplier, float scrollableSize, double currentTime, ScrollAnimator::Parameters* parameters) { if (step * multiplier) m_scrollingDown = (step * multiplier > 0); @@ -310,7 +310,7 @@ return result; } -bool ScrollAnimatorNoneTest::animateScroll(double currentTime) +bool ScrollAnimatorTest::animateScroll(double currentTime) { double oldPosition = *m_data->m_currentPosition; bool testEstimatedMaxVelocity = m_data->m_startTime + m_data->m_animationTime - m_data->m_lastAnimationTime > m_data->m_releaseTime; @@ -338,32 +338,32 @@ return result; } -double ScrollAnimatorNoneTest::attackArea(ScrollAnimatorNone::Curve curve, double startT, double endT) +double ScrollAnimatorTest::attackArea(ScrollAnimator::Curve curve, double startT, double endT) { - return ScrollAnimatorNone::PerAxisData::attackArea(curve, startT, endT); + return ScrollAnimator::PerAxisData::attackArea(curve, startT, endT); } -double ScrollAnimatorNoneTest::releaseArea(ScrollAnimatorNone::Curve curve, double startT, double endT) +double ScrollAnimatorTest::releaseArea(ScrollAnimator::Curve curve, double startT, double endT) { - return ScrollAnimatorNone::PerAxisData::releaseArea(curve, startT, endT); + return ScrollAnimator::PerAxisData::releaseArea(curve, startT, endT); } -double ScrollAnimatorNoneTest::attackCurve(ScrollAnimatorNone::Curve curve, double deltaT, double curveT, double startPosition, double attackPosition) +double ScrollAnimatorTest::attackCurve(ScrollAnimator::Curve curve, double deltaT, double curveT, double startPosition, double attackPosition) { - return ScrollAnimatorNone::PerAxisData::attackCurve(curve, deltaT, curveT, startPosition, attackPosition); + return ScrollAnimator::PerAxisData::attackCurve(curve, deltaT, curveT, startPosition, attackPosition); } -double ScrollAnimatorNoneTest::releaseCurve(ScrollAnimatorNone::Curve curve, double deltaT, double curveT, double releasePosition, double desiredPosition) +double ScrollAnimatorTest::releaseCurve(ScrollAnimator::Curve curve, double deltaT, double curveT, double releasePosition, double desiredPosition) { - return ScrollAnimatorNone::PerAxisData::releaseCurve(curve, deltaT, curveT, releasePosition, desiredPosition); + return ScrollAnimator::PerAxisData::releaseCurve(curve, deltaT, curveT, releasePosition, desiredPosition); } -double ScrollAnimatorNoneTest::coastCurve(ScrollAnimatorNone::Curve curve, double factor) +double ScrollAnimatorTest::coastCurve(ScrollAnimator::Curve curve, double factor) { - return ScrollAnimatorNone::PerAxisData::coastCurve(curve, factor); + return ScrollAnimator::PerAxisData::coastCurve(curve, factor); } -void ScrollAnimatorNoneTest::curveTestInner(ScrollAnimatorNone::Curve curve, double step, double time) +void ScrollAnimatorTest::curveTestInner(ScrollAnimator::Curve curve, double step, double time) { const double kPosition = 1000; @@ -380,7 +380,7 @@ accumulate += (oldPos + newPos) / 2 * (step / time); oldPos = newPos; oldVelocity = velocity; - if (curve != ScrollAnimatorNone::Bounce) { + if (curve != ScrollAnimator::Bounce) { EXPECT_LE(-.0001, velocityDelta); EXPECT_LT(0, delta); } @@ -402,7 +402,7 @@ accumulate -= (kPosition - (oldPos + newPos) / 2) * (step / time); oldPos = newPos; oldVelocity = velocity; - if (curve != ScrollAnimatorNone::Bounce) { + if (curve != ScrollAnimator::Bounce) { EXPECT_GE(0.01, velocityDelta); EXPECT_LT(0, delta); } @@ -413,7 +413,7 @@ } } -void ScrollAnimatorNoneTest::curveTest(ScrollAnimatorNone::Curve curve) +void ScrollAnimatorTest::curveTest(ScrollAnimator::Curve curve) { curveTestInner(curve, 0.01, 0.25); curveTestInner(curve, 0.2, 10); @@ -422,57 +422,57 @@ curveTestInner(curve, 0.25, 40); } -void ScrollAnimatorNoneTest::checkDesiredPosition(float expectedPosition) +void ScrollAnimatorTest::checkDesiredPosition(float expectedPosition) { EXPECT_EQ(expectedPosition, m_data->m_desiredPosition); } -void ScrollAnimatorNoneTest::checkSoftLanding(float expectedPosition) +void ScrollAnimatorTest::checkSoftLanding(float expectedPosition) { EXPECT_EQ(expectedPosition, m_currentPosition); EXPECT_LE(m_data->m_desiredVelocity / 2, m_data->m_currentVelocity); } -TEST_F(ScrollAnimatorNoneTest, CurveMathLinear) +TEST_F(ScrollAnimatorTest, CurveMathLinear) { - curveTest(ScrollAnimatorNone::Linear); + curveTest(ScrollAnimator::Linear); } -TEST_F(ScrollAnimatorNoneTest, CurveMathQuadratic) +TEST_F(ScrollAnimatorTest, CurveMathQuadratic) { - curveTest(ScrollAnimatorNone::Quadratic); + curveTest(ScrollAnimator::Quadratic); } -TEST_F(ScrollAnimatorNoneTest, CurveMathCubic) +TEST_F(ScrollAnimatorTest, CurveMathCubic) { - curveTest(ScrollAnimatorNone::Cubic); + curveTest(ScrollAnimator::Cubic); } -TEST_F(ScrollAnimatorNoneTest, CurveMathQuartic) +TEST_F(ScrollAnimatorTest, CurveMathQuartic) { - curveTest(ScrollAnimatorNone::Quartic); + curveTest(ScrollAnimator::Quartic); } -TEST_F(ScrollAnimatorNoneTest, CurveMathBounce) +TEST_F(ScrollAnimatorTest, CurveMathBounce) { - curveTest(ScrollAnimatorNone::Bounce); + curveTest(ScrollAnimator::Bounce); } -TEST_F(ScrollAnimatorNoneTest, CurveMathCoast) +TEST_F(ScrollAnimatorTest, CurveMathCoast) { for (double t = .25; t < 1; t += .25) { - EXPECT_EQ(t, coastCurve(ScrollAnimatorNone::Linear, t)); - EXPECT_LT(t, coastCurve(ScrollAnimatorNone::Quadratic, t)); - EXPECT_LT(t, coastCurve(ScrollAnimatorNone::Cubic, t)); - EXPECT_LT(coastCurve(ScrollAnimatorNone::Quadratic, t), coastCurve(ScrollAnimatorNone::Cubic, t)); - EXPECT_LT(t, coastCurve(ScrollAnimatorNone::Quartic, t)); - EXPECT_LT(coastCurve(ScrollAnimatorNone::Cubic, t), coastCurve(ScrollAnimatorNone::Quartic, t)); + EXPECT_EQ(t, coastCurve(ScrollAnimator::Linear, t)); + EXPECT_LT(t, coastCurve(ScrollAnimator::Quadratic, t)); + EXPECT_LT(t, coastCurve(ScrollAnimator::Cubic, t)); + EXPECT_LT(coastCurve(ScrollAnimator::Quadratic, t), coastCurve(ScrollAnimator::Cubic, t)); + EXPECT_LT(t, coastCurve(ScrollAnimator::Quartic, t)); + EXPECT_LT(coastCurve(ScrollAnimator::Cubic, t), coastCurve(ScrollAnimator::Quartic, t)); } } -TEST_F(ScrollAnimatorNoneTest, ScrollOnceLinear) +TEST_F(ScrollAnimatorTest, ScrollOnceLinear) { - ScrollAnimatorNone::Parameters parameters(true, 7 * kTickTime, 0, ScrollAnimatorNone::Linear, 3 * kTickTime, ScrollAnimatorNone::Linear, 3 * kTickTime, ScrollAnimatorNone::Linear, 0); + ScrollAnimator::Parameters parameters(true, 7 * kTickTime, 0, ScrollAnimator::Linear, 3 * kTickTime, ScrollAnimator::Linear, 3 * kTickTime, ScrollAnimator::Linear, 0); EXPECT_TRUE(updateDataFromParameters(1, 40, 1000, kStartTime, ¶meters)); bool result = true; @@ -480,9 +480,9 @@ result = animateScroll(t); } -TEST_F(ScrollAnimatorNoneTest, ScrollOnceQuadratic) +TEST_F(ScrollAnimatorTest, ScrollOnceQuadratic) { - ScrollAnimatorNone::Parameters parameters(true, 7 * kTickTime, 0, ScrollAnimatorNone::Quadratic, 3 * kTickTime, ScrollAnimatorNone::Quadratic, 3 * kTickTime, ScrollAnimatorNone::Linear, 0); + ScrollAnimator::Parameters parameters(true, 7 * kTickTime, 0, ScrollAnimator::Quadratic, 3 * kTickTime, ScrollAnimator::Quadratic, 3 * kTickTime, ScrollAnimator::Linear, 0); EXPECT_TRUE(updateDataFromParameters(1, 40, 1000, kStartTime, ¶meters)); bool result = true; @@ -490,9 +490,9 @@ result = animateScroll(t); } -TEST_F(ScrollAnimatorNoneTest, ScrollLongQuadratic) +TEST_F(ScrollAnimatorTest, ScrollLongQuadratic) { - ScrollAnimatorNone::Parameters parameters(true, 20 * kTickTime, 0, ScrollAnimatorNone::Quadratic, 3 * kTickTime, ScrollAnimatorNone::Quadratic, 3 * kTickTime, ScrollAnimatorNone::Linear, 0); + ScrollAnimator::Parameters parameters(true, 20 * kTickTime, 0, ScrollAnimator::Quadratic, 3 * kTickTime, ScrollAnimator::Quadratic, 3 * kTickTime, ScrollAnimator::Linear, 0); EXPECT_TRUE(updateDataFromParameters(1, 40, 1000, kStartTime, ¶meters)); bool result = true; @@ -500,9 +500,9 @@ result = animateScroll(t); } -TEST_F(ScrollAnimatorNoneTest, ScrollQuadraticNoSustain) +TEST_F(ScrollAnimatorTest, ScrollQuadraticNoSustain) { - ScrollAnimatorNone::Parameters parameters(true, 8 * kTickTime, 0, ScrollAnimatorNone::Quadratic, 4 * kTickTime, ScrollAnimatorNone::Quadratic, 4 * kTickTime, ScrollAnimatorNone::Linear, 0); + ScrollAnimator::Parameters parameters(true, 8 * kTickTime, 0, ScrollAnimator::Quadratic, 4 * kTickTime, ScrollAnimator::Quadratic, 4 * kTickTime, ScrollAnimator::Linear, 0); EXPECT_TRUE(updateDataFromParameters(1, 40, 1000, kStartTime, ¶meters)); bool result = true; @@ -510,9 +510,9 @@ result = animateScroll(t); } -TEST_F(ScrollAnimatorNoneTest, ScrollQuadraticSmoothed) +TEST_F(ScrollAnimatorTest, ScrollQuadraticSmoothed) { - ScrollAnimatorNone::Parameters parameters(true, 8 * kTickTime, 8 * kTickTime, ScrollAnimatorNone::Quadratic, 4 * kTickTime, ScrollAnimatorNone::Quadratic, 4 * kTickTime, ScrollAnimatorNone::Linear, 0); + ScrollAnimator::Parameters parameters(true, 8 * kTickTime, 8 * kTickTime, ScrollAnimator::Quadratic, 4 * kTickTime, ScrollAnimator::Quadratic, 4 * kTickTime, ScrollAnimator::Linear, 0); EXPECT_TRUE(updateDataFromParameters(1, 40, 1000, kStartTime, ¶meters)); bool result = true; @@ -520,9 +520,9 @@ result = animateScroll(t); } -TEST_F(ScrollAnimatorNoneTest, ScrollOnceCubic) +TEST_F(ScrollAnimatorTest, ScrollOnceCubic) { - ScrollAnimatorNone::Parameters parameters(true, 7 * kTickTime, 0, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Linear, 0); + ScrollAnimator::Parameters parameters(true, 7 * kTickTime, 0, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Linear, 0); EXPECT_TRUE(updateDataFromParameters(1, 40, 1000, kStartTime, ¶meters)); bool result = true; @@ -530,9 +530,9 @@ result = animateScroll(t); } -TEST_F(ScrollAnimatorNoneTest, ScrollOnceQuartic) +TEST_F(ScrollAnimatorTest, ScrollOnceQuartic) { - ScrollAnimatorNone::Parameters parameters(true, 7 * kTickTime, 0, ScrollAnimatorNone::Quartic, 3 * kTickTime, ScrollAnimatorNone::Quartic, 3 * kTickTime, ScrollAnimatorNone::Linear, 0); + ScrollAnimator::Parameters parameters(true, 7 * kTickTime, 0, ScrollAnimator::Quartic, 3 * kTickTime, ScrollAnimator::Quartic, 3 * kTickTime, ScrollAnimator::Linear, 0); EXPECT_TRUE(updateDataFromParameters(1, 40, 1000, kStartTime, ¶meters)); bool result = true; @@ -540,9 +540,9 @@ result = animateScroll(t); } -TEST_F(ScrollAnimatorNoneTest, ScrollOnceShort) +TEST_F(ScrollAnimatorTest, ScrollOnceShort) { - ScrollAnimatorNone::Parameters parameters(true, 7 * kTickTime, 0, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Linear, 0); + ScrollAnimator::Parameters parameters(true, 7 * kTickTime, 0, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Linear, 0); EXPECT_TRUE(updateDataFromParameters(1, 40, 1000, kStartTime, ¶meters)); bool result = true; @@ -550,9 +550,9 @@ result = animateScroll(t); } -TEST_F(ScrollAnimatorNoneTest, ScrollTwiceQuadratic) +TEST_F(ScrollAnimatorTest, ScrollTwiceQuadratic) { - ScrollAnimatorNone::Parameters parameters(true, 7 * kTickTime, 0, ScrollAnimatorNone::Quadratic, 3 * kTickTime, ScrollAnimatorNone::Quadratic, 3 * kTickTime, ScrollAnimatorNone::Linear, 0); + ScrollAnimator::Parameters parameters(true, 7 * kTickTime, 0, ScrollAnimator::Quadratic, 3 * kTickTime, ScrollAnimator::Quadratic, 3 * kTickTime, ScrollAnimator::Linear, 0); EXPECT_TRUE(updateDataFromParameters(1, 40, 1000, kStartTime, ¶meters)); bool result = true; @@ -581,9 +581,9 @@ result = animateScroll(t); } -TEST_F(ScrollAnimatorNoneTest, ScrollLotsQuadratic) +TEST_F(ScrollAnimatorTest, ScrollLotsQuadratic) { - ScrollAnimatorNone::Parameters parameters(true, 7 * kTickTime, 0, ScrollAnimatorNone::Quadratic, 3 * kTickTime, ScrollAnimatorNone::Quadratic, 3 * kTickTime, ScrollAnimatorNone::Linear, 0); + ScrollAnimator::Parameters parameters(true, 7 * kTickTime, 0, ScrollAnimator::Quadratic, 3 * kTickTime, ScrollAnimator::Quadratic, 3 * kTickTime, ScrollAnimator::Linear, 0); EXPECT_TRUE(updateDataFromParameters(1, 40, 10000, kStartTime, ¶meters)); bool result = true; @@ -602,9 +602,9 @@ result = result && animateScroll(t); } -TEST_F(ScrollAnimatorNoneTest, ScrollLotsQuadraticSmoothed) +TEST_F(ScrollAnimatorTest, ScrollLotsQuadraticSmoothed) { - ScrollAnimatorNone::Parameters parameters(true, 10 * kTickTime, 6 * kTickTime, ScrollAnimatorNone::Quadratic, 3 * kTickTime, ScrollAnimatorNone::Quadratic, 3 * kTickTime, ScrollAnimatorNone::Linear, 0); + ScrollAnimator::Parameters parameters(true, 10 * kTickTime, 6 * kTickTime, ScrollAnimator::Quadratic, 3 * kTickTime, ScrollAnimator::Quadratic, 3 * kTickTime, ScrollAnimator::Linear, 0); EXPECT_TRUE(updateDataFromParameters(1, 40, 10000, kStartTime, ¶meters)); bool result = true; @@ -623,9 +623,9 @@ result = result && animateScroll(t); } -TEST_F(ScrollAnimatorNoneTest, ScrollTwiceCubic) +TEST_F(ScrollAnimatorTest, ScrollTwiceCubic) { - ScrollAnimatorNone::Parameters parameters(true, 7 * kTickTime, 0, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Linear, 0); + ScrollAnimator::Parameters parameters(true, 7 * kTickTime, 0, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Linear, 0); EXPECT_TRUE(updateDataFromParameters(1, 40, 1000, kStartTime, ¶meters)); bool result = true; @@ -654,9 +654,9 @@ result = animateScroll(t); } -TEST_F(ScrollAnimatorNoneTest, ScrollLotsCubic) +TEST_F(ScrollAnimatorTest, ScrollLotsCubic) { - ScrollAnimatorNone::Parameters parameters(true, 7 * kTickTime, 0, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Linear, 0); + ScrollAnimator::Parameters parameters(true, 7 * kTickTime, 0, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Linear, 0); EXPECT_TRUE(updateDataFromParameters(1, 40, 10000, kStartTime, ¶meters)); bool result = true; @@ -675,9 +675,9 @@ result = result && animateScroll(t); } -TEST_F(ScrollAnimatorNoneTest, ScrollLotsCubicSmoothed) +TEST_F(ScrollAnimatorTest, ScrollLotsCubicSmoothed) { - ScrollAnimatorNone::Parameters parameters(true, 10 * kTickTime, 6 * kTickTime, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Linear, 0); + ScrollAnimator::Parameters parameters(true, 10 * kTickTime, 6 * kTickTime, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Linear, 0); EXPECT_TRUE(updateDataFromParameters(1, 40, 10000, kStartTime, ¶meters)); bool result = true; @@ -696,9 +696,9 @@ result = result && animateScroll(t); } -TEST_F(ScrollAnimatorNoneTest, ScrollWheelTrace) +TEST_F(ScrollAnimatorTest, ScrollWheelTrace) { - ScrollAnimatorNone::Parameters parameters(true, 11 * kTickTime, 0, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Linear, 0); + ScrollAnimator::Parameters parameters(true, 11 * kTickTime, 0, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Linear, 0); // Constructed from an actual scroll wheel trace that exhibited a glitch. bool result = updateDataFromParameters(1, 53.33f, 1000, 100.5781f, ¶meters); @@ -720,9 +720,9 @@ result = result && animateScroll(t); } -TEST_F(ScrollAnimatorNoneTest, ScrollWheelTraceSmoothed) +TEST_F(ScrollAnimatorTest, ScrollWheelTraceSmoothed) { - ScrollAnimatorNone::Parameters parameters(true, 11 * kTickTime, 7 * kTickTime, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Linear, 0); + ScrollAnimator::Parameters parameters(true, 11 * kTickTime, 7 * kTickTime, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Linear, 0); // Constructed from an actual scroll wheel trace that exhibited a glitch. bool result = updateDataFromParameters(1, 53.33f, 1000, 100.5781f, ¶meters); @@ -744,9 +744,9 @@ result = result && animateScroll(t); } -TEST_F(ScrollAnimatorNoneTest, LinuxTrackPadTrace) +TEST_F(ScrollAnimatorTest, LinuxTrackPadTrace) { - ScrollAnimatorNone::Parameters parameters(true, 11 * kTickTime, 0, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Linear, 0); + ScrollAnimator::Parameters parameters(true, 11 * kTickTime, 0, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Linear, 0); bool result = updateDataFromParameters(1.00, 60.00, 1000, 100.6863, ¶meters); result = result && updateDataFromParameters(1.00, 20.00, 1000, 100.6897, ¶meters); @@ -774,9 +774,9 @@ result = result && animateScroll(t); } -TEST_F(ScrollAnimatorNoneTest, LinuxTrackPadTraceSmoothed) +TEST_F(ScrollAnimatorTest, LinuxTrackPadTraceSmoothed) { - ScrollAnimatorNone::Parameters parameters(true, 11 * kTickTime, 7 * kTickTime, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Linear, 0); + ScrollAnimator::Parameters parameters(true, 11 * kTickTime, 7 * kTickTime, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Linear, 0); bool result = updateDataFromParameters(1.00, 60.00, 1000, 100.6863, ¶meters); result = result && updateDataFromParameters(1.00, 20.00, 1000, 100.6897, ¶meters); @@ -804,9 +804,9 @@ result = result && animateScroll(t); } -TEST_F(ScrollAnimatorNoneTest, ScrollDownToBumper) +TEST_F(ScrollAnimatorTest, ScrollDownToBumper) { - ScrollAnimatorNone::Parameters parameters(true, 10 * kTickTime, 7 * kTickTime, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Linear, 0); + ScrollAnimator::Parameters parameters(true, 10 * kTickTime, 7 * kTickTime, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Linear, 0); EXPECT_TRUE(updateDataFromParameters(1, 20, 200, kStartTime, ¶meters)); bool result = true; @@ -824,9 +824,9 @@ checkSoftLanding(200); } -TEST_F(ScrollAnimatorNoneTest, ScrollUpToBumper) +TEST_F(ScrollAnimatorTest, ScrollUpToBumper) { - ScrollAnimatorNone::Parameters parameters(true, 10 * kTickTime, 7 * kTickTime, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Linear, 0); + ScrollAnimator::Parameters parameters(true, 10 * kTickTime, 7 * kTickTime, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Linear, 0); EXPECT_TRUE(updateDataFromParameters(1, -20, 200, kStartTime, ¶meters)); bool result = true; @@ -844,9 +844,9 @@ checkSoftLanding(0); } -TEST_F(ScrollAnimatorNoneTest, ScrollUpToBumperCoast) +TEST_F(ScrollAnimatorTest, ScrollUpToBumperCoast) { - ScrollAnimatorNone::Parameters parameters(true, 11 * kTickTime, 2 * kTickTime, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Linear, 1); + ScrollAnimator::Parameters parameters(true, 11 * kTickTime, 2 * kTickTime, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Linear, 1); m_currentPosition = 40000; EXPECT_TRUE(updateDataFromParameters(1, -10000, 50000, kStartTime, ¶meters)); @@ -865,9 +865,9 @@ checkSoftLanding(0); } -TEST_F(ScrollAnimatorNoneTest, ScrollDownToBumperCoast) +TEST_F(ScrollAnimatorTest, ScrollDownToBumperCoast) { - ScrollAnimatorNone::Parameters parameters(true, 11 * kTickTime, 2 * kTickTime, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Linear, 1); + ScrollAnimator::Parameters parameters(true, 11 * kTickTime, 2 * kTickTime, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Linear, 1); m_currentPosition = 10000; EXPECT_TRUE(updateDataFromParameters(1, 10000, 50000, kStartTime, ¶meters)); @@ -886,9 +886,9 @@ checkSoftLanding(50000); } -TEST_F(ScrollAnimatorNoneTest, VaryingInputsEquivalency) +TEST_F(ScrollAnimatorTest, VaryingInputsEquivalency) { - ScrollAnimatorNone::Parameters parameters(true, 15 * kTickTime, 10 * kTickTime, ScrollAnimatorNone::Cubic, 5 * kTickTime, ScrollAnimatorNone::Cubic, 5 * kTickTime, ScrollAnimatorNone::Linear, 0); + ScrollAnimator::Parameters parameters(true, 15 * kTickTime, 10 * kTickTime, ScrollAnimator::Cubic, 5 * kTickTime, ScrollAnimator::Cubic, 5 * kTickTime, ScrollAnimator::Linear, 0); reset(); EXPECT_TRUE(updateDataFromParameters(1, 300, 50000, kStartTime, ¶meters)); @@ -919,9 +919,9 @@ EXPECT_EQ(dataSingle, dataMany); } -TEST_F(ScrollAnimatorNoneTest, VaryingInputsEquivalencyCoast) +TEST_F(ScrollAnimatorTest, VaryingInputsEquivalencyCoast) { - ScrollAnimatorNone::Parameters parameters(true, 15 * kTickTime, 10 * kTickTime, ScrollAnimatorNone::Cubic, 5 * kTickTime, ScrollAnimatorNone::Cubic, 5 * kTickTime, ScrollAnimatorNone::Linear, 1); + ScrollAnimator::Parameters parameters(true, 15 * kTickTime, 10 * kTickTime, ScrollAnimator::Cubic, 5 * kTickTime, ScrollAnimator::Cubic, 5 * kTickTime, ScrollAnimator::Linear, 1); reset(); updateDataFromParameters(1, 300, 50000, kStartTime, ¶meters); @@ -952,9 +952,9 @@ EXPECT_EQ(dataSingle, dataMany); } -TEST_F(ScrollAnimatorNoneTest, VaryingInputsEquivalencyCoastLarge) +TEST_F(ScrollAnimatorTest, VaryingInputsEquivalencyCoastLarge) { - ScrollAnimatorNone::Parameters parameters(true, 15 * kTickTime, 10 * kTickTime, ScrollAnimatorNone::Cubic, 5 * kTickTime, ScrollAnimatorNone::Cubic, 5 * kTickTime, ScrollAnimatorNone::Linear, 1); + ScrollAnimator::Parameters parameters(true, 15 * kTickTime, 10 * kTickTime, ScrollAnimator::Cubic, 5 * kTickTime, ScrollAnimator::Cubic, 5 * kTickTime, ScrollAnimator::Linear, 1); reset(); EXPECT_TRUE(updateDataFromParameters(1, 30000, 50000, kStartTime, ¶meters)); @@ -985,9 +985,9 @@ EXPECT_EQ(dataSingle, dataMany); } -TEST_F(ScrollAnimatorNoneTest, VaryingInputsEquivalencyCoastSteep) +TEST_F(ScrollAnimatorTest, VaryingInputsEquivalencyCoastSteep) { - ScrollAnimatorNone::Parameters parameters(true, 15 * kTickTime, 10 * kTickTime, ScrollAnimatorNone::Cubic, 5 * kTickTime, ScrollAnimatorNone::Cubic, 5 * kTickTime, ScrollAnimatorNone::Quadratic, 1); + ScrollAnimator::Parameters parameters(true, 15 * kTickTime, 10 * kTickTime, ScrollAnimator::Cubic, 5 * kTickTime, ScrollAnimator::Cubic, 5 * kTickTime, ScrollAnimator::Quadratic, 1); reset(); EXPECT_TRUE(updateDataFromParameters(1, 30000, 50000, kStartTime, ¶meters)); @@ -1018,9 +1018,9 @@ EXPECT_EQ(dataSingle, dataMany); } -TEST_F(ScrollAnimatorNoneTest, ScrollStopInMiddle) +TEST_F(ScrollAnimatorTest, ScrollStopInMiddle) { - ScrollAnimatorNone::Parameters parameters(true, 7 * kTickTime, 0, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Linear, 0); + ScrollAnimator::Parameters parameters(true, 7 * kTickTime, 0, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Linear, 0); EXPECT_TRUE(updateDataFromParameters(1, 40, 1000, kStartTime, ¶meters)); bool result = true; @@ -1039,9 +1039,9 @@ checkDesiredPosition(after); } -TEST_F(ScrollAnimatorNoneTest, ReverseInMiddle) +TEST_F(ScrollAnimatorTest, ReverseInMiddle) { - ScrollAnimatorNone::Parameters parameters(true, 7 * kTickTime, 0, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Cubic, 3 * kTickTime, ScrollAnimatorNone::Linear, 0); + ScrollAnimator::Parameters parameters(true, 7 * kTickTime, 0, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Cubic, 3 * kTickTime, ScrollAnimator::Linear, 0); EXPECT_TRUE(updateDataFromParameters(1, 40, 1000, kStartTime, ¶meters)); bool result = true;
diff --git a/third_party/WebKit/Source/web/tests/VisualViewportTest.cpp b/third_party/WebKit/Source/web/tests/VisualViewportTest.cpp index 97e7454..3ff6baf85 100644 --- a/third_party/WebKit/Source/web/tests/VisualViewportTest.cpp +++ b/third_party/WebKit/Source/web/tests/VisualViewportTest.cpp
@@ -1588,7 +1588,7 @@ // Tests that the slow scrolling after an impl scroll on the visual viewport // is continuous. crbug.com/453460 was caused by the impl-path not updating the -// ScrollAnimator class. +// ScrollAnimatorBase class. TEST_P(ParameterizedVisualViewportTest, SlowScrollAfterImplScroll) { initializeWithDesktopSettings();
diff --git a/third_party/WebKit/Source/web/web.gypi b/third_party/WebKit/Source/web/web.gypi index f2398dd..d87ce5c 100644 --- a/third_party/WebKit/Source/web/web.gypi +++ b/third_party/WebKit/Source/web/web.gypi
@@ -156,8 +156,6 @@ 'WebGeolocationPermissionRequestManager.cpp', 'WebGeolocationPosition.cpp', 'WebGlyphCache.cpp', - 'WebGraphicsContextImpl.cpp', - 'WebGraphicsContextImpl.h', 'WebHeap.cpp', 'WebHelperPluginImpl.cpp', 'WebHelperPluginImpl.h', @@ -323,8 +321,8 @@ ['OS!="mac"', { 'web_unittest_files': [ - # Mac uses ScrollAnimatorMac instead of ScrollAnimatorNone. - 'tests/ScrollAnimatorNoneTest.cpp', + # Mac uses ScrollAnimatorMac instead of ScrollAnimator. + 'tests/ScrollAnimatorTest.cpp', ], } ],
diff --git a/third_party/WebKit/public/blink_headers.gypi b/third_party/WebKit/public/blink_headers.gypi index c5f7e281..5200f13 100644 --- a/third_party/WebKit/public/blink_headers.gypi +++ b/third_party/WebKit/public/blink_headers.gypi
@@ -408,7 +408,6 @@ "web/WebGeolocationPermissionRequestManager.h", "web/WebGeolocationPosition.h", "web/WebGlyphCache.h", - "web/WebGraphicsContext.h", "web/WebHeap.h", "web/WebHelperPlugin.h", "web/WebHistoryCommitType.h",
diff --git a/third_party/WebKit/public/platform/WebMediaPlayer.h b/third_party/WebKit/public/platform/WebMediaPlayer.h index cf26022..9670be7 100644 --- a/third_party/WebKit/public/platform/WebMediaPlayer.h +++ b/third_party/WebKit/public/platform/WebMediaPlayer.h
@@ -164,32 +164,17 @@ virtual void paint(WebCanvas*, const WebRect&, unsigned char alpha, SkXfermode::Mode) = 0; + // TODO(dshwang): remove non-|target| version. crbug.com/349871 + virtual bool copyVideoTextureToPlatformTexture(WebGraphicsContext3D*, unsigned texture, unsigned internalFormat, unsigned type, bool premultiplyAlpha, bool flipY) { return false; } + // Do a GPU-GPU textures copy. If the copy is impossible or fails, it returns false. - // Copy the video frame texture to full texture or sub texture depending on |copyType|. - // If FullCopy, |xoffset| and |yoffset| must be 0. - // If SubCopy, |internalFormat| and |type| must be GL_FALSE. - struct CopyVideoTextureParams { - enum CopyType { FullCopy, SubCopy }; - CopyVideoTextureParams(CopyType copyType, unsigned target, - unsigned texture, unsigned internalFormat, unsigned type, int level, - int xoffset, int yoffset, bool premultiplyAlpha, bool flipY) - : copyType(copyType), target(target), texture(texture) - , internalFormat(internalFormat) , type(type), level(level) - , xoffset(xoffset), yoffset(yoffset) - , premultiplyAlpha(premultiplyAlpha), flipY(flipY) - { } - CopyType copyType; - unsigned target; - unsigned texture; - unsigned internalFormat; - unsigned type; - int level; - int xoffset; - int yoffset; - bool premultiplyAlpha; - bool flipY; - }; - virtual bool copyVideoTextureToPlatformTexture(WebGraphicsContext3D*, const CopyVideoTextureParams&) = 0; + virtual bool copyVideoTextureToPlatformTexture(WebGraphicsContext3D*, unsigned target, + unsigned texture, unsigned internalFormat, unsigned type, int level, + bool premultiplyAlpha, bool flipY) { return false; } + // Copy sub video frame texture to |texture|. If the copy is impossible or fails, it returns false. + virtual bool copyVideoSubTextureToPlatformTexture(WebGraphicsContext3D*, unsigned target, + unsigned texture, int level, int xoffset, int yoffset, bool premultiplyAlpha, + bool flipY) { return false; } virtual WebAudioSourceProvider* audioSourceProvider() { return nullptr; }
diff --git a/third_party/WebKit/public/web/WebDevToolsFrontendClient.h b/third_party/WebKit/public/web/WebDevToolsFrontendClient.h index 1f52f40..0377cfe 100644 --- a/third_party/WebKit/public/web/WebDevToolsFrontendClient.h +++ b/third_party/WebKit/public/web/WebDevToolsFrontendClient.h
@@ -39,8 +39,6 @@ public: WebDevToolsFrontendClient() { } - virtual void sendMessageToBackend(const WebString&) { } - virtual void sendMessageToEmbedder(const WebString&) { } virtual bool isUnderTest() { return false; }
diff --git a/third_party/WebKit/public/web/WebGraphicsContext.h b/third_party/WebKit/public/web/WebGraphicsContext.h deleted file mode 100644 index 30053c6..0000000 --- a/third_party/WebKit/public/web/WebGraphicsContext.h +++ /dev/null
@@ -1,27 +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 WebGraphicsContext_h -#define WebGraphicsContext_h - -#include "public/platform/WebCanvas.h" -#include "public/platform/WebFloatRect.h" - -namespace blink { - -// Wraps a blink::GraphicsContext. -// Internal consumers can extract the underlying context (via WebGraphicsContextImpl). -// External consumers can make a single drawing using a WebCanvas. -class WebGraphicsContext { -public: - virtual WebCanvas* beginDrawing(const WebFloatRect& bounds) = 0; - virtual void endDrawing() = 0; - -protected: - ~WebGraphicsContext() { } -}; - -} // namespace blink - -#endif
diff --git a/third_party/WebKit/public/web/WebView.h b/third_party/WebKit/public/web/WebView.h index ccd46ce..49a848d 100644 --- a/third_party/WebKit/public/web/WebView.h +++ b/third_party/WebKit/public/web/WebView.h
@@ -291,8 +291,14 @@ virtual float deviceScaleFactor() const = 0; // Sets the ratio as computed by computePageScaleConstraints. + // TODO(oshima): Remove this once the device scale factor implementation is fully + // migrated to use zooming mechanism. virtual void setDeviceScaleFactor(float) = 0; + // Sets the additional zoom factor used for device scale factor. This is used + // to scale the content by the device scale factor, without affecting zoom level. + virtual void setZoomFactorForDeviceScaleFactor(float) = 0; + // Set and reset the device color profile. virtual void setDeviceColorProfile(const WebVector<char>&) = 0; virtual void resetDeviceColorProfile() = 0;
diff --git a/third_party/WebKit/public/web/WebWidgetClient.h b/third_party/WebKit/public/web/WebWidgetClient.h index 8a937cfa..41fe6692 100644 --- a/third_party/WebKit/public/web/WebWidgetClient.h +++ b/third_party/WebKit/public/web/WebWidgetClient.h
@@ -117,9 +117,6 @@ // displayed. virtual WebScreenInfo screenInfo() { return WebScreenInfo(); } - // Called to get the scale factor of the display. - virtual float deviceScaleFactor() { return 1; } - // When this method gets called, WebWidgetClient implementation should // reset the input method by cancelling any ongoing composition. virtual void resetInputMethod() { }
diff --git a/third_party/libvpx_new/README.chromium b/third_party/libvpx_new/README.chromium index 3e9a70cd..b821f9f 100644 --- a/third_party/libvpx_new/README.chromium +++ b/third_party/libvpx_new/README.chromium
@@ -5,9 +5,9 @@ License File: source/libvpx/LICENSE Security Critical: yes -Date: Monday October 26 2015 +Date: Wednesday October 28 2015 Branch: master -Commit: dc9d36c0a6c749616d5543aa208864d7b0181fea +Commit: 9645cd4826de5a469e163838b997fccfd7907b91 Description: Contains the sources used to compile libvpx binaries used by Google Chrome and
diff --git a/third_party/libvpx_new/source/config/vpx_version.h b/third_party/libvpx_new/source/config/vpx_version.h index 59180dc..b083bbcb 100644 --- a/third_party/libvpx_new/source/config/vpx_version.h +++ b/third_party/libvpx_new/source/config/vpx_version.h
@@ -1,7 +1,7 @@ #define VERSION_MAJOR 1 #define VERSION_MINOR 4 #define VERSION_PATCH 0 -#define VERSION_EXTRA "1593-gdc9d36c" +#define VERSION_EXTRA "1612-g9645cd4" #define VERSION_PACKED ((VERSION_MAJOR<<16)|(VERSION_MINOR<<8)|(VERSION_PATCH)) -#define VERSION_STRING_NOSP "v1.4.0-1593-gdc9d36c" -#define VERSION_STRING " v1.4.0-1593-gdc9d36c" +#define VERSION_STRING_NOSP "v1.4.0-1612-g9645cd4" +#define VERSION_STRING " v1.4.0-1612-g9645cd4"
diff --git a/third_party/libwebp/LICENSE b/third_party/libwebp/LICENSE index 038214a..b111a8a 100644 --- a/third_party/libwebp/LICENSE +++ b/third_party/libwebp/LICENSE
@@ -47,7 +47,7 @@ enforcement activity against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that any of these implementations of WebM or any code incorporated within any of these implementations of WebM -constitutes direct or contributory patent infringement, or inducement of +constitute direct or contributory patent infringement, or inducement of patent infringement, then any patent rights granted to you under this License for these implementations of WebM shall terminate as of the date such litigation is filed.
diff --git a/third_party/libwebp/README.chromium b/third_party/libwebp/README.chromium index 1980a5d..c19fe946 100644 --- a/third_party/libwebp/README.chromium +++ b/third_party/libwebp/README.chromium
@@ -1,14 +1,14 @@ Name: WebP image encoder/decoder Short Name: libwebp URL: http://developers.google.com/speed/webp -Version: v0.4.3 +Version: v0.4.4 License: BSD License File: LICENSE Security Critical: Yes Description: Source archive: - http://downloads.webmproject.org/releases/webp/libwebp-0.4.3.tar.gz + http://downloads.webmproject.org/releases/webp/libwebp-0.4.4.tar.gz WebP is an image format that does both lossy and lossless compression of digital photographic images. WebP consists of a codec based on VP8, that Google @@ -22,4 +22,3 @@ * Merged COPYING/PATENTS to LICENSE Cherry-picks: Revert patch f7fc4bc: dec/webp.c: don't wait for data before reporting w/h - 0250dfc msvc: fix pointer type warning in BitsLog2Floor
diff --git a/third_party/libwebp/dec/buffer.c b/third_party/libwebp/dec/buffer.c index 42feac7..2129312 100644 --- a/third_party/libwebp/dec/buffer.c +++ b/third_party/libwebp/dec/buffer.c
@@ -33,6 +33,11 @@ return (webp_csp_mode >= MODE_RGB && webp_csp_mode < MODE_LAST); } +// strictly speaking, the very last (or first, if flipped) row +// doesn't require padding. +#define MIN_BUFFER_SIZE(WIDTH, HEIGHT, STRIDE) \ + (uint64_t)(STRIDE) * ((HEIGHT) - 1) + (WIDTH) + static VP8StatusCode CheckDecBuffer(const WebPDecBuffer* const buffer) { int ok = 1; const WEBP_CSP_MODE mode = buffer->colorspace; @@ -42,20 +47,22 @@ ok = 0; } else if (!WebPIsRGBMode(mode)) { // YUV checks const WebPYUVABuffer* const buf = &buffer->u.YUVA; + const int uv_width = (width + 1) / 2; + const int uv_height = (height + 1) / 2; const int y_stride = abs(buf->y_stride); const int u_stride = abs(buf->u_stride); const int v_stride = abs(buf->v_stride); const int a_stride = abs(buf->a_stride); - const uint64_t y_size = (uint64_t)y_stride * height; - const uint64_t u_size = (uint64_t)u_stride * ((height + 1) / 2); - const uint64_t v_size = (uint64_t)v_stride * ((height + 1) / 2); - const uint64_t a_size = (uint64_t)a_stride * height; + const uint64_t y_size = MIN_BUFFER_SIZE(width, height, y_stride); + const uint64_t u_size = MIN_BUFFER_SIZE(uv_width, uv_height, u_stride); + const uint64_t v_size = MIN_BUFFER_SIZE(uv_width, uv_height, v_stride); + const uint64_t a_size = MIN_BUFFER_SIZE(width, height, a_stride); ok &= (y_size <= buf->y_size); ok &= (u_size <= buf->u_size); ok &= (v_size <= buf->v_size); ok &= (y_stride >= width); - ok &= (u_stride >= (width + 1) / 2); - ok &= (v_stride >= (width + 1) / 2); + ok &= (u_stride >= uv_width); + ok &= (v_stride >= uv_width); ok &= (buf->y != NULL); ok &= (buf->u != NULL); ok &= (buf->v != NULL); @@ -67,13 +74,14 @@ } else { // RGB checks const WebPRGBABuffer* const buf = &buffer->u.RGBA; const int stride = abs(buf->stride); - const uint64_t size = (uint64_t)stride * height; + const uint64_t size = MIN_BUFFER_SIZE(width, height, stride); ok &= (size <= buf->size); ok &= (stride >= width * kModeBpp[mode]); ok &= (buf->rgba != NULL); } return ok ? VP8_STATUS_OK : VP8_STATUS_INVALID_PARAM; } +#undef MIN_BUFFER_SIZE static VP8StatusCode AllocateBuffer(WebPDecBuffer* const buffer) { const int w = buffer->width;
diff --git a/third_party/libwebp/dec/io.c b/third_party/libwebp/dec/io.c index 8094e44..b2e72f0 100644 --- a/third_party/libwebp/dec/io.c +++ b/third_party/libwebp/dec/io.c
@@ -322,37 +322,31 @@ const size_t work_size = 2 * out_width; // scratch memory for luma rescaler const size_t uv_work_size = 2 * uv_out_width; // and for each u/v ones size_t tmp_size; - int32_t* work; + rescaler_t* work; tmp_size = (work_size + 2 * uv_work_size) * sizeof(*work); if (has_alpha) { tmp_size += work_size * sizeof(*work); } - p->memory = WebPSafeCalloc(1ULL, tmp_size); + p->memory = WebPSafeMalloc(1ULL, tmp_size); if (p->memory == NULL) { return 0; // memory error } - work = (int32_t*)p->memory; + work = (rescaler_t*)p->memory; WebPRescalerInit(&p->scaler_y, io->mb_w, io->mb_h, buf->y, out_width, out_height, buf->y_stride, 1, - io->mb_w, out_width, io->mb_h, out_height, work); WebPRescalerInit(&p->scaler_u, uv_in_width, uv_in_height, buf->u, uv_out_width, uv_out_height, buf->u_stride, 1, - uv_in_width, uv_out_width, - uv_in_height, uv_out_height, work + work_size); WebPRescalerInit(&p->scaler_v, uv_in_width, uv_in_height, buf->v, uv_out_width, uv_out_height, buf->v_stride, 1, - uv_in_width, uv_out_width, - uv_in_height, uv_out_height, work + work_size + uv_work_size); p->emit = EmitRescaledYUV; if (has_alpha) { WebPRescalerInit(&p->scaler_a, io->mb_w, io->mb_h, buf->a, out_width, out_height, buf->a_stride, 1, - io->mb_w, out_width, io->mb_h, out_height, work + work_size + 2 * uv_work_size); p->emit_alpha = EmitRescaledAlphaYUV; WebPInitAlphaProcessing(); @@ -375,9 +369,9 @@ WebPRescalerHasPendingOutput(&p->scaler_u)) { assert(p->last_y + y_pos + num_lines_out < p->output->height); assert(p->scaler_u.y_accum == p->scaler_v.y_accum); - WebPRescalerExportRow(&p->scaler_y, 0); - WebPRescalerExportRow(&p->scaler_u, 0); - WebPRescalerExportRow(&p->scaler_v, 0); + WebPRescalerExportRow(&p->scaler_y); + WebPRescalerExportRow(&p->scaler_u); + WebPRescalerExportRow(&p->scaler_v); convert(p->scaler_y.dst, p->scaler_u.dst, p->scaler_v.dst, dst, p->scaler_y.dst_width); dst += buf->stride; @@ -425,7 +419,7 @@ while (WebPRescalerHasPendingOutput(&p->scaler_a)) { int i; assert(p->last_y + y_pos + num_lines_out < p->output->height); - WebPRescalerExportRow(&p->scaler_a, 0); + WebPRescalerExportRow(&p->scaler_a); for (i = 0; i < width; ++i) { const uint32_t alpha_value = p->scaler_a.dst[i]; dst[4 * i] = alpha_value; @@ -458,7 +452,7 @@ while (WebPRescalerHasPendingOutput(&p->scaler_a)) { int i; assert(p->last_y + y_pos + num_lines_out < p->output->height); - WebPRescalerExportRow(&p->scaler_a, 0); + WebPRescalerExportRow(&p->scaler_a); for (i = 0; i < width; ++i) { // Fill in the alpha value (converted to 4 bits). const uint32_t alpha_value = p->scaler_a.dst[i] >> 4; @@ -495,7 +489,7 @@ const int uv_in_width = (io->mb_w + 1) >> 1; const int uv_in_height = (io->mb_h + 1) >> 1; const size_t work_size = 2 * out_width; // scratch memory for one rescaler - int32_t* work; // rescalers work area + rescaler_t* work; // rescalers work area uint8_t* tmp; // tmp storage for scaled YUV444 samples before RGB conversion size_t tmp_size1, tmp_size2, total_size; @@ -506,30 +500,26 @@ tmp_size2 += out_width; } total_size = tmp_size1 * sizeof(*work) + tmp_size2 * sizeof(*tmp); - p->memory = WebPSafeCalloc(1ULL, total_size); + p->memory = WebPSafeMalloc(1ULL, total_size); if (p->memory == NULL) { return 0; // memory error } - work = (int32_t*)p->memory; + work = (rescaler_t*)p->memory; tmp = (uint8_t*)(work + tmp_size1); WebPRescalerInit(&p->scaler_y, io->mb_w, io->mb_h, tmp + 0 * out_width, out_width, out_height, 0, 1, - io->mb_w, out_width, io->mb_h, out_height, work + 0 * work_size); WebPRescalerInit(&p->scaler_u, uv_in_width, uv_in_height, tmp + 1 * out_width, out_width, out_height, 0, 1, - io->mb_w, 2 * out_width, io->mb_h, 2 * out_height, work + 1 * work_size); WebPRescalerInit(&p->scaler_v, uv_in_width, uv_in_height, tmp + 2 * out_width, out_width, out_height, 0, 1, - io->mb_w, 2 * out_width, io->mb_h, 2 * out_height, work + 2 * work_size); p->emit = EmitRescaledRGB; if (has_alpha) { WebPRescalerInit(&p->scaler_a, io->mb_w, io->mb_h, tmp + 3 * out_width, out_width, out_height, 0, 1, - io->mb_w, out_width, io->mb_h, out_height, work + 3 * work_size); p->emit_alpha = EmitRescaledAlphaRGB; if (p->output->colorspace == MODE_RGBA_4444 ||
diff --git a/third_party/libwebp/dec/vp8i.h b/third_party/libwebp/dec/vp8i.h index a02d9ff..0e6c8f5 100644 --- a/third_party/libwebp/dec/vp8i.h +++ b/third_party/libwebp/dec/vp8i.h
@@ -31,7 +31,7 @@ // version numbers #define DEC_MAJ_VERSION 0 #define DEC_MIN_VERSION 4 -#define DEC_REV_VERSION 3 +#define DEC_REV_VERSION 4 // intra prediction modes enum { B_DC_PRED = 0, // 4x4 modes
diff --git a/third_party/libwebp/dec/vp8l.c b/third_party/libwebp/dec/vp8l.c index e2780e5b..2fa5f40 100644 --- a/third_party/libwebp/dec/vp8l.c +++ b/third_party/libwebp/dec/vp8l.c
@@ -390,13 +390,13 @@ const int in_height = io->mb_h; const int out_height = io->scaled_height; const uint64_t work_size = 2 * num_channels * (uint64_t)out_width; - int32_t* work; // Rescaler work area. - const uint64_t scaled_data_size = num_channels * (uint64_t)out_width; + rescaler_t* work; // Rescaler work area. + const uint64_t scaled_data_size = (uint64_t)out_width; uint32_t* scaled_data; // Temporary storage for scaled BGRA data. const uint64_t memory_size = sizeof(*dec->rescaler) + work_size * sizeof(*work) + scaled_data_size * sizeof(*scaled_data); - uint8_t* memory = (uint8_t*)WebPSafeCalloc(memory_size, sizeof(*memory)); + uint8_t* memory = (uint8_t*)WebPSafeMalloc(memory_size, sizeof(*memory)); if (memory == NULL) { dec->status_ = VP8_STATUS_OUT_OF_MEMORY; return 0; @@ -406,13 +406,12 @@ dec->rescaler = (WebPRescaler*)memory; memory += sizeof(*dec->rescaler); - work = (int32_t*)memory; + work = (rescaler_t*)memory; memory += work_size * sizeof(*work); scaled_data = (uint32_t*)memory; WebPRescalerInit(dec->rescaler, in_width, in_height, (uint8_t*)scaled_data, - out_width, out_height, 0, num_channels, - in_width, out_width, in_height, out_height, work); + out_width, out_height, 0, num_channels, work); return 1; } @@ -427,7 +426,7 @@ int num_lines_out = 0; while (WebPRescalerHasPendingOutput(rescaler)) { uint8_t* const dst = rgba + num_lines_out * rgba_stride; - WebPRescalerExportRow(rescaler, 0); + WebPRescalerExportRow(rescaler); WebPMultARGBRow(src, dst_width, 1); VP8LConvertFromBGRA(src, dst_width, colorspace, dst); ++num_lines_out; @@ -545,7 +544,7 @@ const int dst_width = rescaler->dst_width; int num_lines_out = 0; while (WebPRescalerHasPendingOutput(rescaler)) { - WebPRescalerExportRow(rescaler, 0); + WebPRescalerExportRow(rescaler); WebPMultARGBRow(src, dst_width, 1); ConvertToYUVA(src, dst_width, y_pos, dec->output_); ++y_pos;
diff --git a/third_party/libwebp/dsp/dec_neon.c b/third_party/libwebp/dsp/dec_neon.c index 9c5bc1c..4afae07 100644 --- a/third_party/libwebp/dsp/dec_neon.c +++ b/third_party/libwebp/dsp/dec_neon.c
@@ -24,24 +24,24 @@ // Load/Store vertical edge #define LOAD8x4(c1, c2, c3, c4, b1, b2, stride) \ - "vld4.8 {" #c1"[0], " #c2"[0], " #c3"[0], " #c4"[0]}," #b1 "," #stride"\n" \ - "vld4.8 {" #c1"[1], " #c2"[1], " #c3"[1], " #c4"[1]}," #b2 "," #stride"\n" \ - "vld4.8 {" #c1"[2], " #c2"[2], " #c3"[2], " #c4"[2]}," #b1 "," #stride"\n" \ - "vld4.8 {" #c1"[3], " #c2"[3], " #c3"[3], " #c4"[3]}," #b2 "," #stride"\n" \ - "vld4.8 {" #c1"[4], " #c2"[4], " #c3"[4], " #c4"[4]}," #b1 "," #stride"\n" \ - "vld4.8 {" #c1"[5], " #c2"[5], " #c3"[5], " #c4"[5]}," #b2 "," #stride"\n" \ - "vld4.8 {" #c1"[6], " #c2"[6], " #c3"[6], " #c4"[6]}," #b1 "," #stride"\n" \ - "vld4.8 {" #c1"[7], " #c2"[7], " #c3"[7], " #c4"[7]}," #b2 "," #stride"\n" + "vld4.8 {" #c1 "[0]," #c2 "[0]," #c3 "[0]," #c4 "[0]}," #b1 "," #stride "\n" \ + "vld4.8 {" #c1 "[1]," #c2 "[1]," #c3 "[1]," #c4 "[1]}," #b2 "," #stride "\n" \ + "vld4.8 {" #c1 "[2]," #c2 "[2]," #c3 "[2]," #c4 "[2]}," #b1 "," #stride "\n" \ + "vld4.8 {" #c1 "[3]," #c2 "[3]," #c3 "[3]," #c4 "[3]}," #b2 "," #stride "\n" \ + "vld4.8 {" #c1 "[4]," #c2 "[4]," #c3 "[4]," #c4 "[4]}," #b1 "," #stride "\n" \ + "vld4.8 {" #c1 "[5]," #c2 "[5]," #c3 "[5]," #c4 "[5]}," #b2 "," #stride "\n" \ + "vld4.8 {" #c1 "[6]," #c2 "[6]," #c3 "[6]," #c4 "[6]}," #b1 "," #stride "\n" \ + "vld4.8 {" #c1 "[7]," #c2 "[7]," #c3 "[7]," #c4 "[7]}," #b2 "," #stride "\n" #define STORE8x2(c1, c2, p, stride) \ - "vst2.8 {" #c1"[0], " #c2"[0]}," #p "," #stride " \n" \ - "vst2.8 {" #c1"[1], " #c2"[1]}," #p "," #stride " \n" \ - "vst2.8 {" #c1"[2], " #c2"[2]}," #p "," #stride " \n" \ - "vst2.8 {" #c1"[3], " #c2"[3]}," #p "," #stride " \n" \ - "vst2.8 {" #c1"[4], " #c2"[4]}," #p "," #stride " \n" \ - "vst2.8 {" #c1"[5], " #c2"[5]}," #p "," #stride " \n" \ - "vst2.8 {" #c1"[6], " #c2"[6]}," #p "," #stride " \n" \ - "vst2.8 {" #c1"[7], " #c2"[7]}," #p "," #stride " \n" + "vst2.8 {" #c1 "[0], " #c2 "[0]}," #p "," #stride " \n" \ + "vst2.8 {" #c1 "[1], " #c2 "[1]}," #p "," #stride " \n" \ + "vst2.8 {" #c1 "[2], " #c2 "[2]}," #p "," #stride " \n" \ + "vst2.8 {" #c1 "[3], " #c2 "[3]}," #p "," #stride " \n" \ + "vst2.8 {" #c1 "[4], " #c2 "[4]}," #p "," #stride " \n" \ + "vst2.8 {" #c1 "[5], " #c2 "[5]}," #p "," #stride " \n" \ + "vst2.8 {" #c1 "[6], " #c2 "[6]}," #p "," #stride " \n" \ + "vst2.8 {" #c1 "[7], " #c2 "[7]}," #p "," #stride " \n" #if !defined(WORK_AROUND_GCC)
diff --git a/third_party/libwebp/dsp/dsp.h b/third_party/libwebp/dsp/dsp.h index 2409bae13..a2c3951 100644 --- a/third_party/libwebp/dsp/dsp.h +++ b/third_party/libwebp/dsp/dsp.h
@@ -36,14 +36,9 @@ # define LOCAL_GCC_PREREQ(maj, min) 0 #endif -#ifdef __clang__ -# define LOCAL_CLANG_VERSION ((__clang_major__ << 8) | __clang_minor__) -# define LOCAL_CLANG_PREREQ(maj, min) \ - (LOCAL_CLANG_VERSION >= (((maj) << 8) | (min))) -#else -# define LOCAL_CLANG_VERSION 0 -# define LOCAL_CLANG_PREREQ(maj, min) 0 -#endif // __clang__ +#ifndef __has_builtin +# define __has_builtin(x) 0 +#endif #if defined(_MSC_VER) && _MSC_VER > 1310 && \ (defined(_M_X64) || defined(_M_IX86)) @@ -73,7 +68,8 @@ #define WEBP_USE_NEON #endif -#if defined(__mips__) && !defined(__mips64) && (__mips_isa_rev < 6) +#if defined(__mips__) && !defined(__mips64) && \ + defined(__mips_isa_rev) && (__mips_isa_rev >= 1) && (__mips_isa_rev < 6) #define WEBP_USE_MIPS32 #if (__mips_isa_rev >= 2) #define WEBP_USE_MIPS32_R2
diff --git a/third_party/libwebp/dsp/enc_mips32.c b/third_party/libwebp/dsp/enc_mips32.c index def9a16..6cede18 100644 --- a/third_party/libwebp/dsp/enc_mips32.c +++ b/third_party/libwebp/dsp/enc_mips32.c
@@ -34,26 +34,26 @@ // TEMP0..TEMP3 - registers for corresponding tmp elements // TEMP4..TEMP5 - temporary registers #define VERTICAL_PASS(A, B, C, D, TEMP4, TEMP0, TEMP1, TEMP2, TEMP3) \ - "lh %[temp16], "#A"(%[temp20]) \n\t" \ - "lh %[temp18], "#B"(%[temp20]) \n\t" \ - "lh %[temp17], "#C"(%[temp20]) \n\t" \ - "lh %[temp19], "#D"(%[temp20]) \n\t" \ - "addu %["#TEMP4"], %[temp16], %[temp18] \n\t" \ - "subu %[temp16], %[temp16], %[temp18] \n\t" \ - "mul %["#TEMP0"], %[temp17], %[kC2] \n\t" \ - "mul %[temp18], %[temp19], %[kC1] \n\t" \ - "mul %[temp17], %[temp17], %[kC1] \n\t" \ - "mul %[temp19], %[temp19], %[kC2] \n\t" \ - "sra %["#TEMP0"], %["#TEMP0"], 16 \n\n" \ - "sra %[temp18], %[temp18], 16 \n\n" \ - "sra %[temp17], %[temp17], 16 \n\n" \ - "sra %[temp19], %[temp19], 16 \n\n" \ - "subu %["#TEMP2"], %["#TEMP0"], %[temp18] \n\t" \ - "addu %["#TEMP3"], %[temp17], %[temp19] \n\t" \ - "addu %["#TEMP0"], %["#TEMP4"], %["#TEMP3"] \n\t" \ - "addu %["#TEMP1"], %[temp16], %["#TEMP2"] \n\t" \ - "subu %["#TEMP2"], %[temp16], %["#TEMP2"] \n\t" \ - "subu %["#TEMP3"], %["#TEMP4"], %["#TEMP3"] \n\t" + "lh %[temp16], " #A "(%[temp20]) \n\t" \ + "lh %[temp18], " #B "(%[temp20]) \n\t" \ + "lh %[temp17], " #C "(%[temp20]) \n\t" \ + "lh %[temp19], " #D "(%[temp20]) \n\t" \ + "addu %[" #TEMP4 "], %[temp16], %[temp18] \n\t" \ + "subu %[temp16], %[temp16], %[temp18] \n\t" \ + "mul %[" #TEMP0 "], %[temp17], %[kC2] \n\t" \ + "mul %[temp18], %[temp19], %[kC1] \n\t" \ + "mul %[temp17], %[temp17], %[kC1] \n\t" \ + "mul %[temp19], %[temp19], %[kC2] \n\t" \ + "sra %[" #TEMP0 "], %[" #TEMP0 "], 16 \n\n" \ + "sra %[temp18], %[temp18], 16 \n\n" \ + "sra %[temp17], %[temp17], 16 \n\n" \ + "sra %[temp19], %[temp19], 16 \n\n" \ + "subu %[" #TEMP2 "], %[" #TEMP0 "], %[temp18] \n\t" \ + "addu %[" #TEMP3 "], %[temp17], %[temp19] \n\t" \ + "addu %[" #TEMP0 "], %[" #TEMP4 "], %[" #TEMP3 "] \n\t" \ + "addu %[" #TEMP1 "], %[temp16], %[" #TEMP2 "] \n\t" \ + "subu %[" #TEMP2 "], %[temp16], %[" #TEMP2 "] \n\t" \ + "subu %[" #TEMP3 "], %[" #TEMP4 "], %[" #TEMP3 "] \n\t" // macro for one horizontal pass in ITransformOne // MUL and STORE macros inlined @@ -61,59 +61,59 @@ // temp0..temp15 holds tmp[0]..tmp[15] // A..D - offsets in bytes to load from ref and store to dst buffer // TEMP0, TEMP4, TEMP8 and TEMP12 - registers for corresponding tmp elements -#define HORIZONTAL_PASS(A, B, C, D, TEMP0, TEMP4, TEMP8, TEMP12) \ - "addiu %["#TEMP0"], %["#TEMP0"], 4 \n\t" \ - "addu %[temp16], %["#TEMP0"], %["#TEMP8"] \n\t" \ - "subu %[temp17], %["#TEMP0"], %["#TEMP8"] \n\t" \ - "mul %["#TEMP0"], %["#TEMP4"], %[kC2] \n\t" \ - "mul %["#TEMP8"], %["#TEMP12"], %[kC1] \n\t" \ - "mul %["#TEMP4"], %["#TEMP4"], %[kC1] \n\t" \ - "mul %["#TEMP12"], %["#TEMP12"], %[kC2] \n\t" \ - "sra %["#TEMP0"], %["#TEMP0"], 16 \n\t" \ - "sra %["#TEMP8"], %["#TEMP8"], 16 \n\t" \ - "sra %["#TEMP4"], %["#TEMP4"], 16 \n\t" \ - "sra %["#TEMP12"], %["#TEMP12"], 16 \n\t" \ - "subu %[temp18], %["#TEMP0"], %["#TEMP8"] \n\t" \ - "addu %[temp19], %["#TEMP4"], %["#TEMP12"] \n\t" \ - "addu %["#TEMP0"], %[temp16], %[temp19] \n\t" \ - "addu %["#TEMP4"], %[temp17], %[temp18] \n\t" \ - "subu %["#TEMP8"], %[temp17], %[temp18] \n\t" \ - "subu %["#TEMP12"], %[temp16], %[temp19] \n\t" \ - "lw %[temp20], 0(%[args]) \n\t" \ - "sra %["#TEMP0"], %["#TEMP0"], 3 \n\t" \ - "sra %["#TEMP4"], %["#TEMP4"], 3 \n\t" \ - "sra %["#TEMP8"], %["#TEMP8"], 3 \n\t" \ - "sra %["#TEMP12"], %["#TEMP12"], 3 \n\t" \ - "lbu %[temp16], "#A"(%[temp20]) \n\t" \ - "lbu %[temp17], "#B"(%[temp20]) \n\t" \ - "lbu %[temp18], "#C"(%[temp20]) \n\t" \ - "lbu %[temp19], "#D"(%[temp20]) \n\t" \ - "addu %["#TEMP0"], %[temp16], %["#TEMP0"] \n\t" \ - "addu %["#TEMP4"], %[temp17], %["#TEMP4"] \n\t" \ - "addu %["#TEMP8"], %[temp18], %["#TEMP8"] \n\t" \ - "addu %["#TEMP12"], %[temp19], %["#TEMP12"] \n\t" \ - "slt %[temp16], %["#TEMP0"], $zero \n\t" \ - "slt %[temp17], %["#TEMP4"], $zero \n\t" \ - "slt %[temp18], %["#TEMP8"], $zero \n\t" \ - "slt %[temp19], %["#TEMP12"], $zero \n\t" \ - "movn %["#TEMP0"], $zero, %[temp16] \n\t" \ - "movn %["#TEMP4"], $zero, %[temp17] \n\t" \ - "movn %["#TEMP8"], $zero, %[temp18] \n\t" \ - "movn %["#TEMP12"], $zero, %[temp19] \n\t" \ - "addiu %[temp20], $zero, 255 \n\t" \ - "slt %[temp16], %["#TEMP0"], %[temp20] \n\t" \ - "slt %[temp17], %["#TEMP4"], %[temp20] \n\t" \ - "slt %[temp18], %["#TEMP8"], %[temp20] \n\t" \ - "slt %[temp19], %["#TEMP12"], %[temp20] \n\t" \ - "movz %["#TEMP0"], %[temp20], %[temp16] \n\t" \ - "movz %["#TEMP4"], %[temp20], %[temp17] \n\t" \ - "lw %[temp16], 8(%[args]) \n\t" \ - "movz %["#TEMP8"], %[temp20], %[temp18] \n\t" \ - "movz %["#TEMP12"], %[temp20], %[temp19] \n\t" \ - "sb %["#TEMP0"], "#A"(%[temp16]) \n\t" \ - "sb %["#TEMP4"], "#B"(%[temp16]) \n\t" \ - "sb %["#TEMP8"], "#C"(%[temp16]) \n\t" \ - "sb %["#TEMP12"], "#D"(%[temp16]) \n\t" +#define HORIZONTAL_PASS(A, B, C, D, TEMP0, TEMP4, TEMP8, TEMP12) \ + "addiu %[" #TEMP0 "], %[" #TEMP0 "], 4 \n\t" \ + "addu %[temp16], %[" #TEMP0 "], %[" #TEMP8 "] \n\t" \ + "subu %[temp17], %[" #TEMP0 "], %[" #TEMP8 "] \n\t" \ + "mul %[" #TEMP0 "], %[" #TEMP4 "], %[kC2] \n\t" \ + "mul %[" #TEMP8 "], %[" #TEMP12 "], %[kC1] \n\t" \ + "mul %[" #TEMP4 "], %[" #TEMP4 "], %[kC1] \n\t" \ + "mul %[" #TEMP12 "], %[" #TEMP12 "], %[kC2] \n\t" \ + "sra %[" #TEMP0 "], %[" #TEMP0 "], 16 \n\t" \ + "sra %[" #TEMP8 "], %[" #TEMP8 "], 16 \n\t" \ + "sra %[" #TEMP4 "], %[" #TEMP4 "], 16 \n\t" \ + "sra %[" #TEMP12 "], %[" #TEMP12 "], 16 \n\t" \ + "subu %[temp18], %[" #TEMP0 "], %[" #TEMP8 "] \n\t" \ + "addu %[temp19], %[" #TEMP4 "], %[" #TEMP12 "] \n\t" \ + "addu %[" #TEMP0 "], %[temp16], %[temp19] \n\t" \ + "addu %[" #TEMP4 "], %[temp17], %[temp18] \n\t" \ + "subu %[" #TEMP8 "], %[temp17], %[temp18] \n\t" \ + "subu %[" #TEMP12 "], %[temp16], %[temp19] \n\t" \ + "lw %[temp20], 0(%[args]) \n\t" \ + "sra %[" #TEMP0 "], %[" #TEMP0 "], 3 \n\t" \ + "sra %[" #TEMP4 "], %[" #TEMP4 "], 3 \n\t" \ + "sra %[" #TEMP8 "], %[" #TEMP8 "], 3 \n\t" \ + "sra %[" #TEMP12 "], %[" #TEMP12 "], 3 \n\t" \ + "lbu %[temp16], " #A "(%[temp20]) \n\t" \ + "lbu %[temp17], " #B "(%[temp20]) \n\t" \ + "lbu %[temp18], " #C "(%[temp20]) \n\t" \ + "lbu %[temp19], " #D "(%[temp20]) \n\t" \ + "addu %[" #TEMP0 "], %[temp16], %[" #TEMP0 "] \n\t" \ + "addu %[" #TEMP4 "], %[temp17], %[" #TEMP4 "] \n\t" \ + "addu %[" #TEMP8 "], %[temp18], %[" #TEMP8 "] \n\t" \ + "addu %[" #TEMP12 "], %[temp19], %[" #TEMP12 "] \n\t" \ + "slt %[temp16], %[" #TEMP0 "], $zero \n\t" \ + "slt %[temp17], %[" #TEMP4 "], $zero \n\t" \ + "slt %[temp18], %[" #TEMP8 "], $zero \n\t" \ + "slt %[temp19], %[" #TEMP12 "], $zero \n\t" \ + "movn %[" #TEMP0 "], $zero, %[temp16] \n\t" \ + "movn %[" #TEMP4 "], $zero, %[temp17] \n\t" \ + "movn %[" #TEMP8 "], $zero, %[temp18] \n\t" \ + "movn %[" #TEMP12 "], $zero, %[temp19] \n\t" \ + "addiu %[temp20], $zero, 255 \n\t" \ + "slt %[temp16], %[" #TEMP0 "], %[temp20] \n\t" \ + "slt %[temp17], %[" #TEMP4 "], %[temp20] \n\t" \ + "slt %[temp18], %[" #TEMP8 "], %[temp20] \n\t" \ + "slt %[temp19], %[" #TEMP12 "], %[temp20] \n\t" \ + "movz %[" #TEMP0 "], %[temp20], %[temp16] \n\t" \ + "movz %[" #TEMP4 "], %[temp20], %[temp17] \n\t" \ + "lw %[temp16], 8(%[args]) \n\t" \ + "movz %[" #TEMP8 "], %[temp20], %[temp18] \n\t" \ + "movz %[" #TEMP12 "], %[temp20], %[temp19] \n\t" \ + "sb %[" #TEMP0 "], " #A "(%[temp16]) \n\t" \ + "sb %[" #TEMP4 "], " #B "(%[temp16]) \n\t" \ + "sb %[" #TEMP8 "], " #C "(%[temp16]) \n\t" \ + "sb %[" #TEMP12 "], " #D "(%[temp16]) \n\t" // Does one or two inverse transforms. static WEBP_INLINE void ITransformOne(const uint8_t* ref, const int16_t* in, @@ -164,9 +164,9 @@ // K - offset in bytes (kZigzag[n] * 4) // N - offset in bytes (n * 2) #define QUANTIZE_ONE(J, K, N) \ - "lh %[temp0], "#J"(%[ppin]) \n\t" \ - "lhu %[temp1], "#J"(%[ppsharpen]) \n\t" \ - "lw %[temp2], "#K"(%[ppzthresh]) \n\t" \ + "lh %[temp0], " #J "(%[ppin]) \n\t" \ + "lhu %[temp1], " #J "(%[ppsharpen]) \n\t" \ + "lw %[temp2], " #K "(%[ppzthresh]) \n\t" \ "sra %[sign], %[temp0], 15 \n\t" \ "xor %[coeff], %[temp0], %[sign] \n\t" \ "subu %[coeff], %[coeff], %[sign] \n\t" \ @@ -175,9 +175,9 @@ "addiu %[temp5], $zero, 0 \n\t" \ "addiu %[level], $zero, 0 \n\t" \ "beqz %[temp4], 2f \n\t" \ - "lhu %[temp1], "#J"(%[ppiq]) \n\t" \ - "lw %[temp2], "#K"(%[ppbias]) \n\t" \ - "lhu %[temp3], "#J"(%[ppq]) \n\t" \ + "lhu %[temp1], " #J "(%[ppiq]) \n\t" \ + "lw %[temp2], " #K "(%[ppbias]) \n\t" \ + "lhu %[temp3], " #J "(%[ppq]) \n\t" \ "mul %[level], %[coeff], %[temp1] \n\t" \ "addu %[level], %[level], %[temp2] \n\t" \ "sra %[level], %[level], 17 \n\t" \ @@ -187,8 +187,8 @@ "subu %[level], %[level], %[sign] \n\t" \ "mul %[temp5], %[level], %[temp3] \n\t" \ "2: \n\t" \ - "sh %[temp5], "#J"(%[ppin]) \n\t" \ - "sh %[level], "#N"(%[pout]) \n\t" + "sh %[temp5], " #J "(%[ppin]) \n\t" \ + "sh %[level], " #N "(%[pout]) \n\t" static int QuantizeBlock(int16_t in[16], int16_t out[16], const VP8Matrix* const mtx) { @@ -249,14 +249,14 @@ // E..H - offsets in bytes to store first results to tmp buffer // E1..H1 - offsets in bytes to store second results to tmp buffer #define HORIZONTAL_PASS(A, B, C, D, E, F, G, H, E1, F1, G1, H1) \ - "lbu %[temp0], "#A"(%[a]) \n\t" \ - "lbu %[temp1], "#B"(%[a]) \n\t" \ - "lbu %[temp2], "#C"(%[a]) \n\t" \ - "lbu %[temp3], "#D"(%[a]) \n\t" \ - "lbu %[temp4], "#A"(%[b]) \n\t" \ - "lbu %[temp5], "#B"(%[b]) \n\t" \ - "lbu %[temp6], "#C"(%[b]) \n\t" \ - "lbu %[temp7], "#D"(%[b]) \n\t" \ + "lbu %[temp0], " #A "(%[a]) \n\t" \ + "lbu %[temp1], " #B "(%[a]) \n\t" \ + "lbu %[temp2], " #C "(%[a]) \n\t" \ + "lbu %[temp3], " #D "(%[a]) \n\t" \ + "lbu %[temp4], " #A "(%[b]) \n\t" \ + "lbu %[temp5], " #B "(%[b]) \n\t" \ + "lbu %[temp6], " #C "(%[b]) \n\t" \ + "lbu %[temp7], " #D "(%[b]) \n\t" \ "addu %[temp8], %[temp0], %[temp2] \n\t" \ "subu %[temp0], %[temp0], %[temp2] \n\t" \ "addu %[temp2], %[temp1], %[temp3] \n\t" \ @@ -273,14 +273,14 @@ "subu %[temp3], %[temp3], %[temp6] \n\t" \ "addu %[temp6], %[temp4], %[temp5] \n\t" \ "subu %[temp4], %[temp4], %[temp5] \n\t" \ - "sw %[temp7], "#E"(%[tmp]) \n\t" \ - "sw %[temp2], "#H"(%[tmp]) \n\t" \ - "sw %[temp8], "#F"(%[tmp]) \n\t" \ - "sw %[temp0], "#G"(%[tmp]) \n\t" \ - "sw %[temp1], "#E1"(%[tmp]) \n\t" \ - "sw %[temp3], "#H1"(%[tmp]) \n\t" \ - "sw %[temp6], "#F1"(%[tmp]) \n\t" \ - "sw %[temp4], "#G1"(%[tmp]) \n\t" + "sw %[temp7], " #E "(%[tmp]) \n\t" \ + "sw %[temp2], " #H "(%[tmp]) \n\t" \ + "sw %[temp8], " #F "(%[tmp]) \n\t" \ + "sw %[temp0], " #G "(%[tmp]) \n\t" \ + "sw %[temp1], " #E1 "(%[tmp]) \n\t" \ + "sw %[temp3], " #H1 "(%[tmp]) \n\t" \ + "sw %[temp6], " #F1 "(%[tmp]) \n\t" \ + "sw %[temp4], " #G1 "(%[tmp]) \n\t" // macro for one vertical pass in Disto4x4 (TTransform) // two calls of function TTransform are merged into single one @@ -295,10 +295,10 @@ // A1..D1 - offsets in bytes to load second results from tmp buffer // E..H - offsets in bytes to load from w buffer #define VERTICAL_PASS(A, B, C, D, A1, B1, C1, D1, E, F, G, H) \ - "lw %[temp0], "#A1"(%[tmp]) \n\t" \ - "lw %[temp1], "#C1"(%[tmp]) \n\t" \ - "lw %[temp2], "#B1"(%[tmp]) \n\t" \ - "lw %[temp3], "#D1"(%[tmp]) \n\t" \ + "lw %[temp0], " #A1 "(%[tmp]) \n\t" \ + "lw %[temp1], " #C1 "(%[tmp]) \n\t" \ + "lw %[temp2], " #B1 "(%[tmp]) \n\t" \ + "lw %[temp3], " #D1 "(%[tmp]) \n\t" \ "addu %[temp8], %[temp0], %[temp1] \n\t" \ "subu %[temp0], %[temp0], %[temp1] \n\t" \ "addu %[temp1], %[temp2], %[temp3] \n\t" \ @@ -319,18 +319,18 @@ "subu %[temp1], %[temp1], %[temp5] \n\t" \ "subu %[temp0], %[temp0], %[temp6] \n\t" \ "subu %[temp8], %[temp8], %[temp7] \n\t" \ - "lhu %[temp4], "#E"(%[w]) \n\t" \ - "lhu %[temp5], "#F"(%[w]) \n\t" \ - "lhu %[temp6], "#G"(%[w]) \n\t" \ - "lhu %[temp7], "#H"(%[w]) \n\t" \ + "lhu %[temp4], " #E "(%[w]) \n\t" \ + "lhu %[temp5], " #F "(%[w]) \n\t" \ + "lhu %[temp6], " #G "(%[w]) \n\t" \ + "lhu %[temp7], " #H "(%[w]) \n\t" \ "madd %[temp4], %[temp3] \n\t" \ "madd %[temp5], %[temp1] \n\t" \ "madd %[temp6], %[temp0] \n\t" \ "madd %[temp7], %[temp8] \n\t" \ - "lw %[temp0], "#A"(%[tmp]) \n\t" \ - "lw %[temp1], "#C"(%[tmp]) \n\t" \ - "lw %[temp2], "#B"(%[tmp]) \n\t" \ - "lw %[temp3], "#D"(%[tmp]) \n\t" \ + "lw %[temp0], " #A "(%[tmp]) \n\t" \ + "lw %[temp1], " #C "(%[tmp]) \n\t" \ + "lw %[temp2], " #B "(%[tmp]) \n\t" \ + "lw %[temp3], " #D "(%[tmp]) \n\t" \ "addu %[temp8], %[temp0], %[temp1] \n\t" \ "subu %[temp0], %[temp0], %[temp1] \n\t" \ "addu %[temp1], %[temp2], %[temp3] \n\t" \ @@ -407,71 +407,71 @@ // temp0..temp15 holds tmp[0]..tmp[15] // A..D - offsets in bytes to load from src and ref buffers // TEMP0..TEMP3 - registers for corresponding tmp elements -#define HORIZONTAL_PASS(A, B, C, D, TEMP0, TEMP1, TEMP2, TEMP3) \ - "lw %["#TEMP1"], 0(%[args]) \n\t" \ - "lw %["#TEMP2"], 4(%[args]) \n\t" \ - "lbu %[temp16], "#A"(%["#TEMP1"]) \n\t" \ - "lbu %[temp17], "#A"(%["#TEMP2"]) \n\t" \ - "lbu %[temp18], "#B"(%["#TEMP1"]) \n\t" \ - "lbu %[temp19], "#B"(%["#TEMP2"]) \n\t" \ - "subu %[temp20], %[temp16], %[temp17] \n\t" \ - "lbu %[temp16], "#C"(%["#TEMP1"]) \n\t" \ - "lbu %[temp17], "#C"(%["#TEMP2"]) \n\t" \ - "subu %["#TEMP0"], %[temp18], %[temp19] \n\t" \ - "lbu %[temp18], "#D"(%["#TEMP1"]) \n\t" \ - "lbu %[temp19], "#D"(%["#TEMP2"]) \n\t" \ - "subu %["#TEMP1"], %[temp16], %[temp17] \n\t" \ - "subu %["#TEMP2"], %[temp18], %[temp19] \n\t" \ - "addu %["#TEMP3"], %[temp20], %["#TEMP2"] \n\t" \ - "subu %["#TEMP2"], %[temp20], %["#TEMP2"] \n\t" \ - "addu %[temp20], %["#TEMP0"], %["#TEMP1"] \n\t" \ - "subu %["#TEMP0"], %["#TEMP0"], %["#TEMP1"] \n\t" \ - "mul %[temp16], %["#TEMP2"], %[c5352] \n\t" \ - "mul %[temp17], %["#TEMP2"], %[c2217] \n\t" \ - "mul %[temp18], %["#TEMP0"], %[c5352] \n\t" \ - "mul %[temp19], %["#TEMP0"], %[c2217] \n\t" \ - "addu %["#TEMP1"], %["#TEMP3"], %[temp20] \n\t" \ - "subu %[temp20], %["#TEMP3"], %[temp20] \n\t" \ - "sll %["#TEMP0"], %["#TEMP1"], 3 \n\t" \ - "sll %["#TEMP2"], %[temp20], 3 \n\t" \ - "addiu %[temp16], %[temp16], 1812 \n\t" \ - "addiu %[temp17], %[temp17], 937 \n\t" \ - "addu %[temp16], %[temp16], %[temp19] \n\t" \ - "subu %[temp17], %[temp17], %[temp18] \n\t" \ - "sra %["#TEMP1"], %[temp16], 9 \n\t" \ - "sra %["#TEMP3"], %[temp17], 9 \n\t" +#define HORIZONTAL_PASS(A, B, C, D, TEMP0, TEMP1, TEMP2, TEMP3) \ + "lw %[" #TEMP1 "], 0(%[args]) \n\t" \ + "lw %[" #TEMP2 "], 4(%[args]) \n\t" \ + "lbu %[temp16], " #A "(%[" #TEMP1 "]) \n\t" \ + "lbu %[temp17], " #A "(%[" #TEMP2 "]) \n\t" \ + "lbu %[temp18], " #B "(%[" #TEMP1 "]) \n\t" \ + "lbu %[temp19], " #B "(%[" #TEMP2 "]) \n\t" \ + "subu %[temp20], %[temp16], %[temp17] \n\t" \ + "lbu %[temp16], " #C "(%[" #TEMP1 "]) \n\t" \ + "lbu %[temp17], " #C "(%[" #TEMP2 "]) \n\t" \ + "subu %[" #TEMP0 "], %[temp18], %[temp19] \n\t" \ + "lbu %[temp18], " #D "(%[" #TEMP1 "]) \n\t" \ + "lbu %[temp19], " #D "(%[" #TEMP2 "]) \n\t" \ + "subu %[" #TEMP1 "], %[temp16], %[temp17] \n\t" \ + "subu %[" #TEMP2 "], %[temp18], %[temp19] \n\t" \ + "addu %[" #TEMP3 "], %[temp20], %[" #TEMP2 "] \n\t" \ + "subu %[" #TEMP2 "], %[temp20], %[" #TEMP2 "] \n\t" \ + "addu %[temp20], %[" #TEMP0 "], %[" #TEMP1 "] \n\t" \ + "subu %[" #TEMP0 "], %[" #TEMP0 "], %[" #TEMP1 "] \n\t" \ + "mul %[temp16], %[" #TEMP2 "], %[c5352] \n\t" \ + "mul %[temp17], %[" #TEMP2 "], %[c2217] \n\t" \ + "mul %[temp18], %[" #TEMP0 "], %[c5352] \n\t" \ + "mul %[temp19], %[" #TEMP0 "], %[c2217] \n\t" \ + "addu %[" #TEMP1 "], %[" #TEMP3 "], %[temp20] \n\t" \ + "subu %[temp20], %[" #TEMP3 "], %[temp20] \n\t" \ + "sll %[" #TEMP0 "], %[" #TEMP1 "], 3 \n\t" \ + "sll %[" #TEMP2 "], %[temp20], 3 \n\t" \ + "addiu %[temp16], %[temp16], 1812 \n\t" \ + "addiu %[temp17], %[temp17], 937 \n\t" \ + "addu %[temp16], %[temp16], %[temp19] \n\t" \ + "subu %[temp17], %[temp17], %[temp18] \n\t" \ + "sra %[" #TEMP1 "], %[temp16], 9 \n\t" \ + "sra %[" #TEMP3 "], %[temp17], 9 \n\t" // macro for one vertical pass in FTransform // temp0..temp15 holds tmp[0]..tmp[15] // A..D - offsets in bytes to store to out buffer // TEMP0, TEMP4, TEMP8 and TEMP12 - registers for corresponding tmp elements -#define VERTICAL_PASS(A, B, C, D, TEMP0, TEMP4, TEMP8, TEMP12) \ - "addu %[temp16], %["#TEMP0"], %["#TEMP12"] \n\t" \ - "subu %[temp19], %["#TEMP0"], %["#TEMP12"] \n\t" \ - "addu %[temp17], %["#TEMP4"], %["#TEMP8"] \n\t" \ - "subu %[temp18], %["#TEMP4"], %["#TEMP8"] \n\t" \ - "mul %["#TEMP8"], %[temp19], %[c2217] \n\t" \ - "mul %["#TEMP12"], %[temp18], %[c2217] \n\t" \ - "mul %["#TEMP4"], %[temp19], %[c5352] \n\t" \ - "mul %[temp18], %[temp18], %[c5352] \n\t" \ - "addiu %[temp16], %[temp16], 7 \n\t" \ - "addu %["#TEMP0"], %[temp16], %[temp17] \n\t" \ - "sra %["#TEMP0"], %["#TEMP0"], 4 \n\t" \ - "addu %["#TEMP12"], %["#TEMP12"], %["#TEMP4"] \n\t" \ - "subu %["#TEMP4"], %[temp16], %[temp17] \n\t" \ - "sra %["#TEMP4"], %["#TEMP4"], 4 \n\t" \ - "addiu %["#TEMP8"], %["#TEMP8"], 30000 \n\t" \ - "addiu %["#TEMP12"], %["#TEMP12"], 12000 \n\t" \ - "addiu %["#TEMP8"], %["#TEMP8"], 21000 \n\t" \ - "subu %["#TEMP8"], %["#TEMP8"], %[temp18] \n\t" \ - "sra %["#TEMP12"], %["#TEMP12"], 16 \n\t" \ - "sra %["#TEMP8"], %["#TEMP8"], 16 \n\t" \ - "addiu %[temp16], %["#TEMP12"], 1 \n\t" \ - "movn %["#TEMP12"], %[temp16], %[temp19] \n\t" \ - "sh %["#TEMP0"], "#A"(%[temp20]) \n\t" \ - "sh %["#TEMP4"], "#C"(%[temp20]) \n\t" \ - "sh %["#TEMP8"], "#D"(%[temp20]) \n\t" \ - "sh %["#TEMP12"], "#B"(%[temp20]) \n\t" +#define VERTICAL_PASS(A, B, C, D, TEMP0, TEMP4, TEMP8, TEMP12) \ + "addu %[temp16], %[" #TEMP0 "], %[" #TEMP12 "] \n\t" \ + "subu %[temp19], %[" #TEMP0 "], %[" #TEMP12 "] \n\t" \ + "addu %[temp17], %[" #TEMP4 "], %[" #TEMP8 "] \n\t" \ + "subu %[temp18], %[" #TEMP4 "], %[" #TEMP8 "] \n\t" \ + "mul %[" #TEMP8 "], %[temp19], %[c2217] \n\t" \ + "mul %[" #TEMP12 "], %[temp18], %[c2217] \n\t" \ + "mul %[" #TEMP4 "], %[temp19], %[c5352] \n\t" \ + "mul %[temp18], %[temp18], %[c5352] \n\t" \ + "addiu %[temp16], %[temp16], 7 \n\t" \ + "addu %[" #TEMP0 "], %[temp16], %[temp17] \n\t" \ + "sra %[" #TEMP0 "], %[" #TEMP0 "], 4 \n\t" \ + "addu %[" #TEMP12 "], %[" #TEMP12 "], %[" #TEMP4 "] \n\t" \ + "subu %[" #TEMP4 "], %[temp16], %[temp17] \n\t" \ + "sra %[" #TEMP4 "], %[" #TEMP4 "], 4 \n\t" \ + "addiu %[" #TEMP8 "], %[" #TEMP8 "], 30000 \n\t" \ + "addiu %[" #TEMP12 "], %[" #TEMP12 "], 12000 \n\t" \ + "addiu %[" #TEMP8 "], %[" #TEMP8 "], 21000 \n\t" \ + "subu %[" #TEMP8 "], %[" #TEMP8 "], %[temp18] \n\t" \ + "sra %[" #TEMP12 "], %[" #TEMP12 "], 16 \n\t" \ + "sra %[" #TEMP8 "], %[" #TEMP8 "], 16 \n\t" \ + "addiu %[temp16], %[" #TEMP12 "], 1 \n\t" \ + "movn %[" #TEMP12 "], %[temp16], %[temp19] \n\t" \ + "sh %[" #TEMP0 "], " #A "(%[temp20]) \n\t" \ + "sh %[" #TEMP4 "], " #C "(%[temp20]) \n\t" \ + "sh %[" #TEMP8 "], " #D "(%[temp20]) \n\t" \ + "sh %[" #TEMP12 "], " #B "(%[temp20]) \n\t" static void FTransform(const uint8_t* src, const uint8_t* ref, int16_t* out) { int temp0, temp1, temp2, temp3, temp4, temp5, temp6, temp7, temp8; @@ -622,14 +622,14 @@ } #define GET_SSE_INNER(A, B, C, D) \ - "lbu %[temp0], "#A"(%[a]) \n\t" \ - "lbu %[temp1], "#A"(%[b]) \n\t" \ - "lbu %[temp2], "#B"(%[a]) \n\t" \ - "lbu %[temp3], "#B"(%[b]) \n\t" \ - "lbu %[temp4], "#C"(%[a]) \n\t" \ - "lbu %[temp5], "#C"(%[b]) \n\t" \ - "lbu %[temp6], "#D"(%[a]) \n\t" \ - "lbu %[temp7], "#D"(%[b]) \n\t" \ + "lbu %[temp0], " #A "(%[a]) \n\t" \ + "lbu %[temp1], " #A "(%[b]) \n\t" \ + "lbu %[temp2], " #B "(%[a]) \n\t" \ + "lbu %[temp3], " #B "(%[b]) \n\t" \ + "lbu %[temp4], " #C "(%[a]) \n\t" \ + "lbu %[temp5], " #C "(%[b]) \n\t" \ + "lbu %[temp6], " #D "(%[a]) \n\t" \ + "lbu %[temp7], " #D "(%[b]) \n\t" \ "subu %[temp0], %[temp0], %[temp1] \n\t" \ "subu %[temp2], %[temp2], %[temp3] \n\t" \ "subu %[temp4], %[temp4], %[temp5] \n\t" \
diff --git a/third_party/libwebp/dsp/lossless_mips32.c b/third_party/libwebp/dsp/lossless_mips32.c index 1308580..5562c41 100644 --- a/third_party/libwebp/dsp/lossless_mips32.c +++ b/third_party/libwebp/dsp/lossless_mips32.c
@@ -285,28 +285,28 @@ // literal_ and successive histograms could be unaligned // so we must use ulw and usw #define ADD_TO_OUT(A, B, C, D, E, P0, P1, P2) \ - "ulw %[temp0], "#A"(%["#P0"]) \n\t" \ - "ulw %[temp1], "#B"(%["#P0"]) \n\t" \ - "ulw %[temp2], "#C"(%["#P0"]) \n\t" \ - "ulw %[temp3], "#D"(%["#P0"]) \n\t" \ - "ulw %[temp4], "#A"(%["#P1"]) \n\t" \ - "ulw %[temp5], "#B"(%["#P1"]) \n\t" \ - "ulw %[temp6], "#C"(%["#P1"]) \n\t" \ - "ulw %[temp7], "#D"(%["#P1"]) \n\t" \ + "ulw %[temp0], " #A "(%[" #P0 "]) \n\t" \ + "ulw %[temp1], " #B "(%[" #P0 "]) \n\t" \ + "ulw %[temp2], " #C "(%[" #P0 "]) \n\t" \ + "ulw %[temp3], " #D "(%[" #P0 "]) \n\t" \ + "ulw %[temp4], " #A "(%[" #P1 "]) \n\t" \ + "ulw %[temp5], " #B "(%[" #P1 "]) \n\t" \ + "ulw %[temp6], " #C "(%[" #P1 "]) \n\t" \ + "ulw %[temp7], " #D "(%[" #P1 "]) \n\t" \ "addu %[temp4], %[temp4], %[temp0] \n\t" \ "addu %[temp5], %[temp5], %[temp1] \n\t" \ "addu %[temp6], %[temp6], %[temp2] \n\t" \ "addu %[temp7], %[temp7], %[temp3] \n\t" \ - "addiu %["#P0"], %["#P0"], 16 \n\t" \ - ".if "#E" == 1 \n\t" \ - "addiu %["#P1"], %["#P1"], 16 \n\t" \ + "addiu %[" #P0 "], %[" #P0 "], 16 \n\t" \ + ".if " #E " == 1 \n\t" \ + "addiu %[" #P1 "], %[" #P1 "], 16 \n\t" \ ".endif \n\t" \ - "usw %[temp4], "#A"(%["#P2"]) \n\t" \ - "usw %[temp5], "#B"(%["#P2"]) \n\t" \ - "usw %[temp6], "#C"(%["#P2"]) \n\t" \ - "usw %[temp7], "#D"(%["#P2"]) \n\t" \ - "addiu %["#P2"], %["#P2"], 16 \n\t" \ - "bne %["#P0"], %[LoopEnd], 1b \n\t" \ + "usw %[temp4], " #A "(%[" #P2 "]) \n\t" \ + "usw %[temp5], " #B "(%[" #P2 "]) \n\t" \ + "usw %[temp6], " #C "(%[" #P2 "]) \n\t" \ + "usw %[temp7], " #D "(%[" #P2 "]) \n\t" \ + "addiu %[" #P2 "], %[" #P2 "], 16 \n\t" \ + "bne %[" #P0 "], %[LoopEnd], 1b \n\t" \ ".set pop \n\t" \ #define ASM_END_COMMON_0 \
diff --git a/third_party/libwebp/enc/histogram.c b/third_party/libwebp/enc/histogram.c index 7c6abb4..a2266b41 100644 --- a/third_party/libwebp/enc/histogram.c +++ b/third_party/libwebp/enc/histogram.c
@@ -20,6 +20,9 @@ #include "../dsp/lossless.h" #include "../utils/utils.h" +#define ALIGN_CST 15 +#define DO_ALIGN(PTR) ((uintptr_t)((PTR) + ALIGN_CST) & ~ALIGN_CST) + #define MAX_COST 1.e38 // Number of partitions for the three dominant (literal, red and blue) symbol @@ -101,9 +104,9 @@ VP8LHistogramSet* VP8LAllocateHistogramSet(int size, int cache_bits) { int i; VP8LHistogramSet* set; - const size_t total_size = sizeof(*set) - + sizeof(*set->histograms) * size - + (size_t)VP8LGetHistogramSize(cache_bits) * size; + const int histo_size = VP8LGetHistogramSize(cache_bits); + const size_t total_size = + sizeof(*set) + size * (sizeof(*set->histograms) + histo_size + ALIGN_CST); uint8_t* memory = (uint8_t*)WebPSafeMalloc(total_size, sizeof(*memory)); if (memory == NULL) return NULL; @@ -114,12 +117,12 @@ set->max_size = size; set->size = size; for (i = 0; i < size; ++i) { + memory = (uint8_t*)DO_ALIGN(memory); set->histograms[i] = (VP8LHistogram*)memory; // literal_ won't necessary be aligned. set->histograms[i]->literal_ = (uint32_t*)(memory + sizeof(VP8LHistogram)); VP8LHistogramInit(set->histograms[i], cache_bits); - // There's no padding/alignment between successive histograms. - memory += VP8LGetHistogramSize(cache_bits); + memory += histo_size; } return set; }
diff --git a/third_party/libwebp/enc/picture_rescale.c b/third_party/libwebp/enc/picture_rescale.c index de52848c..9e45551 100644 --- a/third_party/libwebp/enc/picture_rescale.c +++ b/third_party/libwebp/enc/picture_rescale.c
@@ -175,17 +175,13 @@ int src_width, int src_height, int src_stride, uint8_t* dst, int dst_width, int dst_height, int dst_stride, - int32_t* const work, + rescaler_t* const work, int num_channels) { WebPRescaler rescaler; int y = 0; WebPRescalerInit(&rescaler, src_width, src_height, dst, dst_width, dst_height, dst_stride, - num_channels, - src_width, dst_width, - src_height, dst_height, - work); - memset(work, 0, 2 * dst_width * num_channels * sizeof(*work)); + num_channels, work); while (y < src_height) { y += WebPRescalerImport(&rescaler, src_height - y, src + y * src_stride, src_stride); @@ -209,7 +205,7 @@ int WebPPictureRescale(WebPPicture* pic, int width, int height) { WebPPicture tmp; int prev_width, prev_height; - int32_t* work; + rescaler_t* work; if (pic == NULL) return 0; prev_width = pic->width; @@ -231,7 +227,7 @@ if (!WebPPictureAlloc(&tmp)) return 0; if (!pic->use_argb) { - work = (int32_t*)WebPSafeMalloc(2ULL * width, sizeof(*work)); + work = (rescaler_t*)WebPSafeMalloc(2ULL * width, sizeof(*work)); if (work == NULL) { WebPPictureFree(&tmp); return 0; @@ -259,7 +255,7 @@ tmp.v, HALVE(width), HALVE(height), tmp.uv_stride, work, 1); } else { - work = (int32_t*)WebPSafeMalloc(2ULL * width * 4, sizeof(*work)); + work = (rescaler_t*)WebPSafeMalloc(2ULL * width * 4, sizeof(*work)); if (work == NULL) { WebPPictureFree(&tmp); return 0;
diff --git a/third_party/libwebp/enc/vp8enci.h b/third_party/libwebp/enc/vp8enci.h index 74c8f70..20f58c6 100644 --- a/third_party/libwebp/enc/vp8enci.h +++ b/third_party/libwebp/enc/vp8enci.h
@@ -30,7 +30,7 @@ // version numbers #define ENC_MAJ_VERSION 0 #define ENC_MIN_VERSION 4 -#define ENC_REV_VERSION 3 +#define ENC_REV_VERSION 4 // intra prediction modes enum { B_DC_PRED = 0, // 4x4 modes
diff --git a/third_party/libwebp/utils/endian_inl.h b/third_party/libwebp/utils/endian_inl.h index cd56c37..e11260ff 100644 --- a/third_party/libwebp/utils/endian_inl.h +++ b/third_party/libwebp/utils/endian_inl.h
@@ -35,15 +35,15 @@ #endif #if !defined(HAVE_CONFIG_H) -// clang-3.3 and gcc-4.3 have builtin functions for swap32/swap64 -#if LOCAL_GCC_PREREQ(4,3) || LOCAL_CLANG_PREREQ(3,3) -#define HAVE_BUILTIN_BSWAP32 -#define HAVE_BUILTIN_BSWAP64 -#endif -// clang-3.3 and gcc-4.8 have a builtin function for swap16 -#if LOCAL_GCC_PREREQ(4,8) || LOCAL_CLANG_PREREQ(3,3) +#if LOCAL_GCC_PREREQ(4,8) || __has_builtin(__builtin_bswap16) #define HAVE_BUILTIN_BSWAP16 #endif +#if LOCAL_GCC_PREREQ(4,3) || __has_builtin(__builtin_bswap32) +#define HAVE_BUILTIN_BSWAP32 +#endif +#if LOCAL_GCC_PREREQ(4,3) || __has_builtin(__builtin_bswap64) +#define HAVE_BUILTIN_BSWAP64 +#endif #endif // !HAVE_CONFIG_H static WEBP_INLINE uint16_t BSwap16(uint16_t x) {
diff --git a/third_party/libwebp/utils/rescaler.c b/third_party/libwebp/utils/rescaler.c index fad9c6b0..3a43229 100644 --- a/third_party/libwebp/utils/rescaler.c +++ b/third_party/libwebp/utils/rescaler.c
@@ -13,77 +13,192 @@ #include <assert.h> #include <stdlib.h> +#include <string.h> #include "./rescaler.h" #include "../dsp/dsp.h" //------------------------------------------------------------------------------ // Implementations of critical functions ImportRow / ExportRow -void (*WebPRescalerImportRow)(WebPRescaler* const wrk, - const uint8_t* const src, int channel) = NULL; -void (*WebPRescalerExportRow)(WebPRescaler* const wrk, int x_out) = NULL; +// Import a row of data and save its contribution in the rescaler. +// 'channel' denotes the channel number to be imported. 'Expand' corresponds to +// the wrk->x_expand case. Otherwise, 'Shrink' is to be used. +typedef void (*WebPRescalerImportRowFunc)(WebPRescaler* const wrk, + const uint8_t* src); +static WebPRescalerImportRowFunc WebPRescalerImportRowExpand; +static WebPRescalerImportRowFunc WebPRescalerImportRowShrink; -#define RFIX 30 -#define MULT_FIX(x, y) (((int64_t)(x) * (y) + (1 << (RFIX - 1))) >> RFIX) +// Export one row (starting at x_out position) from rescaler. +// 'Expand' corresponds to the wrk->y_expand case. +// Otherwise 'Shrink' is to be used +typedef void (*WebPRescalerExportRowFunc)(WebPRescaler* const wrk); +static WebPRescalerExportRowFunc WebPRescalerExportRowExpand; +static WebPRescalerExportRowFunc WebPRescalerExportRowShrink; -static void ImportRowC(WebPRescaler* const wrk, - const uint8_t* const src, int channel) { +#define WEBP_RESCALER_RFIX 32 // fixed-point precision for multiplies +#define WEBP_RESCALER_ONE (1ull << WEBP_RESCALER_RFIX) +#define WEBP_RESCALER_FRAC(x, y) \ + ((uint32_t)(((uint64_t)(x) << WEBP_RESCALER_RFIX) / (y))) +#define ROUNDER (WEBP_RESCALER_ONE >> 1) +#define MULT_FIX(x, y) (((uint64_t)(x) * (y) + ROUNDER) >> WEBP_RESCALER_RFIX) + +static void ImportRowExpandC(WebPRescaler* const wrk, const uint8_t* src) { const int x_stride = wrk->num_channels; const int x_out_max = wrk->dst_width * wrk->num_channels; - int x_in = channel; - int x_out; - int accum = 0; - if (!wrk->x_expand) { - int sum = 0; - for (x_out = channel; x_out < x_out_max; x_out += x_stride) { - accum += wrk->x_add; - for (; accum > 0; accum -= wrk->x_sub) { - sum += src[x_in]; - x_in += x_stride; - } - { // Emit next horizontal pixel. - const int32_t base = src[x_in]; - const int32_t frac = base * (-accum); - x_in += x_stride; - wrk->frow[x_out] = (sum + base) * wrk->x_sub - frac; - // fresh fractional start for next pixel - sum = (int)MULT_FIX(frac, wrk->fx_scale); - } - } - } else { // simple bilinear interpolation - int left = src[channel], right = src[channel]; - for (x_out = channel; x_out < x_out_max; x_out += x_stride) { + int channel; + assert(!WebPRescalerInputDone(wrk)); + assert(wrk->x_expand); + for (channel = 0; channel < x_stride; ++channel) { + int x_in = channel; + int x_out = channel; + // simple bilinear interpolation + int accum = wrk->x_add; + int left = src[x_in]; + int right = (wrk->src_width > 1) ? src[x_in + x_stride] : left; + x_in += x_stride; + while (1) { + wrk->frow[x_out] = right * wrk->x_add + (left - right) * accum; + x_out += x_stride; + if (x_out >= x_out_max) break; + accum -= wrk->x_sub; if (accum < 0) { left = right; x_in += x_stride; + assert(x_in < wrk->src_width * x_stride); right = src[x_in]; accum += wrk->x_add; } - wrk->frow[x_out] = right * wrk->x_add + (left - right) * accum; - accum -= wrk->x_sub; } - } - // Accumulate the contribution of the new row. - for (x_out = channel; x_out < x_out_max; x_out += x_stride) { - wrk->irow[x_out] += wrk->frow[x_out]; + assert(wrk->x_sub == 0 /* <- special case for src_width=1 */ || accum == 0); } } -static void ExportRowC(WebPRescaler* const wrk, int x_out) { - if (wrk->y_accum <= 0) { - uint8_t* const dst = wrk->dst; - int32_t* const irow = wrk->irow; - const int32_t* const frow = wrk->frow; - const int yscale = wrk->fy_scale * (-wrk->y_accum); - const int x_out_max = wrk->dst_width * wrk->num_channels; - for (; x_out < x_out_max; ++x_out) { - const int frac = (int)MULT_FIX(frow[x_out], yscale); +static void ImportRowShrinkC(WebPRescaler* const wrk, const uint8_t* src) { + const int x_stride = wrk->num_channels; + const int x_out_max = wrk->dst_width * wrk->num_channels; + int channel; + assert(!WebPRescalerInputDone(wrk)); + assert(!wrk->x_expand); + for (channel = 0; channel < x_stride; ++channel) { + int x_in = channel; + int x_out = channel; + uint32_t sum = 0; + int accum = 0; + while (x_out < x_out_max) { + uint32_t base = 0; + accum += wrk->x_add; + while (accum > 0) { + accum -= wrk->x_sub; + assert(x_in < wrk->src_width * x_stride); + base = src[x_in]; + sum += base; + x_in += x_stride; + } + { // Emit next horizontal pixel. + const rescaler_t frac = base * (-accum); + wrk->frow[x_out] = sum * wrk->x_sub - frac; + // fresh fractional start for next pixel + sum = (int)MULT_FIX(frac, wrk->fx_scale); + } + x_out += x_stride; + } + assert(accum == 0); + } +} + +//------------------------------------------------------------------------------ +// Row export + +static void ExportRowExpandC(WebPRescaler* const wrk) { + int x_out; + uint8_t* const dst = wrk->dst; + rescaler_t* const irow = wrk->irow; + const int x_out_max = wrk->dst_width * wrk->num_channels; + const rescaler_t* const frow = wrk->frow; + assert(!WebPRescalerOutputDone(wrk)); + assert(wrk->y_accum <= 0); + assert(wrk->y_expand); + assert(wrk->y_sub != 0); + if (wrk->y_accum == 0) { + for (x_out = 0; x_out < x_out_max; ++x_out) { + const uint32_t J = frow[x_out]; + const int v = (int)MULT_FIX(J, wrk->fy_scale); + assert(v >= 0 && v <= 255); + dst[x_out] = v; + } + } else { + const uint32_t B = WEBP_RESCALER_FRAC(-wrk->y_accum, wrk->y_sub); + const uint32_t A = (uint32_t)(WEBP_RESCALER_ONE - B); + for (x_out = 0; x_out < x_out_max; ++x_out) { + const uint64_t I = (uint64_t)A * frow[x_out] + + (uint64_t)B * irow[x_out]; + const uint32_t J = (uint32_t)((I + ROUNDER) >> WEBP_RESCALER_RFIX); + const int v = (int)MULT_FIX(J, wrk->fy_scale); + assert(v >= 0 && v <= 255); + dst[x_out] = v; + } + } +} + +static void ExportRowShrinkC(WebPRescaler* const wrk) { + int x_out; + uint8_t* const dst = wrk->dst; + rescaler_t* const irow = wrk->irow; + const int x_out_max = wrk->dst_width * wrk->num_channels; + const rescaler_t* const frow = wrk->frow; + const uint32_t yscale = wrk->fy_scale * (-wrk->y_accum); + assert(!WebPRescalerOutputDone(wrk)); + assert(wrk->y_accum <= 0); + assert(!wrk->y_expand); + if (yscale) { + for (x_out = 0; x_out < x_out_max; ++x_out) { + const uint32_t frac = (uint32_t)MULT_FIX(frow[x_out], yscale); const int v = (int)MULT_FIX(irow[x_out] - frac, wrk->fxy_scale); - dst[x_out] = (!(v & ~0xff)) ? v : (v < 0) ? 0 : 255; + assert(v >= 0 && v <= 255); + dst[x_out] = v; irow[x_out] = frac; // new fractional start } + } else { + for (x_out = 0; x_out < x_out_max; ++x_out) { + const int v = (int)MULT_FIX(irow[x_out], wrk->fxy_scale); + assert(v >= 0 && v <= 255); + dst[x_out] = v; + irow[x_out] = 0; + } + } +} + +//------------------------------------------------------------------------------ +// Main entry calls + +void WebPRescalerImportRow(WebPRescaler* const wrk, const uint8_t* src) { + assert(!WebPRescalerInputDone(wrk)); + if (!wrk->x_expand) { + WebPRescalerImportRowShrink(wrk, src); + } else { + WebPRescalerImportRowExpand(wrk, src); + } +} + +void WebPRescalerExportRow(WebPRescaler* const wrk) { + if (wrk->y_accum <= 0) { + assert(!WebPRescalerOutputDone(wrk)); + if (wrk->y_expand) { + WebPRescalerExportRowExpand(wrk); + } else if (wrk->fxy_scale) { + WebPRescalerExportRowShrink(wrk); + } else { // very special case for src = dst = 1x1 + int i; + assert(wrk->src_width == 1 && wrk->dst_width <= 2); + assert(wrk->src_height == 1 && wrk->dst_height == 1); + for (i = 0; i < wrk->num_channels * wrk->dst_width; ++i) { + wrk->dst[i] = wrk->irow[i]; + wrk->irow[i] = 0; + } + } wrk->y_accum += wrk->y_add; wrk->dst += wrk->dst_stride; + ++wrk->dst_y; } } @@ -92,23 +207,25 @@ #if defined(WEBP_USE_MIPS32) -static void ImportRowMIPS(WebPRescaler* const wrk, - const uint8_t* const src, int channel) { +static void ImportRowShrinkMIPS(WebPRescaler* const wrk, const uint8_t* src) { const int x_stride = wrk->num_channels; const int x_out_max = wrk->dst_width * wrk->num_channels; const int fx_scale = wrk->fx_scale; const int x_add = wrk->x_add; const int x_sub = wrk->x_sub; - int* frow = wrk->frow + channel; - int* irow = wrk->irow + channel; - const uint8_t* src1 = src + channel; - int temp1, temp2, temp3; - int base, frac, sum; - int accum, accum1; const int x_stride1 = x_stride << 2; - int loop_c = x_out_max - channel; + int channel; + assert(!wrk->x_expand); + assert(!WebPRescalerInputDone(wrk)); - if (!wrk->x_expand) { + for (channel = 0; channel < x_stride; ++channel) { + const uint8_t* src1 = src + channel; + rescaler_t* frow = wrk->frow + channel; + int temp1, temp2, temp3; + int base, frac, sum; + int accum, accum1; + int loop_c = x_out_max - channel; + __asm__ volatile ( "li %[temp1], 0x8000 \n\t" "li %[temp2], 0x10000 \n\t" @@ -116,179 +233,295 @@ "li %[accum], 0 \n\t" "1: \n\t" "addu %[accum], %[accum], %[x_add] \n\t" + "li %[base], 0 \n\t" "blez %[accum], 3f \n\t" "2: \n\t" - "lbu %[temp3], 0(%[src1]) \n\t" + "lbu %[base], 0(%[src1]) \n\t" "subu %[accum], %[accum], %[x_sub] \n\t" "addu %[src1], %[src1], %[x_stride] \n\t" - "addu %[sum], %[sum], %[temp3] \n\t" + "addu %[sum], %[sum], %[base] \n\t" "bgtz %[accum], 2b \n\t" "3: \n\t" - "lbu %[base], 0(%[src1]) \n\t" - "addu %[src1], %[src1], %[x_stride] \n\t" "negu %[accum1], %[accum] \n\t" "mul %[frac], %[base], %[accum1] \n\t" - "addu %[temp3], %[sum], %[base] \n\t" - "mul %[temp3], %[temp3], %[x_sub] \n\t" - "lw %[base], 0(%[irow]) \n\t" + "mul %[temp3], %[sum], %[x_sub] \n\t" "subu %[loop_c], %[loop_c], %[x_stride] \n\t" - "sll %[accum1], %[frac], 2 \n\t" "mult %[temp1], %[temp2] \n\t" - "madd %[accum1], %[fx_scale] \n\t" + "maddu %[frac], %[fx_scale] \n\t" "mfhi %[sum] \n\t" "subu %[temp3], %[temp3], %[frac] \n\t" "sw %[temp3], 0(%[frow]) \n\t" - "add %[base], %[base], %[temp3] \n\t" - "sw %[base], 0(%[irow]) \n\t" - "addu %[irow], %[irow], %[x_stride1] \n\t" "addu %[frow], %[frow], %[x_stride1] \n\t" "bgtz %[loop_c], 1b \n\t" + : [accum]"=&r"(accum), [src1]"+r"(src1), [temp3]"=&r"(temp3), + [sum]"=&r"(sum), [base]"=&r"(base), [frac]"=&r"(frac), + [frow]"+r"(frow), [accum1]"=&r"(accum1), + [temp2]"=&r"(temp2), [temp1]"=&r"(temp1) + : [x_stride]"r"(x_stride), [fx_scale]"r"(fx_scale), + [x_sub]"r"(x_sub), [x_add]"r"(x_add), + [loop_c]"r"(loop_c), [x_stride1]"r"(x_stride1) + : "memory", "hi", "lo" + ); + assert(accum == 0); + } +} - : [accum] "=&r" (accum), [src1] "+r" (src1), [temp3] "=&r" (temp3), - [sum] "=&r" (sum), [base] "=&r" (base), [frac] "=&r" (frac), - [frow] "+r" (frow), [irow] "+r" (irow), [accum1] "=&r" (accum1), - [temp2] "=&r" (temp2), [temp1] "=&r" (temp1) - : [x_stride] "r" (x_stride), [fx_scale] "r" (fx_scale), - [x_sub] "r" (x_sub), [x_add] "r" (x_add), - [loop_c] "r" (loop_c), [x_stride1] "r" (x_stride1) +static void ImportRowExpandMIPS(WebPRescaler* const wrk, const uint8_t* src) { + const int x_stride = wrk->num_channels; + const int x_out_max = wrk->dst_width * wrk->num_channels; + const int x_add = wrk->x_add; + const int x_sub = wrk->x_sub; + const int src_width = wrk->src_width; + const int x_stride1 = x_stride << 2; + int channel; + assert(wrk->x_expand); + assert(!WebPRescalerInputDone(wrk)); + + for (channel = 0; channel < x_stride; ++channel) { + const uint8_t* src1 = src + channel; + rescaler_t* frow = wrk->frow + channel; + int temp1, temp2, temp3, temp4; + int frac; + int accum; + int x_out = channel; + + __asm__ volatile ( + "addiu %[temp3], %[src_width], -1 \n\t" + "lbu %[temp2], 0(%[src1]) \n\t" + "addu %[src1], %[src1], %[x_stride] \n\t" + "bgtz %[temp3], 0f \n\t" + "addiu %[temp1], %[temp2], 0 \n\t" + "b 3f \n\t" + "0: \n\t" + "lbu %[temp1], 0(%[src1]) \n\t" + "3: \n\t" + "addiu %[accum], %[x_add], 0 \n\t" + "1: \n\t" + "subu %[temp3], %[temp2], %[temp1] \n\t" + "mul %[temp3], %[temp3], %[accum] \n\t" + "mul %[temp4], %[temp1], %[x_add] \n\t" + "addu %[temp3], %[temp4], %[temp3] \n\t" + "sw %[temp3], 0(%[frow]) \n\t" + "addu %[frow], %[frow], %[x_stride1] \n\t" + "addu %[x_out], %[x_out], %[x_stride] \n\t" + "subu %[temp3], %[x_out], %[x_out_max] \n\t" + "bgez %[temp3], 2f \n\t" + "subu %[accum], %[accum], %[x_sub] \n\t" + "bgez %[accum], 4f \n\t" + "addiu %[temp2], %[temp1], 0 \n\t" + "addu %[src1], %[src1], %[x_stride] \n\t" + "lbu %[temp1], 0(%[src1]) \n\t" + "addu %[accum], %[accum], %[x_add] \n\t" + "4: \n\t" + "b 1b \n\t" + "2: \n\t" + : [src1]"+r"(src1), [accum]"=&r"(accum), [temp1]"=&r"(temp1), + [temp2]"=&r"(temp2), [temp3]"=&r"(temp3), [temp4]"=&r"(temp4), + [x_out]"+r"(x_out), [frac]"=&r"(frac), [frow]"+r"(frow) + : [x_stride]"r"(x_stride), [x_add]"r"(x_add), [x_sub]"r"(x_sub), + [x_stride1]"r"(x_stride1), [src_width]"r"(src_width), + [x_out_max]"r"(x_out_max) + : "memory", "hi", "lo" + ); + assert(wrk->x_sub == 0 /* <- special case for src_width=1 */ || accum == 0); + } +} + +//------------------------------------------------------------------------------ +// Row export + +static void ExportRowExpandMIPS(WebPRescaler* const wrk) { + uint8_t* dst = wrk->dst; + rescaler_t* irow = wrk->irow; + const int x_out_max = wrk->dst_width * wrk->num_channels; + const rescaler_t* frow = wrk->frow; + int temp0, temp1, temp3, temp4, temp5, loop_end; + const int temp2 = (int)wrk->fy_scale; + const int temp6 = x_out_max << 2; + assert(!WebPRescalerOutputDone(wrk)); + assert(wrk->y_accum <= 0); + assert(wrk->y_expand); + assert(wrk->y_sub != 0); + if (wrk->y_accum == 0) { + __asm__ volatile ( + "li %[temp3], 0x10000 \n\t" + "li %[temp4], 0x8000 \n\t" + "addu %[loop_end], %[frow], %[temp6] \n\t" + "1: \n\t" + "lw %[temp0], 0(%[frow]) \n\t" + "addiu %[dst], %[dst], 1 \n\t" + "addiu %[frow], %[frow], 4 \n\t" + "mult %[temp3], %[temp4] \n\t" + "maddu %[temp0], %[temp2] \n\t" + "mfhi %[temp5] \n\t" + "sb %[temp5], -1(%[dst]) \n\t" + "bne %[frow], %[loop_end], 1b \n\t" + : [temp0]"=&r"(temp0), [temp1]"=&r"(temp1), [temp3]"=&r"(temp3), + [temp4]"=&r"(temp4), [temp5]"=&r"(temp5), [frow]"+r"(frow), + [dst]"+r"(dst), [loop_end]"=&r"(loop_end) + : [temp2]"r"(temp2), [temp6]"r"(temp6) + : "memory", "hi", "lo" + ); + } else { + const uint32_t B = WEBP_RESCALER_FRAC(-wrk->y_accum, wrk->y_sub); + const uint32_t A = (uint32_t)(WEBP_RESCALER_ONE - B); + __asm__ volatile ( + "li %[temp3], 0x10000 \n\t" + "li %[temp4], 0x8000 \n\t" + "addu %[loop_end], %[frow], %[temp6] \n\t" + "1: \n\t" + "lw %[temp0], 0(%[frow]) \n\t" + "lw %[temp1], 0(%[irow]) \n\t" + "addiu %[dst], %[dst], 1 \n\t" + "mult %[temp3], %[temp4] \n\t" + "maddu %[A], %[temp0] \n\t" + "maddu %[B], %[temp1] \n\t" + "addiu %[frow], %[frow], 4 \n\t" + "addiu %[irow], %[irow], 4 \n\t" + "mfhi %[temp5] \n\t" + "mult %[temp3], %[temp4] \n\t" + "maddu %[temp5], %[temp2] \n\t" + "mfhi %[temp5] \n\t" + "sb %[temp5], -1(%[dst]) \n\t" + "bne %[frow], %[loop_end], 1b \n\t" + : [temp0]"=&r"(temp0), [temp1]"=&r"(temp1), [temp3]"=&r"(temp3), + [temp4]"=&r"(temp4), [temp5]"=&r"(temp5), [frow]"+r"(frow), + [irow]"+r"(irow), [dst]"+r"(dst), [loop_end]"=&r"(loop_end) + : [temp2]"r"(temp2), [temp6]"r"(temp6), [A]"r"(A), [B]"r"(B) + : "memory", "hi", "lo" + ); + } +} + +static void ExportRowShrinkMIPS(WebPRescaler* const wrk) { + const int x_out_max = wrk->dst_width * wrk->num_channels; + uint8_t* dst = wrk->dst; + rescaler_t* irow = wrk->irow; + const rescaler_t* frow = wrk->frow; + const int yscale = wrk->fy_scale * (-wrk->y_accum); + int temp0, temp1, temp3, temp4, temp5, loop_end; + const int temp2 = (int)wrk->fxy_scale; + const int temp6 = x_out_max << 2; + + assert(!WebPRescalerOutputDone(wrk)); + assert(wrk->y_accum <= 0); + assert(!wrk->y_expand); + assert(wrk->fxy_scale != 0); + if (yscale) { + __asm__ volatile ( + "li %[temp3], 0x10000 \n\t" + "li %[temp4], 0x8000 \n\t" + "addu %[loop_end], %[frow], %[temp6] \n\t" + "1: \n\t" + "lw %[temp0], 0(%[frow]) \n\t" + "mult %[temp3], %[temp4] \n\t" + "addiu %[frow], %[frow], 4 \n\t" + "maddu %[temp0], %[yscale] \n\t" + "mfhi %[temp1] \n\t" + "lw %[temp0], 0(%[irow]) \n\t" + "addiu %[dst], %[dst], 1 \n\t" + "addiu %[irow], %[irow], 4 \n\t" + "subu %[temp0], %[temp0], %[temp1] \n\t" + "mult %[temp3], %[temp4] \n\t" + "maddu %[temp0], %[temp2] \n\t" + "mfhi %[temp5] \n\t" + "sw %[temp1], -4(%[irow]) \n\t" + "sb %[temp5], -1(%[dst]) \n\t" + "bne %[frow], %[loop_end], 1b \n\t" + : [temp0]"=&r"(temp0), [temp1]"=&r"(temp1), [temp3]"=&r"(temp3), + [temp4]"=&r"(temp4), [temp5]"=&r"(temp5), [frow]"+r"(frow), + [irow]"+r"(irow), [dst]"+r"(dst), [loop_end]"=&r"(loop_end) + : [temp2]"r"(temp2), [yscale]"r"(yscale), [temp6]"r"(temp6) : "memory", "hi", "lo" ); } else { __asm__ volatile ( - "lbu %[temp1], 0(%[src1]) \n\t" - "move %[temp2], %[temp1] \n\t" - "li %[accum], 0 \n\t" - "1: \n\t" - "bgez %[accum], 2f \n\t" - "move %[temp2], %[temp1] \n\t" - "addu %[src1], %[x_stride] \n\t" - "lbu %[temp1], 0(%[src1]) \n\t" - "addu %[accum], %[x_add] \n\t" - "2: \n\t" - "subu %[temp3], %[temp2], %[temp1] \n\t" - "mul %[temp3], %[temp3], %[accum] \n\t" - "mul %[base], %[temp1], %[x_add] \n\t" - "subu %[accum], %[accum], %[x_sub] \n\t" - "lw %[frac], 0(%[irow]) \n\t" - "subu %[loop_c], %[loop_c], %[x_stride] \n\t" - "addu %[temp3], %[base], %[temp3] \n\t" - "sw %[temp3], 0(%[frow]) \n\t" - "addu %[frow], %[x_stride1] \n\t" - "addu %[frac], %[temp3] \n\t" - "sw %[frac], 0(%[irow]) \n\t" - "addu %[irow], %[x_stride1] \n\t" - "bgtz %[loop_c], 1b \n\t" - - : [src1] "+r" (src1), [accum] "=&r" (accum), [temp1] "=&r" (temp1), - [temp2] "=&r" (temp2), [temp3] "=&r" (temp3), [base] "=&r" (base), - [frac] "=&r" (frac), [frow] "+r" (frow), [irow] "+r" (irow) - : [x_stride] "r" (x_stride), [x_add] "r" (x_add), [x_sub] "r" (x_sub), - [x_stride1] "r" (x_stride1), [loop_c] "r" (loop_c) + "li %[temp3], 0x10000 \n\t" + "li %[temp4], 0x8000 \n\t" + "addu %[loop_end], %[irow], %[temp6] \n\t" + "1: \n\t" + "lw %[temp0], 0(%[irow]) \n\t" + "addiu %[dst], %[dst], 1 \n\t" + "addiu %[irow], %[irow], 4 \n\t" + "mult %[temp3], %[temp4] \n\t" + "maddu %[temp0], %[temp2] \n\t" + "mfhi %[temp5] \n\t" + "sw $zero, -4(%[irow]) \n\t" + "sb %[temp5], -1(%[dst]) \n\t" + "bne %[irow], %[loop_end], 1b \n\t" + : [temp0]"=&r"(temp0), [temp1]"=&r"(temp1), [temp3]"=&r"(temp3), + [temp4]"=&r"(temp4), [temp5]"=&r"(temp5), [irow]"+r"(irow), + [dst]"+r"(dst), [loop_end]"=&r"(loop_end) + : [temp2]"r"(temp2), [temp6]"r"(temp6) : "memory", "hi", "lo" ); } } -static void ExportRowMIPS(WebPRescaler* const wrk, int x_out) { - if (wrk->y_accum <= 0) { - uint8_t* const dst = wrk->dst; - int32_t* const irow = wrk->irow; - const int32_t* const frow = wrk->frow; - const int yscale = wrk->fy_scale * (-wrk->y_accum); - const int x_out_max = wrk->dst_width * wrk->num_channels; - // if wrk->fxy_scale can fit into 32 bits use optimized code, - // otherwise use C code - if ((wrk->fxy_scale >> 32) == 0) { - int temp0, temp1, temp3, temp4, temp5, temp6, temp7, loop_end; - const int temp2 = (int)(wrk->fxy_scale); - const int temp8 = x_out_max << 2; - uint8_t* dst_t = (uint8_t*)dst; - int32_t* irow_t = (int32_t*)irow; - const int32_t* frow_t = (const int32_t*)frow; - - __asm__ volatile( - "addiu %[temp6], $zero, -256 \n\t" - "addiu %[temp7], $zero, 255 \n\t" - "li %[temp3], 0x10000 \n\t" - "li %[temp4], 0x8000 \n\t" - "addu %[loop_end], %[frow_t], %[temp8] \n\t" - "1: \n\t" - "lw %[temp0], 0(%[frow_t]) \n\t" - "mult %[temp3], %[temp4] \n\t" - "addiu %[frow_t], %[frow_t], 4 \n\t" - "sll %[temp0], %[temp0], 2 \n\t" - "madd %[temp0], %[yscale] \n\t" - "mfhi %[temp1] \n\t" - "lw %[temp0], 0(%[irow_t]) \n\t" - "addiu %[dst_t], %[dst_t], 1 \n\t" - "addiu %[irow_t], %[irow_t], 4 \n\t" - "subu %[temp0], %[temp0], %[temp1] \n\t" - "mult %[temp3], %[temp4] \n\t" - "sll %[temp0], %[temp0], 2 \n\t" - "madd %[temp0], %[temp2] \n\t" - "mfhi %[temp5] \n\t" - "sw %[temp1], -4(%[irow_t]) \n\t" - "and %[temp0], %[temp5], %[temp6] \n\t" - "slti %[temp1], %[temp5], 0 \n\t" - "beqz %[temp0], 2f \n\t" - "xor %[temp5], %[temp5], %[temp5] \n\t" - "movz %[temp5], %[temp7], %[temp1] \n\t" - "2: \n\t" - "sb %[temp5], -1(%[dst_t]) \n\t" - "bne %[frow_t], %[loop_end], 1b \n\t" - - : [temp0]"=&r"(temp0), [temp1]"=&r"(temp1), [temp3]"=&r"(temp3), - [temp4]"=&r"(temp4), [temp5]"=&r"(temp5), [temp6]"=&r"(temp6), - [temp7]"=&r"(temp7), [frow_t]"+r"(frow_t), [irow_t]"+r"(irow_t), - [dst_t]"+r"(dst_t), [loop_end]"=&r"(loop_end) - : [temp2]"r"(temp2), [yscale]"r"(yscale), [temp8]"r"(temp8) - : "memory", "hi", "lo" - ); - wrk->y_accum += wrk->y_add; - wrk->dst += wrk->dst_stride; - } else { - ExportRowC(wrk, x_out); - } - } -} #endif // WEBP_USE_MIPS32 //------------------------------------------------------------------------------ void WebPRescalerInit(WebPRescaler* const wrk, int src_width, int src_height, - uint8_t* const dst, int dst_width, int dst_height, - int dst_stride, int num_channels, int x_add, int x_sub, - int y_add, int y_sub, int32_t* const work) { + uint8_t* const dst, + int dst_width, int dst_height, int dst_stride, + int num_channels, rescaler_t* const work) { + const int x_add = src_width, x_sub = dst_width; + const int y_add = src_height, y_sub = dst_height; wrk->x_expand = (src_width < dst_width); + wrk->y_expand = (src_height < dst_height); wrk->src_width = src_width; wrk->src_height = src_height; wrk->dst_width = dst_width; wrk->dst_height = dst_height; + wrk->src_y = 0; + wrk->dst_y = 0; wrk->dst = dst; wrk->dst_stride = dst_stride; wrk->num_channels = num_channels; + // for 'x_expand', we use bilinear interpolation - wrk->x_add = wrk->x_expand ? (x_sub - 1) : x_add - x_sub; + wrk->x_add = wrk->x_expand ? (x_sub - 1) : x_add; wrk->x_sub = wrk->x_expand ? (x_add - 1) : x_sub; - wrk->y_accum = y_add; - wrk->y_add = y_add; - wrk->y_sub = y_sub; - wrk->fx_scale = (1 << RFIX) / x_sub; - wrk->fy_scale = (1 << RFIX) / y_sub; - wrk->fxy_scale = wrk->x_expand ? - ((int64_t)dst_height << RFIX) / (x_sub * src_height) : - ((int64_t)dst_height << RFIX) / (x_add * src_height); + if (!wrk->x_expand) { // fx_scale is not used otherwise + wrk->fx_scale = WEBP_RESCALER_FRAC(1, wrk->x_sub); + } + // vertical scaling parameters + wrk->y_add = wrk->y_expand ? y_add - 1 : y_add; + wrk->y_sub = wrk->y_expand ? y_sub - 1 : y_sub; + wrk->y_accum = wrk->y_expand ? wrk->y_sub : wrk->y_add; + if (!wrk->y_expand) { + // this is WEBP_RESCALER_FRAC(dst_height, x_add * y_add) without the cast. + const uint64_t ratio = + (uint64_t)dst_height * WEBP_RESCALER_ONE / (wrk->x_add * wrk->y_add); + if (ratio != (uint32_t)ratio) { + // We can't represent the ratio with the current fixed-point precision. + // => We special-case fxy_scale = 0, in WebPRescalerExportRow(). + wrk->fxy_scale = 0; + } else { + wrk->fxy_scale = (uint32_t)ratio; + } + wrk->fy_scale = WEBP_RESCALER_FRAC(1, wrk->y_sub); + } else { + wrk->fy_scale = WEBP_RESCALER_FRAC(1, wrk->x_add); + // wrk->fxy_scale is unused here. + } wrk->irow = work; wrk->frow = work + num_channels * dst_width; + memset(work, 0, 2 * dst_width * num_channels * sizeof(*work)); - if (WebPRescalerImportRow == NULL) { - WebPRescalerImportRow = ImportRowC; - WebPRescalerExportRow = ExportRowC; + if (WebPRescalerImportRowExpand == NULL) { + WebPRescalerImportRowExpand = ImportRowExpandC; + WebPRescalerImportRowShrink = ImportRowShrinkC; + WebPRescalerExportRowExpand = ExportRowExpandC; + WebPRescalerExportRowShrink = ExportRowShrinkC; if (VP8GetCPUInfo != NULL) { #if defined(WEBP_USE_MIPS32) if (VP8GetCPUInfo(kMIPS32)) { - WebPRescalerImportRow = ImportRowMIPS; - WebPRescalerExportRow = ExportRowMIPS; + WebPRescalerImportRowExpand = ImportRowExpandMIPS; + WebPRescalerImportRowShrink = ImportRowShrinkMIPS; + WebPRescalerExportRowExpand = ExportRowExpandMIPS; + WebPRescalerExportRowShrink = ExportRowShrinkMIPS; } #endif } @@ -296,7 +529,10 @@ } #undef MULT_FIX -#undef RFIX +#undef WEBP_RESCALER_RFIX +#undef WEBP_RESCALER_ONE +#undef WEBP_RESCALER_FRAC +#undef ROUNDER //------------------------------------------------------------------------------ // all-in-one calls @@ -309,11 +545,20 @@ int WebPRescalerImport(WebPRescaler* const wrk, int num_lines, const uint8_t* src, int src_stride) { int total_imported = 0; - while (total_imported < num_lines && wrk->y_accum > 0) { - int channel; - for (channel = 0; channel < wrk->num_channels; ++channel) { - WebPRescalerImportRow(wrk, src, channel); + while (total_imported < num_lines && !WebPRescalerHasPendingOutput(wrk)) { + if (wrk->y_expand) { + rescaler_t* const tmp = wrk->irow; + wrk->irow = wrk->frow; + wrk->frow = tmp; } + WebPRescalerImportRow(wrk, src); + if (!wrk->y_expand) { // Accumulate the contribution of the new row. + int x; + for (x = 0; x < wrk->num_channels * wrk->dst_width; ++x) { + wrk->irow[x] += wrk->frow[x]; + } + } + ++wrk->src_y; src += src_stride; ++total_imported; wrk->y_accum -= wrk->y_sub; @@ -324,7 +569,7 @@ int WebPRescalerExport(WebPRescaler* const rescaler) { int total_exported = 0; while (WebPRescalerHasPendingOutput(rescaler)) { - WebPRescalerExportRow(rescaler, 0); + WebPRescalerExportRow(rescaler); ++total_exported; } return total_exported;
diff --git a/third_party/libwebp/utils/rescaler.h b/third_party/libwebp/utils/rescaler.h index a6f37871..8244cfe 100644 --- a/third_party/libwebp/utils/rescaler.h +++ b/third_party/libwebp/utils/rescaler.h
@@ -21,20 +21,23 @@ #include "../webp/types.h" // Structure used for on-the-fly rescaling +typedef uint32_t rescaler_t; // type for side-buffer typedef struct { int x_expand; // true if we're expanding in the x direction + int y_expand; // true if we're expanding in the y direction int num_channels; // bytes to jump between pixels - int fy_scale, fx_scale; // fixed-point scaling factor - int64_t fxy_scale; // '' - // we need hpel-precise add/sub increments, for the downsampled U/V planes. + uint32_t fx_scale; // fixed-point scaling factors + uint32_t fy_scale; // '' + uint32_t fxy_scale; // '' int y_accum; // vertical accumulator - int y_add, y_sub; // vertical increments (add ~= src, sub ~= dst) - int x_add, x_sub; // horizontal increments (add ~= src, sub ~= dst) + int y_add, y_sub; // vertical increments + int x_add, x_sub; // horizontal increments int src_width, src_height; // source dimensions int dst_width, dst_height; // destination dimensions + int src_y, dst_y; // row counters for input and output uint8_t* dst; int dst_stride; - int32_t* irow, *frow; // work buffer + rescaler_t* irow, *frow; // work buffer } WebPRescaler; // Initialize a rescaler given scratch area 'work' and dimensions of src & dst. @@ -43,9 +46,7 @@ uint8_t* const dst, int dst_width, int dst_height, int dst_stride, int num_channels, - int x_add, int x_sub, - int y_add, int y_sub, - int32_t* const work); + rescaler_t* const work); // Returns the number of input lines needed next to produce one output line, // considering that the maximum available input lines are 'max_num_lines'. @@ -57,21 +58,29 @@ int WebPRescalerImport(WebPRescaler* const rescaler, int num_rows, const uint8_t* src, int src_stride); -// Import a row of data and save its contribution in the rescaler. -// 'channel' denotes the channel number to be imported. -extern void (*WebPRescalerImportRow)(WebPRescaler* const wrk, - const uint8_t* const src, int channel); -// Export one row (starting at x_out position) from rescaler. -extern void (*WebPRescalerExportRow)(WebPRescaler* const wrk, int x_out); - -// Return true if there is pending output rows ready. -static WEBP_INLINE -int WebPRescalerHasPendingOutput(const WebPRescaler* const rescaler) { - return (rescaler->y_accum <= 0); -} - // Export as many rows as possible. Return the numbers of rows written. int WebPRescalerExport(WebPRescaler* const rescaler); +void WebPRescalerImportRow(WebPRescaler* const wrk, + const uint8_t* src); +// Export one row (starting at x_out position) from rescaler. +void WebPRescalerExportRow(WebPRescaler* const wrk); + +// Return true if input is finished +static WEBP_INLINE +int WebPRescalerInputDone(const WebPRescaler* const rescaler) { + return (rescaler->src_y >= rescaler->src_height); +} +// Return true if output is finished +static WEBP_INLINE +int WebPRescalerOutputDone(const WebPRescaler* const rescaler) { + return (rescaler->dst_y >= rescaler->dst_height); +} + +// Return true if there are pending output rows ready. +static WEBP_INLINE +int WebPRescalerHasPendingOutput(const WebPRescaler* const rescaler) { + return !WebPRescalerOutputDone(rescaler) && (rescaler->y_accum <= 0); +} //------------------------------------------------------------------------------
diff --git a/third_party/tcmalloc/README.chromium b/third_party/tcmalloc/README.chromium index 10800df..5ab67d0 100644 --- a/third_party/tcmalloc/README.chromium +++ b/third_party/tcmalloc/README.chromium
@@ -99,3 +99,4 @@ - Changed DEFINE_string to define const char*s instead of strings - Disabled HEAPPROFILE envvar unless ENABLE_PROFILING is defined - Add "ARMv8-a" to the supporting list of ARM architecture +- Add generic.total_physical_bytes property to MallocExtension
diff --git a/third_party/tcmalloc/chromium/src/gperftools/malloc_extension.h b/third_party/tcmalloc/chromium/src/gperftools/malloc_extension.h index d1148de..0a9b4ed 100644 --- a/third_party/tcmalloc/chromium/src/gperftools/malloc_extension.h +++ b/third_party/tcmalloc/chromium/src/gperftools/malloc_extension.h
@@ -159,6 +159,14 @@ // freed memory regions // This property is not writable. // + // "generic.total_physical_bytes" + // Estimate of total bytes of the physical memory usage by the + // allocator == + // current_allocated_bytes + + // fragmentation + + // metadata + // This property is not writable. + // // tcmalloc // -------- // "tcmalloc.max_total_thread_cache_bytes"
diff --git a/third_party/tcmalloc/chromium/src/tcmalloc.cc b/third_party/tcmalloc/chromium/src/tcmalloc.cc index c8a705f..4709411 100644 --- a/third_party/tcmalloc/chromium/src/tcmalloc.cc +++ b/third_party/tcmalloc/chromium/src/tcmalloc.cc
@@ -678,6 +678,14 @@ return true; } + if (strcmp(name, "generic.total_physical_bytes") == 0) { + TCMallocStats stats; + ExtractStats(&stats, NULL, NULL, NULL); + *value = stats.pageheap.system_bytes + stats.metadata_bytes - + stats.pageheap.unmapped_bytes - stats.metadata_unmapped_bytes; + return true; + } + if (strcmp(name, "tcmalloc.slack_bytes") == 0) { // Kept for backwards compatibility. Now defined externally as: // pageheap_free_bytes + pageheap_unmapped_bytes.
diff --git a/tools/battor_agent/BUILD.gn b/tools/battor_agent/BUILD.gn index 32a98961..c92bfa82 100644 --- a/tools/battor_agent/BUILD.gn +++ b/tools/battor_agent/BUILD.gn
@@ -8,6 +8,7 @@ ] deps = [ ":battor_agent_lib", + "//base", ] }
diff --git a/tools/battor_agent/battor_agent.cc b/tools/battor_agent/battor_agent.cc index 744c61b..73d2fc8 100644 --- a/tools/battor_agent/battor_agent.cc +++ b/tools/battor_agent/battor_agent.cc
@@ -6,30 +6,38 @@ #include <iostream> +#include "base/callback.h" +#include "base/memory/scoped_ptr.h" + namespace battor { BattOrAgent::BattOrAgent(const std::string& path) : path_(path) { - // TODO: Open up a serial connection with the BattOr. + // TODO(charliea): Open up a serial connection with the BattOr. } BattOrAgent::~BattOrAgent() { - // TODO: Close the serial connection with the BattOr. + // TODO(charliea): Close the serial connection with the BattOr. } void BattOrAgent::StartTracing() { - // TODO: Tell the BattOr to start tracing. + // TODO(charliea): Tell the BattOr to start tracing. } -void BattOrAgent::StopTracing(std::string* out_trace) { - // TODO: Tell the BattOr to stop tracing. +void BattOrAgent::StopTracing(std::string* trace_output, + const base::Closure& callback) { + // TODO(charliea): Tell the BattOr to stop tracing. + *trace_output = "battor trace output"; + callback.Run(); } -void BattOrAgent::RecordClockSyncMarker(const std::string& marker) { - // TODO: Tell the BattOr to record the specified clock sync marker. +void BattOrAgent::RecordClockSyncMarker(const std::string& marker, + const base::Closure& callback) { + // TODO(charliea): Tell the BattOr to record the specified clock sync marker. + callback.Run(); } void BattOrAgent::IssueClockSyncMarker() { - // TODO: Tell atrace to issue a clock sync marker. + // TODO(charliea): Tell atrace to issue a clock sync marker. } } // namespace battor
diff --git a/tools/battor_agent/battor_agent.h b/tools/battor_agent/battor_agent.h index ced696e..7b49f67 100644 --- a/tools/battor_agent/battor_agent.h +++ b/tools/battor_agent/battor_agent.h
@@ -4,7 +4,9 @@ #include <string> +#include "base/callback_forward.h" #include "base/macros.h" +#include "base/memory/scoped_ptr.h" namespace battor { @@ -13,17 +15,20 @@ explicit BattOrAgent(const std::string& path); virtual ~BattOrAgent(); - // Tells the BattOr to start tracing. + // Tells the BattOr (using a best-effort signal) to start tracing. void StartTracing(); - // Tells the BattOr to stop tracing and returns the trace contents. - void StopTracing(std::string* out_trace); + // Tells the BattOr to stop tracing and write the trace output to + // the specified location and calls the callback when complete. + void StopTracing(std::string* trace_output, const base::Closure& callback); - // Tells the BattOr to record a clock sync marker in its own trace log. - void RecordClockSyncMarker(const std::string& marker); + // Tells the BattOr to record a clock sync marker in its own trace + // log and calls the callback when complete. + void RecordClockSyncMarker(const std::string& marker, + const base::Closure& callback); - // Tells the BattOr to issue clock sync markers to all other tracing - // agents that it's connected to. + // Tells the BattOr (using a best-effort signal) to issue clock sync + // markers to all other tracing agents that it's connected to. void IssueClockSyncMarker(); // Returns whether the BattOr is able to record clock sync markers
diff --git a/tools/battor_agent/battor_agent_bin.cc b/tools/battor_agent/battor_agent_bin.cc index 5980403..9caa3bd32 100644 --- a/tools/battor_agent/battor_agent_bin.cc +++ b/tools/battor_agent/battor_agent_bin.cc
@@ -2,8 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// This file provides a thin binary wrapper around the BattOr Agent +// library. This binary wrapper provides a means for non-C++ tracing +// controllers, such as Telemetry and Android Systrace, to issue high-level +// tracing commands to the BattOr.. + #include <iostream> +#include "base/bind.h" +#include "base/memory/scoped_ptr.h" +#include "base/synchronization/waitable_event.h" #include "tools/battor_agent/battor_agent.h" using std::cout; @@ -12,12 +20,16 @@ namespace { +// An event used to signal that the BattOr Agent has finished executing its +// command. +base::WaitableEvent g_stop_tracing_complete_event(false, false); + void PrintUsage() { cout << "Usage: battor_agent <command> <arguments>" << endl << endl << "Commands:" << endl << endl << " StartTracing <path>" << endl << " StopTracing <path>" << endl - << " SupportsExplicitClockSync <path>" << endl + << " SupportsExplicitClockSync" << endl << " RecordClockSyncMarker <path> <marker>" << endl << " IssueClockSyncMarker <path>" << endl << " Help" << endl; @@ -36,6 +48,10 @@ return true; } +void OnCommandComplete() { + g_stop_tracing_complete_event.Signal(); +} + } // namespace int main(int argc, char* argv[]) { @@ -55,10 +71,12 @@ if (!GetArg(2, argc, argv, &path)) return 1; - string out_trace; cout << "Calling StopTracing()" << endl; - battor::BattOrAgent(path).StopTracing(&out_trace); - cout << out_trace << endl; + std::string trace_output; + battor::BattOrAgent(path) + .StopTracing(&trace_output, base::Bind(&OnCommandComplete)); + g_stop_tracing_complete_event.Wait(); + cout << trace_output << endl; } else if (cmd == "SupportsExplicitClockSync") { cout << "Calling SupportsExplicitClockSync" << endl; cout << battor::BattOrAgent::SupportsExplicitClockSync() << endl; @@ -69,7 +87,11 @@ cout << "Marker: " << marker << endl; cout << "Calling RecordClockSyncMarker()" << endl; - battor::BattOrAgent(path).RecordClockSyncMarker(marker); + // TODO(charliea): Write the time to STDOUT + battor::BattOrAgent(path) + .RecordClockSyncMarker(marker, base::Bind(&OnCommandComplete)); + g_stop_tracing_complete_event.Wait(); + // TODO(charliea): Write the time to STDOUT } else if (cmd == "IssueClockSyncMarker") { string path; if (!GetArg(2, argc, argv, &path))
diff --git a/tools/metrics/actions/actions.xml b/tools/metrics/actions/actions.xml index 3ce2f05..399bb33 100644 --- a/tools/metrics/actions/actions.xml +++ b/tools/metrics/actions/actions.xml
@@ -2803,18 +2803,18 @@ </action> <action name="DocumentActivity_OptOutShownOnHome"> - <owner>Please list the metric's owners. Add more owner tags as needed.</owner> - <description>Please enter the description of the metric.</description> + <owner>mariakhomenko@chromium.org</owner> + <description>User was presented with the opt out promo.</description> </action> <action name="DocumentActivity_UserOptIn"> - <owner>Please list the metric's owners. Add more owner tags as needed.</owner> - <description>Please enter the description of the metric.</description> + <owner>mariakhomenko@chromium.org</owner> + <description>User opted in to document mode through settings.</description> </action> <action name="DocumentActivity_UserOptOut"> - <owner>Please list the metric's owners. Add more owner tags as needed.</owner> - <description>Please enter the description of the metric.</description> + <owner>mariakhomenko@chromium.org</owner> + <description>User opted out of document mode through settings.</description> </action> <action name="DomDistiller_DistilledPageOpened"> @@ -11813,23 +11813,32 @@ </action> <action name="Stars_SignInPromoActivity_Launched"> - <owner>Please list the metric's owners. Add more owner tags as needed.</owner> - <description>Please enter the description of the metric.</description> + <owner>kkimlabs@google.com</owner> + <description> + User launches Signin activity from the promo header shown in Android Stars + UI. + </description> </action> <action name="Stars_SignInPromoActivity_NewAccount"> - <owner>Please list the metric's owners. Add more owner tags as needed.</owner> - <description>Please enter the description of the metric.</description> + <owner>kkimlabs@google.com</owner> + <description> + User attempts to create a new account on Android Stars signin activity. + </description> </action> <action name="Stars_SignInPromoActivity_SignedIn"> - <owner>Please list the metric's owners. Add more owner tags as needed.</owner> - <description>Please enter the description of the metric.</description> + <owner>kkimlabs@google.com</owner> + <description> + User confirms an account to sign in on Android Stars signin activity. + </description> </action> <action name="Stars_SignInPromoHeader_Dismissed"> - <owner>Please list the metric's owners. Add more owner tags as needed.</owner> - <description>Please enter the description of the metric.</description> + <owner>kkimlabs@google.com</owner> + <description> + User dismisses the promo header shown in Android Stars UI + </description> </action> <action name="Stars_SignInPromoHeader_Displayed">
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 5690d24..731b5b6e 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -712,8 +712,8 @@ <owner>kuscher@google.com</owner> <owner>varkha@chromium.org</owner> <summary> - Source (mouse, touch or unknown) of the user-initiated action for docked - windows. + Source (mouse, touch, keyboard or unknown) of the user-initiated action for + docked windows. </summary> </histogram> @@ -30101,15 +30101,6 @@ </summary> </histogram> -<histogram name="OSX.SharedMemory.Mechanism" enum="OSXSharedMemoryMechanism"> - <owner>erikchen@chromium.org</owner> - <summary> - A histogram entry is emitted each time a base::SharedMemory object is - constructed. The value of the entry indicates the mechanism used to back the - shared memory region. - </summary> -</histogram> - <histogram name="OSX.SystemHotkeyMap.LoadSuccess" enum="BooleanSuccess"> <owner>erikchen@chromium.org</owner> <summary> @@ -43369,6 +43360,39 @@ </summary> </histogram> +<histogram name="SiteIsolation.IsolateNothingProcessCountEstimate"> + <owner>creis@chromium.org</owner> + <summary> + The upper bound of the estimated renderer process count if we isolated no + sites, subject to the process limit. Recorded once per UMA ping. + </summary> +</histogram> + +<histogram name="SiteIsolation.IsolateNothingProcessCountLowerBound"> + <owner>creis@chromium.org</owner> + <summary> + The lower bound of the predicted renderer process count if we isolated no + sites, subject to the process limit. Happens to be the number of isolated + sites. Recorded once per UMA ping. + </summary> +</histogram> + +<histogram name="SiteIsolation.IsolateNothingProcessCountNoLimit"> + <owner>creis@chromium.org</owner> + <summary> + The predicted renderer process count if we isolated no sites and if there + were no process limit. Recorded once per UMA ping. + </summary> +</histogram> + +<histogram name="SiteIsolation.IsolateNothingTotalProcessCountEstimate"> + <owner>creis@chromium.org</owner> + <summary> + The predicted total process count if we isolated no sites, subject to the + process limit. Recorded once per UMA ping. + </summary> +</histogram> + <histogram name="SiteIsolation.XSD.DataLength" units="byte"> <owner>creis@chromium.org</owner> <summary> @@ -44579,6 +44603,9 @@ </histogram> <histogram name="Startup.FirstWebContents.UINotResponsive" units="milliseconds"> + <obsolete> + Deprecated 10/2015. + </obsolete> <owner>gayane@chromium.org</owner> <summary> [Desktop] Measures the execution time for a single task to execute on UI if @@ -44590,6 +44617,9 @@ <histogram name="Startup.FirstWebContents.UINotResponsive_10sec" units="milliseconds"> + <obsolete> + Deprecated 10/2015. + </obsolete> <owner>gayane@chromium.org</owner> <summary> [Desktop] Measures the elapsed time for a single task to execute on UI if it @@ -44601,6 +44631,9 @@ <histogram name="Startup.FirstWebContents.UINotResponsive_1sec" units="milliseconds"> + <obsolete> + Deprecated 10/2015. + </obsolete> <owner>gayane@chromium.org</owner> <summary> [Desktop] Measures the elapsed time for a single task to execute on UI if it @@ -44611,6 +44644,9 @@ </histogram> <histogram name="Startup.FirstWebContents.UIResponsive" units="milliseconds"> + <obsolete> + Deprecated 10/2015. + </obsolete> <owner>gayane@chromium.org</owner> <summary> [Desktop] Measures the elapsed time it takes for a task to execute on UI @@ -44622,6 +44658,9 @@ <histogram name="Startup.FirstWebContents.UIResponsive_10sec" units="milliseconds"> + <obsolete> + Deprecated 10/2015. + </obsolete> <owner>gayane@chromium.org</owner> <summary> [Desktop] Measures the elapsed time it takes for a task to execute on UI @@ -44633,6 +44672,9 @@ <histogram name="Startup.FirstWebContents.UIResponsive_1sec" units="milliseconds"> + <obsolete> + Deprecated 10/2015. + </obsolete> <owner>gayane@chromium.org</owner> <summary> [Desktop] Measures the elapsed time it takes for a task to execute on UI @@ -47193,6 +47235,14 @@ </summary> </histogram> +<histogram name="TabManager.Discarding.ReloadToCloseTime" units="ms"> + <owner>georgesak@chromium.org</owner> + <summary> + Elapsed time between the last time a discarded tab was reloaded and the time + it gets closed. + </summary> +</histogram> + <histogram name="Tabs.CountAtResume" units="tabs"> <owner>lliabraa@chromium.org</owner> <summary> @@ -53714,6 +53764,7 @@ <int value="6" label="Trace finalization disallowed"/> <int value="7" label="Trace finalization started"/> <int value="8" label="Trace finalization complete"/> + <int value="9" label="Scenario activation failed due to lowres clock"/> </enum> <enum name="BackingStoreResults" type="int"> @@ -56219,6 +56270,7 @@ <int value="0" label="Unknown"/> <int value="1" label="Mouse"/> <int value="2" label="Touch"/> + <int value="3" label="Keyboard"/> </enum> <enum name="DomainBoundCerts.GetCertResult" type="int"> @@ -68139,15 +68191,6 @@ </int> </enum> -<enum name="OSXSharedMemoryMechanism" type="int"> - <int value="0" label="POSIX"> - The shared memory region is backed by a POSIX fd. - </int> - <int value="1" label="MACH"> - The shared memory region is backed by a Mach memory object. - </int> -</enum> - <enum name="OtherPossibleUsernamesUsage" type="int"> <int value="0" label="Nothing to Autofill"/> <int value="1" label="No other possible usernames"/>
diff --git a/tools/perf/benchmarks/memory.py b/tools/perf/benchmarks/memory.py index 2d511518..2624333 100644 --- a/tools/perf/benchmarks/memory.py +++ b/tools/perf/benchmarks/memory.py
@@ -43,6 +43,7 @@ return 'memory.long_running_idle_gmail' +@benchmark.Disabled('android') # crbug.com/542682 class MemoryLongRunningIdleGmailBackground(perf_benchmark.PerfBenchmark): """Use (recorded) real world web sites and measure memory consumption of long running idle Gmail page in background tab"""
diff --git a/tools/perf/pylintrc b/tools/perf/pylintrc index cd635d3..039dd56 100644 --- a/tools/perf/pylintrc +++ b/tools/perf/pylintrc
@@ -11,6 +11,12 @@ reports=no +[VARIABLES] + +# Google style +dummy-variables-rgx=_$|unused_ + + [FORMAT] # We use two spaces for indents, instead of the usual four spaces or tab.
diff --git a/tools/telemetry/pylintrc b/tools/telemetry/pylintrc index 9811c3c..5bb10384 100644 --- a/tools/telemetry/pylintrc +++ b/tools/telemetry/pylintrc
@@ -11,6 +11,12 @@ reports=no +[VARIABLES] + +# Google style +dummy-variables-rgx=_$|unused_ + + [FORMAT] # We use two spaces for indents, instead of the usual four spaces or tab.
diff --git a/tools/telemetry/telemetry/benchmark_run_unittest.py b/tools/telemetry/telemetry/benchmark_run_unittest.py index c1d84cbe..4913bffd 100644 --- a/tools/telemetry/telemetry/benchmark_run_unittest.py +++ b/tools/telemetry/telemetry/benchmark_run_unittest.py
@@ -82,7 +82,7 @@ parser = finder_options.CreateParser() benchmark_module.AddCommandLineArgs(parser) benchmarkclass.AddCommandLineArgs(parser) - options, dummy_args = parser.parse_args([]) + options, unused_args = parser.parse_args([]) benchmark_module.ProcessCommandLineArgs(parser, options) benchmarkclass.ProcessCommandLineArgs(parser, options) benchmark = benchmarkclass()
diff --git a/tools/telemetry/telemetry/internal/actions/action_runner_unittest.py b/tools/telemetry/telemetry/internal/actions/action_runner_unittest.py index 99a00bd2..49ca8829 100644 --- a/tools/telemetry/telemetry/internal/actions/action_runner_unittest.py +++ b/tools/telemetry/telemetry/internal/actions/action_runner_unittest.py
@@ -229,7 +229,7 @@ action_runner.ScrollPage(direction='right', left_start_ratio=0.9, distance=100) self.assertTrue(action_runner.EvaluateJavaScript( - 'document.scrollingElement.scrollLeft') > 75) + '(document.scrollingElement || document.body).scrollLeft') > 75) @decorators.Disabled('android', # crbug.com/437065. 'chromeos') # crbug.com/483212. @@ -253,7 +253,7 @@ action_runner.SwipePage(direction='left', left_start_ratio=0.9) self.assertTrue(action_runner.EvaluateJavaScript( - 'document.scrollingElement.scrollLeft') > 75) + '(document.scrollingElement || document.body).scrollLeft') > 75) class InteractionTest(unittest.TestCase):
diff --git a/tools/telemetry/telemetry/internal/actions/scroll.js b/tools/telemetry/telemetry/internal/actions/scroll.js index ba809605..1e903de4 100644 --- a/tools/telemetry/telemetry/internal/actions/scroll.js +++ b/tools/telemetry/telemetry/internal/actions/scroll.js
@@ -20,7 +20,7 @@ this.speed_ = opt_options.speed; this.gesture_source_type_ = opt_options.gesture_source_type; } else { - this.element_ = document.scrollingElement; + this.element_ = document.scrollingElement || document.body; this.left_start_ratio_ = 0.5; this.top_start_ratio_ = 0.5; this.direction_ = 'down';
diff --git a/tools/telemetry/telemetry/internal/actions/scroll.py b/tools/telemetry/telemetry/internal/actions/scroll.py index f0a6c1b..0cd53ef 100644 --- a/tools/telemetry/telemetry/internal/actions/scroll.py +++ b/tools/telemetry/telemetry/internal/actions/scroll.py
@@ -78,7 +78,7 @@ def RunAction(self, tab): if (self._selector is None and self._text is None and self._element_function is None): - self._element_function = 'document.scrollingElement' + self._element_function = '(document.scrollingElement || document.body)' gesture_source_type = self._synthetic_gesture_source if self._use_touch:
diff --git a/tools/telemetry/telemetry/internal/actions/scroll_bounce.py b/tools/telemetry/telemetry/internal/actions/scroll_bounce.py index 7782fcc3..672351f 100644 --- a/tools/telemetry/telemetry/internal/actions/scroll_bounce.py +++ b/tools/telemetry/telemetry/internal/actions/scroll_bounce.py
@@ -38,7 +38,7 @@ if (self._selector is None and self._text is None and self._element_function is None): - self._element_function = 'document.scrollingElement' + self._element_function = '(document.scrollingElement || document.body)' def WillRunAction(self, tab): for js_file in ['gesture_common.js', 'scroll_bounce.js']:
diff --git a/tools/telemetry/telemetry/internal/actions/swipe.py b/tools/telemetry/telemetry/internal/actions/swipe.py index 502d0c8..3376de8c 100644 --- a/tools/telemetry/telemetry/internal/actions/swipe.py +++ b/tools/telemetry/telemetry/internal/actions/swipe.py
@@ -56,7 +56,7 @@ def RunAction(self, tab): if (self._selector is None and self._text is None and self._element_function is None): - self._element_function = 'document.scrollingElement' + self._element_function = '(document.scrollingElement || document.body)' code = ''' function(element, info) { if (!element) {
diff --git a/tools/telemetry/telemetry/internal/platform/power_monitor/android_dumpsys_power_monitor.py b/tools/telemetry/telemetry/internal/platform/power_monitor/android_dumpsys_power_monitor.py index 360baa8..6e363bb 100644 --- a/tools/telemetry/telemetry/internal/platform/power_monitor/android_dumpsys_power_monitor.py +++ b/tools/telemetry/telemetry/internal/platform/power_monitor/android_dumpsys_power_monitor.py
@@ -41,10 +41,10 @@ # Disable the charging of the device over USB. This is necessary because the # device only collects information about power usage when the device is not # charging. - self._battery.TieredSetCharging(False) + self._battery.SetCharging(False) def StopMonitoringPower(self): - self._battery.TieredSetCharging(True) + self._battery.SetCharging(True) if self._browser: package = self._browser._browser_backend.package self._browser = None
diff --git a/tools/telemetry/telemetry/internal/platform/power_monitor/android_fuelgauge_power_monitor.py b/tools/telemetry/telemetry/internal/platform/power_monitor/android_fuelgauge_power_monitor.py index 653bcf3..8b219e00 100644 --- a/tools/telemetry/telemetry/internal/platform/power_monitor/android_fuelgauge_power_monitor.py +++ b/tools/telemetry/telemetry/internal/platform/power_monitor/android_fuelgauge_power_monitor.py
@@ -26,7 +26,7 @@ return self._battery.SupportsFuelGauge() def StartMonitoringPower(self, browser): - self._battery.TieredSetCharging(False) + self._battery.SetCharging(False) self._starting_fuel_gauge = self._battery.GetFuelGaugeChargeCounter() def StopMonitoringPower(self): @@ -34,7 +34,7 @@ fuel_gauge_delta = ( float((self._starting_fuel_gauge) - self._battery.GetFuelGaugeChargeCounter()) / 1000000) - self._battery.TieredSetCharging(True) + self._battery.SetCharging(True) voltage = self._battery.GetBatteryInfo().get('voltage') if voltage is None:
diff --git a/tools/telemetry/telemetry/internal/platform/power_monitor/power_monitor_controller.py b/tools/telemetry/telemetry/internal/platform/power_monitor/power_monitor_controller.py index 183273c..46514e1 100644 --- a/tools/telemetry/telemetry/internal/platform/power_monitor/power_monitor_controller.py +++ b/tools/telemetry/telemetry/internal/platform/power_monitor/power_monitor_controller.py
@@ -10,7 +10,7 @@ def _ReenableChargingIfNeeded(battery): if not battery.GetCharging(): - battery.TieredSetCharging(True) + battery.SetCharging(True) class PowerMonitorController(power_monitor.PowerMonitor): """
diff --git a/tools/valgrind/gtest_exclude/browser_tests.gtest-drmemory.txt b/tools/valgrind/gtest_exclude/browser_tests.gtest-drmemory.txt index 11c32dd..bd6d7dcd 100644 --- a/tools/valgrind/gtest_exclude/browser_tests.gtest-drmemory.txt +++ b/tools/valgrind/gtest_exclude/browser_tests.gtest-drmemory.txt
@@ -78,8 +78,3 @@ # https://crbug.com/530729 SiteDetailsBrowserTest.ManyCrossSiteIframes - -# https://crbug.com/542521 -PhishingClassifierDelegateTest.* -PhishingClassifierTest.* -PhishingDOMFeatureExtractorTest.*
diff --git a/ui/compositor/layer.cc b/ui/compositor/layer.cc index 1dc861d..d68d043 100644 --- a/ui/compositor/layer.cc +++ b/ui/compositor/layer.cc
@@ -823,12 +823,11 @@ } void Layer::CollectAnimators( - std::vector<scoped_refptr<LayerAnimator> >* animators) { + std::vector<scoped_refptr<LayerAnimator>>* animators) { if (IsAnimating()) animators->push_back(animator_); - std::for_each(children_.begin(), children_.end(), - std::bind2nd(std::mem_fun(&Layer::CollectAnimators), - animators)); + for (auto* child : children_) + child->CollectAnimators(animators); } void Layer::StackRelativeTo(Layer* child, Layer* other, bool above) { @@ -1082,11 +1081,8 @@ DCHECK(collection); if (IsAnimating()) animator_->AddToCollection(collection); - std::for_each( - children_.begin(), - children_.end(), - std::bind2nd(std::mem_fun(&Layer::AddAnimatorsInTreeToCollection), - collection)); + for (auto* child : children_) + child->AddAnimatorsInTreeToCollection(collection); } void Layer::RemoveAnimatorsInTreeFromCollection( @@ -1094,11 +1090,8 @@ DCHECK(collection); if (IsAnimating()) animator_->RemoveFromCollection(collection); - std::for_each( - children_.begin(), - children_.end(), - std::bind2nd(std::mem_fun(&Layer::RemoveAnimatorsInTreeFromCollection), - collection)); + for (auto* child : children_) + child->RemoveAnimatorsInTreeFromCollection(collection); } bool Layer::IsAnimating() const {
diff --git a/ui/events/devices/x11/device_data_manager_x11.cc b/ui/events/devices/x11/device_data_manager_x11.cc index 39a1ff1c..dc839df 100644 --- a/ui/events/devices/x11/device_data_manager_x11.cc +++ b/ui/events/devices/x11/device_data_manager_x11.cc
@@ -113,8 +113,13 @@ namespace { -bool DeviceHasId(const ui::InputDevice input_device, int id) { - return input_device.id == id; +template <typename Iterator> +Iterator FindDeviceWithId(Iterator begin, Iterator end, int id) { + for (auto it = begin; it != end; ++it) { + if (it->id == id) + return it; + } + return end; } } // namespace @@ -696,9 +701,8 @@ const std::vector<TouchscreenDevice>& touch_devices = ui::DeviceDataManager::GetInstance()->touchscreen_devices(); - std::vector<TouchscreenDevice>::const_iterator it = - std::find_if(touch_devices.begin(), touch_devices.end(), - std::bind2nd(std::ptr_fun(&DeviceHasId), touch_device_id)); + std::vector<TouchscreenDevice>::const_iterator it = FindDeviceWithId( + touch_devices.begin(), touch_devices.end(), touch_device_id); return it != touch_devices.end() && it->type == INPUT_DEVICE_INTERNAL; #endif // defined(OS_CHROMEOS) return false; @@ -716,9 +720,7 @@ // TODO(rsadam@): Support blocking touchscreen devices. std::vector<KeyboardDevice> keyboards = keyboard_devices(); std::vector<KeyboardDevice>::iterator it = - std::find_if(keyboards.begin(), - keyboards.end(), - std::bind2nd(std::ptr_fun(&DeviceHasId), deviceid)); + FindDeviceWithId(keyboards.begin(), keyboards.end(), deviceid); if (it != std::end(keyboards)) { blocked_keyboards_.insert( std::pair<int, KeyboardDevice>(deviceid, *it)); @@ -767,9 +769,9 @@ blocked_keyboards_.begin(); blocked_iter != blocked_keyboards_.end();) { // Check if the blocked device still exists in list of devices. - std::vector<KeyboardDevice>::iterator it = std::find_if( - keyboards.begin(), keyboards.end(), - std::bind2nd(std::ptr_fun(&DeviceHasId), (*blocked_iter).first)); + int device_id = blocked_iter->first; + std::vector<KeyboardDevice>::iterator it = + FindDeviceWithId(keyboards.begin(), keyboards.end(), device_id); // If the device no longer exists, unblock it, else filter it out from our // active list. if (it == keyboards.end()) {
diff --git a/ui/gfx/canvas.cc b/ui/gfx/canvas.cc index 2465cfae..b81f995d 100644 --- a/ui/gfx/canvas.cc +++ b/ui/gfx/canvas.cc
@@ -175,17 +175,16 @@ paint); } -void Canvas::Save() { - canvas_->save(); -} - -float Canvas::SaveAndUnscale() { - Save(); +float Canvas::UndoDeviceScaleFactor() { SkScalar scale_factor = 1.0f / image_scale_; canvas_->scale(scale_factor, scale_factor); return image_scale_; } +void Canvas::Save() { + canvas_->save(); +} + void Canvas::SaveLayerAlpha(uint8 alpha) { canvas_->saveLayerAlpha(NULL, alpha); }
diff --git a/ui/gfx/canvas.h b/ui/gfx/canvas.h index 8183dfa..fd6e3c71 100644 --- a/ui/gfx/canvas.h +++ b/ui/gfx/canvas.h
@@ -165,15 +165,15 @@ // Draws a dashed rectangle of the specified color. void DrawDashedRect(const Rect& rect, SkColor color); + // Unscales by the image scale factor (aka device scale factor), and returns + // that factor. This is useful when callers want to draw directly in the + // native scale. + float UndoDeviceScaleFactor(); + // Saves a copy of the drawing state onto a stack, operating on this copy // until a balanced call to Restore() is made. void Save(); - // Saves the drawing state, unscales by the image scale factor, and returns - // that factor. This is useful when callers want to draw directly in the - // native scale. - float SaveAndUnscale(); - // As with Save(), except draws to a layer that is blended with the canvas // at the specified alpha once Restore() is called. // |layer_bounds| are the bounds of the layer relative to the current
diff --git a/ui/gfx/nine_image_painter.cc b/ui/gfx/nine_image_painter.cc index 040678d1..cfed62a 100644 --- a/ui/gfx/nine_image_painter.cc +++ b/ui/gfx/nine_image_painter.cc
@@ -88,8 +88,11 @@ if (IsEmpty()) return; - // Painting at physical device pixels (undo device scale factor). - float scale = canvas->SaveAndUnscale(); + ScopedCanvas scoped_canvas(canvas); + + // Painting and doing layout at physical device pixels to avoid cracks or + // overlap. + const float scale = canvas->UndoDeviceScaleFactor(); // Since the drawing from the following Fill() calls assumes the mapped origin // is at (0,0), we need to translate the canvas to the mapped origin. @@ -130,41 +133,42 @@ int i7h = ImageRepHeightInPixels(image_reps[7]); int i8h = ImageRepHeightInPixels(image_reps[8]); - bool has_room_for_border = - i0w + i2w <= width_in_pixels && i3w + i5w <= width_in_pixels && - i6w + i8w <= width_in_pixels && i0h + i6h <= height_in_pixels && - i1h + i7h <= height_in_pixels && i2h + i8h <= height_in_pixels; + i0w = std::min(i0w, width_in_pixels); + i2w = std::min(i2w, width_in_pixels - i0w); + i3w = std::min(i3w, width_in_pixels); + i5w = std::min(i5w, width_in_pixels - i3w); + i6w = std::min(i6w, width_in_pixels); + i8w = std::min(i8w, width_in_pixels - i6w); - int i4x = has_room_for_border ? std::min(std::min(i0w, i3w), i6w) : 0; - int i4w = width_in_pixels - - (has_room_for_border ? i4x + std::min(std::min(i2w, i5w), i8w) : 0); + i0h = std::min(i0h, height_in_pixels); + i1h = std::min(i1h, height_in_pixels); + i2h = std::min(i2h, height_in_pixels); + i6h = std::min(i6h, height_in_pixels - i0h); + i7h = std::min(i7h, height_in_pixels - i1h); + i8h = std::min(i8h, height_in_pixels - i2h); - int i4y = has_room_for_border ? std::min(std::min(i0h, i1h), i2h) : 0; - int i4h = height_in_pixels - - (has_room_for_border ? i4y + std::min(std::min(i6h, i7h), i8h) : 0); + int i4x = std::min(std::min(i0w, i3w), i6w); + int i4y = std::min(std::min(i0h, i1h), i2h); + int i4w = + std::max(width_in_pixels - i4x - std::min(std::min(i2w, i5w), i8w), 0); + int i4h = + std::max(height_in_pixels - i4y - std::min(std::min(i6h, i7h), i8h), 0); SkPaint paint; paint.setAlpha(alpha); Fill(canvas, image_reps[4], i4x, i4y, i4w, i4h, paint); - - if (has_room_for_border) { - Fill(canvas, image_reps[0], 0, 0, i0w, i0h, paint); - Fill(canvas, image_reps[1], i0w, 0, width_in_pixels - i0w - i2w, i1h, - paint); - Fill(canvas, image_reps[2], width_in_pixels - i2w, 0, i2w, i2h, paint); - Fill(canvas, image_reps[3], 0, i0h, i3w, height_in_pixels - i0h - i6h, - paint); - Fill(canvas, image_reps[5], width_in_pixels - i5w, i2h, i5w, - height_in_pixels - i2h - i8h, paint); - Fill(canvas, image_reps[6], 0, height_in_pixels - i6h, i6w, i6h, paint); - Fill(canvas, image_reps[7], i6w, height_in_pixels - i7h, - width_in_pixels - i6w - i8w, i7h, paint); - Fill(canvas, image_reps[8], width_in_pixels - i8w, height_in_pixels - i8h, - i8w, i8h, paint); - } - - canvas->Restore(); + Fill(canvas, image_reps[0], 0, 0, i0w, i0h, paint); + Fill(canvas, image_reps[1], i0w, 0, width_in_pixels - i0w - i2w, i1h, paint); + Fill(canvas, image_reps[2], width_in_pixels - i2w, 0, i2w, i2h, paint); + Fill(canvas, image_reps[3], 0, i0h, i3w, height_in_pixels - i0h - i6h, paint); + Fill(canvas, image_reps[5], width_in_pixels - i5w, i2h, i5w, + height_in_pixels - i2h - i8h, paint); + Fill(canvas, image_reps[6], 0, height_in_pixels - i6h, i6w, i6h, paint); + Fill(canvas, image_reps[7], i6w, height_in_pixels - i7h, + width_in_pixels - i6w - i8w, i7h, paint); + Fill(canvas, image_reps[8], width_in_pixels - i8w, height_in_pixels - i8h, + i8w, i8h, paint); } // static
diff --git a/ui/gfx/nine_image_painter_unittest.cc b/ui/gfx/nine_image_painter_unittest.cc index 9fc0688..759c7f4 100644 --- a/ui/gfx/nine_image_painter_unittest.cc +++ b/ui/gfx/nine_image_painter_unittest.cc
@@ -100,10 +100,12 @@ TEST(NineImagePainterTest, PaintStaysInBounds) { // In this test the bounds rect is 1x1 but each image is 2x2. // The NineImagePainter should not paint outside the bounds. + // The border images should be cropped, but still painted. SkBitmap src; src.allocN32Pixels(6, 6); - src.eraseColor(SK_ColorRED); + src.eraseColor(SK_ColorGREEN); + src.erase(SK_ColorRED, SkIRect::MakeXYWH(2, 2, 2, 2)); gfx::ImageSkia image(gfx::ImageSkiaRep(src, 0.0f)); gfx::Insets insets(2, 2, 2, 2); @@ -122,7 +124,7 @@ result.allocN32Pixels(size.width(), size.height()); canvas.sk_canvas()->readPixels(&result, 0, 0); - EXPECT_EQ(SK_ColorRED, result.getColor(1, 1)); + EXPECT_EQ(SK_ColorGREEN, result.getColor(1, 1)); EXPECT_EQ(SK_ColorBLACK, result.getColor(0, 0)); EXPECT_EQ(SK_ColorBLACK, result.getColor(0, 1));
diff --git a/ui/gfx/scoped_canvas.h b/ui/gfx/scoped_canvas.h index 2e59a07..7701f7c5 100644 --- a/ui/gfx/scoped_canvas.h +++ b/ui/gfx/scoped_canvas.h
@@ -20,12 +20,6 @@ if (canvas_) canvas_->Restore(); } - void SetCanvas(gfx::Canvas* canvas) { - if (canvas_) - canvas_->Restore(); - canvas_ = canvas; - canvas_->Save(); - } private: gfx::Canvas* canvas_;
diff --git a/ui/ozone/platform/drm/gpu/crtc_controller.cc b/ui/ozone/platform/drm/gpu/crtc_controller.cc index adc3c84..1b92b0e 100644 --- a/ui/ozone/platform/drm/gpu/crtc_controller.cc +++ b/ui/ozone/platform/drm/gpu/crtc_controller.cc
@@ -32,7 +32,8 @@ SetCursor(nullptr); drm_->DisableCrtc(crtc_); - SignalPageFlipRequest(); + if (page_flip_request_) + SignalPageFlipRequest(); } } @@ -168,15 +169,9 @@ } void CrtcController::SignalPageFlipRequest() { - if (page_flip_request_.get()) { - // If another frame is queued up and available immediately, calling Signal() - // may result in a call to SchedulePageFlip(), which will override - // page_flip_request_ and possibly release the ref. Stash previous request - // locally to avoid deleting the object we are making a call on. - scoped_refptr<PageFlipRequest> last_request; - last_request.swap(page_flip_request_); - last_request->Signal(gfx::SwapResult::SWAP_ACK); - } + scoped_refptr<PageFlipRequest> request; + request.swap(page_flip_request_); + request->Signal(gfx::SwapResult::SWAP_ACK); } } // namespace ui
diff --git a/ui/views/mus/native_widget_mus.cc b/ui/views/mus/native_widget_mus.cc index bdde2ecb..01f63fd 100644 --- a/ui/views/mus/native_widget_mus.cc +++ b/ui/views/mus/native_widget_mus.cc
@@ -92,7 +92,7 @@ // NativeWidgetMus, internal::NativeWidgetPrivate implementation: void NativeWidgetMus::InitNativeWidget(const Widget::InitParams& params) { - window_tree_host_.reset(new WindowTreeHostMojo(shell_, window_)); + window_tree_host_.reset(new WindowTreeHostMus(shell_, window_)); window_tree_host_->InitHost(); focus_client_.reset(new wm::FocusController(new FocusRulesImpl));
diff --git a/ui/views/mus/native_widget_mus.h b/ui/views/mus/native_widget_mus.h index f56a9bf..916d37d 100644 --- a/ui/views/mus/native_widget_mus.h +++ b/ui/views/mus/native_widget_mus.h
@@ -30,7 +30,7 @@ } namespace views { -class WindowTreeHostMojo; +class WindowTreeHostMus; // An implementation of NativeWidget that binds to a mus::Window. Because Aura // is used extensively within Views code, this code uses aura and binds to the @@ -170,7 +170,7 @@ mus::mojom::ShowState show_state_before_fullscreen_; // Aura configuration. - scoped_ptr<WindowTreeHostMojo> window_tree_host_; + scoped_ptr<WindowTreeHostMus> window_tree_host_; aura::Window* content_; scoped_ptr<wm::FocusController> focus_client_; scoped_ptr<aura::client::DefaultCaptureClient> capture_client_;
diff --git a/ui/views/mus/native_widget_view_manager.cc b/ui/views/mus/native_widget_view_manager.cc index e6a0e67..36a27aa00 100644 --- a/ui/views/mus/native_widget_view_manager.cc +++ b/ui/views/mus/native_widget_view_manager.cc
@@ -53,7 +53,7 @@ DCHECK_EQ(view, view_manager_->window_); view->RemoveObserver(this); view_manager_->window_ = nullptr; - // TODO(sky): WindowTreeHostMojo assumes the View outlives it. + // TODO(sky): WindowTreeHostMus assumes the View outlives it. // NativeWidgetWindowObserver needs to deal, likely by deleting this. } @@ -94,7 +94,7 @@ mojo::Shell* shell, mus::Window* window) : NativeWidgetAura(delegate), window_(window), window_manager_(nullptr) { - window_tree_host_.reset(new WindowTreeHostMojo(shell, window_)); + window_tree_host_.reset(new WindowTreeHostMus(shell, window_)); window_tree_host_->InitHost(); focus_client_.reset(new wm::FocusController(new FocusRulesImpl));
diff --git a/ui/views/mus/native_widget_view_manager.h b/ui/views/mus/native_widget_view_manager.h index 2f63b299..f5f8a37 100644 --- a/ui/views/mus/native_widget_view_manager.h +++ b/ui/views/mus/native_widget_view_manager.h
@@ -40,7 +40,7 @@ class NativeWidgetWindowObserver; } -class WindowTreeHostMojo; +class WindowTreeHostMus; class NativeWidgetViewManager : public views::NativeWidgetAura { public: @@ -64,7 +64,7 @@ void SetBounds(const gfx::Rect& bounds) override; void SetSize(const gfx::Size& size) override; - scoped_ptr<WindowTreeHostMojo> window_tree_host_; + scoped_ptr<WindowTreeHostMus> window_tree_host_; scoped_ptr<NativeWidgetWindowObserver> window_observer_; scoped_ptr<wm::FocusController> focus_client_;
diff --git a/ui/views/mus/window_tree_host_mus.cc b/ui/views/mus/window_tree_host_mus.cc index 9ad0bdd..aef5df5 100644 --- a/ui/views/mus/window_tree_host_mus.cc +++ b/ui/views/mus/window_tree_host_mus.cc
@@ -27,9 +27,9 @@ } // namespace //////////////////////////////////////////////////////////////////////////////// -// WindowTreeHostMojo, public: +// WindowTreeHostMus, public: -WindowTreeHostMojo::WindowTreeHostMojo(mojo::Shell* shell, mus::Window* window) +WindowTreeHostMus::WindowTreeHostMus(mojo::Shell* shell, mus::Window* window) : mus_window_(window) { mus_window_->AddObserver(this); @@ -49,93 +49,93 @@ SetSharedInputMethod(input_method_.get()); } -WindowTreeHostMojo::~WindowTreeHostMojo() { +WindowTreeHostMus::~WindowTreeHostMus() { mus_window_->RemoveObserver(this); DestroyCompositor(); DestroyDispatcher(); } -void WindowTreeHostMojo::SetShowState(mus::mojom::ShowState show_state) { +void WindowTreeHostMus::SetShowState(mus::mojom::ShowState show_state) { show_state_ = show_state; WindowManagerConnection::Get()->window_manager()->SetShowState( mus_window_->id(), show_state_, base::Bind(&WindowManagerCallback)); } //////////////////////////////////////////////////////////////////////////////// -// WindowTreeHostMojo, aura::WindowTreeHost implementation: +// WindowTreeHostMus, aura::WindowTreeHost implementation: -ui::EventSource* WindowTreeHostMojo::GetEventSource() { +ui::EventSource* WindowTreeHostMus::GetEventSource() { return this; } -gfx::AcceleratedWidget WindowTreeHostMojo::GetAcceleratedWidget() { +gfx::AcceleratedWidget WindowTreeHostMus::GetAcceleratedWidget() { return gfx::kNullAcceleratedWidget; } -void WindowTreeHostMojo::ShowImpl() { +void WindowTreeHostMus::ShowImpl() { mus_window_->SetVisible(true); window()->Show(); } -void WindowTreeHostMojo::HideImpl() { +void WindowTreeHostMus::HideImpl() { mus_window_->SetVisible(false); window()->Hide(); } -gfx::Rect WindowTreeHostMojo::GetBounds() const { +gfx::Rect WindowTreeHostMus::GetBounds() const { return mus_window_->bounds(); } -void WindowTreeHostMojo::SetBounds(const gfx::Rect& bounds) { +void WindowTreeHostMus::SetBounds(const gfx::Rect& bounds) { window()->SetBounds(gfx::Rect(bounds.size())); } -gfx::Point WindowTreeHostMojo::GetLocationOnNativeScreen() const { +gfx::Point WindowTreeHostMus::GetLocationOnNativeScreen() const { return gfx::Point(0, 0); } -void WindowTreeHostMojo::SetCapture() { +void WindowTreeHostMus::SetCapture() { NOTIMPLEMENTED(); } -void WindowTreeHostMojo::ReleaseCapture() { +void WindowTreeHostMus::ReleaseCapture() { NOTIMPLEMENTED(); } -void WindowTreeHostMojo::SetCursorNative(gfx::NativeCursor cursor) { +void WindowTreeHostMus::SetCursorNative(gfx::NativeCursor cursor) { NOTIMPLEMENTED(); } -void WindowTreeHostMojo::MoveCursorToNative(const gfx::Point& location) { +void WindowTreeHostMus::MoveCursorToNative(const gfx::Point& location) { NOTIMPLEMENTED(); } -void WindowTreeHostMojo::OnCursorVisibilityChangedNative(bool show) { +void WindowTreeHostMus::OnCursorVisibilityChangedNative(bool show) { NOTIMPLEMENTED(); } //////////////////////////////////////////////////////////////////////////////// -// WindowTreeHostMojo, WindowObserver implementation: +// WindowTreeHostMus, WindowObserver implementation: -void WindowTreeHostMojo::OnWindowBoundsChanged(mus::Window* window, - const gfx::Rect& old_bounds, - const gfx::Rect& new_bounds) { +void WindowTreeHostMus::OnWindowBoundsChanged(mus::Window* window, + const gfx::Rect& old_bounds, + const gfx::Rect& new_bounds) { if (old_bounds.origin() != new_bounds.origin()) OnHostMoved(new_bounds.origin()); if (old_bounds.size() != new_bounds.size()) OnHostResized(new_bounds.size()); } -void WindowTreeHostMojo::OnWindowFocusChanged(mus::Window* gained_focus, - mus::Window* lost_focus) { +void WindowTreeHostMus::OnWindowFocusChanged(mus::Window* gained_focus, + mus::Window* lost_focus) { if (gained_focus == mus_window_) GetInputMethod()->OnFocus(); else if (lost_focus == mus_window_) GetInputMethod()->OnBlur(); } -void WindowTreeHostMojo::OnWindowInputEvent(mus::Window* view, - const mus::mojom::EventPtr& event) { +void WindowTreeHostMus::OnWindowInputEvent(mus::Window* view, + const mus::mojom::EventPtr& event) { scoped_ptr<ui::Event> ui_event(event.To<scoped_ptr<ui::Event>>()); if (!ui_event) return; @@ -148,7 +148,7 @@ } } -void WindowTreeHostMojo::OnWindowSharedPropertyChanged( +void WindowTreeHostMus::OnWindowSharedPropertyChanged( mus::Window* window, const std::string& name, const std::vector<uint8_t>* old_data,
diff --git a/ui/views/mus/window_tree_host_mus.h b/ui/views/mus/window_tree_host_mus.h index ca1b4ca..f1af068 100644 --- a/ui/views/mus/window_tree_host_mus.h +++ b/ui/views/mus/window_tree_host_mus.h
@@ -27,11 +27,11 @@ class InputMethodMUS; class SurfaceContextFactory; -class WindowTreeHostMojo : public aura::WindowTreeHost, - public mus::WindowObserver { +class WindowTreeHostMus : public aura::WindowTreeHost, + public mus::WindowObserver { public: - WindowTreeHostMojo(mojo::Shell* shell, mus::Window* window); - ~WindowTreeHostMojo() override; + WindowTreeHostMus(mojo::Shell* shell, mus::Window* window); + ~WindowTreeHostMus() override; mus::Window* mus_window() { return mus_window_; } @@ -79,7 +79,7 @@ scoped_ptr<SurfaceContextFactory> context_factory_; - DISALLOW_COPY_AND_ASSIGN(WindowTreeHostMojo); + DISALLOW_COPY_AND_ASSIGN(WindowTreeHostMus); }; } // namespace views
diff --git a/ui/webui/resources/cr_elements/cr_search_field/cr_search_field.css b/ui/webui/resources/cr_elements/cr_search_field/cr_search_field.css index cd28d1f..ee849b4 100644 --- a/ui/webui/resources/cr_elements/cr_search_field/cr_search_field.css +++ b/ui/webui/resources/cr_elements/cr_search_field/cr_search_field.css
@@ -44,9 +44,9 @@ --iron-icon-height: 20px; --iron-icon-width: 20px; --paper-icon-button: { - height: 20px; + height: 32px; padding: 6px; - width: 20px; + width: 32px; }; } @@ -55,9 +55,9 @@ --iron-icon-width: 16px; --paper-icon-button: { -webkit-margin-end: -8px; - height: 16px; + height: 32px; padding: 8px; - width: 16px; + width: 32px; }; position: absolute; right: 0;