diff --git a/.gn b/.gn index 62f3a61..a6bd5c5 100644 --- a/.gn +++ b/.gn
@@ -662,4 +662,5 @@ "//remoting/host/installer/win/generate_clsids.gni", "//tools/grit/grit_rule.gni", + "//tools/gritsettings/BUILD.gn", ]
diff --git a/DEPS b/DEPS index 65b7014..4c7941c 100644 --- a/DEPS +++ b/DEPS
@@ -31,6 +31,7 @@ 'build_with_chromium', 'checkout_android', 'checkout_android_native_support', + 'checkout_google_benchmark', 'checkout_ios_webkit', 'checkout_nacl', 'checkout_oculus_sdk', @@ -73,6 +74,11 @@ # restricted to Googlers only. 'checkout_chromium_password_manager_test_dependencies': False, + # By default, do not check out Google Benchmark. The library is only used by a + # few specialized benchmarks that most developers do not interact with. Will + # be overridden by gclient variables. + 'checkout_google_benchmark': False, + # Check out and download nacl by default. This can be disabled e.g. with # custom_vars. 'checkout_nacl': True, @@ -179,7 +185,7 @@ # 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': '2eca5b1e7f9577981ce4caef380e2395aacb1fe9', + 'v8_revision': '2de68515d603bebe3a3048fd3c34db3c48e0e958', # 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. @@ -187,7 +193,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. - 'angle_revision': '1fdf6ca5141d8e349e875eab6e51d93d929a7f0e', + 'angle_revision': '93061d4e764fdef4d3187f82bee8356b94a2ab43', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. @@ -238,7 +244,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling catapult # and whatever else without interference from each other. - 'catapult_revision': '7c4300cb193f74ea6e0f04e1dbfca78b7140a241', + 'catapult_revision': 'a5b4ab17af94f75937ed4bebbd2f0d60e5dadd27', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -246,7 +252,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling devtools-frontend # and whatever else without interference from each other. - 'devtools_frontend_revision': 'f3b0f52a1eb10b9d02a8db72e38a55f646485247', + 'devtools_frontend_revision': '17463ef0e0d942518e750841a7a0e380bac8cbe7', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libprotobuf-mutator # and whatever else without interference from each other. @@ -453,7 +459,7 @@ 'packages': [ { 'package': 'chromium/chrome/test/data/autofill/captured_sites', - 'version': 'rawtdUZtNp6EQjsm2CopH_UeLQnDqgz3ZRmuROF_JYoC', + 'version': '6HKEuK8hN8Q2Zagxk2BJpa1Dw_Zr-Xpdis3BCiWjHg4C', } ], 'condition': 'checkout_chromium_autofill_test_dependencies', @@ -533,7 +539,7 @@ }, 'src/ios/third_party/material_components_ios/src': { - 'url': Var('chromium_git') + '/external/github.com/material-components/material-components-ios.git' + '@' + '7967e9ed75ed62d5613a4f4e646f57666c78306c', + 'url': Var('chromium_git') + '/external/github.com/material-components/material-components-ios.git' + '@' + 'c2500e4ea9dc2b99a080df244247abaae061a198', 'condition': 'checkout_ios', }, @@ -800,6 +806,11 @@ 'dep_type': 'cipd', }, + 'src/third_party/google_benchmark/src': { + 'url': Var('chromium_git') + '/external/github.com/google/benchmark.git' + '@' + '367119482ff4abc3d73e4a109b410090fc281337', + 'condition': 'checkout_google_benchmark', + }, + 'src/third_party/boringssl/src': Var('boringssl_git') + '/boringssl.git' + '@' + Var('boringssl_revision'), @@ -1483,7 +1494,7 @@ Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + '53655df4cde60b121fc530842ba9a6d5dfec1ae1', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + 'a43777dead46df4575a58c5ca2733c5f3ff0212b', + Var('webrtc_git') + '/src.git' + '@' + 'c0734715d1c05b1613e44594184cefb31a785e7b', 'src/third_party/libgifcodec': Var('skia_git') + '/libgifcodec' + '@'+ Var('libgifcodec_revision'), @@ -1553,7 +1564,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@79df1292b2aa53e51015d78e64ea96499e53b208', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@e7ad3848550e40b9dced6103c1d1a5464a27620b', 'condition': 'checkout_src_internal', },
diff --git a/android_webview/browser/gfx/aw_gl_surface.cc b/android_webview/browser/gfx/aw_gl_surface.cc index a32aa211..237a96f 100644 --- a/android_webview/browser/gfx/aw_gl_surface.cc +++ b/android_webview/browser/gfx/aw_gl_surface.cc
@@ -49,7 +49,7 @@ bool AwGLSurface::Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) { size_ = size; return true;
diff --git a/android_webview/browser/gfx/aw_gl_surface.h b/android_webview/browser/gfx/aw_gl_surface.h index 541fb8f..544b9f9b 100644 --- a/android_webview/browser/gfx/aw_gl_surface.h +++ b/android_webview/browser/gfx/aw_gl_surface.h
@@ -28,7 +28,7 @@ gl::GLSurfaceFormat GetFormat() override; bool Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) override; void SetSize(const gfx::Size& size);
diff --git a/ash/app_list/views/app_list_main_view_unittest.cc b/ash/app_list/views/app_list_main_view_unittest.cc index de8d516..9a7d2a8 100644 --- a/ash/app_list/views/app_list_main_view_unittest.cc +++ b/ash/app_list/views/app_list_main_view_unittest.cc
@@ -122,16 +122,13 @@ // |point| is in |grid_view|'s coordinates. AppListItemView* GetItemViewAtPointInGrid(AppsGridView* grid_view, const gfx::Point& point) { - const views::ViewModelT<AppListItemView>* view_model = - grid_view->view_model(); - for (int i = 0; i < view_model->view_size(); ++i) { - views::View* view = view_model->view_at(i); - if (view->bounds().Contains(point)) { - return static_cast<AppListItemView*>(view); - } - } - - return nullptr; + const auto& entries = grid_view->view_model()->entries(); + const auto iter = std::find_if( + entries.begin(), entries.end(), [&point](const auto& entry) { + return entry.view->bounds().Contains(point); + }); + return iter == entries.end() ? nullptr + : static_cast<AppListItemView*>(iter->view); } void SimulateClick(views::View* view) {
diff --git a/ash/app_list/views/app_list_view_unittest.cc b/ash/app_list/views/app_list_view_unittest.cc index 89bfe44c..a65a0c1b5 100644 --- a/ash/app_list/views/app_list_view_unittest.cc +++ b/ash/app_list/views/app_list_view_unittest.cc
@@ -863,8 +863,8 @@ forward_view_list.push_back(v); const views::ViewModelT<AppListItemView>* view_model = apps_grid_view()->view_model(); - for (int i = 0; i < view_model->view_size(); ++i) - forward_view_list.push_back(view_model->view_at(i)); + for (const auto& entry : view_model->entries()) + forward_view_list.push_back(entry.view); forward_view_list.push_back(search_box_view()->search_box()); std::vector<views::View*> backward_view_list = forward_view_list; std::reverse(backward_view_list.begin(), backward_view_list.end()); @@ -1006,8 +1006,8 @@ forward_view_list.push_back(search_box_view()->search_box()); const views::ViewModelT<AppListItemView>* view_model = app_list_folder_view()->items_grid_view()->view_model(); - for (int i = 0; i < view_model->view_size(); ++i) - forward_view_list.push_back(view_model->view_at(i)); + for (const auto& entry : view_model->entries()) + forward_view_list.push_back(entry.view); TestFocusTraversal(forward_view_list, ui::VKEY_TAB, false); } @@ -1102,8 +1102,8 @@ std::vector<views::View*> forward_view_list; const views::ViewModelT<AppListItemView>* view_model = app_list_folder_view()->items_grid_view()->view_model(); - for (int i = 0; i < view_model->view_size(); ++i) - forward_view_list.push_back(view_model->view_at(i)); + for (const auto& entry : view_model->entries()) + forward_view_list.push_back(entry.view); forward_view_list.push_back( app_list_folder_view()->folder_header_view()->GetFolderNameViewForTest()); forward_view_list.push_back(search_box_view()->search_box());
diff --git a/ash/app_list/views/apps_grid_view.cc b/ash/app_list/views/apps_grid_view.cc index d7983ed..6aca8ea7 100644 --- a/ash/app_list/views/apps_grid_view.cc +++ b/ash/app_list/views/apps_grid_view.cc
@@ -464,8 +464,8 @@ } void AppsGridView::DisableFocusForShowingActiveFolder(bool disabled) { - for (int i = 0; i < view_model_.view_size(); ++i) - view_model_.view_at(i)->SetEnabled(!disabled); + for (const auto& entry : view_model_.entries()) + entry.view->SetEnabled(!disabled); // Ignore the grid view in accessibility tree so that items inside it will not // be accessed by ChromeVox. @@ -478,8 +478,8 @@ pagination_controller_->set_is_tablet_mode(started); // Enable/Disable folder icons's background blur based on tablet mode. - for (int i = 0; i < view_model_.view_size(); ++i) { - auto* item_view = view_model_.view_at(i); + for (const auto& entry : view_model_.entries()) { + auto* item_view = static_cast<AppListItemView*>(entry.view); if (item_view->item()->is_folder()) item_view->SetBackgroundBlurEnabled(started); } @@ -548,8 +548,8 @@ if (drag_view_ || pulsing_blocks_model_.view_size()) return; - for (int i = 0; i < view_model_.view_size(); ++i) - view_model_.view_at(i)->EnsureLayer(); + for (const auto& entry : view_model_.entries()) + static_cast<AppListItemView*>(entry.view)->EnsureLayer(); drag_view_ = view; // Dragged view should have focus. This also fixed the issue @@ -849,8 +849,8 @@ contents_view_->GetAppListMainView()->view_delegate(), false /* is_in_folder */); items_container_->AddChildView(view); - for (int i = 0; i < view_model_.view_size(); ++i) - view_model_.view_at(i)->EnsureLayer(); + for (const auto& entry : view_model_.entries()) + static_cast<AppListItemView*>(entry.view)->EnsureLayer(); view->EnsureLayer(); drag_view_ = view; @@ -2023,8 +2023,8 @@ // opacity. This needs to be done on all views within |view_model_| because // some item view might have been moved out from the current page. See also // https://crbug.com/990529. - for (int i = 0; i < view_model_.view_size(); ++i) - view_model_.view_at(i)->DestroyLayer(); + for (const auto& entry : view_model_.entries()) + entry.view->DestroyLayer(); return; } @@ -2876,8 +2876,8 @@ void AppsGridView::OnBoundsAnimatorDone(views::BoundsAnimator* animator) { if (drag_view_) return; - for (int i = 0; i < view_model_.view_size(); ++i) - view_model_.view_at(i)->DestroyLayer(); + for (const auto& entry : view_model_.entries()) + entry.view->DestroyLayer(); } GridIndex AppsGridView::GetNearestTileIndexForPoint( @@ -2946,12 +2946,13 @@ tile_rect.Offset( CalculateTransitionOffset(pagination_model_.selected_page())); - for (int i = 0; i < view_model_.view_size(); ++i) { - AppListItemView* view = GetItemViewAt(i); - if (view->bounds() == tile_rect && view != drag_view_) - return view; - } - return nullptr; + const auto& entries = view_model_.entries(); + const auto iter = + std::find_if(entries.begin(), entries.end(), [&](const auto& entry) { + return entry.view->bounds() == tile_rect && entry.view != drag_view_; + }); + return iter == entries.end() ? nullptr + : static_cast<AppListItemView*>(iter->view); } void AppsGridView::SetAsFolderDroppingTarget(const GridIndex& target_index, @@ -3286,12 +3287,12 @@ } int AppsGridView::GetModelIndexOfItem(const AppListItem* item) const { - for (int i = 0; i < view_model_.view_size(); ++i) { - if (view_model_.view_at(i)->item() == item) { - return i; - } - } - return view_model_.view_size(); + const auto& entries = view_model_.entries(); + const auto iter = + std::find_if(entries.begin(), entries.end(), [item](const auto& entry) { + return static_cast<AppListItemView*>(entry.view)->item() == item; + }); + return std::distance(entries.begin(), iter); } int AppsGridView::GetTargetModelIndexFromItemIndex(size_t item_index) {
diff --git a/ash/shelf/shelf_view.cc b/ash/shelf/shelf_view.cc index 094fd0a..2982c796 100644 --- a/ash/shelf/shelf_view.cc +++ b/ash/shelf/shelf_view.cc
@@ -2558,15 +2558,14 @@ // previously hidden status can be shown again. Since the button itself // might have gone away or changed locations we check that the button // is still in the shelf and show its status again. - for (int index = 0; index < view_model_->view_size(); index++) { - views::View* view = view_model_->view_at(index); - if (view == snap_back_from_rip_off_view_) { - CHECK_EQ(ShelfAppButton::kViewClassName, view->GetClassName()); - ShelfAppButton* button = static_cast<ShelfAppButton*>(view); - button->ClearState(ShelfAppButton::STATE_HIDDEN); - break; - } - } + const auto& entries = view_model_->entries(); + const auto iter = std::find_if( + entries.begin(), entries.end(), [this](const auto& entry) { + return entry.view == snap_back_from_rip_off_view_; + }); + if (iter != entries.end()) + snap_back_from_rip_off_view_->ClearState(ShelfAppButton::STATE_HIDDEN); + snap_back_from_rip_off_view_ = nullptr; } }
diff --git a/ash/shelf/shelf_view.h b/ash/shelf/shelf_view.h index 97a4475..40577f54 100644 --- a/ash/shelf/shelf_view.h +++ b/ash/shelf/shelf_view.h
@@ -671,7 +671,7 @@ bool dragged_to_another_shelf_ = false; // The rip off view when a snap back operation is underway. - views::View* snap_back_from_rip_off_view_ = nullptr; + ShelfAppButton* snap_back_from_rip_off_view_ = nullptr; // True when this ShelfView is used for Overflow Bubble. bool overflow_mode_ = false;
diff --git a/ash/shelf/shelf_widget.cc b/ash/shelf/shelf_widget.cc index a93a00f..6eca31e3 100644 --- a/ash/shelf/shelf_widget.cc +++ b/ash/shelf/shelf_widget.cc
@@ -189,11 +189,8 @@ // |animating_background_| will be made visible during hotseat animations. ShowAnimatingBackground(false); - if (features::IsBackgroundBlurEnabled()) { - animating_background_.SetBackdropFilterQuality(0.33f); - animating_background_.SetColor( - ShelfConfig::Get()->GetMaximizedShelfColor()); - } + animating_background_.SetColor(ShelfConfig::Get()->GetMaximizedShelfColor()); + std::unique_ptr<views::View> drag_handle_ptr = std::make_unique<views::View>(); const int radius = kDragHandleCornerRadius; @@ -406,11 +403,6 @@ void ShelfWidget::DelegateView::ShowAnimatingBackground(bool show) { animating_background_.SetVisible(show); - - // To ensure smooth scrollable shelf animations, we disable blur when the - // |animating_background_| is not visible. - if (features::IsBackgroundBlurEnabled()) - animating_background_.SetBackgroundBlur(show ? 30 : 0); } SkColor ShelfWidget::DelegateView::GetShelfBackgroundColor() const {
diff --git a/ash/wm/overview/overview_grid.cc b/ash/wm/overview/overview_grid.cc index f97ffda9..5576f10e 100644 --- a/ash/wm/overview/overview_grid.cc +++ b/ash/wm/overview/overview_grid.cc
@@ -248,6 +248,12 @@ return window->GetBoundsInRootWindow(); } +bool ShouldExcludeItemFromGridLayout( + OverviewItem* item, + const base::flat_set<OverviewItem*>& ignored_items) { + return item->animating_to_close() || ignored_items.contains(item); +} + } // namespace // The class to observe the overview window that the dragged tabs will merge @@ -452,8 +458,7 @@ for (size_t i = 0; i < window_list_.size(); ++i) { OverviewItem* window_item = window_list_[i].get(); - if (window_item->animating_to_close() || - ignored_items.contains(window_item)) { + if (ShouldExcludeItemFromGridLayout(window_item, ignored_items)) { rects[i].SetRect(0, 0, 0, 0); continue; } @@ -1699,7 +1704,7 @@ // that the items are always aligned left or right. float rightmost_window_right = 0; for (const auto& item : window_list_) { - if (item->animating_to_close() || ignored_items.contains(item.get())) + if (ShouldExcludeItemFromGridLayout(item.get(), ignored_items)) continue; rightmost_window_right = std::max(rightmost_window_right, item->target_bounds().right()); @@ -1729,7 +1734,7 @@ std::vector<gfx::RectF> rects; for (size_t i = 0; i < window_list_.size(); ++i) { OverviewItem* item = window_list_[i].get(); - if (item->animating_to_close() || ignored_items.contains(item)) { + if (ShouldExcludeItemFromGridLayout(item, ignored_items)) { rects.push_back(gfx::RectF()); continue; } @@ -1782,10 +1787,8 @@ // All elements are of same height and only the height is necessary to // determine each item's scale. for (size_t i = 0u; i < window_count; ++i) { - if (window_list_[i]->animating_to_close() || - ignored_items.contains(window_list_[i].get())) { + if (ShouldExcludeItemFromGridLayout(window_list_[i].get(), ignored_items)) continue; - } int width = CalculateWidthAndMaybeSetUnclippedBounds(window_list_[i].get(), height);
diff --git a/build/android/gyp/aar.py b/build/android/gyp/aar.py index c31d87b..a6b4af9 100755 --- a/build/android/gyp/aar.py +++ b/build/android/gyp/aar.py
@@ -91,6 +91,9 @@ os.mkdir(tmp_dir) build_utils.ExtractAll( aar_file, path=tmp_dir, predicate=name_whitelist.__contains__) + # Write a breadcrumb so that SuperSize can attribute files back to the .aar. + with open(os.path.join(tmp_dir, 'source.info'), 'w') as f: + f.write('source={}\n'.format(aar_file)) shutil.rmtree(output_dir, ignore_errors=True) shutil.move(tmp_dir, output_dir) @@ -147,10 +150,12 @@ if args.ignore_resources: names = [n for n in names if not n.startswith('res')] + output_paths = [os.path.join(args.output_dir, n) for n in names] + output_paths.append(os.path.join(args.output_dir, 'source.info')) md5_check.CallAndRecordIfStale( lambda: _PerformExtract(args.aar_file, args.output_dir, set(names)), input_paths=[args.aar_file], - output_paths=[os.path.join(args.output_dir, n) for n in names]) + output_paths=output_paths) elif args.command == 'list': aar_output_present = args.output != '-' and os.path.isfile(args.output)
diff --git a/build/android/gyp/create_size_info_files.py b/build/android/gyp/create_size_info_files.py index 381a23b..b2feeed 100755 --- a/build/android/gyp/create_size_info_files.py +++ b/build/android/gyp/create_size_info_files.py
@@ -60,29 +60,41 @@ Args: output: output file path. - inputs: List of .info.jar or .jar files. + inputs: List of .jar.info or .jar files. """ info_data = dict() for path in inputs: - # android_java_prebuilt adds jar files in the src directory (relative to - # the output directory, usually ../../third_party/example.jar). - # android_aar_prebuilt collects jar files in the aar file and uses the - # java_prebuilt rule to generate gen/example/classes.jar files. - # We scan these prebuilt jars to parse each class path for the FQN. This - # allows us to later map these classes back to their respective src - # directories. - # TODO(agrieve): This should probably also check that the mtime of the .info - # is newer than that of the .jar, or change prebuilts to always output - # .info files so that they always exist (and change the depfile to - # depend directly on them). + # For non-prebuilts: .jar.info files are written by compile_java.py and map + # .class files to .java source paths. + # + # For prebuilts: No .jar.info file exists, we scan the .jar files here and + # map .class files to the .jar. + # + # For .aar files: We look for a "source.info" file in the containing + # directory in order to map classes back to the .aar (rather than mapping + # them to the extracted .jar file). if path.endswith('.info'): info_data.update(jar_info_utils.ParseJarInfoFile(path)) else: + attributed_path = path + if not path.startswith('..'): + parent_path = os.path.dirname(path) + # See if it's an sub-jar within the .aar. + if os.path.basename(parent_path) == 'libs': + parent_path = os.path.dirname(parent_path) + aar_source_info_path = os.path.join(parent_path, 'source.info') + # source.info files exist only for jars from android_aar_prebuilt(). + # E.g. Could have an java_prebuilt() pointing to a generated .jar. + if os.path.exists(aar_source_info_path): + attributed_path = jar_info_utils.ReadAarSourceInfo( + aar_source_info_path) + with zipfile.ZipFile(path) as zip_info: for name in zip_info.namelist(): fully_qualified_name = _FullJavaNameFromClassFilePath(name) if fully_qualified_name: - info_data[fully_qualified_name] = '{}/{}'.format(path, name) + info_data[fully_qualified_name] = '{}/{}'.format( + attributed_path, name) # only_if_changed=False since no build rules depend on this as an input. with build_utils.AtomicOutput(output, only_if_changed=False) as f: @@ -147,7 +159,7 @@ # Don't bother re-running if no .info files have changed (saves ~250ms). md5_check.CallAndRecordIfStale( lambda: _MergeJarInfoFiles(options.jar_info_path, jar_inputs), - input_paths=jar_inputs, + input_paths=jar_inputs + [__file__], output_paths=[options.jar_info_path]) # Always recreate these (just as fast as md5 checking them).
diff --git a/build/android/gyp/prepare_resources.py b/build/android/gyp/prepare_resources.py index a526604..8e92787 100755 --- a/build/android/gyp/prepare_resources.py +++ b/build/android/gyp/prepare_resources.py
@@ -16,6 +16,7 @@ import zipfile from util import build_utils +from util import jar_info_utils from util import manifest_utils from util import md5_check from util import resource_utils @@ -108,10 +109,21 @@ files_to_zip = [] path_info = resource_utils.ResourceInfoFile() for index, resource_dir in enumerate(resource_dirs): + attributed_aar = None + if not resource_dir.startswith('..'): + aar_source_info_path = os.path.join( + os.path.dirname(resource_dir), 'source.info') + if os.path.exists(aar_source_info_path): + attributed_aar = jar_info_utils.ReadAarSourceInfo(aar_source_info_path) + for path, archive_path in resource_utils.IterResourceFilesInDirectories( [resource_dir], ignore_pattern): - # Put the non-prefixed path in the .info file. - path_info.AddMapping(archive_path, path) + attributed_path = path + if attributed_aar: + attributed_path = os.path.join(attributed_aar, 'res', + path[len(resource_dir) + 1:]) + # Use the non-prefixed archive_path in the .info file. + path_info.AddMapping(archive_path, attributed_path) resource_dir_name = os.path.basename(resource_dir) archive_path = '{}_{}/{}'.format(index, resource_dir_name, archive_path)
diff --git a/build/android/gyp/prepare_resources.pydeps b/build/android/gyp/prepare_resources.pydeps index 8c65cf9..7b6331f 100644 --- a/build/android/gyp/prepare_resources.pydeps +++ b/build/android/gyp/prepare_resources.pydeps
@@ -25,6 +25,7 @@ prepare_resources.py util/__init__.py util/build_utils.py +util/jar_info_utils.py util/manifest_utils.py util/md5_check.py util/resource_utils.py
diff --git a/build/android/gyp/util/jar_info_utils.py b/build/android/gyp/util/jar_info_utils.py index 677e4e42..355bcb0 100644 --- a/build/android/gyp/util/jar_info_utils.py +++ b/build/android/gyp/util/jar_info_utils.py
@@ -13,6 +13,13 @@ # contains its .class definition instead. +def ReadAarSourceInfo(info_path): + """Returns the source= path from an .aar's source.info file.""" + # The .info looks like: "source=path/to/.aar\n". + with open(info_path) as f: + return f.read().rstrip().split('=', 1)[1] + + def ParseJarInfoFile(info_path): """Parse a given .jar.info file as a dictionary.
diff --git a/build/fuchsia/linux.sdk.sha1 b/build/fuchsia/linux.sdk.sha1 index 6ae4be3f..bacc9f16 100644 --- a/build/fuchsia/linux.sdk.sha1 +++ b/build/fuchsia/linux.sdk.sha1
@@ -1 +1 @@ -8892367722555030832 \ No newline at end of file +8892303229666828080 \ No newline at end of file
diff --git a/cc/test/pixel_test_output_surface.cc b/cc/test/pixel_test_output_surface.cc index 38353f25..baa2e11 100644 --- a/cc/test/pixel_test_output_surface.cc +++ b/cc/test/pixel_test_output_surface.cc
@@ -13,6 +13,7 @@ #include "gpu/command_buffer/client/gles2_interface.h" #include "third_party/khronos/GLES2/gl2.h" #include "ui/gfx/presentation_feedback.h" +#include "ui/gfx/swap_result.h" #include "ui/gfx/transform.h" #include "ui/gl/color_space_utils.h"
diff --git a/cc/test/pixel_test_utils.cc b/cc/test/pixel_test_utils.cc index bd4372b1..7aad20d 100644 --- a/cc/test/pixel_test_utils.cc +++ b/cc/test/pixel_test_utils.cc
@@ -52,6 +52,8 @@ bool MatchesBitmap(const SkBitmap& gen_bmp, const SkBitmap& ref_bmp, const PixelComparator& comparator) { + bool pixels_match = true; + // Check if images size matches if (gen_bmp.width() != ref_bmp.width() || gen_bmp.height() != ref_bmp.height()) { @@ -60,22 +62,25 @@ << "Actual: " << gen_bmp.width() << "x" << gen_bmp.height() << "; " << "Expected: " << ref_bmp.width() << "x" << ref_bmp.height(); - return false; + pixels_match = false; } // Shortcut for empty images. They are always equal. - if (gen_bmp.width() == 0 || gen_bmp.height() == 0) + if (pixels_match && (gen_bmp.width() == 0 || gen_bmp.height() == 0)) return true; - bool compare = comparator.Compare(gen_bmp, ref_bmp); - if (!compare) { - std::string gen_bmp_data_url = GetPNGDataUrl(gen_bmp); - std::string ref_bmp_data_url = GetPNGDataUrl(ref_bmp); + if (pixels_match && !comparator.Compare(gen_bmp, ref_bmp)) { LOG(ERROR) << "Pixels do not match!"; - LOG(ERROR) << "Actual pixels (open in browser):\n" << gen_bmp_data_url; - LOG(ERROR) << "Expected pixels (open in browser):\n" << ref_bmp_data_url; + pixels_match = false; } - return compare; + + if (!pixels_match) { + LOG(ERROR) << "Actual pixels (open in browser):\n" + << GetPNGDataUrl(gen_bmp); + LOG(ERROR) << "Expected pixels (open in browser):\n" + << GetPNGDataUrl(ref_bmp); + } + return pixels_match; } bool MatchesPNGFile(const SkBitmap& gen_bmp,
diff --git a/chrome/VERSION b/chrome/VERSION index c06cd55..a56c6e22 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=81 MINOR=0 -BUILD=4016 +BUILD=4017 PATCH=0
diff --git a/chrome/android/chrome_java_sources.gni b/chrome/android/chrome_java_sources.gni index cd8ab18..9ccd1ac1 100644 --- a/chrome/android/chrome_java_sources.gni +++ b/chrome/android/chrome_java_sources.gni
@@ -84,6 +84,23 @@ "java/src/org/chromium/chrome/browser/autofill/CreditCardScannerBridge.java", "java/src/org/chromium/chrome/browser/autofill/PersonalDataManager.java", "java/src/org/chromium/chrome/browser/autofill/PhoneNumberUtil.java", + "java/src/org/chromium/chrome/browser/autofill/prefeditor/Completable.java", + "java/src/org/chromium/chrome/browser/autofill/prefeditor/DropdownFieldAdapter.java", + "java/src/org/chromium/chrome/browser/autofill/prefeditor/EditableOption.java", + "java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorBase.java", + "java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorDialog.java", + "java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorDialogToolbar.java", + "java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorDropdownField.java", + "java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorFieldModel.java", + "java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorFieldView.java", + "java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorIconsField.java", + "java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorLabelField.java", + "java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorModel.java", + "java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorObserverForTest.java", + "java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorTextField.java", + "java/src/org/chromium/chrome/browser/autofill/prefeditor/ExpandableGridView.java", + "java/src/org/chromium/chrome/browser/autofill/prefeditor/HintedDropDownAdapter.java", + "java/src/org/chromium/chrome/browser/autofill/prefeditor/HintedDropDownAdapterWithPlusIcon.java", "java/src/org/chromium/chrome/browser/background_sync/BackgroundSyncBackgroundTask.java", "java/src/org/chromium/chrome/browser/background_sync/BackgroundSyncBackgroundTaskScheduler.java", "java/src/org/chromium/chrome/browser/background_sync/BackgroundSyncPwaDetector.java", @@ -663,6 +680,7 @@ "java/src/org/chromium/chrome/browser/favicon/FaviconHelper.java", "java/src/org/chromium/chrome/browser/favicon/FaviconUtils.java", "java/src/org/chromium/chrome/browser/favicon/LargeIconBridge.java", + "java/src/org/chromium/chrome/browser/favicon/RoundedIconGenerator.java", "java/src/org/chromium/chrome/browser/feature_engagement/ScreenshotMonitor.java", "java/src/org/chromium/chrome/browser/feature_engagement/ScreenshotMonitorDelegate.java", "java/src/org/chromium/chrome/browser/feature_engagement/ScreenshotTabObserver.java", @@ -892,7 +910,6 @@ "java/src/org/chromium/chrome/browser/media/ui/MediaNotificationListener.java", "java/src/org/chromium/chrome/browser/media/ui/MediaNotificationManager.java", "java/src/org/chromium/chrome/browser/media/ui/MediaSessionTabHelper.java", - "java/src/org/chromium/chrome/browser/metrics/ActivityStopMetrics.java", "java/src/org/chromium/chrome/browser/metrics/ActivityTabStartupMetricsTracker.java", "java/src/org/chromium/chrome/browser/metrics/BackgroundTaskMemoryMetricsEmitter.java", "java/src/org/chromium/chrome/browser/metrics/ImpressionTracker.java", @@ -1565,6 +1582,8 @@ "java/src/org/chromium/chrome/browser/suggestions/tile/TileGroup.java", "java/src/org/chromium/chrome/browser/suggestions/tile/TileGroupDelegateImpl.java", "java/src/org/chromium/chrome/browser/suggestions/tile/TileRenderer.java", + "java/src/org/chromium/chrome/browser/suggestions/tile/TileView.java", + "java/src/org/chromium/chrome/browser/suggestions/tile/TileWithTextView.java", "java/src/org/chromium/chrome/browser/suggestions/tile/TopSitesTileView.java", "java/src/org/chromium/chrome/browser/survey/ChromeSurveyController.java", "java/src/org/chromium/chrome/browser/survey/SurveyController.java", @@ -1847,7 +1866,6 @@ "java/src/org/chromium/chrome/browser/widget/DateDividedAdapter.java", "java/src/org/chromium/chrome/browser/widget/FeatureHighlightProvider.java", "java/src/org/chromium/chrome/browser/widget/NumberRollView.java", - "java/src/org/chromium/chrome/browser/widget/RoundedIconGenerator.java", "java/src/org/chromium/chrome/browser/widget/ScrimView.java", "java/src/org/chromium/chrome/browser/widget/ThumbnailDiskStorage.java", "java/src/org/chromium/chrome/browser/widget/ThumbnailGenerator.java", @@ -1862,29 +1880,10 @@ "java/src/org/chromium/chrome/browser/widget/bottomsheet/BottomSheetSwipeDetector.java", "java/src/org/chromium/chrome/browser/widget/bottomsheet/EmptyBottomSheetObserver.java", "java/src/org/chromium/chrome/browser/widget/bottomsheet/TouchRestrictingFrameLayout.java", - "java/src/org/chromium/chrome/browser/widget/prefeditor/Completable.java", - "java/src/org/chromium/chrome/browser/widget/prefeditor/DropdownFieldAdapter.java", - "java/src/org/chromium/chrome/browser/widget/prefeditor/EditableOption.java", - "java/src/org/chromium/chrome/browser/widget/prefeditor/EditorBase.java", - "java/src/org/chromium/chrome/browser/widget/prefeditor/EditorDialog.java", - "java/src/org/chromium/chrome/browser/widget/prefeditor/EditorDialogToolbar.java", - "java/src/org/chromium/chrome/browser/widget/prefeditor/EditorDropdownField.java", - "java/src/org/chromium/chrome/browser/widget/prefeditor/EditorFieldModel.java", - "java/src/org/chromium/chrome/browser/widget/prefeditor/EditorFieldView.java", - "java/src/org/chromium/chrome/browser/widget/prefeditor/EditorIconsField.java", - "java/src/org/chromium/chrome/browser/widget/prefeditor/EditorLabelField.java", - "java/src/org/chromium/chrome/browser/widget/prefeditor/EditorModel.java", - "java/src/org/chromium/chrome/browser/widget/prefeditor/EditorObserverForTest.java", - "java/src/org/chromium/chrome/browser/widget/prefeditor/EditorTextField.java", - "java/src/org/chromium/chrome/browser/widget/prefeditor/ExpandableGridView.java", - "java/src/org/chromium/chrome/browser/widget/prefeditor/HintedDropDownAdapter.java", - "java/src/org/chromium/chrome/browser/widget/prefeditor/HintedDropDownAdapterWithPlusIcon.java", "java/src/org/chromium/chrome/browser/widget/selection/SelectableItemView.java", "java/src/org/chromium/chrome/browser/widget/selection/SelectableItemViewBase.java", "java/src/org/chromium/chrome/browser/widget/selection/SelectableItemViewHolder.java", "java/src/org/chromium/chrome/browser/widget/selection/SelectableListLayout.java", "java/src/org/chromium/chrome/browser/widget/selection/SelectableListToolbar.java", "java/src/org/chromium/chrome/browser/widget/selection/SelectionDelegate.java", - "java/src/org/chromium/chrome/browser/widget/tile/TileView.java", - "java/src/org/chromium/chrome/browser/widget/tile/TileWithTextView.java", ]
diff --git a/chrome/android/chrome_test_java_sources.gni b/chrome/android/chrome_test_java_sources.gni index 31be77cc..3e52843 100644 --- a/chrome/android/chrome_test_java_sources.gni +++ b/chrome/android/chrome_test_java_sources.gni
@@ -170,6 +170,7 @@ "javatests/src/org/chromium/chrome/browser/externalnav/ExternalNavigationHandlerTest.java", "javatests/src/org/chromium/chrome/browser/externalnav/IntentWithGesturesHandlerTest.java", "javatests/src/org/chromium/chrome/browser/externalnav/UrlOverridingTest.java", + "javatests/src/org/chromium/chrome/browser/favicon/RoundedIconGeneratorTest.java", "javatests/src/org/chromium/chrome/browser/feature_engagement/ScreenshotMonitorTest.java", "javatests/src/org/chromium/chrome/browser/feature_engagement/ScreenshotTabObserverTest.java", "javatests/src/org/chromium/chrome/browser/feedback/ConnectivityCheckerTest.java", @@ -524,7 +525,6 @@ "javatests/src/org/chromium/chrome/browser/webauth/AuthenticatorTest.java", "javatests/src/org/chromium/chrome/browser/webshare/WebShareTest.java", "javatests/src/org/chromium/chrome/browser/widget/ChromeTextInputLayoutRenderTest.java", - "javatests/src/org/chromium/chrome/browser/widget/RoundedIconGeneratorTest.java", "javatests/src/org/chromium/chrome/browser/widget/ScrimTest.java", "javatests/src/org/chromium/chrome/browser/widget/ThumbnailDiskStorageTest.java", "javatests/src/org/chromium/chrome/browser/widget/ThumbnailProviderImplTest.java",
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/user_data/AssistantCollectUserDataBinder.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/user_data/AssistantCollectUserDataBinder.java index aa3669bb..391ec3e 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/user_data/AssistantCollectUserDataBinder.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/user_data/AssistantCollectUserDataBinder.java
@@ -14,6 +14,7 @@ import org.chromium.base.task.PostTask; import org.chromium.chrome.browser.ChromeVersionInfo; import org.chromium.chrome.browser.autofill.PersonalDataManager; +import org.chromium.chrome.browser.autofill.prefeditor.EditorDialog; import org.chromium.chrome.browser.autofill_assistant.user_data.additional_sections.AssistantAdditionalSectionContainer; import org.chromium.chrome.browser.payments.AddressEditor; import org.chromium.chrome.browser.payments.AutofillAddress; @@ -22,7 +23,6 @@ import org.chromium.chrome.browser.payments.BasicCardUtils; import org.chromium.chrome.browser.payments.CardEditor; import org.chromium.chrome.browser.payments.ContactEditor; -import org.chromium.chrome.browser.widget.prefeditor.EditorDialog; import org.chromium.components.payments.MethodStrings; import org.chromium.content_public.browser.UiThreadTaskTraits; import org.chromium.content_public.browser.WebContents; @@ -557,14 +557,14 @@ model.get(AssistantCollectUserDataModel.REQUEST_PHONE), model.get(AssistantCollectUserDataModel.REQUEST_EMAIL), !webContents.isIncognito()); - contactEditor.setEditorDialog(new EditorDialog(view.mActivity, null, + contactEditor.setEditorDialog(new EditorDialog(view.mActivity, /*deleteRunnable =*/null)); view.mContactDetailsSection.setEditor(contactEditor); } AddressEditor addressEditor = new AddressEditor(AddressEditor.Purpose.PAYMENT_REQUEST, /* saveToDisk= */ !webContents.isIncognito()); - addressEditor.setEditorDialog(new EditorDialog(view.mActivity, null, + addressEditor.setEditorDialog(new EditorDialog(view.mActivity, /*deleteRunnable =*/null)); CardEditor cardEditor = new CardEditor(webContents, addressEditor, @@ -576,7 +576,7 @@ getPaymentMethodDataFromNetworks(supportedCardNetworks)); } - EditorDialog cardEditorDialog = new EditorDialog(view.mActivity, null, + EditorDialog cardEditorDialog = new EditorDialog(view.mActivity, /*deleteRunnable =*/null); if (ChromeVersionInfo.isBetaBuild() || ChromeVersionInfo.isStableBuild()) { cardEditorDialog.disableScreenshots();
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/user_data/AssistantCollectUserDataSection.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/user_data/AssistantCollectUserDataSection.java index b4b8f25..3d7cc641 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/user_data/AssistantCollectUserDataSection.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/user_data/AssistantCollectUserDataSection.java
@@ -17,9 +17,9 @@ import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.Callback; import org.chromium.chrome.autofill_assistant.R; +import org.chromium.chrome.browser.autofill.prefeditor.EditableOption; import org.chromium.chrome.browser.autofill_assistant.AssistantTagsForTesting; import org.chromium.chrome.browser.autofill_assistant.AssistantTextUtils; -import org.chromium.chrome.browser.widget.prefeditor.EditableOption; import java.util.ArrayList; import java.util.List;
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/user_data/AssistantLoginChoice.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/user_data/AssistantLoginChoice.java index 574526cd..590bb69 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/user_data/AssistantLoginChoice.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/user_data/AssistantLoginChoice.java
@@ -6,8 +6,8 @@ import android.support.annotation.Nullable; +import org.chromium.chrome.browser.autofill.prefeditor.EditableOption; import org.chromium.chrome.browser.autofill_assistant.AssistantInfoPopup; -import org.chromium.chrome.browser.widget.prefeditor.EditableOption; /** * Represents a single login choice.
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/user_data/additional_sections/AssistantTextInputSection.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/user_data/additional_sections/AssistantTextInputSection.java index 3029889..76a0e587 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/user_data/additional_sections/AssistantTextInputSection.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/user_data/additional_sections/AssistantTextInputSection.java
@@ -4,7 +4,7 @@ package org.chromium.chrome.browser.autofill_assistant.user_data.additional_sections; -import static org.chromium.chrome.browser.widget.prefeditor.EditorFieldModel.INPUT_TYPE_HINT_ALPHA_NUMERIC; +import static org.chromium.chrome.browser.autofill.prefeditor.EditorFieldModel.INPUT_TYPE_HINT_ALPHA_NUMERIC; import android.content.Context; import android.support.annotation.Nullable; @@ -21,10 +21,10 @@ import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.Callback; import org.chromium.chrome.autofill_assistant.R; +import org.chromium.chrome.browser.autofill.prefeditor.EditorFieldModel; +import org.chromium.chrome.browser.autofill.prefeditor.EditorTextField; import org.chromium.chrome.browser.autofill_assistant.AssistantTextUtils; import org.chromium.chrome.browser.autofill_assistant.user_data.AssistantVerticalExpander; -import org.chromium.chrome.browser.widget.prefeditor.EditorFieldModel; -import org.chromium.chrome.browser.widget.prefeditor.EditorTextField; import java.util.List; @@ -80,7 +80,7 @@ /* invalidErrorMessage = */ null, mValue), (v, actionId, event) -> false, - /* filter = */ null, textWatcher, /* observer = */ null); + /* filter = */ null, textWatcher); } }
diff --git a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessorySheetViewBinder.java b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessorySheetViewBinder.java index 4858799..e7d5090 100644 --- a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessorySheetViewBinder.java +++ b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessorySheetViewBinder.java
@@ -26,6 +26,7 @@ import org.chromium.base.Callback; import org.chromium.chrome.browser.favicon.FaviconUtils; import org.chromium.chrome.browser.favicon.LargeIconBridge; +import org.chromium.chrome.browser.favicon.RoundedIconGenerator; import org.chromium.chrome.browser.keyboard_accessory.R; import org.chromium.chrome.browser.keyboard_accessory.data.KeyboardAccessoryData; import org.chromium.chrome.browser.keyboard_accessory.data.KeyboardAccessoryData.FooterCommand; @@ -33,7 +34,6 @@ import org.chromium.chrome.browser.keyboard_accessory.sheet_tabs.AccessorySheetTabModel.AccessorySheetDataPiece; import org.chromium.chrome.browser.keyboard_accessory.sheet_tabs.AccessorySheetTabViewBinder.ElementViewHolder; import org.chromium.chrome.browser.profiles.Profile; -import org.chromium.chrome.browser.widget.RoundedIconGenerator; import org.chromium.ui.HorizontalListDividerDrawable; import org.chromium.ui.modelutil.ListModel;
diff --git a/chrome/android/java/DEPS b/chrome/android/java/DEPS index 689cdeb..6e0a47c 100644 --- a/chrome/android/java/DEPS +++ b/chrome/android/java/DEPS
@@ -9,6 +9,7 @@ "+chrome/browser/download/android/java", "+chrome/browser/image_fetcher/android/java", "+chrome/browser/preferences/android/java", + "+chrome/browser/settings/android/java", "+chrome/browser/util/android/java", "+chrome/lib/lifecycle/public", "+components/autofill/android/java/src/org/chromium/components/autofill",
diff --git a/chrome/android/java/res/layout/editable_option_editor_icons.xml b/chrome/android/java/res/layout/editable_option_editor_icons.xml index 328b728..37c0be3 100644 --- a/chrome/android/java/res/layout/editable_option_editor_icons.xml +++ b/chrome/android/java/res/layout/editable_option_editor_icons.xml
@@ -19,7 +19,7 @@ android:layout_height="wrap_content" android:textAppearance="@style/TextAppearance.BlackCaption" /> - <org.chromium.chrome.browser.widget.prefeditor.ExpandableGridView + <org.chromium.chrome.browser.autofill.prefeditor.ExpandableGridView android:id="@+id/icons_container" android:layout_width="match_parent" android:layout_height="wrap_content"
diff --git a/chrome/android/java/res/layout/payment_request_editor.xml b/chrome/android/java/res/layout/payment_request_editor.xml index 58aea00..0ceefbe 100644 --- a/chrome/android/java/res/layout/payment_request_editor.xml +++ b/chrome/android/java/res/layout/payment_request_editor.xml
@@ -10,7 +10,7 @@ android:background="@color/modern_primary_color"> <!-- Toolbar --> - <org.chromium.chrome.browser.widget.prefeditor.EditorDialogToolbar + <org.chromium.chrome.browser.autofill.prefeditor.EditorDialogToolbar android:id="@+id/action_bar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ChromeTabbedActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/ChromeTabbedActivity.java index ea59c4eb..a84a6bb 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ChromeTabbedActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ChromeTabbedActivity.java
@@ -28,7 +28,6 @@ import android.view.Window; import android.view.WindowManager; -import androidx.annotation.IntDef; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; @@ -94,7 +93,6 @@ import org.chromium.chrome.browser.infobar.DataReductionPromoInfoBar; import org.chromium.chrome.browser.lifecycle.ActivityLifecycleDispatcher; import org.chromium.chrome.browser.locale.LocaleManager; -import org.chromium.chrome.browser.metrics.ActivityStopMetrics; import org.chromium.chrome.browser.metrics.LaunchMetrics; import org.chromium.chrome.browser.metrics.MainIntentBehaviorMetrics; import org.chromium.chrome.browser.modaldialog.TabModalLifetimeHandler; @@ -165,8 +163,6 @@ import org.chromium.ui.modaldialog.ModalDialogManager; import org.chromium.ui.widget.Toast; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; import java.util.List; import java.util.Locale; @@ -175,30 +171,6 @@ * are accessible via a chrome specific tab switching UI. */ public class ChromeTabbedActivity extends ChromeActivity implements ScreenshotMonitorDelegate { - /** - * The results of a system back press action. - */ - @IntDef({BackPressedResult.NOTHING_HAPPENED, BackPressedResult.HELP_URL_CLOSED, - BackPressedResult.MINIMIZED_NO_TAB_CLOSED, BackPressedResult.MINIMIZED_TAB_CLOSED, - BackPressedResult.TAB_CLOSED, BackPressedResult.TAB_IS_NULL, - BackPressedResult.EXITED_TAB_SWITCHER, BackPressedResult.EXITED_FULLSCREEN, - BackPressedResult.NAVIGATED_BACK, BackPressedResult.EXITED_TAB_GROUP_DIALOG}) - @Retention(RetentionPolicy.SOURCE) - public @interface BackPressedResult { - int NOTHING_HAPPENED = 0; - int HELP_URL_CLOSED = 1; - int MINIMIZED_NO_TAB_CLOSED = 2; - int MINIMIZED_TAB_CLOSED = 3; - int TAB_CLOSED = 4; - int TAB_IS_NULL = 5; - int EXITED_TAB_SWITCHER = 6; - int EXITED_FULLSCREEN = 7; - int NAVIGATED_BACK = 8; - int EXITED_TAB_GROUP_DIALOG = 9; - - int NUM_ENTRIES = 10; - } - private static final String TAG = "ChromeTabbedActivity"; private static final String HELP_URL_PREFIX = "https://support.google.com/chrome/"; @@ -252,7 +224,6 @@ // Count histogram used to track number of tabs when we show the Overview on Return to Chrome. private static final String TAB_COUNT_ON_RETURN = "Tabs.TabCountOnStartScreenShown"; - private final ActivityStopMetrics mActivityStopMetrics; private final MainIntentBehaviorMetrics mMainIntentMetrics; private final @Nullable MultiInstanceManager mMultiInstanceManager; @@ -480,7 +451,6 @@ * Constructs a ChromeTabbedActivity. */ public ChromeTabbedActivity() { - mActivityStopMetrics = new ActivityStopMetrics(); mMainIntentMetrics = new MainIntentBehaviorMetrics(this); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { mMultiInstanceManager = new MultiInstanceManager(this, mTabModelSelectorSupplier, @@ -911,7 +881,6 @@ super.onStopWithNative(); mTabModelSelectorImpl.saveState(); - mActivityStopMetrics.onStopWithNative(this); } @Override @@ -1790,13 +1759,6 @@ mTabModalHandler.onOmniboxFocusChanged(hasFocus); } - private void recordBackPressedUma(String logMessage, @BackPressedResult int action) { - Log.i(TAG, "Back pressed: " + logMessage); - RecordHistogram.recordEnumeratedHistogram( - "Android.Activity.ChromeTabbedActivity.SystemBackAction", action, - BackPressedResult.NUM_ENTRIES); - } - private void recordLauncherShortcutAction(boolean isIncognito) { if (isIncognito) { RecordUserAction.record("Android.LauncherShortcut.NewIncognitoTab"); @@ -1814,7 +1776,6 @@ final Tab currentTab = getActivityTab(); if (exitFullscreenIfShowing()) { - recordBackPressedUma("Exited fullscreen", BackPressedResult.EXITED_FULLSCREEN); return true; } @@ -1823,34 +1784,17 @@ if (mTabModalHandler.handleBackPress()) return true; if (currentTab == null) { - recordBackPressedUma("currentTab is null", BackPressedResult.TAB_IS_NULL); moveTaskToBack(true); return true; } // If we are in overview mode and not a tablet, then leave overview mode on back. if (mOverviewModeController.overviewVisible() && !isTablet()) { - recordBackPressedUma("Hide overview", BackPressedResult.EXITED_TAB_SWITCHER); mOverviewModeController.hideOverview(true); return true; } - Integer toolbarManagerBackPressResult = getToolbarManager().back(); - if (toolbarManagerBackPressResult != null) { - String logMessage = ""; - switch (toolbarManagerBackPressResult) { - case BackPressedResult.NAVIGATED_BACK: - logMessage = "Navigating backward"; - break; - case BackPressedResult.EXITED_TAB_GROUP_DIALOG: - logMessage = "Exiting tab group dialog"; - break; - default: - assert false; - } - recordBackPressedUma(logMessage, toolbarManagerBackPressResult); - return true; - } + if (getToolbarManager().back()) return true; // If the current tab url is HELP_URL, then the back button should close the tab to // get back to the previous state. The reason for startsWith check is that the @@ -1859,7 +1803,6 @@ final boolean helpUrl = currentTab.getUrl().startsWith(HELP_URL_PREFIX); if (type == TabLaunchType.FROM_CHROME_UI && helpUrl) { getCurrentTabModel().closeTab(currentTab); - recordBackPressedUma("Closed tab for help URL", BackPressedResult.HELP_URL_CLOSED); return true; } @@ -1881,26 +1824,18 @@ !shouldCloseTab || TabAssociatedApp.isOpenedFromExternalApp(currentTab); if (minimizeApp) { if (shouldCloseTab) { - recordBackPressedUma( - "Minimized and closed tab", BackPressedResult.MINIMIZED_TAB_CLOSED); - mActivityStopMetrics.setStopReason(ActivityStopMetrics.StopReason.BACK_BUTTON); sendToBackground(currentTab); return true; } else { - recordBackPressedUma( - "Minimized, kept tab", BackPressedResult.MINIMIZED_NO_TAB_CLOSED); - mActivityStopMetrics.setStopReason(ActivityStopMetrics.StopReason.BACK_BUTTON); sendToBackground(null); return true; } } else if (shouldCloseTab) { - recordBackPressedUma("Tab closed", BackPressedResult.TAB_CLOSED); getCurrentTabModel().closeTab(currentTab, true, false, false); return true; } assert false : "The back button should have already been handled by this point"; - recordBackPressedUma("Unhandled", BackPressedResult.NOTHING_HAPPENED); return false; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ShortcutHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/ShortcutHelper.java index b0cc53e..fdb5551 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ShortcutHelper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ShortcutHelper.java
@@ -40,6 +40,7 @@ import org.chromium.base.annotations.NativeMethods; import org.chromium.base.task.AsyncTask; import org.chromium.chrome.R; +import org.chromium.chrome.browser.favicon.RoundedIconGenerator; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.webapps.WebDisplayMode; import org.chromium.chrome.browser.webapps.WebappActivity; @@ -48,7 +49,6 @@ import org.chromium.chrome.browser.webapps.WebappInfo; import org.chromium.chrome.browser.webapps.WebappLauncherActivity; import org.chromium.chrome.browser.webapps.WebappRegistry; -import org.chromium.chrome.browser.widget.RoundedIconGenerator; import org.chromium.content_public.common.ScreenOrientationConstants; import org.chromium.ui.widget.Toast; import org.chromium.webapk.lib.client.WebApkValidator;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/Completable.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/Completable.java similarity index 90% rename from chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/Completable.java rename to chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/Completable.java index 49b1d08..9af3d38df 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/Completable.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/Completable.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.chrome.browser.widget.prefeditor; +package org.chromium.chrome.browser.autofill.prefeditor; /** * The interface for types that may be complete, i.e., can be sent to the merchant as-is, without
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/DropdownFieldAdapter.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/DropdownFieldAdapter.java similarity index 97% rename from chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/DropdownFieldAdapter.java rename to chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/DropdownFieldAdapter.java index 6f22da26..e00ceca 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/DropdownFieldAdapter.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/DropdownFieldAdapter.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.chrome.browser.widget.prefeditor; +package org.chromium.chrome.browser.autofill.prefeditor; import android.content.Context; import android.graphics.Rect;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditableOption.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditableOption.java similarity index 98% rename from chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditableOption.java rename to chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditableOption.java index 24d678a..418cffd2 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditableOption.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditableOption.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.chrome.browser.widget.prefeditor; +package org.chromium.chrome.browser.autofill.prefeditor; import android.graphics.drawable.Drawable; import android.text.TextUtils;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorBase.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorBase.java similarity index 96% rename from chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorBase.java rename to chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorBase.java index 11b2d230..f8b6a58 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorBase.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorBase.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.chrome.browser.widget.prefeditor; +package org.chromium.chrome.browser.autofill.prefeditor; import android.content.Context;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorDialog.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorDialog.java similarity index 95% rename from chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorDialog.java rename to chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorDialog.java index 155f1d9..6977a3a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorDialog.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorDialog.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.chrome.browser.widget.prefeditor; +package org.chromium.chrome.browser.autofill.prefeditor; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; @@ -74,8 +74,9 @@ /** Duration of the animation to hide the UI. */ private static final int DIALOG_EXIT_ANIMATION_MS = 195; + private static EditorObserverForTest sObserverForTest; + private final Context mContext; - private final EditorObserverForTest mObserverForTest; private final Handler mHandler; private final TextView.OnEditorActionListener mEditorActionListener; private final int mHalfRowMargin; @@ -107,20 +108,18 @@ * Builds the editor dialog. * * @param activity The activity on top of which the UI should be displayed. - * @param observerForTest Optional event observer for testing. * @param deleteRunnable The runnable that when called will delete the profile. */ - public EditorDialog( - Activity activity, EditorObserverForTest observerForTest, Runnable deleteRunnable) { + public EditorDialog(Activity activity, Runnable deleteRunnable) { super(activity, R.style.Theme_Chromium_Fullscreen); // Sets transparent background for animating content view. getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); mContext = activity; - mObserverForTest = observerForTest; mHandler = new Handler(); mIsDismissed = false; mEditorActionListener = new TextView.OnEditorActionListener() { @Override + @SuppressWarnings("WrongConstant") // https://crbug.com/1038784 public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { mDoneButton.performClick(); @@ -263,8 +262,8 @@ } } - if (!invalidViews.isEmpty() && mObserverForTest != null) { - mObserverForTest.onEditorValidationError(); + if (!invalidViews.isEmpty() && sObserverForTest != null) { + sObserverForTest.onEditorValidationError(); } return invalidViews.isEmpty(); @@ -451,11 +450,11 @@ // The fields may have changed. prepareEditor(); - if (mObserverForTest != null) mObserverForTest.onEditorReadyToEdit(); + if (sObserverForTest != null) sObserverForTest.onEditorReadyToEdit(); } }; - EditorDropdownField dropdownView = new EditorDropdownField( - mContext, parent, fieldModel, prepareEditorRunnable, mObserverForTest); + EditorDropdownField dropdownView = + new EditorDropdownField(mContext, parent, fieldModel, prepareEditorRunnable); mFieldViews.add(dropdownView); mDropdownFields.add(dropdownView.getDropdown()); @@ -469,7 +468,7 @@ @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { fieldModel.setIsChecked(isChecked); - if (mObserverForTest != null) mObserverForTest.onEditorReadyToEdit(); + if (sObserverForTest != null) sObserverForTest.onEditorReadyToEdit(); } }); @@ -486,8 +485,8 @@ formatter = mPhoneFormatter; } - EditorTextField inputLayout = new EditorTextField(mContext, fieldModel, - mEditorActionListener, filter, formatter, mObserverForTest); + EditorTextField inputLayout = new EditorTextField( + mContext, fieldModel, mEditorActionListener, filter, formatter); mFieldViews.add(inputLayout); EditText input = inputLayout.getEditText(); @@ -589,12 +588,12 @@ @Override public void run() { invalidViews.get(0).scrollToAndFocus(); - if (mObserverForTest != null) mObserverForTest.onEditorReadyToEdit(); + if (sObserverForTest != null) sObserverForTest.onEditorReadyToEdit(); } }); } else { // The first field will be focused, we are ready to edit. - if (mObserverForTest != null) mObserverForTest.onEditorReadyToEdit(); + if (sObserverForTest != null) sObserverForTest.onEditorReadyToEdit(); } } @@ -622,6 +621,13 @@ return mDropdownFields; } + @VisibleForTesting + public static void setEditorObserverForTest(EditorObserverForTest observerForTest) { + sObserverForTest = observerForTest; + EditorDropdownField.setEditorObserverForTest(sObserverForTest); + EditorTextField.setEditorObserverForTest(sObserverForTest); + } + private Drawable getTintedBackIcon() { return TintedDrawable.constructTintedDrawable( getContext(), R.drawable.ic_arrow_back_white_24dp, R.color.default_icon_color);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorDialogToolbar.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorDialogToolbar.java similarity index 95% rename from chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorDialogToolbar.java rename to chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorDialogToolbar.java index fe332c0..08a5967 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorDialogToolbar.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorDialogToolbar.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.chrome.browser.widget.prefeditor; +package org.chromium.chrome.browser.autofill.prefeditor; import android.content.Context; import android.support.v7.widget.Toolbar;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorDropdownField.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorDropdownField.java similarity index 94% rename from chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorDropdownField.java rename to chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorDropdownField.java index d83b48a7..eef26fb3 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorDropdownField.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorDropdownField.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.chrome.browser.widget.prefeditor; +package org.chromium.chrome.browser.autofill.prefeditor; import android.annotation.SuppressLint; import android.content.Context; @@ -21,6 +21,7 @@ import android.widget.TextView; import androidx.annotation.Nullable; +import androidx.annotation.VisibleForTesting; import org.chromium.base.ApiCompatibilityUtils; import org.chromium.chrome.R; @@ -34,6 +35,9 @@ * Helper class for creating a dropdown view with a label. */ class EditorDropdownField implements EditorFieldView { + @Nullable + private static EditorObserverForTest sObserverForTest; + private final Context mContext; private final EditorFieldModel mFieldModel; private final View mLayout; @@ -43,8 +47,6 @@ private final TextView mErrorLabel; private int mSelectedIndex; private ArrayAdapter<CharSequence> mAdapter; - @Nullable - private EditorObserverForTest mObserverForTest; /** * Builds a dropdown view. @@ -56,11 +58,10 @@ * processed. */ public EditorDropdownField(Context context, ViewGroup root, final EditorFieldModel fieldModel, - final Runnable changedCallback, @Nullable EditorObserverForTest observer) { + final Runnable changedCallback) { assert fieldModel.getInputTypeHint() == EditorFieldModel.INPUT_TYPE_HINT_DROPDOWN; mContext = context; mFieldModel = fieldModel; - mObserverForTest = observer; mLayout = LayoutInflater.from(context).inflate( R.layout.payment_request_editor_dropdown, root, false); @@ -132,8 +133,8 @@ mFieldModel.setCustomErrorMessage(null); updateDisplayedError(false); } - if (mObserverForTest != null) { - mObserverForTest.onEditorTextUpdate(); + if (sObserverForTest != null) { + sObserverForTest.onEditorTextUpdate(); } } @@ -220,7 +221,7 @@ mSelectedIndex = TextUtils.isEmpty(mFieldModel.getValue()) ? 0 : mAdapter.getPosition( - mFieldModel.getDropdownValueByKey((mFieldModel.getValue().toString()))); + mFieldModel.getDropdownValueByKey((mFieldModel.getValue().toString()))); assert mSelectedIndex >= 0; mDropdown.setSelection(mSelectedIndex); } @@ -232,4 +233,9 @@ } return dropdownValues; } + + @VisibleForTesting + public static void setEditorObserverForTest(EditorObserverForTest observerForTest) { + sObserverForTest = observerForTest; + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorFieldModel.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorFieldModel.java similarity index 97% rename from chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorFieldModel.java rename to chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorFieldModel.java index 67fbefb..b44443f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorFieldModel.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorFieldModel.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.chrome.browser.widget.prefeditor; +package org.chromium.chrome.browser.autofill.prefeditor; import android.text.TextUtils; import android.text.TextWatcher; @@ -406,8 +406,10 @@ return mIconResourceIds; } - /** @return The list of string identifiers of the descriptions of the displayed icons. This is - * for the screen reader. */ + /** + * @return The list of string identifiers of the descriptions of the displayed icons. This is + * for the screen reader. + */ public List<Integer> getIconDescriptionsForAccessibility() { assert mInputTypeHint == INPUT_TYPE_HINT_ICONS; return mIconDescriptionsForAccessibility; @@ -544,8 +546,10 @@ mCustomErrorMessage = errorMessage; } - /** @return The value that the user has typed into the field or the key of the value that the - * user has selected in the dropdown. Can be null. */ + /** + * @return The value that the user has typed into the field or the key of the value that the + * user has selected in the dropdown. Can be null. + */ @Nullable public CharSequence getValue() { return mValue; @@ -643,8 +647,10 @@ mDropdownCallback = callback; } - /** @return True if the input field should take up the full line, instead of sharing with other - * input fields. This is the default.*/ + /** + * @return True if the input field should take up the full line, instead of sharing with other + * input fields. This is the default. + */ public boolean isFullLine() { return mIsFullLine; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorFieldView.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorFieldView.java similarity index 92% rename from chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorFieldView.java rename to chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorFieldView.java index 81016d1..c05464e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorFieldView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorFieldView.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.chrome.browser.widget.prefeditor; +package org.chromium.chrome.browser.autofill.prefeditor; /** The interface for editor fields that handle validation, display errors, and can be updated. */ interface EditorFieldView {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorIconsField.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorIconsField.java similarity index 98% rename from chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorIconsField.java rename to chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorIconsField.java index 58b3ed6c..8eb0790 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorIconsField.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorIconsField.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.chrome.browser.widget.prefeditor; +package org.chromium.chrome.browser.autofill.prefeditor; import android.content.Context; import android.support.v7.content.res.AppCompatResources;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorLabelField.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorLabelField.java similarity index 97% rename from chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorLabelField.java rename to chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorLabelField.java index 2fa9d34..0b50f44 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorLabelField.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorLabelField.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.chrome.browser.widget.prefeditor; +package org.chromium.chrome.browser.autofill.prefeditor; import android.content.Context; import android.support.v7.content.res.AppCompatResources;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorModel.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorModel.java similarity index 97% rename from chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorModel.java rename to chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorModel.java index e14b9a4..1728ec6 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorModel.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorModel.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.chrome.browser.widget.prefeditor; +package org.chromium.chrome.browser.autofill.prefeditor; import androidx.annotation.Nullable;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorObserverForTest.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorObserverForTest.java similarity index 92% rename from chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorObserverForTest.java rename to chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorObserverForTest.java index 10336ce..208c4a4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorObserverForTest.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorObserverForTest.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.chrome.browser.widget.prefeditor; +package org.chromium.chrome.browser.autofill.prefeditor; /** * A test-only observer for Editor UI.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorTextField.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorTextField.java similarity index 96% rename from chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorTextField.java rename to chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorTextField.java index 512bb28..6a2cda6e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/EditorTextField.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorTextField.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.chrome.browser.widget.prefeditor; +package org.chromium.chrome.browser.autofill.prefeditor; import android.content.Context; import android.support.v4.view.ViewCompat; @@ -34,6 +34,9 @@ /** Handles validation and display of one field from the {@link EditorFieldModel}. */ @VisibleForTesting public class EditorTextField extends FrameLayout implements EditorFieldView, View.OnClickListener { + @Nullable + private static EditorObserverForTest sObserverForTest; + private EditorFieldModel mEditorFieldModel; private OnEditorActionListener mEditorActionListener; private ChromeTextInputLayout mInputLayout; @@ -43,17 +46,14 @@ private ImageView mValueIcon; private int mValueIconId; private boolean mHasFocusedAtLeastOnce; - @Nullable - private EditorObserverForTest mObserverForTest; public EditorTextField(Context context, final EditorFieldModel fieldModel, OnEditorActionListener actionListener, @Nullable InputFilter filter, - @Nullable TextWatcher formatter, @Nullable EditorObserverForTest observer) { + @Nullable TextWatcher formatter) { super(context); assert fieldModel.getInputTypeHint() != EditorFieldModel.INPUT_TYPE_HINT_DROPDOWN; mEditorFieldModel = fieldModel; mEditorActionListener = actionListener; - mObserverForTest = observer; LayoutInflater.from(context).inflate(R.layout.payments_request_editor_textview, this, true); mInputLayout = (ChromeTextInputLayout) findViewById(R.id.text_input_layout); @@ -124,8 +124,8 @@ fieldModel.setValue(s.toString()); updateDisplayedError(false); updateFieldValueIcon(false); - if (mObserverForTest != null) { - mObserverForTest.onEditorTextUpdate(); + if (sObserverForTest != null) { + sObserverForTest.onEditorTextUpdate(); } if (!mEditorFieldModel.isLengthMaximum()) return; updateDisplayedError(true); @@ -283,4 +283,9 @@ mValueIcon.setVisibility(VISIBLE); } } + + @VisibleForTesting + public static void setEditorObserverForTest(EditorObserverForTest observerForTest) { + sObserverForTest = observerForTest; + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/ExpandableGridView.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/ExpandableGridView.java similarity index 95% rename from chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/ExpandableGridView.java rename to chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/ExpandableGridView.java index ad769a9d..a948ca7 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/ExpandableGridView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/ExpandableGridView.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.chrome.browser.widget.prefeditor; +package org.chromium.chrome.browser.autofill.prefeditor; import android.content.Context; import android.util.AttributeSet;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/HintedDropDownAdapter.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/HintedDropDownAdapter.java similarity index 98% rename from chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/HintedDropDownAdapter.java rename to chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/HintedDropDownAdapter.java index 155efbd..4ea3241 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/HintedDropDownAdapter.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/HintedDropDownAdapter.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.chrome.browser.widget.prefeditor; +package org.chromium.chrome.browser.autofill.prefeditor; import android.content.Context; import android.support.v4.view.ViewCompat;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/HintedDropDownAdapterWithPlusIcon.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/HintedDropDownAdapterWithPlusIcon.java similarity index 98% rename from chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/HintedDropDownAdapterWithPlusIcon.java rename to chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/HintedDropDownAdapterWithPlusIcon.java index fa83ebc..986b8547 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/HintedDropDownAdapterWithPlusIcon.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/HintedDropDownAdapterWithPlusIcon.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.chrome.browser.widget.prefeditor; +package org.chromium.chrome.browser.autofill.prefeditor; import android.content.Context; import android.content.res.Resources;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/OWNERS b/chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/OWNERS similarity index 100% rename from chrome/android/java/src/org/chromium/chrome/browser/widget/prefeditor/OWNERS rename to chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/OWNERS
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkItemRow.java b/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkItemRow.java index de415df..805ebc1d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkItemRow.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkItemRow.java
@@ -14,7 +14,7 @@ import org.chromium.chrome.browser.favicon.FaviconUtils; import org.chromium.chrome.browser.favicon.IconType; import org.chromium.chrome.browser.favicon.LargeIconBridge.LargeIconCallback; -import org.chromium.chrome.browser.widget.RoundedIconGenerator; +import org.chromium.chrome.browser.favicon.RoundedIconGenerator; import org.chromium.components.bookmarks.BookmarkId; /**
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/bookmarkswidget/BookmarkWidgetService.java b/chrome/android/java/src/org/chromium/chrome/browser/bookmarkswidget/BookmarkWidgetService.java index 520e42a..bbab895 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/bookmarkswidget/BookmarkWidgetService.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/bookmarkswidget/BookmarkWidgetService.java
@@ -35,11 +35,11 @@ import org.chromium.chrome.browser.favicon.IconType; import org.chromium.chrome.browser.favicon.LargeIconBridge; import org.chromium.chrome.browser.favicon.LargeIconBridge.LargeIconCallback; +import org.chromium.chrome.browser.favicon.RoundedIconGenerator; import org.chromium.chrome.browser.init.ChromeBrowserInitializer; import org.chromium.chrome.browser.night_mode.SystemNightModeMonitor; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.util.IntentUtils; -import org.chromium.chrome.browser.widget.RoundedIconGenerator; import org.chromium.components.bookmarks.BookmarkId; import org.chromium.content_public.browser.UiThreadTaskTraits;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/ephemeraltab/EphemeralTabCoordinator.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/ephemeraltab/EphemeralTabCoordinator.java index fd6b6f3a..e4ce254 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/ephemeraltab/EphemeralTabCoordinator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/ephemeraltab/EphemeralTabCoordinator.java
@@ -19,12 +19,12 @@ import org.chromium.chrome.browser.compositor.bottombar.OverlayPanelContent; import org.chromium.chrome.browser.favicon.FaviconHelper; import org.chromium.chrome.browser.favicon.FaviconUtils; +import org.chromium.chrome.browser.favicon.RoundedIconGenerator; import org.chromium.chrome.browser.ntp.NewTabPage; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.ssl.SecurityStateModel; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tab.TabLaunchType; -import org.chromium.chrome.browser.widget.RoundedIconGenerator; import org.chromium.chrome.browser.widget.bottomsheet.BottomSheetContent; import org.chromium.chrome.browser.widget.bottomsheet.BottomSheetController; import org.chromium.chrome.browser.widget.bottomsheet.BottomSheetController.SheetState;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contacts_picker/PickerCategoryView.java b/chrome/android/java/src/org/chromium/chrome/browser/contacts_picker/PickerCategoryView.java index 3c6f2fe1..19e9ca9b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contacts_picker/PickerCategoryView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contacts_picker/PickerCategoryView.java
@@ -23,9 +23,9 @@ import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.GlobalDiscardableReferencePool; +import org.chromium.chrome.browser.favicon.RoundedIconGenerator; import org.chromium.chrome.browser.util.BitmapCache; import org.chromium.chrome.browser.util.ConversionUtils; -import org.chromium.chrome.browser.widget.RoundedIconGenerator; import org.chromium.chrome.browser.widget.selection.SelectableListLayout; import org.chromium.chrome.browser.widget.selection.SelectableListToolbar; import org.chromium.chrome.browser.widget.selection.SelectionDelegate;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/RevampedContextMenuHeaderMediator.java b/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/RevampedContextMenuHeaderMediator.java index d45eea92..d806661 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/RevampedContextMenuHeaderMediator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/RevampedContextMenuHeaderMediator.java
@@ -27,8 +27,8 @@ import org.chromium.chrome.R; import org.chromium.chrome.browser.favicon.IconType; import org.chromium.chrome.browser.favicon.LargeIconBridge; +import org.chromium.chrome.browser.favicon.RoundedIconGenerator; import org.chromium.chrome.browser.profiles.Profile; -import org.chromium.chrome.browser.widget.RoundedIconGenerator; import org.chromium.ui.modelutil.PropertyModel; class RevampedContextMenuHeaderMediator implements View.OnClickListener {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabTaskDescriptionIconGenerator.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabTaskDescriptionIconGenerator.java index c12685f2..3cbb76b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabTaskDescriptionIconGenerator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabTaskDescriptionIconGenerator.java
@@ -8,7 +8,7 @@ import android.graphics.Bitmap; import android.text.TextUtils; -import org.chromium.chrome.browser.widget.RoundedIconGenerator; +import org.chromium.chrome.browser.favicon.RoundedIconGenerator; /** * Generates icons suitable for Custom Tabs in the recent tasks list.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/content/CustomTabActivityNavigationController.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/content/CustomTabActivityNavigationController.java index 25e23cd..c9d5c290 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/content/CustomTabActivityNavigationController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/content/CustomTabActivityNavigationController.java
@@ -220,7 +220,7 @@ } private void executeDefaultBackHandling() { - if (mToolbarManager != null && mToolbarManager.back() != null) return; + if (mToolbarManager != null && mToolbarManager.back()) return; // mTabController.closeTab may result in either closing the only tab (through the back // button or the close button), or swapping to the previous tab. In the first case we need
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/CategoryCardAdapter.java b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/CategoryCardAdapter.java index bc74b55..cf2f894 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/CategoryCardAdapter.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/CategoryCardAdapter.java
@@ -12,11 +12,11 @@ import androidx.annotation.Nullable; import org.chromium.chrome.R; +import org.chromium.chrome.browser.favicon.RoundedIconGenerator; import org.chromium.chrome.browser.native_page.ContextMenuManager; import org.chromium.chrome.browser.native_page.NativePageNavigationDelegate; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.ui.widget.LoadingView; -import org.chromium.chrome.browser.widget.RoundedIconGenerator; import org.chromium.ui.modelutil.ForwardingListObservable; import org.chromium.ui.modelutil.ListObservable.ListObserver; import org.chromium.ui.modelutil.PropertyKey;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExperimentalExploreSitesCategoryTileView.java b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExperimentalExploreSitesCategoryTileView.java index 1790678..313b64b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExperimentalExploreSitesCategoryTileView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExperimentalExploreSitesCategoryTileView.java
@@ -16,8 +16,8 @@ import org.chromium.base.ApiCompatibilityUtils; import org.chromium.chrome.R; +import org.chromium.chrome.browser.favicon.RoundedIconGenerator; import org.chromium.chrome.browser.util.ViewUtils; -import org.chromium.chrome.browser.widget.RoundedIconGenerator; /** * The View representing a single explore sites category.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategoryCardView.java b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategoryCardView.java index 6f13d017..42501714 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategoryCardView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategoryCardView.java
@@ -19,11 +19,11 @@ import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.RecordUserAction; import org.chromium.chrome.R; +import org.chromium.chrome.browser.favicon.RoundedIconGenerator; import org.chromium.chrome.browser.native_page.ContextMenuManager; import org.chromium.chrome.browser.native_page.NativePageNavigationDelegate; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.suggestions.tile.TileGridLayout; -import org.chromium.chrome.browser.widget.RoundedIconGenerator; import org.chromium.content_public.browser.LoadUrlParams; import org.chromium.ui.base.PageTransition; import org.chromium.ui.modelutil.PropertyKey;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategoryTileView.java b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategoryTileView.java index 941370e6..3889a8a72 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategoryTileView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategoryTileView.java
@@ -15,7 +15,7 @@ import org.chromium.chrome.browser.compositor.animation.CompositorAnimationHandler; import org.chromium.chrome.browser.ntp.TitleUtil; import org.chromium.chrome.browser.profiles.Profile; -import org.chromium.chrome.browser.widget.tile.TileWithTextView; +import org.chromium.chrome.browser.suggestions.tile.TileWithTextView; /** * A category tile for ExploreSites, containing an icon that is a composition of sites' favicons
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesIPH.java b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesIPH.java index 6e0a500..5b194e2 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesIPH.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesIPH.java
@@ -11,10 +11,10 @@ import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.feature_engagement.TrackerFactory; import org.chromium.chrome.browser.profiles.Profile; +import org.chromium.chrome.browser.suggestions.tile.TileView; import org.chromium.chrome.browser.ui.widget.highlight.PulseDrawable; import org.chromium.chrome.browser.ui.widget.highlight.ViewHighlighter; import org.chromium.chrome.browser.ui.widget.textbubble.TextBubble; -import org.chromium.chrome.browser.widget.tile.TileView; import org.chromium.components.feature_engagement.FeatureConstants; import org.chromium.components.feature_engagement.Tracker; import org.chromium.ui.widget.ViewRectProvider;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesPage.java b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesPage.java index 5e9105a0..5e0a25e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesPage.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesPage.java
@@ -23,6 +23,7 @@ import org.chromium.base.metrics.RecordUserAction; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeActivity; +import org.chromium.chrome.browser.favicon.RoundedIconGenerator; import org.chromium.chrome.browser.gesturenav.HistoryNavigationLayout; import org.chromium.chrome.browser.native_page.BasicNativePage; import org.chromium.chrome.browser.native_page.ContextMenuManager; @@ -35,7 +36,6 @@ import org.chromium.chrome.browser.tab.TabImpl; import org.chromium.chrome.browser.tab.TabObserver; import org.chromium.chrome.browser.util.UrlConstants; -import org.chromium.chrome.browser.widget.RoundedIconGenerator; import org.chromium.content_public.browser.NavigationController; import org.chromium.content_public.browser.NavigationEntry; import org.chromium.ui.modelutil.ListModel;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesTileView.java b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesTileView.java index e36890f2..c4ab605 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesTileView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesTileView.java
@@ -15,8 +15,8 @@ import android.view.View; import org.chromium.chrome.R; -import org.chromium.chrome.browser.widget.RoundedIconGenerator; -import org.chromium.chrome.browser.widget.tile.TileWithTextView; +import org.chromium.chrome.browser.favicon.RoundedIconGenerator; +import org.chromium.chrome.browser.suggestions.tile.TileWithTextView; /** * View for a category name and site tiles.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/favicon/FaviconUtils.java b/chrome/android/java/src/org/chromium/chrome/browser/favicon/FaviconUtils.java index e3eb917..db4de1be 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/favicon/FaviconUtils.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/favicon/FaviconUtils.java
@@ -15,7 +15,6 @@ import org.chromium.base.ApiCompatibilityUtils; import org.chromium.chrome.R; import org.chromium.chrome.browser.util.ViewUtils; -import org.chromium.chrome.browser.widget.RoundedIconGenerator; /** * Utilities to deal with favicons.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/RoundedIconGenerator.java b/chrome/android/java/src/org/chromium/chrome/browser/favicon/RoundedIconGenerator.java similarity index 99% rename from chrome/android/java/src/org/chromium/chrome/browser/widget/RoundedIconGenerator.java rename to chrome/android/java/src/org/chromium/chrome/browser/favicon/RoundedIconGenerator.java index fd15a32ea..737a9600 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/RoundedIconGenerator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/favicon/RoundedIconGenerator.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.chrome.browser.widget; +package org.chromium.chrome.browser.favicon; import android.content.res.Resources; import android.graphics.Bitmap;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/gesturenav/NavigationSheetMediator.java b/chrome/android/java/src/org/chromium/chrome/browser/gesturenav/NavigationSheetMediator.java index 632aa10..75f379d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/gesturenav/NavigationSheetMediator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/gesturenav/NavigationSheetMediator.java
@@ -16,11 +16,11 @@ import org.chromium.chrome.R; import org.chromium.chrome.browser.favicon.FaviconHelper; import org.chromium.chrome.browser.favicon.FaviconUtils; +import org.chromium.chrome.browser.favicon.RoundedIconGenerator; import org.chromium.chrome.browser.ntp.NewTabPage; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.ui.widget.TintedDrawable; import org.chromium.chrome.browser.util.UrlConstants; -import org.chromium.chrome.browser.widget.RoundedIconGenerator; import org.chromium.content_public.browser.NavigationEntry; import org.chromium.content_public.browser.NavigationHistory; import org.chromium.ui.modelutil.MVCListAdapter.ListItem;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/history/HistoryItemView.java b/chrome/android/java/src/org/chromium/chrome/browser/history/HistoryItemView.java index 1b9a5e8..ff573a9 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/history/HistoryItemView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/history/HistoryItemView.java
@@ -22,9 +22,9 @@ import org.chromium.chrome.browser.favicon.FaviconUtils; import org.chromium.chrome.browser.favicon.IconType; import org.chromium.chrome.browser.favicon.LargeIconBridge.LargeIconCallback; +import org.chromium.chrome.browser.favicon.RoundedIconGenerator; import org.chromium.chrome.browser.preferences.Pref; import org.chromium.chrome.browser.preferences.PrefServiceBridge; -import org.chromium.chrome.browser.widget.RoundedIconGenerator; import org.chromium.chrome.browser.widget.selection.SelectableItemView; /**
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/metrics/ActivityStopMetrics.java b/chrome/android/java/src/org/chromium/chrome/browser/metrics/ActivityStopMetrics.java deleted file mode 100644 index 7fe8431..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/metrics/ActivityStopMetrics.java +++ /dev/null
@@ -1,83 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package org.chromium.chrome.browser.metrics; - -import android.app.Activity; - -import androidx.annotation.IntDef; - -import org.chromium.base.ApplicationStatus; -import org.chromium.base.metrics.RecordHistogram; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -/** - * Tracks metrics caused by a particular Activity stopping. - */ -public class ActivityStopMetrics { - // NUM_ENTRIES is intentionally included into @IntDef. - @IntDef({StopReason.UNKNOWN, StopReason.BACK_BUTTON, - StopReason.OTHER_CHROME_ACTIVITY_IN_FOREGROUND, StopReason.NUM_ENTRIES}) - @Retention(RetentionPolicy.SOURCE) - public @interface StopReason { - /** Activity stopped for unknown reasons. */ - int UNKNOWN = 0; - /** Activity stopped after the user hit the back button. */ - int BACK_BUTTON = 1; - // Obsolete -- Activity stopped after the user hit the close/return UI button. - // int RETURN_BUTTON = 2; - // Obsolete -- Activity stopped because it launched a {@link CustomTabActivity} on top of - // itself. - // int CUSTOM_TAB_STARTED = 3; - // Obsolete -- Activity stopped because its child {@link CustomTabActivity} stopped itself. - // int CUSTOM_TAB_STOPPED = 4; - /** Activity stopped because another of Chrome Activities came into focus. */ - int OTHER_CHROME_ACTIVITY_IN_FOREGROUND = 5; - - /** Boundary. Shouldn't ever be passed to the metrics service. */ - int NUM_ENTRIES = 6; - } - - /** Name of the histogram that will be recorded. */ - private static final String HISTOGRAM_NAME = "Android.Activity.ChromeTabbedActivity.StopReason"; - - /** Why the Activity is being stopped. */ - @StopReason private int mStopReason; - - /** - * Constructs an {@link ActivityStopMetrics} instance. - */ - public ActivityStopMetrics() { - mStopReason = StopReason.NUM_ENTRIES; - } - - /** - * Records the reason that the parent Activity was stopped. - * @param parent Activity that owns this {@link ActivityStopMetrics} instance. - */ - public void onStopWithNative(Activity parent) { - if (mStopReason == StopReason.NUM_ENTRIES) { - if (parent != ApplicationStatus.getLastTrackedFocusedActivity() - && ApplicationStatus.hasVisibleActivities()) { - mStopReason = StopReason.OTHER_CHROME_ACTIVITY_IN_FOREGROUND; - } else { - mStopReason = StopReason.UNKNOWN; - } - } - RecordHistogram.recordEnumeratedHistogram( - HISTOGRAM_NAME, mStopReason, StopReason.NUM_ENTRIES); - mStopReason = StopReason.NUM_ENTRIES; - } - - /** - * Tracks the reason that the parent Activity was stopped. - * @param reason Reason the Activity was stopped (see {@link StopReason}). - */ - public void setStopReason(@StopReason int reason) { - if (mStopReason != StopReason.NUM_ENTRIES) return; - mStopReason = reason; - } -}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationBuilderBase.java b/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationBuilderBase.java index db2ab50..abe52e7 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationBuilderBase.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationBuilderBase.java
@@ -25,7 +25,7 @@ import androidx.annotation.VisibleForTesting; import org.chromium.chrome.browser.ChromeFeatureList; -import org.chromium.chrome.browser.widget.RoundedIconGenerator; +import org.chromium.chrome.browser.favicon.RoundedIconGenerator; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ntp/RecentTabsRowAdapter.java b/chrome/android/java/src/org/chromium/chrome/browser/ntp/RecentTabsRowAdapter.java index 60d428d4d..abbe8a3c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ntp/RecentTabsRowAdapter.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ntp/RecentTabsRowAdapter.java
@@ -30,12 +30,12 @@ import org.chromium.chrome.browser.favicon.FaviconHelper.DefaultFaviconHelper; import org.chromium.chrome.browser.favicon.FaviconHelper.FaviconImageCallback; import org.chromium.chrome.browser.favicon.FaviconUtils; +import org.chromium.chrome.browser.favicon.RoundedIconGenerator; import org.chromium.chrome.browser.ntp.ForeignSessionHelper.ForeignSession; import org.chromium.chrome.browser.ntp.ForeignSessionHelper.ForeignSessionTab; import org.chromium.chrome.browser.ntp.ForeignSessionHelper.ForeignSessionWindow; import org.chromium.chrome.browser.signin.SyncPromoView; import org.chromium.chrome.browser.util.UrlUtilities; -import org.chromium.chrome.browser.widget.RoundedIconGenerator; import org.chromium.components.signin.metrics.SigninAccessPoint; import org.chromium.ui.base.DeviceFormFactor; import org.chromium.ui.mojom.WindowOpenDisposition;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/SearchEngineLogoUtils.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/SearchEngineLogoUtils.java index b83b2e8..35a5f2f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/SearchEngineLogoUtils.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/SearchEngineLogoUtils.java
@@ -21,13 +21,13 @@ import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.favicon.FaviconHelper; +import org.chromium.chrome.browser.favicon.RoundedIconGenerator; import org.chromium.chrome.browser.locale.LocaleManager; import org.chromium.chrome.browser.ntp.NewTabPage; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.search_engines.TemplateUrlServiceFactory; import org.chromium.chrome.browser.toolbar.ToolbarCommonPropertiesModel; import org.chromium.chrome.browser.util.UrlUtilities; -import org.chromium.chrome.browser.widget.RoundedIconGenerator; import org.chromium.content_public.browser.BrowserStartupController; import java.lang.annotation.Retention;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/base/BaseSuggestionView.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/base/BaseSuggestionView.java index 16fbc72df..80dc0e51 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/base/BaseSuggestionView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/base/BaseSuggestionView.java
@@ -27,7 +27,7 @@ */ public class BaseSuggestionView extends SimpleHorizontalLayoutView { protected final ImageView mActionView; - protected final DecoratedSuggestionView mContentView; + protected final DecoratedSuggestionView mDecoratedView; private SuggestionViewDelegate mDelegate; @@ -44,14 +44,14 @@ @DrawableRes int selectableBackgroundRes = themeRes.resourceId; - mContentView = new DecoratedSuggestionView(getContext(), selectableBackgroundRes); - mContentView.setOnClickListener(v -> mDelegate.onSelection()); - mContentView.setOnLongClickListener(v -> { + mDecoratedView = new DecoratedSuggestionView(getContext(), selectableBackgroundRes); + mDecoratedView.setOnClickListener(v -> mDelegate.onSelection()); + mDecoratedView.setOnLongClickListener(v -> { mDelegate.onLongPress(); return true; }); - mContentView.setLayoutParams(LayoutParams.forDynamicView()); - addView(mContentView); + mDecoratedView.setLayoutParams(LayoutParams.forDynamicView()); + addView(mDecoratedView); // Action icons. Currently we only support the Refine button. mActionView = new ImageView(getContext()); @@ -106,7 +106,7 @@ @Override public void setSelected(boolean selected) { - mContentView.setSelected(selected); + mDecoratedView.setSelected(selected); mDelegate.onSetUrlToSuggestion(); } @@ -116,12 +116,17 @@ * @param view View to be displayed as suggestion content. */ void setContentView(View view) { - mContentView.setContentView(view); + mDecoratedView.setContentView(view); } /** @return Embedded suggestion content view. */ public View getContentView() { - return mContentView.getContentView(); + return mDecoratedView.getContentView(); + } + + /** @return Decorated suggestion view. */ + DecoratedSuggestionView getDecoratedSuggestionView() { + return mDecoratedView; } /** @@ -135,7 +140,7 @@ /** @return Widget holding suggestion decoration icon. */ RoundedCornerImageView getSuggestionImageView() { - return mContentView.getImageView(); + return mDecoratedView.getImageView(); } /** @return Widget holding action icon. */ @@ -153,6 +158,6 @@ * @return View with the specified ID or null, if view could not be found. */ public <T extends View> T findContentView(@IdRes int id) { - return mContentView.findContentView(id); + return mDecoratedView.findContentView(id); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/base/BaseSuggestionViewBinder.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/base/BaseSuggestionViewBinder.java index 9694963..33f243af 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/base/BaseSuggestionViewBinder.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/base/BaseSuggestionViewBinder.java
@@ -32,16 +32,16 @@ public void bind(PropertyModel model, BaseSuggestionView view, PropertyKey propertyKey) { if (BaseSuggestionViewProperties.SUGGESTION_DELEGATE == propertyKey) { view.setDelegate(model.get(BaseSuggestionViewProperties.SUGGESTION_DELEGATE)); - updateContentViewPadding(model, view); + updateContentViewPadding(model, view.getDecoratedSuggestionView()); } else if (BaseSuggestionViewProperties.ICON == propertyKey) { updateSuggestionIcon(model, view); - updateContentViewPadding(model, view); + updateContentViewPadding(model, view.getDecoratedSuggestionView()); } else if (BaseSuggestionViewProperties.ACTION_ICON == propertyKey) { updateActionIcon(model, view); } else if (SuggestionCommonProperties.LAYOUT_DIRECTION == propertyKey) { ViewCompat.setLayoutDirection( view, model.get(SuggestionCommonProperties.LAYOUT_DIRECTION)); - updateContentViewPadding(model, view); + updateContentViewPadding(model, view.getDecoratedSuggestionView()); } else if (SuggestionCommonProperties.USE_DARK_COLORS == propertyKey) { updateSuggestionIcon(model, view); updateActionIcon(model, view); @@ -101,7 +101,8 @@ * This is required only to adjust the leading padding for undecorated suggestions. * TODO(crbug.com/1019937): remove after suggestion favicons are launched. */ - private static void updateContentViewPadding(PropertyModel model, BaseSuggestionView view) { + private static void updateContentViewPadding( + PropertyModel model, DecoratedSuggestionView view) { final int direction = view.getLayoutDirection(); final SuggestionDrawableState sds = model.get(BaseSuggestionViewProperties.ICON); final int startSpace = sds == null ? view.getResources().getDimensionPixelSize(
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/AddressEditor.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/AddressEditor.java index ec218914..2d0f1508 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/AddressEditor.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/AddressEditor.java
@@ -19,13 +19,13 @@ import org.chromium.chrome.browser.autofill.PersonalDataManager.AutofillProfile; import org.chromium.chrome.browser.autofill.PersonalDataManager.GetSubKeysRequestDelegate; import org.chromium.chrome.browser.autofill.PhoneNumberUtil; +import org.chromium.chrome.browser.autofill.prefeditor.EditorBase; +import org.chromium.chrome.browser.autofill.prefeditor.EditorFieldModel; +import org.chromium.chrome.browser.autofill.prefeditor.EditorFieldModel.EditorFieldValidator; +import org.chromium.chrome.browser.autofill.prefeditor.EditorModel; import org.chromium.chrome.browser.settings.autofill.AutofillProfileBridge; import org.chromium.chrome.browser.settings.autofill.AutofillProfileBridge.AddressField; import org.chromium.chrome.browser.settings.autofill.AutofillProfileBridge.AddressUiComponent; -import org.chromium.chrome.browser.widget.prefeditor.EditorBase; -import org.chromium.chrome.browser.widget.prefeditor.EditorFieldModel; -import org.chromium.chrome.browser.widget.prefeditor.EditorFieldModel.EditorFieldValidator; -import org.chromium.chrome.browser.widget.prefeditor.EditorModel; import org.chromium.payments.mojom.AddressErrors; import java.lang.annotation.Retention;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/AutofillAddress.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/AutofillAddress.java index c29974c4..50056a0a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/AutofillAddress.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/AutofillAddress.java
@@ -16,9 +16,9 @@ import org.chromium.chrome.R; import org.chromium.chrome.browser.autofill.PersonalDataManager; import org.chromium.chrome.browser.autofill.PersonalDataManager.AutofillProfile; +import org.chromium.chrome.browser.autofill.prefeditor.EditableOption; import org.chromium.chrome.browser.settings.autofill.AutofillProfileBridge; import org.chromium.chrome.browser.settings.autofill.AutofillProfileBridge.AddressField; -import org.chromium.chrome.browser.widget.prefeditor.EditableOption; import org.chromium.payments.mojom.PaymentAddress; import java.lang.annotation.Retention;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/AutofillContact.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/AutofillContact.java index 99dd921..f50e349 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/AutofillContact.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/AutofillContact.java
@@ -11,7 +11,7 @@ import org.chromium.chrome.R; import org.chromium.chrome.browser.autofill.PersonalDataManager.AutofillProfile; -import org.chromium.chrome.browser.widget.prefeditor.EditableOption; +import org.chromium.chrome.browser.autofill.prefeditor.EditableOption; import org.chromium.payments.mojom.PayerDetail; /**
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/CardEditor.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/CardEditor.java index d26c67f..020e978 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/CardEditor.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/CardEditor.java
@@ -24,13 +24,13 @@ import org.chromium.chrome.browser.autofill.PersonalDataManager; import org.chromium.chrome.browser.autofill.PersonalDataManager.AutofillProfile; import org.chromium.chrome.browser.autofill.PersonalDataManager.CreditCard; +import org.chromium.chrome.browser.autofill.prefeditor.EditorBase; +import org.chromium.chrome.browser.autofill.prefeditor.EditorFieldModel; +import org.chromium.chrome.browser.autofill.prefeditor.EditorFieldModel.EditorFieldValidator; +import org.chromium.chrome.browser.autofill.prefeditor.EditorFieldModel.EditorValueIconGenerator; +import org.chromium.chrome.browser.autofill.prefeditor.EditorModel; import org.chromium.chrome.browser.payments.PaymentRequestImpl.PaymentRequestServiceObserverForTest; import org.chromium.chrome.browser.settings.autofill.AutofillProfileBridge.DropdownKeyValue; -import org.chromium.chrome.browser.widget.prefeditor.EditorBase; -import org.chromium.chrome.browser.widget.prefeditor.EditorFieldModel; -import org.chromium.chrome.browser.widget.prefeditor.EditorFieldModel.EditorFieldValidator; -import org.chromium.chrome.browser.widget.prefeditor.EditorFieldModel.EditorValueIconGenerator; -import org.chromium.chrome.browser.widget.prefeditor.EditorModel; import org.chromium.components.payments.MethodStrings; import org.chromium.content_public.browser.WebContents; import org.chromium.payments.mojom.PaymentMethodData;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/ContactEditor.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/ContactEditor.java index 088a647..c8fbb1a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/ContactEditor.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/ContactEditor.java
@@ -16,10 +16,10 @@ import org.chromium.chrome.browser.autofill.PersonalDataManager; import org.chromium.chrome.browser.autofill.PersonalDataManager.AutofillProfile; import org.chromium.chrome.browser.autofill.PhoneNumberUtil; -import org.chromium.chrome.browser.widget.prefeditor.EditorBase; -import org.chromium.chrome.browser.widget.prefeditor.EditorFieldModel; -import org.chromium.chrome.browser.widget.prefeditor.EditorFieldModel.EditorFieldValidator; -import org.chromium.chrome.browser.widget.prefeditor.EditorModel; +import org.chromium.chrome.browser.autofill.prefeditor.EditorBase; +import org.chromium.chrome.browser.autofill.prefeditor.EditorFieldModel; +import org.chromium.chrome.browser.autofill.prefeditor.EditorFieldModel.EditorFieldValidator; +import org.chromium.chrome.browser.autofill.prefeditor.EditorModel; import org.chromium.payments.mojom.PayerErrors; import java.util.HashSet;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentInstrument.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentInstrument.java index 34a620b..41a7c4a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentInstrument.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentInstrument.java
@@ -9,7 +9,7 @@ import androidx.annotation.Nullable; import org.chromium.base.task.PostTask; -import org.chromium.chrome.browser.widget.prefeditor.EditableOption; +import org.chromium.chrome.browser.autofill.prefeditor.EditableOption; import org.chromium.content_public.browser.UiThreadTaskTraits; import org.chromium.payments.mojom.PaymentDetailsModifier; import org.chromium.payments.mojom.PaymentItem;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentRequestImpl.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentRequestImpl.java index 2629d7c..5f46954 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentRequestImpl.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentRequestImpl.java
@@ -23,6 +23,8 @@ import org.chromium.chrome.browser.autofill.PersonalDataManager.AutofillProfile; import org.chromium.chrome.browser.autofill.PersonalDataManager.CreditCard; import org.chromium.chrome.browser.autofill.PersonalDataManager.NormalizedAddressRequestDelegate; +import org.chromium.chrome.browser.autofill.prefeditor.Completable; +import org.chromium.chrome.browser.autofill.prefeditor.EditableOption; import org.chromium.chrome.browser.browserservices.Origin; import org.chromium.chrome.browser.compositor.layouts.EmptyOverviewModeObserver; import org.chromium.chrome.browser.compositor.layouts.OverviewModeBehavior; @@ -55,8 +57,6 @@ import org.chromium.chrome.browser.widget.ScrimView; import org.chromium.chrome.browser.widget.ScrimView.EmptyScrimObserver; import org.chromium.chrome.browser.widget.ScrimView.ScrimParams; -import org.chromium.chrome.browser.widget.prefeditor.Completable; -import org.chromium.chrome.browser.widget.prefeditor.EditableOption; import org.chromium.components.payments.CurrencyFormatter; import org.chromium.components.payments.ErrorStrings; import org.chromium.components.payments.MethodStrings;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentResponseHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentResponseHelper.java index 00cfb155..1318ccb 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentResponseHelper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentResponseHelper.java
@@ -8,7 +8,7 @@ import org.chromium.chrome.browser.autofill.PersonalDataManager.AutofillProfile; import org.chromium.chrome.browser.autofill.PersonalDataManager.NormalizedAddressRequestDelegate; import org.chromium.chrome.browser.autofill.PhoneNumberUtil; -import org.chromium.chrome.browser.widget.prefeditor.EditableOption; +import org.chromium.chrome.browser.autofill.prefeditor.EditableOption; import org.chromium.payments.mojom.PayerDetail; import org.chromium.payments.mojom.PaymentOptions; import org.chromium.payments.mojom.PaymentResponse;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/PaymentRequestSection.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/PaymentRequestSection.java index 0306b843..5006812 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/PaymentRequestSection.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/PaymentRequestSection.java
@@ -36,9 +36,9 @@ import org.chromium.base.ApiCompatibilityUtils; import org.chromium.chrome.R; +import org.chromium.chrome.browser.autofill.prefeditor.EditableOption; import org.chromium.chrome.browser.ui.widget.TintedDrawable; import org.chromium.chrome.browser.ui.widget.animation.Interpolators; -import org.chromium.chrome.browser.widget.prefeditor.EditableOption; import org.chromium.components.browser_ui.widget.DualControlLayout; import org.chromium.ui.HorizontalListDividerDrawable; import org.chromium.ui.UiUtils;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/PaymentRequestUI.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/PaymentRequestUI.java index bd099dc..b5edaa7 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/PaymentRequestUI.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/PaymentRequestUI.java
@@ -39,6 +39,9 @@ import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.ChromeVersionInfo; +import org.chromium.chrome.browser.autofill.prefeditor.EditableOption; +import org.chromium.chrome.browser.autofill.prefeditor.EditorDialog; +import org.chromium.chrome.browser.autofill.prefeditor.EditorObserverForTest; import org.chromium.chrome.browser.payments.PaymentRequestImpl.PaymentUisShowStateReconciler; import org.chromium.chrome.browser.payments.ShippingStrings; import org.chromium.chrome.browser.payments.ui.PaymentRequestSection.LineItemBreakdownSection; @@ -46,9 +49,6 @@ import org.chromium.chrome.browser.payments.ui.PaymentRequestSection.SectionSeparator; import org.chromium.chrome.browser.ui.widget.animation.FocusAnimator; import org.chromium.chrome.browser.ui.widget.animation.Interpolators; -import org.chromium.chrome.browser.widget.prefeditor.EditableOption; -import org.chromium.chrome.browser.widget.prefeditor.EditorDialog; -import org.chromium.chrome.browser.widget.prefeditor.EditorObserverForTest; import org.chromium.components.browser_ui.widget.FadingEdgeScrollView; import org.chromium.components.signin.ChromeSigninController; import org.chromium.ui.text.NoUnderlineClickableSpan; @@ -406,12 +406,10 @@ (ViewGroup) LayoutInflater.from(mContext).inflate(R.layout.payment_request, null); prepareRequestView(mContext, title, origin, securityLevel, canAddCards); - mEditorDialog = new EditorDialog(activity, sEditorObserverForTest, - /*deleteRunnable =*/null); + mEditorDialog = new EditorDialog(activity, /*deleteRunnable =*/null); DimmingDialog.setVisibleStatusBarIconColor(mEditorDialog.getWindow()); - mCardEditorDialog = new EditorDialog(activity, sEditorObserverForTest, - /*deleteRunnable =*/null); + mCardEditorDialog = new EditorDialog(activity, /*deleteRunnable =*/null); DimmingDialog.setVisibleStatusBarIconColor(mCardEditorDialog.getWindow()); // Allow screenshots of the credit card number in Canary, Dev, and developer builds. @@ -1376,6 +1374,7 @@ @VisibleForTesting public static void setEditorObserverForTest(EditorObserverForTest editorObserverForTest) { sEditorObserverForTest = editorObserverForTest; + EditorDialog.setEditorObserverForTest(sEditorObserverForTest); } @VisibleForTesting
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/SectionInformation.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/SectionInformation.java index f90dd347..509e1bd6 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/SectionInformation.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/SectionInformation.java
@@ -10,7 +10,7 @@ import androidx.annotation.VisibleForTesting; import org.chromium.chrome.R; -import org.chromium.chrome.browser.widget.prefeditor.EditableOption; +import org.chromium.chrome.browser.autofill.prefeditor.EditableOption; import java.util.ArrayList; import java.util.Arrays;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/SectionUiUtils.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/SectionUiUtils.java index 3010d21..0f072267 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/SectionUiUtils.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/SectionUiUtils.java
@@ -13,7 +13,7 @@ import androidx.annotation.Nullable; import org.chromium.chrome.R; -import org.chromium.chrome.browser.widget.prefeditor.EditableOption; +import org.chromium.chrome.browser.autofill.prefeditor.EditableOption; /** * Utility functions for PaymentRequestSection.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/settings/autofill/AutofillEditorBase.java b/chrome/android/java/src/org/chromium/chrome/browser/settings/autofill/AutofillEditorBase.java index 37f276a..85a4b7a7 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/settings/autofill/AutofillEditorBase.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/settings/autofill/AutofillEditorBase.java
@@ -26,9 +26,9 @@ import android.widget.Spinner; import org.chromium.chrome.R; +import org.chromium.chrome.browser.autofill.prefeditor.EditorDialog; import org.chromium.chrome.browser.settings.MainPreferences; import org.chromium.chrome.browser.settings.SettingsUtils; -import org.chromium.chrome.browser.widget.prefeditor.EditorDialog; import org.chromium.components.browser_ui.widget.FadingEdgeScrollView; /** Base class for Autofill editors (e.g. credit cards and profiles). */
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/settings/autofill/AutofillProfileEditorPreference.java b/chrome/android/java/src/org/chromium/chrome/browser/settings/autofill/AutofillProfileEditorPreference.java index a0a63d75..4d38b9c6 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/settings/autofill/AutofillProfileEditorPreference.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/settings/autofill/AutofillProfileEditorPreference.java
@@ -9,31 +9,32 @@ import android.os.Bundle; import android.support.v7.preference.Preference; +import androidx.annotation.VisibleForTesting; + import org.chromium.base.Callback; import org.chromium.chrome.browser.autofill.PersonalDataManager; +import org.chromium.chrome.browser.autofill.prefeditor.EditorDialog; +import org.chromium.chrome.browser.autofill.prefeditor.EditorObserverForTest; import org.chromium.chrome.browser.payments.AddressEditor; import org.chromium.chrome.browser.payments.AutofillAddress; import org.chromium.chrome.browser.payments.SettingsAutofillAndPaymentsObserver; import org.chromium.chrome.browser.settings.MainPreferences; -import org.chromium.chrome.browser.widget.prefeditor.EditorDialog; -import org.chromium.chrome.browser.widget.prefeditor.EditorObserverForTest; /** * Launches the UI to edit, create or delete an Autofill profile entry. */ public class AutofillProfileEditorPreference extends Preference { + private static EditorObserverForTest sObserverForTest; + private final Activity mActivity; - private final EditorObserverForTest mObserverForTest; private EditorDialog mEditorDialog; private AutofillAddress mAutofillAddress; private String mGUID; // TODO(crbug.com/982338): Remove Activity usage for Support Library migration. - public AutofillProfileEditorPreference( - Activity activity, Context styledContext, EditorObserverForTest observerForTest) { + public AutofillProfileEditorPreference(Activity activity, Context styledContext) { super(styledContext); mActivity = activity; - mObserverForTest = observerForTest; } public EditorDialog getEditorDialog() { @@ -72,8 +73,8 @@ SettingsAutofillAndPaymentsObserver.getInstance().notifyOnAddressUpdated( address); } - if (mObserverForTest != null) { - mObserverForTest.onEditorReadyToEdit(); + if (sObserverForTest != null) { + sObserverForTest.onEditorReadyToEdit(); } } }); @@ -91,11 +92,17 @@ SettingsAutofillAndPaymentsObserver.getInstance().notifyOnAddressDeleted( mGUID); } - if (mObserverForTest != null) { - mObserverForTest.onEditorReadyToEdit(); + if (sObserverForTest != null) { + sObserverForTest.onEditorReadyToEdit(); } }; } - mEditorDialog = new EditorDialog(mActivity, mObserverForTest, runnable); + mEditorDialog = new EditorDialog(mActivity, runnable); + } + + @VisibleForTesting + public static void setEditorObserverForTest(EditorObserverForTest observerForTest) { + sObserverForTest = observerForTest; + EditorDialog.setEditorObserverForTest(sObserverForTest); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/settings/autofill/AutofillProfilesFragment.java b/chrome/android/java/src/org/chromium/chrome/browser/settings/autofill/AutofillProfilesFragment.java index ba8a7ea..ebd32185 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/settings/autofill/AutofillProfilesFragment.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/settings/autofill/AutofillProfilesFragment.java
@@ -19,10 +19,10 @@ import org.chromium.chrome.R; import org.chromium.chrome.browser.autofill.PersonalDataManager; import org.chromium.chrome.browser.autofill.PersonalDataManager.AutofillProfile; +import org.chromium.chrome.browser.autofill.prefeditor.EditorObserverForTest; import org.chromium.chrome.browser.settings.ChromeSwitchPreference; import org.chromium.chrome.browser.settings.MainPreferences; import org.chromium.chrome.browser.settings.ManagedPreferenceDelegate; -import org.chromium.chrome.browser.widget.prefeditor.EditorObserverForTest; /** * Autofill profiles fragment, which allows the user to edit autofill profiles. @@ -85,8 +85,8 @@ // Add a preference for the profile. Preference pref; if (profile.getIsLocal()) { - AutofillProfileEditorPreference localPref = new AutofillProfileEditorPreference( - getActivity(), getStyledContext(), sObserverForTest); + AutofillProfileEditorPreference localPref = + new AutofillProfileEditorPreference(getActivity(), getStyledContext()); localPref.setTitle(profile.getFullName()); localPref.setSummary(profile.getLabel()); localPref.setKey(localPref.getTitle().toString()); // For testing. @@ -106,8 +106,8 @@ // Add 'Add address' button. Tap of it brings up address editor which allows users type in // new addresses. if (PersonalDataManager.isAutofillProfileEnabled()) { - AutofillProfileEditorPreference pref = new AutofillProfileEditorPreference( - getActivity(), getStyledContext(), sObserverForTest); + AutofillProfileEditorPreference pref = + new AutofillProfileEditorPreference(getActivity(), getStyledContext()); Drawable plusIcon = ApiCompatibilityUtils.getDrawable(getResources(), R.drawable.plus); plusIcon.mutate(); plusIcon.setColorFilter( @@ -144,6 +144,7 @@ @VisibleForTesting public static void setObserverForTest(EditorObserverForTest observerForTest) { sObserverForTest = observerForTest; + AutofillProfileEditorPreference.setEditorObserverForTest(sObserverForTest); } private Context getStyledContext() {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/settings/privacy/ConfirmImportantSitesDialogFragment.java b/chrome/android/java/src/org/chromium/chrome/browser/settings/privacy/ConfirmImportantSitesDialogFragment.java index 2d705ae..8b94d9c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/settings/privacy/ConfirmImportantSitesDialogFragment.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/settings/privacy/ConfirmImportantSitesDialogFragment.java
@@ -34,9 +34,9 @@ import org.chromium.chrome.browser.favicon.IconType; import org.chromium.chrome.browser.favicon.LargeIconBridge; import org.chromium.chrome.browser.favicon.LargeIconBridge.LargeIconCallback; +import org.chromium.chrome.browser.favicon.RoundedIconGenerator; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.util.ConversionUtils; -import org.chromium.chrome.browser.widget.RoundedIconGenerator; import java.util.ArrayList; import java.util.HashMap;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/settings/website/WebsitePreference.java b/chrome/android/java/src/org/chromium/chrome/browser/settings/website/WebsitePreference.java index 06398f8..2de8bc3 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/settings/website/WebsitePreference.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/settings/website/WebsitePreference.java
@@ -20,9 +20,9 @@ import org.chromium.chrome.R; import org.chromium.chrome.browser.favicon.FaviconHelper; import org.chromium.chrome.browser.favicon.FaviconHelper.FaviconImageCallback; +import org.chromium.chrome.browser.favicon.RoundedIconGenerator; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.settings.ChromeImageViewPreference; -import org.chromium.chrome.browser.widget.RoundedIconGenerator; /** * A preference that displays a website's favicon and URL and, optionally, the amount of local
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/ConfirmSyncDataStateMachine.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/ConfirmSyncDataStateMachine.java index 593d8434..6604006d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/ConfirmSyncDataStateMachine.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/ConfirmSyncDataStateMachine.java
@@ -56,12 +56,30 @@ int DONE = 4; } + /** + * Callback for completion of the {@link ConfirmSyncDataStateMachine}. + */ + interface Listener { + /** + * The state machine has completed and the state is done, or all necessary + * confirmations were given and the sign-in flow can proceed. + * @param wipeData Whether the user requested that existing data should be wiped. + */ + void onConfirm(boolean wipeData); + + /** + * The state machine is cancelled or the user cancels the sign-in process + * of the dialogs. + */ + void onCancel(); + } + @State private int mState = State.BEFORE_OLD_ACCOUNT_DIALOG; private static final int ACCOUNT_CHECK_TIMEOUT_MS = 30000; - private final ConfirmImportSyncDataDialog.Listener mCallback; + private final Listener mListener; private final @Nullable String mOldAccountName; private final String mNewAccountName; private final ConfirmSyncDataStateMachineDelegate mDelegate; @@ -75,21 +93,18 @@ * Create and run state machine, displaying the appropriate dialogs. * @param oldAccountName the name of the last signed in account or null * @param newAccountName the name of the account user is signing in with - * @param callback the listener to receive the result of this state machine + * @param listener the listener to receive the result of this state machine * @param delegate the delegate responsible of showing dialogs - * TODO(https://crbug.com/1038502): - * Use a separate interface for the callback to avoid confusion. */ public ConfirmSyncDataStateMachine(ConfirmSyncDataStateMachineDelegate delegate, - @Nullable String oldAccountName, String newAccountName, - ConfirmImportSyncDataDialog.Listener callback) { + @Nullable String oldAccountName, String newAccountName, Listener listener) { ThreadUtils.assertOnUiThread(); assert !TextUtils.isEmpty(newAccountName) : "New account name must be provided."; mDelegate = delegate; mOldAccountName = oldAccountName; mNewAccountName = newAccountName; - mCallback = callback; + mListener = listener; // New account management status isn't needed right now, but fetching it // can take a few seconds, so we kick it off early. @@ -111,7 +126,7 @@ mState = State.DONE; if (isBeingDestroyed) return; - mCallback.onCancel(); + mListener.onCancel(); mDelegate.dismissAllDialogs(); } @@ -149,7 +164,7 @@ break; case State.AFTER_NEW_ACCOUNT_DIALOG: mState = State.DONE; - mCallback.onConfirm(mWipeData); + mListener.onConfirm(mWipeData); break; case State.DONE: throw new IllegalStateException("Can't progress from DONE state!");
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninFragmentBase.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninFragmentBase.java index 7411037..9eafc400 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninFragmentBase.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninFragmentBase.java
@@ -439,7 +439,7 @@ mConfirmSyncDataStateMachine = new ConfirmSyncDataStateMachine( new ConfirmSyncDataStateMachineDelegate(getChildFragmentManager()), PrefServiceBridge.getInstance().getString(Pref.SYNC_LAST_ACCOUNT_NAME), - mSelectedAccountName, new ConfirmImportSyncDataDialog.Listener() { + mSelectedAccountName, new ConfirmSyncDataStateMachine.Listener() { @Override public void onConfirm(boolean wipeData) { mConfirmSyncDataStateMachine = null;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/suggestions/tile/SuggestionsTileView.java b/chrome/android/java/src/org/chromium/chrome/browser/suggestions/tile/SuggestionsTileView.java index a00bb6e..9f0358b4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/suggestions/tile/SuggestionsTileView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/suggestions/tile/SuggestionsTileView.java
@@ -11,7 +11,6 @@ import org.chromium.chrome.R; import org.chromium.chrome.browser.ntp.TitleUtil; import org.chromium.chrome.browser.suggestions.SiteSuggestion; -import org.chromium.chrome.browser.widget.tile.TileWithTextView; /** * The view for a site suggestion tile. Displays the title of the site beneath a large icon. If a
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/suggestions/tile/TileRenderer.java b/chrome/android/java/src/org/chromium/chrome/browser/suggestions/tile/TileRenderer.java index f7c21884..8505f83 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/suggestions/tile/TileRenderer.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/suggestions/tile/TileRenderer.java
@@ -27,13 +27,13 @@ import org.chromium.chrome.browser.explore_sites.MostLikelyVariation; import org.chromium.chrome.browser.favicon.IconType; import org.chromium.chrome.browser.favicon.LargeIconBridge; +import org.chromium.chrome.browser.favicon.RoundedIconGenerator; import org.chromium.chrome.browser.feature_engagement.TrackerFactory; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.suggestions.ImageFetcher; import org.chromium.chrome.browser.suggestions.SiteSuggestion; import org.chromium.chrome.browser.suggestions.SuggestionsConfig.TileStyle; import org.chromium.chrome.browser.util.ViewUtils; -import org.chromium.chrome.browser.widget.RoundedIconGenerator; import org.chromium.components.feature_engagement.EventConstants; import org.chromium.components.feature_engagement.Tracker;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/tile/TileView.java b/chrome/android/java/src/org/chromium/chrome/browser/suggestions/tile/TileView.java similarity index 91% rename from chrome/android/java/src/org/chromium/chrome/browser/widget/tile/TileView.java rename to chrome/android/java/src/org/chromium/chrome/browser/suggestions/tile/TileView.java index 779d9ff1..68d274c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/tile/TileView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/suggestions/tile/TileView.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.chrome.browser.widget.tile; +package org.chromium.chrome.browser.suggestions.tile; import android.content.Context; import android.graphics.drawable.Drawable; @@ -39,10 +39,8 @@ /** * Initializes the view. This should be called immediately after inflation. * - * @param title The title of the tile. * @param showOfflineBadge Whether to show the offline badge. * @param icon The icon to display on the tile. - * @param titleLines The number of text lines to use for the tile title. */ public void initialize(boolean showOfflineBadge, Drawable icon) { setOfflineBadgeVisibility(showOfflineBadge);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/tile/TileWithTextView.java b/chrome/android/java/src/org/chromium/chrome/browser/suggestions/tile/TileWithTextView.java similarity index 96% rename from chrome/android/java/src/org/chromium/chrome/browser/widget/tile/TileWithTextView.java rename to chrome/android/java/src/org/chromium/chrome/browser/suggestions/tile/TileWithTextView.java index 9dd12a7..2a7435a1 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/tile/TileWithTextView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/suggestions/tile/TileWithTextView.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.chrome.browser.widget.tile; +package org.chromium.chrome.browser.suggestions.tile; import android.content.Context; import android.graphics.drawable.Drawable;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarManager.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarManager.java index b743cb0..094bc6b4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarManager.java
@@ -1519,18 +1519,18 @@ } @Override - public @ChromeTabbedActivity.BackPressedResult Integer back() { + public boolean back() { if (mBottomControlsCoordinator != null && mBottomControlsCoordinator.onBackPressed()) { - return ChromeTabbedActivity.BackPressedResult.EXITED_TAB_GROUP_DIALOG; + return true; } Tab tab = mLocationBarModel.getTab(); if (tab != null && tab.canGoBack()) { tab.goBack(); updateButtonStatus(); - return ChromeTabbedActivity.BackPressedResult.NAVIGATED_BACK; + return true; } - return null; + return false; } @Override
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarTabController.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarTabController.java index 20f4854b..92bfc363 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarTabController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarTabController.java
@@ -4,8 +4,6 @@ package org.chromium.chrome.browser.toolbar; -import org.chromium.chrome.browser.ChromeTabbedActivity; - /** * Handles toolbar triggered actions on the specific tab. */ @@ -20,11 +18,9 @@ /** * Handles a back press action in tab page. - * @return A {@link ChromeTabbedActivity.BackPressedResult} indicating the result of this back - * press. If returning null, the back press event is not consumed here. + * @return True if back press event is consumed here. */ - @ChromeTabbedActivity.BackPressedResult - Integer back(); + boolean back(); /** * Navigates the current Tab forward.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/ToolbarLayout.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/ToolbarLayout.java index 387bee1b..e07c582 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/ToolbarLayout.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/ToolbarLayout.java
@@ -804,7 +804,7 @@ if (getLocationBar() != null) { getLocationBar().setUrlBarFocus(false, null, LocationBar.OmniboxFocusReason.UNFOCUS); } - return mToolbarTabController != null && mToolbarTabController.back() != null; + return mToolbarTabController != null && mToolbarTabController.back(); } /**
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/widget/RoundedIconGeneratorTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/favicon/RoundedIconGeneratorTest.java similarity index 98% rename from chrome/android/javatests/src/org/chromium/chrome/browser/widget/RoundedIconGeneratorTest.java rename to chrome/android/javatests/src/org/chromium/chrome/browser/favicon/RoundedIconGeneratorTest.java index f837298..37e3c1f8 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/widget/RoundedIconGeneratorTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/favicon/RoundedIconGeneratorTest.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.chrome.browser.widget; +package org.chromium.chrome.browser.favicon; import android.content.Context; import android.graphics.Color;
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/notifications/NotificationBuilderBaseTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/notifications/NotificationBuilderBaseTest.java index 7774c2d..9c61581 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/notifications/NotificationBuilderBaseTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/notifications/NotificationBuilderBaseTest.java
@@ -19,9 +19,9 @@ import org.chromium.base.test.BaseJUnit4ClassRunner; import org.chromium.base.test.util.Feature; +import org.chromium.chrome.browser.favicon.RoundedIconGenerator; import org.chromium.chrome.browser.notifications.channels.ChannelDefinitions; import org.chromium.chrome.browser.util.UrlUtilities; -import org.chromium.chrome.browser.widget.RoundedIconGenerator; import org.chromium.content_public.browser.test.NativeLibraryTestRule; /**
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/notifications/NotificationPlatformBridgeTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/notifications/NotificationPlatformBridgeTest.java index 8ae0e5f..b0dacbb 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/notifications/NotificationPlatformBridgeTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/notifications/NotificationPlatformBridgeTest.java
@@ -37,6 +37,7 @@ import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.engagement.SiteEngagementService; +import org.chromium.chrome.browser.favicon.RoundedIconGenerator; import org.chromium.chrome.browser.permissions.PermissionDialogController; import org.chromium.chrome.browser.permissions.PermissionTestRule; import org.chromium.chrome.browser.preferences.Pref; @@ -44,7 +45,6 @@ import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.settings.website.ContentSettingValues; import org.chromium.chrome.browser.tab.Tab; -import org.chromium.chrome.browser.widget.RoundedIconGenerator; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.chrome.test.util.browser.TabTitleObserver; import org.chromium.chrome.test.util.browser.notifications.MockNotificationManagerProxy.NotificationEntry;
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/notifications/StandardNotificationBuilderTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/notifications/StandardNotificationBuilderTest.java index 6f67160..51aa026c 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/notifications/StandardNotificationBuilderTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/notifications/StandardNotificationBuilderTest.java
@@ -30,9 +30,9 @@ import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.MinAndroidSdkLevel; import org.chromium.chrome.R; +import org.chromium.chrome.browser.favicon.RoundedIconGenerator; import org.chromium.chrome.browser.notifications.channels.ChannelDefinitions; import org.chromium.chrome.browser.util.UrlUtilities; -import org.chromium.chrome.browser.widget.RoundedIconGenerator; import org.chromium.content_public.browser.test.NativeLibraryTestRule; /**
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestContactDetailsSectionUnitTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestContactDetailsSectionUnitTest.java index bd4a77e..0f7d515e 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestContactDetailsSectionUnitTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestContactDetailsSectionUnitTest.java
@@ -15,9 +15,9 @@ import org.chromium.base.test.BaseJUnit4ClassRunner; import org.chromium.base.test.util.Feature; import org.chromium.chrome.browser.autofill.PersonalDataManager.AutofillProfile; +import org.chromium.chrome.browser.autofill.prefeditor.EditableOption; import org.chromium.chrome.browser.payments.ui.ContactDetailsSection; import org.chromium.chrome.browser.payments.ui.SectionInformation; -import org.chromium.chrome.browser.widget.prefeditor.EditableOption; import org.chromium.chrome.test.ChromeBrowserTestRule; import java.util.ArrayList;
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestTestRule.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestTestRule.java index 1a678acd..5f66bf6 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestTestRule.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestTestRule.java
@@ -27,13 +27,13 @@ import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.autofill.CardUnmaskPrompt; import org.chromium.chrome.browser.autofill.CardUnmaskPrompt.CardUnmaskObserverForTest; +import org.chromium.chrome.browser.autofill.prefeditor.EditorObserverForTest; +import org.chromium.chrome.browser.autofill.prefeditor.EditorTextField; import org.chromium.chrome.browser.payments.PaymentRequestImpl.PaymentRequestServiceObserverForTest; import org.chromium.chrome.browser.payments.ui.PaymentRequestSection.OptionSection; import org.chromium.chrome.browser.payments.ui.PaymentRequestSection.OptionSection.OptionRow; import org.chromium.chrome.browser.payments.ui.PaymentRequestUI; import org.chromium.chrome.browser.payments.ui.PaymentRequestUI.PaymentRequestObserverForTest; -import org.chromium.chrome.browser.widget.prefeditor.EditorObserverForTest; -import org.chromium.chrome.browser.widget.prefeditor.EditorTextField; import org.chromium.chrome.test.ChromeTabbedActivityTestRule; import org.chromium.content_public.browser.UiThreadTaskTraits; import org.chromium.content_public.browser.WebContents;
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/settings/autofill/AutofillTestRule.java b/chrome/android/javatests/src/org/chromium/chrome/browser/settings/autofill/AutofillTestRule.java index 619aebda..094a07a 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/settings/autofill/AutofillTestRule.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/settings/autofill/AutofillTestRule.java
@@ -9,8 +9,8 @@ import org.chromium.base.ThreadUtils; import org.chromium.base.test.util.CallbackHelper; -import org.chromium.chrome.browser.widget.prefeditor.EditorDialog; -import org.chromium.chrome.browser.widget.prefeditor.EditorObserverForTest; +import org.chromium.chrome.browser.autofill.prefeditor.EditorDialog; +import org.chromium.chrome.browser.autofill.prefeditor.EditorObserverForTest; import org.chromium.chrome.test.ChromeBrowserTestRule; import org.chromium.content_public.browser.test.util.TestThreadUtils;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/customtabs/content/CustomTabActivityContentTestEnvironment.java b/chrome/android/junit/src/org/chromium/chrome/browser/customtabs/content/CustomTabActivityContentTestEnvironment.java index ab59d49..1276229 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/customtabs/content/CustomTabActivityContentTestEnvironment.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/customtabs/content/CustomTabActivityContentTestEnvironment.java
@@ -124,7 +124,7 @@ when(connection.getSpeculatedUrl(any())).thenReturn(SPECULATED_URL); when(browserInitializer.hasNativeInitializationCompleted()).thenReturn(true); // Default setup is toolbarManager doesn't consume back press event. - when(toolbarManager.back()).thenReturn(null); + when(toolbarManager.back()).thenReturn(false); when(startupTabPreloader.takeTabIfMatchingOrDestroy(any(), anyInt())).thenReturn(null); when(reparentingTaskProvider.get(any())).thenReturn(reparentingTask);
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/SearchEngineLogoUtilsUnitTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/SearchEngineLogoUtilsUnitTest.java index 3ab7143..f283a48 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/SearchEngineLogoUtilsUnitTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/SearchEngineLogoUtilsUnitTest.java
@@ -34,10 +34,10 @@ import org.chromium.base.metrics.test.ShadowRecordHistogram; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.chrome.browser.favicon.FaviconHelper; +import org.chromium.chrome.browser.favicon.RoundedIconGenerator; import org.chromium.chrome.browser.omnibox.SearchEngineLogoUtils.Delegate; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.search_engines.TemplateUrlServiceFactory; -import org.chromium.chrome.browser.widget.RoundedIconGenerator; import org.chromium.components.search_engines.TemplateUrlService; /**
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/suggestions/base/BaseSuggestionViewBinderUnitTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/suggestions/base/BaseSuggestionViewBinderUnitTest.java index b874b4df..14a5aa3 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/suggestions/base/BaseSuggestionViewBinderUnitTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/suggestions/base/BaseSuggestionViewBinderUnitTest.java
@@ -40,7 +40,10 @@ BaseSuggestionView mBaseView; @Mock - RoundedCornerImageView mDecorView; + DecoratedSuggestionView mDecoratedView; + + @Mock + RoundedCornerImageView mIconView; @Mock ImageView mActionView; @@ -57,11 +60,13 @@ mResources = mActivity.getResources(); when(mBaseView.getContext()).thenReturn(mActivity); - when(mDecorView.getContext()).thenReturn(mActivity); + when(mIconView.getContext()).thenReturn(mActivity); when(mActionView.getContext()).thenReturn(mActivity); - when(mBaseView.getSuggestionImageView()).thenReturn(mDecorView); + when(mBaseView.getDecoratedSuggestionView()).thenReturn(mDecoratedView); + when(mBaseView.getSuggestionImageView()).thenReturn(mIconView); when(mBaseView.getActionImageView()).thenReturn(mActionView); - when(mBaseView.getResources()).thenReturn(mResources); + + when(mDecoratedView.getResources()).thenReturn(mResources); mModel = new PropertyModel(BaseSuggestionViewProperties.ALL_KEYS); PropertyModelChangeProcessor.create(mModel, mBaseView, new BaseSuggestionViewBinder()); @@ -73,11 +78,11 @@ mModel.set(BaseSuggestionViewProperties.ICON, state); // Expect a single call to setRoundedCorners, and make sure this call sets all radii to 0. - verify(mDecorView).setRoundedCorners(0, 0, 0, 0); - verify(mDecorView).setRoundedCorners(anyInt(), anyInt(), anyInt(), anyInt()); + verify(mIconView).setRoundedCorners(0, 0, 0, 0); + verify(mIconView).setRoundedCorners(anyInt(), anyInt(), anyInt(), anyInt()); - verify(mDecorView).setVisibility(View.VISIBLE); - verify(mDecorView).setImageDrawable(state.drawable); + verify(mIconView).setVisibility(View.VISIBLE); + verify(mIconView).setImageDrawable(state.drawable); } @Test @@ -87,26 +92,26 @@ mModel.set(BaseSuggestionViewProperties.ICON, state); // Expect a single call to setRoundedCorners, and make sure this call sets radii to non-0. - verify(mDecorView, never()).setRoundedCorners(0, 0, 0, 0); - verify(mDecorView).setRoundedCorners(anyInt(), anyInt(), anyInt(), anyInt()); + verify(mIconView, never()).setRoundedCorners(0, 0, 0, 0); + verify(mIconView).setRoundedCorners(anyInt(), anyInt(), anyInt(), anyInt()); - verify(mDecorView).setVisibility(View.VISIBLE); - verify(mDecorView).setImageDrawable(state.drawable); + verify(mIconView).setVisibility(View.VISIBLE); + verify(mIconView).setImageDrawable(state.drawable); } @Test public void decorIcon_hideIcon() { - InOrder ordered = inOrder(mDecorView); + InOrder ordered = inOrder(mIconView); SuggestionDrawableState state = SuggestionDrawableState.Builder.forColor(0).build(); mModel.set(BaseSuggestionViewProperties.ICON, state); mModel.set(BaseSuggestionViewProperties.ICON, null); - ordered.verify(mDecorView).setVisibility(View.VISIBLE); - ordered.verify(mDecorView).setImageDrawable(state.drawable); - ordered.verify(mDecorView).setVisibility(View.GONE); + ordered.verify(mIconView).setVisibility(View.VISIBLE); + ordered.verify(mIconView).setImageDrawable(state.drawable); + ordered.verify(mIconView).setVisibility(View.GONE); // Ensure we're releasing drawable to free memory. - ordered.verify(mDecorView).setImageDrawable(null); + ordered.verify(mIconView).setImageDrawable(null); } @Test @@ -141,7 +146,8 @@ SuggestionDrawableState state = SuggestionDrawableState.Builder.forColor(0).build(); mModel.set(BaseSuggestionViewProperties.ICON, state); - verify(mBaseView).setPaddingRelative(startSpace, 0, endSpace, 0); + verify(mDecoratedView).setPaddingRelative(startSpace, 0, endSpace, 0); + verify(mBaseView, never()).setPaddingRelative(anyInt(), anyInt(), anyInt(), anyInt()); } @Test @@ -152,6 +158,7 @@ R.dimen.omnibox_suggestion_refine_view_modern_end_padding); mModel.set(BaseSuggestionViewProperties.ICON, null); - verify(mBaseView).setPaddingRelative(startSpace, 0, endSpace, 0); + verify(mDecoratedView).setPaddingRelative(startSpace, 0, endSpace, 0); + verify(mBaseView, never()).setPaddingRelative(anyInt(), anyInt(), anyInt(), anyInt()); } }
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/suggestions/base/BaseSuggestionViewTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/suggestions/base/BaseSuggestionViewTest.java index 77c67cc6..817f132 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/suggestions/base/BaseSuggestionViewTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/suggestions/base/BaseSuggestionViewTest.java
@@ -72,7 +72,7 @@ } View getDecoratedView() { - return mContentView; + return mDecoratedView; } View getRefineView() {
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/signin/ConfirmSyncDataStateMachineTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/signin/ConfirmSyncDataStateMachineTest.java index fd9af16..12bfaf8 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/signin/ConfirmSyncDataStateMachineTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/signin/ConfirmSyncDataStateMachineTest.java
@@ -40,7 +40,7 @@ private ConfirmSyncDataStateMachineDelegate mDelegateMock; @Mock - private ConfirmImportSyncDataDialog.Listener mImportSyncDataListenerMock; + private ConfirmSyncDataStateMachine.Listener mStateMachineListenerMock; @Mock private SigninManager mSigninManagerMock; @@ -63,13 +63,13 @@ @Test(expected = AssertionError.class) public void testNewAccountNameCannotBeEmpty() { ConfirmSyncDataStateMachine stateMachine = new ConfirmSyncDataStateMachine( - mDelegateMock, mOldAccountName, null, mImportSyncDataListenerMock); + mDelegateMock, mOldAccountName, null, mStateMachineListenerMock); } @Test public void testImportSyncDataDialogShownWhenOldAndNewAccountNamesAreDifferent() { ConfirmSyncDataStateMachine stateMachine = new ConfirmSyncDataStateMachine( - mDelegateMock, mOldAccountName, mNewAccountName, mImportSyncDataListenerMock); + mDelegateMock, mOldAccountName, mNewAccountName, mStateMachineListenerMock); verify(mDelegateMock) .showConfirmImportSyncDataDialog(any(ConfirmImportSyncDataDialog.Listener.class), eq(mOldAccountName), eq(mNewAccountName)); @@ -79,7 +79,7 @@ public void testProgressDialogShownWhenOldAndNewAccountNamesAreEqual() { String oldAndNewAccountName = "test.old.new@testdomain.com"; ConfirmSyncDataStateMachine stateMachine = new ConfirmSyncDataStateMachine(mDelegateMock, - oldAndNewAccountName, oldAndNewAccountName, mImportSyncDataListenerMock); + oldAndNewAccountName, oldAndNewAccountName, mStateMachineListenerMock); verify(mDelegateMock, never()) .showConfirmImportSyncDataDialog( any(ConfirmImportSyncDataDialog.Listener.class), anyString(), anyString()); @@ -91,7 +91,7 @@ @Test public void testProgressDialogShownWhenOldAccountNameIsEmpty() { ConfirmSyncDataStateMachine stateMachine = new ConfirmSyncDataStateMachine( - mDelegateMock, null, mNewAccountName, mImportSyncDataListenerMock); + mDelegateMock, null, mNewAccountName, mStateMachineListenerMock); verify(mDelegateMock, never()) .showConfirmImportSyncDataDialog( any(ConfirmImportSyncDataDialog.Listener.class), anyString(), anyString()); @@ -104,9 +104,9 @@ public void testListenerConfirmedWhenNewAccountIsNotManaged() { mockSigninManagerIsAccountManaged(false); ConfirmSyncDataStateMachine stateMachine = new ConfirmSyncDataStateMachine( - mDelegateMock, null, mNewAccountName, mImportSyncDataListenerMock); + mDelegateMock, null, mNewAccountName, mStateMachineListenerMock); verify(mDelegateMock).dismissAllDialogs(); - verify(mImportSyncDataListenerMock).onConfirm(false); + verify(mStateMachineListenerMock).onConfirm(false); } @Test @@ -114,7 +114,7 @@ mockSigninManagerIsAccountManaged(true); when(mSigninManagerNativeMock.extractDomainName(anyString())).thenReturn(mNewAccountName); ConfirmSyncDataStateMachine stateMachine = new ConfirmSyncDataStateMachine( - mDelegateMock, null, mNewAccountName, mImportSyncDataListenerMock); + mDelegateMock, null, mNewAccountName, mStateMachineListenerMock); verify(mDelegateMock) .showSignInToManagedAccountDialog( any(ConfirmManagedSyncDataDialog.Listener.class), eq(mNewAccountName)); @@ -126,7 +126,7 @@ String domain = "manageddomain.com"; when(mSigninManagerNativeMock.extractDomainName(newAccountName)).thenReturn(domain); ConfirmSyncDataStateMachine stateMachine = new ConfirmSyncDataStateMachine( - mDelegateMock, null, newAccountName, mImportSyncDataListenerMock); + mDelegateMock, null, newAccountName, mStateMachineListenerMock); verify(mDelegateMock, never()) .showSignInToManagedAccountDialog( any(ConfirmManagedSyncDataDialog.Listener.class), anyString()); @@ -142,25 +142,25 @@ @Test public void testCancelWhenIsNotBeingDestroyed() { ConfirmSyncDataStateMachine stateMachine = new ConfirmSyncDataStateMachine( - mDelegateMock, mOldAccountName, mNewAccountName, mImportSyncDataListenerMock); + mDelegateMock, mOldAccountName, mNewAccountName, mStateMachineListenerMock); stateMachine.onCancel(); - verify(mImportSyncDataListenerMock).onCancel(); + verify(mStateMachineListenerMock).onCancel(); verify(mDelegateMock).dismissAllDialogs(); } @Test public void testCancelWhenIsBeingDestroyed() { ConfirmSyncDataStateMachine stateMachine = new ConfirmSyncDataStateMachine( - mDelegateMock, mOldAccountName, mNewAccountName, mImportSyncDataListenerMock); + mDelegateMock, mOldAccountName, mNewAccountName, mStateMachineListenerMock); stateMachine.cancel(true); - verify(mImportSyncDataListenerMock, never()).onCancel(); + verify(mStateMachineListenerMock, never()).onCancel(); verify(mDelegateMock, never()).dismissAllDialogs(); } @Test(expected = IllegalStateException.class) public void testStateCannotChangeOnceDone() { ConfirmSyncDataStateMachine stateMachine = new ConfirmSyncDataStateMachine( - mDelegateMock, mOldAccountName, mNewAccountName, mImportSyncDataListenerMock); + mDelegateMock, mOldAccountName, mNewAccountName, mStateMachineListenerMock); stateMachine.cancel(true); stateMachine.onConfirm(); }
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index 56fdaea1..a517cd1 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -459,6 +459,12 @@ <message name="IDS_SEARCH_RESULTS_PLURAL" desc="Message announced to screenreader users when searching completes and results are showing."> <ph name="RESULT_COUNT">$1<ex>15</ex></ph> results for '<ph name="SEARCH_TEXT">$2<ex>cookies</ex></ph>' </message> + <message name="IDS_SEARCH_RESULT_BUBBLE_TEXT" desc="Text that shows in search result bubbles that point at parts of the settings UI which, when clicked, reveal new places for a search results (singular)."> + 1 result + </message> + <message name="IDS_SEARCH_RESULTS_BUBBLE_TEXT" desc="Text that shows in search result bubbles that point at parts of the settings UI which, when clicked, reveal new places for search results (plural)."> + <ph name="NUM_RESULTS">$1<ex>5</ex></ph> results + </message> <message name="IDS_SEARCH_NO_RESULTS" desc="Text description of a search that has no results."> No search results found </message> @@ -5767,9 +5773,6 @@ <message name="IDS_PASSWORDS_VIA_FEDERATION" desc="Text for federated credential's value."> with <ph name="PROVIDER">$1<ex>facebook.com</ex></ph> </message> - <message name="IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON" desc="Text for passwords page view's button to hide a stored password"> - Hide - </message> <!-- Confirm MessageBox Dialog --> <message name="IDS_CONFIRM_MESSAGEBOX_YES_BUTTON_LABEL" desc="Confirm MessageBox Dialog's 'Yes' button text"> @@ -6473,6 +6476,9 @@ <message name="IDS_MEDIA_TAB_CAPTURE_WITH_AUDIO_NOTIFICATION_TEXT_DELEGATED" desc="label used in screen capture notification UI to show the screen sharing status when the stream is consumed by a tab instead of the app initiating the window picker"> <ph name="APP_NAME">$1<ex>html5rocks.com</ex></ph> is sharing a Chrome tab and audio with <ph name="TAB_NAME">$2<ex>https://google.com</ex></ph>. </message> + <message name="IDS_MEDIA_SCREEN_CAPTURE_NOTIFICATION_HIDE" desc="Text shown on a link that hides the notification that the screen is being captured."> + Hide + </message> <message name="IDS_MEDIA_SCREEN_CAPTURE_NOTIFICATION_SOURCE" desc="Text shown on the button that changes the screen capture source."> Change source </message>
diff --git a/chrome/app/generated_resources_grd/IDS_SEARCH_RESULTS_BUBBLE_TEXT.png.sha1 b/chrome/app/generated_resources_grd/IDS_SEARCH_RESULTS_BUBBLE_TEXT.png.sha1 new file mode 100644 index 0000000..00b63fa5 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_SEARCH_RESULTS_BUBBLE_TEXT.png.sha1
@@ -0,0 +1 @@ +5e6b94f71d78c186cc33d0373726364c50c23d7b \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_SEARCH_RESULT_BUBBLE_TEXT.png.sha1 b/chrome/app/generated_resources_grd/IDS_SEARCH_RESULT_BUBBLE_TEXT.png.sha1 new file mode 100644 index 0000000..00b63fa5 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_SEARCH_RESULT_BUBBLE_TEXT.png.sha1
@@ -0,0 +1 @@ +5e6b94f71d78c186cc33d0373726364c50c23d7b \ No newline at end of file
diff --git a/chrome/app/settings_chromium_strings.grdp b/chrome/app/settings_chromium_strings.grdp index 596ee6a..772475d3 100644 --- a/chrome/app/settings_chromium_strings.grdp +++ b/chrome/app/settings_chromium_strings.grdp
@@ -101,10 +101,10 @@ <message name="IDS_SETTINGS_PROFILE_NAME_AND_PICTURE" desc="Label of the link that takes you to the page to edit your name and picture for your chrome profile."> Chromium name and picture </message> +</if> <message name="IDS_SETTINGS_PEOPLE_SIGN_IN_PROMPT_SECONDARY_WITH_ACCOUNT" desc="The secondary text displayed to prompt users to enable sync for an account that is alredy present in Chromium."> Sync and personalize Chromium across your devices </message> -</if> <!-- Sync Page --> <message name="IDS_SETTINGS_SYNC_SIGNIN" desc="The label that appears on the sync button in the options dialog when sync has not been set up by the user."> @@ -119,14 +119,12 @@ <message name="IDS_DRIVE_SUGGEST_PREF_DESC" desc="The documentation string of the 'Show Drive Results in Omnibox' - full description sentence"> Chromium will access your Drive to make suggestions in the address bar </message> -<if expr="not chromeos"> - <message name="IDS_SETTINGS_SYNC_SIGN_IN_PROMPT_WITH_NO_ACCOUNT" desc="The text displayed to prompt users to sign in to Chromium."> - Sign in to sync and personalize Chromium across your devices - </message> - <message name="IDS_SETTINGS_SYNC_SIGN_IN_PROMPT_WITH_ACCOUNT" desc="The text displayed to prompt users to enable sync for an account that is alredy present in Chromium."> - Sync and personalize Chromium across your devices - </message> -</if> + <message name="IDS_SETTINGS_SYNC_SIGN_IN_PROMPT_WITH_NO_ACCOUNT" desc="The text displayed to prompt users to sign in to Chromium."> + Sign in to sync and personalize Chromium across your devices + </message> + <message name="IDS_SETTINGS_SYNC_SIGN_IN_PROMPT_WITH_ACCOUNT" desc="The text displayed to prompt users to enable sync for an account that is alredy present in Chromium."> + Sync and personalize Chromium across your devices + </message> <!-- Languages Page --> <!-- Chrome OS string is in settings_strings.grdp. -->
diff --git a/chrome/app/settings_google_chrome_strings.grdp b/chrome/app/settings_google_chrome_strings.grdp index fdc9f36..5eb64ec4 100644 --- a/chrome/app/settings_google_chrome_strings.grdp +++ b/chrome/app/settings_google_chrome_strings.grdp
@@ -101,10 +101,10 @@ <message name="IDS_SETTINGS_PROFILE_NAME_AND_PICTURE" desc="Label of the link that takes you to the page to edit your name and picture for your chrome profile."> Chrome name and picture </message> +</if> <message name="IDS_SETTINGS_PEOPLE_SIGN_IN_PROMPT_SECONDARY_WITH_ACCOUNT" desc="The secondary text displayed to prompt users to enable sync for an account that is alredy present in Chrome."> Sync and personalize Chrome across your devices </message> -</if> <!-- Sync Page --> <message name="IDS_SETTINGS_SYNC_SIGNIN" desc="The label that appears on the sync button in the options dialog when sync has not been set up by the user."> @@ -119,14 +119,12 @@ <message name="IDS_DRIVE_SUGGEST_PREF_DESC" desc="The documentation string of the 'Show Drive Results in Omnibox' - full description sentence"> Chrome will access your Drive to make suggestions in the address bar </message> -<if expr="not chromeos"> - <message name="IDS_SETTINGS_SYNC_SIGN_IN_PROMPT_WITH_NO_ACCOUNT" desc="The text displayed to prompt users to sign in to Chrome."> - Sign in to sync and personalize Chrome across your devices - </message> - <message name="IDS_SETTINGS_SYNC_SIGN_IN_PROMPT_WITH_ACCOUNT" desc="The text displayed to prompt users to enable sync for an account that is alredy present in Chrome."> - Sync and personalize Chrome across your devices - </message> -</if> + <message name="IDS_SETTINGS_SYNC_SIGN_IN_PROMPT_WITH_NO_ACCOUNT" desc="The text displayed to prompt users to sign in to Chrome."> + Sign in to sync and personalize Chrome across your devices + </message> + <message name="IDS_SETTINGS_SYNC_SIGN_IN_PROMPT_WITH_ACCOUNT" desc="The text displayed to prompt users to enable sync for an account that is alredy present in Chrome."> + Sync and personalize Chrome across your devices + </message> <!-- Languages Page --> <!-- Chrome OS string is in settings_strings.grdp. -->
diff --git a/chrome/app/settings_strings.grdp b/chrome/app/settings_strings.grdp index 1d8bc47..8138f4f0 100644 --- a/chrome/app/settings_strings.grdp +++ b/chrome/app/settings_strings.grdp
@@ -4208,55 +4208,53 @@ </message> </if> + <message name="IDS_SETTINGS_PEOPLE_SIGN_IN" desc="The label of the button that lets user sign-in to chrome."> + Sign in + </message> + <message name="IDS_SETTINGS_PEOPLE_SIGN_IN_PROMPT" desc="The text displayed to prompt users to sign in to chrome."> + Get Google smarts in Chrome + </message> + <message name="IDS_SETTINGS_PEOPLE_SYNC_ANOTHER_ACCOUNT" desc="The label for the button that lets the user choose another account to sync with."> + Use another account + </message> + <message name="IDS_SETTINGS_PEOPLE_SYNCING_TO_ACCOUNT" desc="The text displayed to the user that the profile is currently syncing to a specific account."> + Syncing to <ph name="EMAIL">$1<ex>abcd@google.com</ex></ph> + </message> + <message name="IDS_SETTINGS_PEOPLE_SYNC_TURN_OFF" desc="The label for the button that lets the user turn off profile syncing with their gaia account."> + Turn off + </message> + <message name="IDS_SETTINGS_PEOPLE_SYNC_NOT_WORKING" desc="The label informing the user that sync is currently not working."> + Sync isn't working + </message> + <message name="IDS_SETTINGS_PEOPLE_SYNC_PASSWORDS_NOT_WORKING" desc="The label informing the user that password sync is currently not working."> + Error syncing passwords + </message> + <message name="IDS_SETTINGS_PEOPLE_SYNC_PAUSED" desc="The label informing the user that sync is currently paused."> + Sync is paused + </message> + <message name="IDS_SETTINGS_SYNC_DISCONNECT_MANAGED_PROFILE_EXPLANATION" desc="The text to display in the 'Sign out of Chrome' dialog to stop syncing for managed profiles."> + Because this account is managed by <ph name="DOMAIN">$1<ex>example.com</ex></ph>, your bookmarks, history, passwords, and other settings will be cleared from this device. However, your data will remain stored in your Google Account and can be managed on <ph name="BEGIN_LINK"><a href="$2" target="_blank"><ex><a href="$2" target="_blank"></ex></ph>Google Dashboard<ph name="END_LINK"></a><ex></a></ex></ph>. + </message> + <message name="IDS_SETTINGS_EDIT_PERSON" desc="Title of the edit person subpage. This is a subpage to edit the name and icon of a Chrome Profile."> + Edit person + </message> + <message name="IDS_SETTINGS_TURN_OFF_SYNC_AND_SIGN_OUT_DIALOG_TITLE" desc="The text to display on the title of the dialog to turn off sync and sign out."> + Turn off sync and personalization? + </message> + <message name="IDS_SETTINGS_TURN_OFF_SYNC_DIALOG_MANAGED_CONFIRM" desc="The text to display on the confirm button of the dialog to turn off sync, when the profile is managed by admin."> + Clear and continue + </message> + <message name="IDS_SETTINGS_TURN_OFF_SYNC_DIALOG_CHECKBOX" desc="The text to display next to the checkbox of the dialog to turn off sync, asking users if they want to clear these data from the device."> + Clear bookmarks, history, passwords, and more from this device + </message> + <message name="IDS_SETTINGS_SYNC_SETTINGS_SAVED_TOAST_LABEL" desc="The notification shown to user after they saved sync settings, and sync is now started."> + Settings saved. Sync started. + </message> + <if expr="not chromeos"> - <message name="IDS_SETTINGS_PEOPLE_DOMAIN_MANAGED_PROFILE" desc="Provides the domain information for domain-managed accounts."> - Managed by <ph name="DOMAIN">$1<ex>example.com</ex></ph> - </message> - <message name="IDS_SETTINGS_PEOPLE_SIGN_IN" desc="The label of the button that lets user sign-in to chrome."> - Sign in - </message> - <message name="IDS_SETTINGS_PEOPLE_SIGN_IN_PROMPT" desc="The text displayed to prompt users to sign in to chrome."> - Get Google smarts in Chrome - </message> - <message name="IDS_SETTINGS_PEOPLE_SYNC_ANOTHER_ACCOUNT" desc="The label for the button that lets the user choose another account to sync with."> - Use another account - </message> - <message name="IDS_SETTINGS_PEOPLE_SYNCING_TO_ACCOUNT" desc="The text displayed to the user that the profile is currently syncing to a specific account."> - Syncing to <ph name="EMAIL">$1<ex>abcd@google.com</ex></ph> - </message> - <message name="IDS_SETTINGS_PEOPLE_SYNC_TURN_OFF" desc="The label for the button that lets the user turn off profile syncing with their gaia account."> - Turn off - </message> - <message name="IDS_SETTINGS_PEOPLE_SYNC_NOT_WORKING" desc="The label informing the user that sync is currently not working."> - Sync isn't working - </message> - <message name="IDS_SETTINGS_PEOPLE_SYNC_PASSWORDS_NOT_WORKING" desc="The label informing the user that password sync is currently not working."> - Error syncing passwords - </message> - <message name="IDS_SETTINGS_PEOPLE_SYNC_PAUSED" desc="The label informing the user that sync is currently paused."> - Sync is paused - </message> - <message name="IDS_SETTINGS_SYNC_DISCONNECT_MANAGED_PROFILE_EXPLANATION" desc="The text to display in the 'Sign out of Chrome' dialog to stop syncing for managed profiles."> - Because this account is managed by <ph name="DOMAIN">$1<ex>example.com</ex></ph>, your bookmarks, history, passwords, and other settings will be cleared from this device. However, your data will remain stored in your Google Account and can be managed on <ph name="BEGIN_LINK"><a href="$2" target="_blank"><ex><a href="$2" target="_blank"></ex></ph>Google Dashboard<ph name="END_LINK"></a><ex></a></ex></ph>. - </message> - <message name="IDS_SETTINGS_EDIT_PERSON" desc="Title of the edit person subpage. This is a subpage to edit the name and icon of a Chrome Profile."> - Edit person - </message> <message name="IDS_SETTINGS_PROFILE_SHORTCUT_TOGGLE_LABEL" desc="Label of the toggle that creates or removes a desktop shortcut for the profile."> Show desktop shortcut </message> - <message name="IDS_SETTINGS_TURN_OFF_SYNC_AND_SIGN_OUT_DIALOG_TITLE" desc="The text to display on the title of the dialog to turn off sync and sign out."> - Turn off sync and personalization? - </message> - <message name="IDS_SETTINGS_TURN_OFF_SYNC_DIALOG_MANAGED_CONFIRM" desc="The text to display on the confirm button of the dialog to turn off sync, when the profile is managed by admin."> - Clear and continue - </message> - <message name="IDS_SETTINGS_TURN_OFF_SYNC_DIALOG_CHECKBOX" desc="The text to display next to the checkbox of the dialog to turn off sync, asking users if they want to clear these data from the device."> - Clear bookmarks, history, passwords, and more from this device - </message> - <message name="IDS_SETTINGS_SYNC_SETTINGS_SAVED_TOAST_LABEL" desc="The notification shown to user after they saved sync settings, and sync is now started."> - Settings saved. Sync started. - </message> </if> <message name="IDS_SETTINGS_SYNC_OVERVIEW" desc="The message that appears in the options dialog when sync has not been set up by the user."> @@ -4293,20 +4291,18 @@ <message name="IDS_SETTINGS_SYNC_LOADING" desc="The message shown when waiting for the sync backend to start up."> Please wait... </message> - <if expr="not chromeos"> - <message name="IDS_SETTINGS_SYNC_WILL_START" desc="The message to tell users that sync will start once they leave the sync setup page."> - Sync will start once you leave sync settings - </message> - <message name="IDS_SETTINGS_SYNC_SETTINGS_CANCEL_SYNC" desc="The label of button that allows user to cancel sync."> - Cancel sync - </message> - <message name="IDS_SETTINGS_SYNC_SETUP_CANCEL_DIALOG_TITLE" desc="The title of the dialog to confirm the sync cancellation."> - Cancel sync? - </message> - <message name="IDS_SETTINGS_SYNC_SETUP_CANCEL_DIALOG_BODY" desc="The body text of the dialog to confirm the sync cancellation."> - You can turn on sync anytime in settings - </message> - </if> + <message name="IDS_SETTINGS_SYNC_WILL_START" desc="The message to tell users that sync will start once they leave the sync setup page."> + Sync will start once you leave sync settings + </message> + <message name="IDS_SETTINGS_SYNC_SETTINGS_CANCEL_SYNC" desc="The label of button that allows user to cancel sync."> + Cancel sync + </message> + <message name="IDS_SETTINGS_SYNC_SETUP_CANCEL_DIALOG_TITLE" desc="The title of the dialog to confirm the sync cancellation."> + Cancel sync? + </message> + <message name="IDS_SETTINGS_SYNC_SETUP_CANCEL_DIALOG_BODY" desc="The body text of the dialog to confirm the sync cancellation."> + You can turn on sync anytime in settings + </message> <message name="IDS_SETTINGS_SYNC_TIMEOUT" desc="Text explaining what to do if sync times out."> Check your internet connection. If the problem continues, try signing out and signing in again. </message>
diff --git a/chrome/app/vector_icons/BUILD.gn b/chrome/app/vector_icons/BUILD.gn index b43f94be4..4935e7a1 100644 --- a/chrome/app/vector_icons/BUILD.gn +++ b/chrome/app/vector_icons/BUILD.gn
@@ -23,7 +23,6 @@ "blocked_redirect.icon", "bluetooth.icon", "browser_tools.icon", - "browser_tools_animated.icon", "browser_tools_error.icon", "browser_tools_update.icon", "caret_down.icon",
diff --git a/chrome/app/vector_icons/browser_tools_animated.icon b/chrome/app/vector_icons/browser_tools_animated.icon deleted file mode 100644 index bd94e1af..0000000 --- a/chrome/app/vector_icons/browser_tools_animated.icon +++ /dev/null
@@ -1,200 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -CANVAS_DIMENSIONS, 32, - -// Top dot. -TRANSITION_FROM, -TRANSITION_FROM, -MOVE_TO, 16, 9, -CUBIC_TO, 17.66f, 9, 19, 7.66f, 19, 6, -CUBIC_TO, 19, 4.34f, 17.66f, 3, 16, 3, -R_H_LINE_TO, 0, -CUBIC_TO, 14.34f, 3, 13, 4.34f, 13, 6, -CUBIC_TO, 13, 7.66f, 14.34f, 9, 16, 9, - -TRANSITION_TO, -MOVE_TO, 21.65f, 8, -CUBIC_TO, 22.76f, 8, 23.65f, 6.66f, 23.65f, 6, -CUBIC_TO, 23.65f, 5.34f, 22.76f, 4, 21.65f, 4, -R_H_LINE_TO, -11.29f, -CUBIC_TO, 9.24f, 4, 8.35f, 5.34f, 8.35f, 6, -CUBIC_TO, 8.35f, 6.66f, 9.24f, 8, 10.35f, 8, -TRANSITION_END, 133, 150, gfx::Tween::FAST_OUT_SLOW_IN, - -TRANSITION_TO, -MOVE_TO, 16, 9, -CUBIC_TO, 17.66f, 9, 19, 7.66f, 19, 6, -CUBIC_TO, 19, 4.34f, 17.66f, 3, 16, 3, -R_H_LINE_TO, 0, -CUBIC_TO, 14.34f, 3, 13, 4.34f, 13, 6, -CUBIC_TO, 13, 7.66f, 14.34f, 9, 16, 9, -TRANSITION_END, 416, 533, gfx::Tween::FAST_OUT_SLOW_IN, - -CLOSE, -NEW_PATH, - -// Middle dot. -TRANSITION_FROM, -TRANSITION_FROM, -MOVE_TO, 16, 19, -CUBIC_TO, 17.66f, 19, 19, 17.66f, 19, 16, -CUBIC_TO, 19, 14.34f, 17.66f, 13, 16, 13, -R_H_LINE_TO, 0, -CUBIC_TO, 14.34f, 13, 13, 14.34f, 13, 16, -CUBIC_TO, 13, 17.66f, 14.34f, 19, 16, 19, - -TRANSITION_TO, -MOVE_TO, 21.65f, 18, -CUBIC_TO, 22.76f, 18, 23.65f, 16.66f, 23.65f, 16, -CUBIC_TO, 23.65f, 15.34f, 22.76f, 14, 21.65f, 14, -R_H_LINE_TO, -11.29f, -CUBIC_TO, 9.24f, 14, 8.35f, 15.34f, 8.35f, 16, -CUBIC_TO, 8.35f, 16.66f, 9.24f, 18, 10.35f, 18, -TRANSITION_END, 67, 150, gfx::Tween::FAST_OUT_SLOW_IN, - -TRANSITION_TO, -MOVE_TO, 16, 19, -CUBIC_TO, 17.66f, 19, 19, 17.66f, 19, 16, -CUBIC_TO, 19, 14.34f, 17.66f, 13, 16, 13, -R_H_LINE_TO, 0, -CUBIC_TO, 14.34f, 13, 13, 14.34f, 13, 16, -CUBIC_TO, 13, 17.66f, 14.34f, 19, 16, 19, -TRANSITION_END, 350, 383, gfx::Tween::FAST_OUT_SLOW_IN, - -CLOSE, -NEW_PATH, - -// Bottom dot. -TRANSITION_FROM, -TRANSITION_FROM, -MOVE_TO, 16, 29, -CUBIC_TO, 17.66f, 29, 19, 27.66f, 19, 26, -CUBIC_TO, 19, 24.34f, 17.66f, 23, 16, 23, -R_H_LINE_TO, 0, -CUBIC_TO, 14.34f, 23, 13, 24.34f, 13, 26, -CUBIC_TO, 13, 27.66f, 14.34f, 29, 16, 29, - -TRANSITION_TO, -MOVE_TO, 21.65f, 28, -CUBIC_TO, 22.76f, 28, 23.65f, 26.66f, 23.65f, 26, -CUBIC_TO, 23.65f, 25.34f, 22.76f, 24, 21.65f, 24, -R_H_LINE_TO, -11.29f, -CUBIC_TO, 9.24f, 24, 8.35f, 25.34f, 8.35f, 26, -CUBIC_TO, 8.35f, 26.66f, 9.24f, 28, 10.35f, 28, -TRANSITION_END, 0, 150, gfx::Tween::FAST_OUT_SLOW_IN, - -TRANSITION_TO, -MOVE_TO, 16, 29, -CUBIC_TO, 17.66f, 29, 19, 27.66f, 19, 26, -CUBIC_TO, 19, 24.34f, 17.66f, 23, 16, 23, -R_H_LINE_TO, 0, -CUBIC_TO, 14.34f, 23, 13, 24.34f, 13, 26, -CUBIC_TO, 13, 27.66f, 14.34f, 29, 16, 29, -TRANSITION_END, 283, 400, gfx::Tween::FAST_OUT_SLOW_IN, - -CLOSE, - -CANVAS_DIMENSIONS, 16, - -// Top dot. -TRANSITION_FROM, -TRANSITION_FROM, -MOVE_TO, 7, 3.5f, -CUBIC_TO, 7, 2.67f, 7.67f, 2, 8.5f, 2, -R_H_LINE_TO, 0, -CUBIC_TO, 9.33f, 2, 10, 2.67f, 10, 3.5f, -CUBIC_TO, 10, 4.33f, 9.33f, 5, 8.5f, 5, -R_H_LINE_TO, 0, -CUBIC_TO, 7.67f, 5, 7, 4.33f, 7, 3.5f, - -TRANSITION_TO, -MOVE_TO, 4.68f, 3.5f, -CUBIC_TO, 4.68f, 2.95f, 5.13f, 2.5f, 5.68f, 2.5f, -R_H_LINE_TO, 5.65f, -CUBIC_TO, 11.87f, 2.5f, 12.32f, 2.95f, 12.32f, 3.5f, -CUBIC_TO, 12.32f, 4.05f, 11.87f, 4.5f, 11.32f, 4.5f, -R_H_LINE_TO, -5.65f, -CUBIC_TO, 5.13f, 4.5f, 4.68f, 4.05f, 4.68f, 2.5f, -TRANSITION_END, 133, 150, gfx::Tween::FAST_OUT_SLOW_IN, - -TRANSITION_TO, -MOVE_TO, 7, 3.5f, -CUBIC_TO, 7, 2.67f, 7.67f, 2, 8.5f, 2, -R_H_LINE_TO, 0, -CUBIC_TO, 9.33f, 2, 10, 2.67f, 10, 3.5f, -CUBIC_TO, 10, 4.33f, 9.33f, 5, 8.5f, 5, -R_H_LINE_TO, 0, -CUBIC_TO, 7.67f, 5, 7, 4.33f, 7, 3.5f, -TRANSITION_END, 416, 533, gfx::Tween::FAST_OUT_SLOW_IN, - -CLOSE, -NEW_PATH, - -// Middle dot. -TRANSITION_FROM, -TRANSITION_FROM, -MOVE_TO, 7, 8.5f, -CUBIC_TO, 7, 7.67f, 7.67f, 7, 8.5f, 7, -R_H_LINE_TO, 0, -CUBIC_TO, 9.33f, 7, 10, 7.67f, 10, 8.5f, -CUBIC_TO, 10, 9.33f, 9.33f, 10, 8.5f, 10, -R_H_LINE_TO, 0, -CUBIC_TO, 7.67f, 10, 7, 9.33f, 7, 8.5f, - -TRANSITION_TO, -MOVE_TO, 4.68f, 8.5f, -CUBIC_TO, 4.68f, 7.95f, 5.13f, 7.5f, 5.68f, 7.5f, -R_H_LINE_TO, 5.65f, -CUBIC_TO, 11.87f, 7.5f, 12.32f, 7.95f, 12.32f, 8.5f, -CUBIC_TO, 12.32f, 9.05f, 11.87f, 9.5f, 11.32f, 9.5f, -R_H_LINE_TO, -5.65f, -CUBIC_TO, 5.13f, 9.5f, 4.68f, 9.05f, 4.68f, 7.5f, -TRANSITION_END, 67, 150, gfx::Tween::FAST_OUT_SLOW_IN, - -TRANSITION_TO, -MOVE_TO, 7, 8.5f, -CUBIC_TO, 7, 7.67f, 7.67f, 7, 8.5f, 7, -R_H_LINE_TO, 0, -CUBIC_TO, 9.33f, 7, 10, 7.67f, 10, 8.5f, -CUBIC_TO, 10, 9.33f, 9.33f, 10, 8.5f, 10, -R_H_LINE_TO, 0, -CUBIC_TO, 7.67f, 10, 7, 9.33f, 7, 8.5f, -TRANSITION_END, 350, 383, gfx::Tween::FAST_OUT_SLOW_IN, - -CLOSE, -NEW_PATH, - -// Bottom dot. -TRANSITION_FROM, -TRANSITION_FROM, -MOVE_TO, 7, 13.5f, -CUBIC_TO, 7, 12.67f, 7.67f, 12, 8.5f, 12, -R_H_LINE_TO, 0, -CUBIC_TO, 9.33f, 12, 10, 12.67f, 10, 13.5f, -CUBIC_TO, 10, 14.33f, 9.33f, 15, 8.5f, 15, -R_H_LINE_TO, 0, -CUBIC_TO, 7.67f, 15, 7, 14.33f, 7, 13.5f, - -TRANSITION_TO, -MOVE_TO, 4.68f, 13.5f, -CUBIC_TO, 4.68f, 12.95f, 5.13f, 12.5f, 5.68f, 12.5f, -R_H_LINE_TO, 5.65f, -CUBIC_TO, 11.87f, 12.5f, 12.32f, 12.95f, 12.32f, 13.5f, -CUBIC_TO, 12.32f, 14.05f, 11.87f, 14.5f, 11.32f, 14.5f, -R_H_LINE_TO, -5.65f, -CUBIC_TO, 5.13f, 14.5f, 4.68f, 14.05f, 4.68f, 12.5f, -TRANSITION_END, 0, 150, gfx::Tween::FAST_OUT_SLOW_IN, - -TRANSITION_TO, -MOVE_TO, 7, 13.5f, -CUBIC_TO, 7, 12.67f, 7.67f, 12, 8.5f, 12, -R_H_LINE_TO, 0, -CUBIC_TO, 9.33f, 12, 10, 12.67f, 10, 13.5f, -CUBIC_TO, 10, 14.33f, 9.33f, 15, 8.5f, 15, -R_H_LINE_TO, 0, -CUBIC_TO, 7.67f, 15, 7, 14.33f, 7, 13.5f, -TRANSITION_END, 283, 400, gfx::Tween::FAST_OUT_SLOW_IN, - -CLOSE
diff --git a/chrome/browser/chromeos/chrome_content_browser_client_chromeos_part.cc b/chrome/browser/chromeos/chrome_content_browser_client_chromeos_part.cc index 8ff38bc..951f986f 100644 --- a/chrome/browser/chromeos/chrome_content_browser_client_chromeos_part.cc +++ b/chrome/browser/chromeos/chrome_content_browser_client_chromeos_part.cc
@@ -15,7 +15,6 @@ #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.h" #include "chrome/common/webui_url_constants.h" -#include "chromeos/constants/chromeos_features.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/render_view_host.h" @@ -98,10 +97,6 @@ void OverrideFontSize(content::WebContents* contents, content::WebPreferences* web_prefs) { DCHECK(contents); - // Prior to SplitSettings, system UI font size follows browser font size. - if (!chromeos::features::IsSplitSettingsEnabled()) - return; - // Check the URL because |contents| may not yet be associated with a window, // SettingsWindowManager, etc. GURL url = GetURL(contents);
diff --git a/chrome/browser/extensions/api/preference/preference_api.cc b/chrome/browser/extensions/api/preference/preference_api.cc index f961cdd..c7a9349 100644 --- a/chrome/browser/extensions/api/preference/preference_api.cc +++ b/chrome/browser/extensions/api/preference/preference_api.cc
@@ -41,6 +41,7 @@ #include "extensions/browser/extensions_browser_client.h" #include "extensions/browser/pref_names.h" #include "extensions/common/error_utils.h" +#include "extensions/common/extension_id.h" #include "extensions/common/permissions/api_permission.h" #include "extensions/common/permissions/permissions_data.h" #include "media/media_buildflags.h"
diff --git a/chrome/browser/extensions/chrome_app_sorting.h b/chrome/browser/extensions/chrome_app_sorting.h index 463d0db3..949d3bf 100644 --- a/chrome/browser/extensions/chrome_app_sorting.h +++ b/chrome/browser/extensions/chrome_app_sorting.h
@@ -15,7 +15,7 @@ #include "components/sync/model/string_ordinal.h" #include "extensions/browser/app_sorting.h" #include "extensions/browser/extension_prefs.h" -#include "extensions/common/extension.h" +#include "extensions/common/extension_id.h" namespace extensions {
diff --git a/chrome/browser/extensions/chrome_app_sorting_unittest.cc b/chrome/browser/extensions/chrome_app_sorting_unittest.cc index b60f60c..f29144f 100644 --- a/chrome/browser/extensions/chrome_app_sorting_unittest.cc +++ b/chrome/browser/extensions/chrome_app_sorting_unittest.cc
@@ -10,6 +10,8 @@ #include "components/crx_file/id_util.h" #include "components/sync/model/string_ordinal.h" #include "extensions/common/constants.h" +#include "extensions/common/extension.h" +#include "extensions/common/extension_id.h" #include "extensions/common/manifest_constants.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/extensions/extension_message_bubble_controller.cc b/chrome/browser/extensions/extension_message_bubble_controller.cc index f1ed3d8c..197ea802 100644 --- a/chrome/browser/extensions/extension_message_bubble_controller.cc +++ b/chrome/browser/extensions/extension_message_bubble_controller.cc
@@ -21,6 +21,7 @@ #include "components/strings/grit/components_strings.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_system.h" +#include "extensions/common/extension.h" #include "ui/base/l10n/l10n_util.h" namespace extensions {
diff --git a/chrome/browser/extensions/extension_message_bubble_controller.h b/chrome/browser/extensions/extension_message_bubble_controller.h index bb25bf4..bafc554 100644 --- a/chrome/browser/extensions/extension_message_bubble_controller.h +++ b/chrome/browser/extensions/extension_message_bubble_controller.h
@@ -15,14 +15,14 @@ #include "extensions/browser/browser_context_keyed_api_factory.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" -#include "extensions/common/extension.h" +#include "extensions/common/extension_id.h" class Browser; class ToolbarActionsModel; class Profile; namespace extensions { - +class Extension; class ExtensionService; class ExtensionMessageBubbleController : public BrowserListObserver,
diff --git a/chrome/browser/extensions/install_verifier.cc b/chrome/browser/extensions/install_verifier.cc index 96659327..85701c47 100644 --- a/chrome/browser/extensions/install_verifier.cc +++ b/chrome/browser/extensions/install_verifier.cc
@@ -32,6 +32,8 @@ #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/pref_names.h" +#include "extensions/common/extension.h" +#include "extensions/common/extension_id.h" #include "extensions/common/extension_set.h" #include "extensions/common/manifest.h" #include "extensions/common/manifest_url_handlers.h"
diff --git a/chrome/browser/extensions/install_verifier.h b/chrome/browser/extensions/install_verifier.h index f09653ca..727a74b 100644 --- a/chrome/browser/extensions/install_verifier.h +++ b/chrome/browser/extensions/install_verifier.h
@@ -15,14 +15,13 @@ #include "base/memory/weak_ptr.h" #include "components/keyed_service/core/keyed_service.h" #include "extensions/browser/management_policy.h" -#include "extensions/common/extension.h" namespace content { class BrowserContext; } namespace extensions { - +class Extension; class ExtensionPrefs; class InstallSigner; struct InstallSignature;
diff --git a/chrome/browser/extensions/service_worker_apitest.cc b/chrome/browser/extensions/service_worker_apitest.cc index 2a70d38..2742d46 100644 --- a/chrome/browser/extensions/service_worker_apitest.cc +++ b/chrome/browser/extensions/service_worker_apitest.cc
@@ -1181,9 +1181,8 @@ // Tests that updating a packed extension with modified scripts works // properly -- we expect that the new script will execute, rather than the // previous one. -// Flaky on all platforms: https://crbug.com/1003244 IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTest, - DISABLED_UpdatePackedExtension) { + UpdatePackedExtension) { constexpr char kManifest1[] = R"({ "name": "Test Extension",
diff --git a/chrome/browser/resources/chromeos/camera/src/js/externs/BUILD.gn b/chrome/browser/resources/chromeos/camera/src/js/externs/BUILD.gn index e414990..7db53ba 100644 --- a/chrome/browser/resources/chromeos/camera/src/js/externs/BUILD.gn +++ b/chrome/browser/resources/chromeos/camera/src/js/externs/BUILD.gn
@@ -9,3 +9,9 @@ externs_list = [ "chrome_platform_analytics.js" ] } + +js_library("w3c_fileapi") { + sources = [] + + externs_list = [ "w3c_fileapi.js" ] +}
diff --git a/chrome/browser/resources/chromeos/camera/src/js/externs/w3c_fileapi.js b/chrome/browser/resources/chromeos/camera/src/js/externs/w3c_fileapi.js new file mode 100644 index 0000000..168113a --- /dev/null +++ b/chrome/browser/resources/chromeos/camera/src/js/externs/w3c_fileapi.js
@@ -0,0 +1,16 @@ +// Copyright 2020 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. + +// TODO(inker): Put it to the externs/browser/w3c_fileapi.js of the upstream +// Closure Compiler, uprev the one bundled in Chromium repo, and remove the +// definition here. + +/* eslint-disable valid-jsdoc */ + +/** + * @see http://www.w3.org/TR/FileAPI/#arraybuffer-method-algo + * @return {!Promise<!ArrayBuffer>} + * @nosideeffects + */ +Blob.prototype.arrayBuffer = function() {};
diff --git a/chrome/browser/resources/chromeos/camera/src/js/models/BUILD.gn b/chrome/browser/resources/chromeos/camera/src/js/models/BUILD.gn index 2e74d1e6..deb5bd2 100644 --- a/chrome/browser/resources/chromeos/camera/src/js/models/BUILD.gn +++ b/chrome/browser/resources/chromeos/camera/src/js/models/BUILD.gn
@@ -36,5 +36,6 @@ ] deps = [ "..:intent", + "../externs:w3c_fileapi", ] }
diff --git a/chrome/browser/resources/chromeos/camera/src/js/models/file_video_saver.js b/chrome/browser/resources/chromeos/camera/src/js/models/file_video_saver.js index 91a724e..0395caac 100644 --- a/chrome/browser/resources/chromeos/camera/src/js/models/file_video_saver.js +++ b/chrome/browser/resources/chromeos/camera/src/js/models/file_video_saver.js
@@ -2,23 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -'use strict'; - -/** - * Namespace for the Camera app. - */ -var cca = cca || {}; - -/** - * Namespace for models. - */ -cca.models = cca.models || {}; +// eslint-disable-next-line no-unused-vars +import {VideoSaver} from './video_saver_interface.js'; /** * Used to save captured video. - * @implements {cca.models.VideoSaver} + * @implements {VideoSaver} */ -cca.models.FileVideoSaver = class { +export class FileVideoSaver { /** * @param {!FileEntry} file * @param {!FileWriter} writer @@ -68,11 +59,14 @@ * Creates FileVideoSaver. * @param {!FileEntry} file The file which FileVideoSaver saves the result * video into. - * @return {!Promise<!cca.models.FileVideoSaver>} + * @return {!Promise<!FileVideoSaver>} */ static async create(file) { const writer = await new Promise( (resolve, reject) => file.createWriter(resolve, reject)); - return new cca.models.FileVideoSaver(file, writer); + return new FileVideoSaver(file, writer); } -}; +} + +/** @const */ +cca.models.FileVideoSaver = FileVideoSaver;
diff --git a/chrome/browser/resources/chromeos/camera/src/js/models/intent_video_saver.js b/chrome/browser/resources/chromeos/camera/src/js/models/intent_video_saver.js index d7c5e91..992ce40 100644 --- a/chrome/browser/resources/chromeos/camera/src/js/models/intent_video_saver.js +++ b/chrome/browser/resources/chromeos/camera/src/js/models/intent_video_saver.js
@@ -2,37 +2,31 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -'use strict'; - -/** - * Namespace for the Camera app. - */ -var cca = cca || {}; - -/** - * Namespace for models. - */ -cca.models = cca.models || {}; +import {Intent} from '../intent.js'; // eslint-disable-line no-unused-vars +import {FileVideoSaver} from './file_video_saver.js'; +import {createPrivateTempVideoFile} from './filesystem.js'; +// eslint-disable-next-line no-unused-vars +import {VideoSaver} from './video_saver_interface.js'; /** * Used to save captured video into a preview file and forward to intent result. - * @implements {cca.models.VideoSaver} + * @implements {VideoSaver} */ -cca.models.IntentVideoSaver = class { +export class IntentVideoSaver { /** - * @param {!cca.intent.Intent} intent - * @param {!cca.models.FileVideoSaver} fileSaver + * @param {!Intent} intent + * @param {!FileVideoSaver} fileSaver * @private */ constructor(intent, fileSaver) { /** - * @const {!cca.intent.Intent} intent + * @const {!Intent} intent * @private */ this.intent_ = intent; /** - * @const {!cca.models.FileVideoSaver} + * @const {!FileVideoSaver} * @private */ this.fileSaver_ = fileSaver; @@ -56,12 +50,15 @@ /** * Creates IntentVideoSaver. - * @param {!cca.intent.Intent} intent - * @return {!Promise<!cca.models.IntentVideoSaver>} + * @param {!Intent} intent + * @return {!Promise<!IntentVideoSaver>} */ static async create(intent) { - const tmpFile = await cca.models.FileSystem.createPrivateTempVideoFile(); - const fileSaver = await cca.models.FileVideoSaver.create(tmpFile); - return new cca.models.IntentVideoSaver(intent, fileSaver); + const tmpFile = await createPrivateTempVideoFile(); + const fileSaver = await FileVideoSaver.create(tmpFile); + return new IntentVideoSaver(intent, fileSaver); } -}; +} + +/** @const */ +cca.models.IntentVideoSaver = IntentVideoSaver;
diff --git a/chrome/browser/resources/chromeos/camera/src/js/models/result_saver.js b/chrome/browser/resources/chromeos/camera/src/js/models/result_saver.js index 976f397..c1fd4eaa4 100644 --- a/chrome/browser/resources/chromeos/camera/src/js/models/result_saver.js +++ b/chrome/browser/resources/chromeos/camera/src/js/models/result_saver.js
@@ -2,23 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -'use strict'; - -/** - * Namespace for the Camera app. - */ -var cca = cca || {}; - -/** - * Namespace for models. - */ -cca.models = cca.models || {}; +// eslint-disable-next-line no-unused-vars +import {VideoSaver} from './video_saver_interface.js'; /** * Handles captured result photos and video. * @interface */ -cca.models.ResultSaver = class { +export class ResultSaver { /** * Saves photo capture result. * @param {!Blob} blob Data of the photo to be added. @@ -29,16 +20,19 @@ /** * Returns a video saver to save captured result video. - * @return {!Promise<!cca.models.VideoSaver>} + * @return {!Promise<!VideoSaver>} */ async startSaveVideo() {} /** * Saves captured video result. - * @param {!cca.models.VideoSaver} video Contains the video result to be + * @param {!VideoSaver} video Contains the video result to be * saved. * @param {string} name Name of the video to be saved. * @return {!Promise} */ async finishSaveVideo(video, name) {} -}; +} + +/** @const */ +cca.models.ResultSaver = ResultSaver;
diff --git a/chrome/browser/resources/chromeos/camera/src/js/models/video_saver_interface.js b/chrome/browser/resources/chromeos/camera/src/js/models/video_saver_interface.js index 7b56956..e52cba8 100644 --- a/chrome/browser/resources/chromeos/camera/src/js/models/video_saver_interface.js +++ b/chrome/browser/resources/chromeos/camera/src/js/models/video_saver_interface.js
@@ -2,23 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -'use strict'; - -/** - * Namespace for the Camera app. - */ -var cca = cca || {}; - -/** - * Namespace for models. - */ -cca.models = cca.models || {}; - /** * Used to save captured video. * @interface */ -cca.models.VideoSaver = class { +export class VideoSaver { /** * Writes video data to result video. * @param {!Blob} blob Video data to be written. @@ -31,4 +19,7 @@ * @return {!Promise<!FileEntry>} Result video file. */ async endWrite() {} -}; +} + +/** @const */ +cca.models.VideoSaver = VideoSaver;
diff --git a/chrome/browser/resources/chromeos/camera/src/js/mojo/device_operator.js b/chrome/browser/resources/chromeos/camera/src/js/mojo/device_operator.js index 2ff8767..a51dd8e 100644 --- a/chrome/browser/resources/chromeos/camera/src/js/mojo/device_operator.js +++ b/chrome/browser/resources/chromeos/camera/src/js/mojo/device_operator.js
@@ -14,7 +14,7 @@ * to the format of input |tag|. * @throws {Error} if entry type is not supported. */ -export function parseMetadataData(entry) { +export function parseMetadata(entry) { const {buffer} = Uint8Array.from(entry.data); switch (entry.type) { case cros.mojom.EntryType.TYPE_BYTE: @@ -60,7 +60,7 @@ for (let i = 0; i < metadata.entryCount; i++) { const entry = metadata.entries[i]; if (entry.tag === tag) { - return parseMetadataData(entry); + return parseMetadata(entry); } } return []; @@ -466,4 +466,4 @@ /** @const */ cca.mojo.DeviceOperator = DeviceOperator; /** @const */ -cca.mojo.parseMetadataData = parseMetadataData; +cca.mojo.parseMetadata = parseMetadata;
diff --git a/chrome/browser/resources/chromeos/camera/src/js/namespace.js b/chrome/browser/resources/chromeos/camera/src/js/namespace.js index a9127785..dbd58c31 100644 --- a/chrome/browser/resources/chromeos/camera/src/js/namespace.js +++ b/chrome/browser/resources/chromeos/camera/src/js/namespace.js
@@ -23,5 +23,7 @@ toast: {}, tooltip: {}, util: {}, - views: {}, + views: { + camera: {}, + }, };
diff --git a/chrome/browser/resources/chromeos/camera/src/js/state.js b/chrome/browser/resources/chromeos/camera/src/js/state.js index 43d78c5..52b3c643 100644 --- a/chrome/browser/resources/chromeos/camera/src/js/state.js +++ b/chrome/browser/resources/chromeos/camera/src/js/state.js
@@ -34,7 +34,7 @@ REVIEW_RESULT: 'review-result', REVIEW_VIDEO_RESULT: 'review-video-result', SAVE_METADATA: 'save-metadata', - SHOULD_HANDLE_INTENT_RESULT: 'should_handle_intent_result', + SHOULD_HANDLE_INTENT_RESULT: 'should-handle-intent-result', SHOW_METADATA: 'show-metadata', SQUARE_PREVIEW: 'square-preview', STREAMING: 'streaming',
diff --git a/chrome/browser/resources/chromeos/camera/src/js/views/camera/layout.js b/chrome/browser/resources/chromeos/camera/src/js/views/camera/layout.js index 8891950..bfd11b1 100644 --- a/chrome/browser/resources/chromeos/camera/src/js/views/camera/layout.js +++ b/chrome/browser/resources/chromeos/camera/src/js/views/camera/layout.js
@@ -2,27 +2,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -'use strict'; +import {assert} from '../../chrome_util.js'; +import * as state from '../../state.js'; +import {Mode, Resolution} from '../../type.js'; +import * as util from '../../util.js'; /** - * Namespace for the Camera app. + * CSS rules. + * @type {!Array<!CSSRule>} */ -var cca = cca || {}; - -/** - * Namespace for views. - */ -cca.views = cca.views || {}; - -/** - * Namespace for Camera view. - */ -cca.views.camera = cca.views.camera || {}; +const cssRules = [].slice.call(document.styleSheets[0].cssRules); /** * Creates a controller to handle layouts of Camera view. */ -cca.views.camera.Layout = class { +export class Layout { /** * @public */ @@ -58,16 +52,15 @@ * @private */ static cssStyle_(selector) { - const rule = cca.views.camera.Layout.cssRules_.find( - (rule) => rule.selectorText === selector); - cca.assert(rule !== undefined); - cca.assert(rule.style !== null); + const rule = cssRules.find((rule) => rule.selectorText === selector); + assert(rule !== undefined); + assert(rule.style !== null); return rule.style; } /** * Updates the video element size for previewing in the window. - * @return {!cca.Resolution} Letterbox size. + * @return {!Resolution} Letterbox size. * @private */ updatePreviewSize_() { @@ -79,7 +72,7 @@ let contentWidth = 0; let contentHeight = 0; if (video.videoHeight) { - const scale = cca.state.get(cca.Mode.SQUARE) ? + const scale = state.get(Mode.SQUARE) ? Math.min(window.innerHeight, window.innerWidth) / Math.min(video.videoHeight, video.videoWidth) : Math.min( @@ -92,9 +85,8 @@ } let viewportW = contentWidth; let viewportH = contentHeight; - cca.state.set( - cca.state.State.SQUARE_PREVIEW, cca.state.get(cca.Mode.SQUARE)); - if (cca.state.get(cca.Mode.SQUARE)) { + state.set(state.State.SQUARE_PREVIEW, state.get(Mode.SQUARE)); + if (state.get(Mode.SQUARE)) { viewportW = viewportH = Math.min(contentWidth, contentHeight); this.squareVideo_.setProperty( 'left', `${(viewportW - contentWidth) / 2}px`); @@ -103,7 +95,7 @@ this.squareViewport_.setProperty('width', `${viewportW}px`); this.squareViewport_.setProperty('height', `${viewportH}px`); } - return new cca.Resolution( + return new Resolution( window.innerWidth - viewportW, window.innerHeight - viewportH); } @@ -111,28 +103,28 @@ * Updates the layout for video-size or window-size changes. */ update() { - const fullWindow = cca.util.isWindowFullSize(); + const fullWindow = util.isWindowFullSize(); const tall = window.innerHeight > window.innerWidth; const tabletLandscape = fullWindow && !tall; - cca.state.set(cca.state.State.TABLET_LANDSCAPE, tabletLandscape); - cca.state.set(cca.state.State.MAX_WND, fullWindow); - cca.state.set(cca.state.State.TALL, tall); + state.set(state.State.TABLET_LANDSCAPE, tabletLandscape); + state.set(state.State.MAX_WND, fullWindow); + state.set(state.State.TALL, tall); const {width: letterboxW, height: letterboxH} = this.updatePreviewSize_(); const isLetterboxW = letterboxH < letterboxW; - cca.state.set(cca.state.State.W_LETTERBOX, isLetterboxW); + state.set(state.State.W_LETTERBOX, isLetterboxW); if (isLetterboxW) { const modeWidth = document.querySelector('#modes-group').getBoundingClientRect().width; let layoutToggled = false; - [[modeWidth + 30, cca.state.State.W_LETTERBOX_S], - [modeWidth + 30 + 72, cca.state.State.W_LETTERBOX_M], - [(modeWidth + 30) * 2, cca.state.State.W_LETTERBOX_L], - [Infinity, cca.state.State.W_LETTERBOX_XL], + [[modeWidth + 30, state.State.W_LETTERBOX_S], + [modeWidth + 30 + 72, state.State.W_LETTERBOX_M], + [(modeWidth + 30) * 2, state.State.W_LETTERBOX_L], + [Infinity, state.State.W_LETTERBOX_XL], ] .forEach( - ([wSize, classname]) => cca.state.set( + ([wSize, classname]) => state.set( classname, /* Enable only state which the letterboxW size falls in range * of its wSize and previous wSize. And disable all other @@ -142,16 +134,10 @@ // preview-vertical-dock: Dock bottom line of preview between gallery and // mode selector. // otherwise: Vertically center the preview. - cca.state.set( - cca.state.State.PREVIEW_VERTICAL_DOCK, letterboxH / 2 >= 112); + state.set(state.State.PREVIEW_VERTICAL_DOCK, letterboxH / 2 >= 112); } } -}; +} -/** - * CSS rules. - * @type {!Array<!CSSRule>} - * @private - */ -cca.views.camera.Layout.cssRules_ = - [].slice.call(document.styleSheets[0].cssRules); +/** @const */ +cca.views.camera.Layout = Layout;
diff --git a/chrome/browser/resources/chromeos/camera/src/js/views/camera/modes.js b/chrome/browser/resources/chromeos/camera/src/js/views/camera/modes.js index 65d91e9..bfdabac 100644 --- a/chrome/browser/resources/chromeos/camera/src/js/views/camera/modes.js +++ b/chrome/browser/resources/chromeos/camera/src/js/views/camera/modes.js
@@ -858,7 +858,7 @@ continue; } - const val = cca.mojo.parseMetadataData(entry); + const val = cca.mojo.parseMetadata(entry); parsedMetadata[key] = val; }
diff --git a/chrome/browser/resources/chromeos/camera/src/js/views/camera/options.js b/chrome/browser/resources/chromeos/camera/src/js/views/camera/options.js index 0b9a0272..51500d27 100644 --- a/chrome/browser/resources/chromeos/camera/src/js/views/camera/options.js +++ b/chrome/browser/resources/chromeos/camera/src/js/views/camera/options.js
@@ -2,34 +2,29 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -'use strict'; - -/** - * Namespace for the Camera app. - */ -var cca = cca || {}; - -/** - * Namespace for views. - */ -cca.views = cca.views || {}; - -/** - * Namespace for Camera view. - */ -cca.views.camera = cca.views.camera || {}; +import {browserProxy} from '../../browser_proxy/browser_proxy.js'; +import {assertInstanceof} from '../../chrome_util.js'; +// eslint-disable-next-line no-unused-vars +import {Camera3DeviceInfo} from '../../device/camera3_device_info.js'; +// eslint-disable-next-line no-unused-vars +import {DeviceInfoUpdater} from '../../device/device_info_updater.js'; +import {ChromeHelper} from '../../mojo/chrome_helper.js'; +import * as nav from '../../nav.js'; +import {PerfEvent} from '../../perf.js'; +import * as state from '../../state.js'; +import * as util from '../../util.js'; /** * Creates a controller for the options of Camera view. */ -cca.views.camera.Options = class { +export class Options { /** - * @param {!cca.device.DeviceInfoUpdater} infoUpdater + * @param {!DeviceInfoUpdater} infoUpdater * @param {!function()} doSwitchDevice Callback to trigger device switching. */ constructor(infoUpdater, doSwitchDevice) { /** - * @type {!cca.device.DeviceInfoUpdater} + * @type {!DeviceInfoUpdater} * @private * @const */ @@ -47,17 +42,16 @@ * @private * @const */ - this.toggleMic_ = - /** @type {!HTMLInputElement} */ ( - document.querySelector('#toggle-mic')); + this.toggleMic_ = assertInstanceof( + document.querySelector('#toggle-mic'), HTMLInputElement); /** * @type {!HTMLInputElement} * @private * @const */ - this.toggleMirror_ = /** @type {!HTMLInputElement} */ ( - document.querySelector('#toggle-mirror')); + this.toggleMirror_ = assertInstanceof( + document.querySelector('#toggle-mirror'), HTMLInputElement); /** * Device id of the camera device currently used or selected. @@ -97,7 +91,7 @@ [['#switch-device', () => this.switchDevice_()], ['#toggle-grid', () => this.animatePreviewGrid_()], - ['#open-settings', () => cca.nav.open('settings')], + ['#open-settings', () => nav.open('settings')], ] .forEach( ([selector, fn]) => @@ -107,16 +101,16 @@ this.toggleMirror_.addEventListener('click', () => this.saveMirroring_()); // Restore saved mirroring states per video device. - cca.proxy.browserProxy.localStorageGet( + browserProxy.localStorageGet( {mirroringToggles: {}}, (values) => this.mirroringToggles_ = values.mirroringToggles); // Remove the deprecated values. - cca.proxy.browserProxy.localStorageRemove( + browserProxy.localStorageRemove( ['effectIndex', 'toggleMulti', 'toggleMirror']); this.infoUpdater_.addDeviceChangeListener(async (updater) => { - cca.state.set( - cca.state.State.MULTI_CAMERA, + state.set( + state.State.MULTI_CAMERA, (await updater.getDevicesInfo()).length >= 2); }); } @@ -134,14 +128,13 @@ * @private */ async switchDevice_() { - if (!cca.state.get(cca.state.State.STREAMING) || - cca.state.get(cca.state.State.TAKING)) { + if (!state.get(state.State.STREAMING) || state.get(state.State.TAKING)) { return; } - cca.state.set(cca.perf.PerfEvent.CAMERA_SWITCHING, true); + state.set(PerfEvent.CAMERA_SWITCHING, true); const devices = await this.infoUpdater_.getDevicesInfo(); - cca.util.animateOnce( - /** @type {!HTMLElement} */ (document.querySelector('#switch-device'))); + util.animateOnce(assertInstanceof( + document.querySelector('#switch-device'), HTMLElement)); let index = devices.findIndex((entry) => entry.deviceId === this.videoDeviceId_); if (index === -1) { @@ -152,8 +145,7 @@ this.videoDeviceId_ = devices[index].deviceId; } const isSuccess = await this.doSwitchDevice_(); - cca.state.set( - cca.perf.PerfEvent.CAMERA_SWITCHING, false, {hasError: !isSuccess}); + state.set(PerfEvent.CAMERA_SWITCHING, false, {hasError: !isSuccess}); } /** @@ -162,7 +154,7 @@ */ animatePreviewGrid_() { Array.from(document.querySelector('#preview-grid').children) - .forEach((grid) => cca.util.animateOnce(grid)); + .forEach((grid) => util.animateOnce(grid)); } /** @@ -206,7 +198,7 @@ enabled = this.mirroringToggles_[this.videoDeviceId_]; } - cca.util.toggleChecked(this.toggleMirror_, enabled); + util.toggleChecked(this.toggleMirror_, enabled); } /** @@ -215,8 +207,7 @@ */ saveMirroring_() { this.mirroringToggles_[this.videoDeviceId_] = this.toggleMirror_.checked; - cca.proxy.browserProxy.localStorageSet( - {mirroringToggles: this.mirroringToggles_}); + browserProxy.localStorageSet({mirroringToggles: this.mirroringToggles_}); } /** @@ -235,7 +226,7 @@ * on HALv1 devices. */ async videoDeviceIds() { - /** @type{!Array<(!cca.device.Camera3DeviceInfo|!MediaDeviceInfo)>} */ + /** @type{!Array<(!Camera3DeviceInfo|!MediaDeviceInfo)>} */ let devices; let facings = null; @@ -251,8 +242,7 @@ devices = await this.infoUpdater_.getDevicesInfo(); } - const defaultFacing = - await cca.mojo.ChromeHelper.getInstance().isTabletMode() ? + const defaultFacing = await ChromeHelper.getInstance().isTabletMode() ? cros.mojom.CameraFacing.CAMERA_FACING_BACK : cros.mojom.CameraFacing.CAMERA_FACING_FRONT; // Put the selected video device id first. @@ -273,4 +263,7 @@ } return sorted; } -}; +} + +/** @const */ +cca.views.camera.Options = Options;
diff --git a/chrome/browser/resources/chromeos/camera/src/js/views/camera/preview.js b/chrome/browser/resources/chromeos/camera/src/js/views/camera/preview.js index 99bdbca..4133a161 100644 --- a/chrome/browser/resources/chromeos/camera/src/js/views/camera/preview.js +++ b/chrome/browser/resources/chromeos/camera/src/js/views/camera/preview.js
@@ -2,27 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -'use strict'; - -/** - * Namespace for the Camera app. - */ -var cca = cca || {}; - -/** - * Namespace for views. - */ -cca.views = cca.views || {}; - -/** - * Namespace for Camera view. - */ -cca.views.camera = cca.views.camera || {}; +import {assertInstanceof} from '../../chrome_util.js'; +import {DeviceOperator, parseMetadata} from '../../mojo/device_operator.js'; +import * as nav from '../../nav.js'; +import * as state from '../../state.js'; +import * as util from '../../util.js'; /** * Creates a controller for the video preview of Camera view. */ -cca.views.camera.Preview = class { +export class Preview { /** * @param {!function()} onNewStreamNeeded Callback to request new stream. */ @@ -38,7 +27,7 @@ * @type {!HTMLVideoElement} * @private */ - this.video_ = cca.assertInstanceof( + this.video_ = assertInstanceof( document.querySelector('#preview-video'), HTMLVideoElement); /** @@ -46,7 +35,7 @@ * @type {!HTMLElement} * @private */ - this.metadata_ = cca.assertInstanceof( + this.metadata_ = assertInstanceof( document.querySelector('#preview-metadata'), HTMLElement); /** @@ -86,8 +75,8 @@ window.addEventListener('resize', () => this.onWindowResize_()); - [cca.state.State.EXPERT, cca.state.State.SHOW_METADATA].forEach((state) => { - cca.state.addObserver(state, this.updateShowMetadata_.bind(this)); + [state.State.EXPERT, state.State.SHOW_METADATA].forEach((s) => { + state.addObserver(s, this.updateShowMetadata_.bind(this)); }); this.video_.cleanup = () => {}; @@ -124,7 +113,7 @@ */ setSource_(stream) { const video = - cca.assertInstanceof(document.createElement('video'), HTMLVideoElement); + assertInstanceof(document.createElement('video'), HTMLVideoElement); video.id = 'preview-video'; video.classList = this.video_.classList; video.muted = true; // Mute to avoid echo from the captured audio. @@ -173,7 +162,7 @@ }, 100); this.stream_ = stream; this.updateShowMetadata_(); - cca.state.set(cca.state.State.STREAMING, true); + state.set(state.State.STREAMING, true); }); } @@ -191,7 +180,7 @@ this.stream_.getVideoTracks()[0].stop(); this.stream_ = null; } - cca.state.set(cca.state.State.STREAMING, false); + state.set(state.State.STREAMING, false); } /** @@ -199,8 +188,7 @@ * @private */ updateShowMetadata_() { - if (cca.state.get(cca.state.State.EXPERT) && - cca.state.get(cca.state.State.SHOW_METADATA)) { + if (state.get(state.State.EXPERT) && state.get(state.State.SHOW_METADATA)) { this.enableShowMetadata_(); } else { this.disableShowMetadata_(); @@ -347,11 +335,11 @@ if (handler === undefined) { continue; } - handler(cca.mojo.parseMetadataData(entry)); + handler(parseMetadata(entry)); } }; - const deviceOperator = await cca.mojo.DeviceOperator.getInstance(); + const deviceOperator = await DeviceOperator.getInstance(); if (!deviceOperator) { return; } @@ -371,7 +359,7 @@ return; } - const deviceOperator = await cca.mojo.DeviceOperator.getInstance(); + const deviceOperator = await DeviceOperator.getInstance(); if (!deviceOperator) { return; } @@ -397,7 +385,7 @@ clearTimeout(this.resizeWindowTimeout_); this.resizeWindowTimeout_ = null; } - cca.nav.onWindowResized(); + nav.onWindowResized(); // Resize window for changed preview's aspect ratio or restore window size // by the last known window's aspect ratio. @@ -414,10 +402,10 @@ .then(() => { // Resize window by aspect ratio only if it's not maximized or // fullscreen. - if (cca.util.isWindowFullSize()) { + if (util.isWindowFullSize()) { return; } - return cca.util.fitWindow(); + return util.fitWindow(); }); } @@ -472,4 +460,7 @@ this.focus_ = null; document.querySelector('#preview-focus-aim').hidden = true; } -}; +} + +/** @const */ +cca.views.camera.Preview = Preview;
diff --git a/chrome/browser/resources/chromeos/camera/src/js/views/camera/recordtime.js b/chrome/browser/resources/chromeos/camera/src/js/views/camera/recordtime.js index 9ea79c3e..90225fc 100644 --- a/chrome/browser/resources/chromeos/camera/src/js/views/camera/recordtime.js +++ b/chrome/browser/resources/chromeos/camera/src/js/views/camera/recordtime.js
@@ -2,27 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -'use strict'; - -/** - * Namespace for the Camera app. - */ -var cca = cca || {}; - -/** - * Namespace for views. - */ -cca.views = cca.views || {}; - -/** - * Namespace for Camera view. - */ -cca.views.camera = cca.views.camera || {}; +import {speak} from '../../toast.js'; /** * Controller for the record-time of Camera view. */ -cca.views.camera.RecordTime = class { +export class RecordTime { /** * @public */ @@ -87,7 +72,7 @@ * @return {number} Recorded time in 1 minute buckets. */ stop() { - cca.toast.speak('status_msg_recording_stopped'); + speak('status_msg_recording_stopped'); if (this.tickTimeout_) { clearInterval(this.tickTimeout_); this.tickTimeout_ = null; @@ -98,4 +83,7 @@ this.update_(0); return mins; } -}; +} + +/** @const */ +cca.views.camera.RecordTime = RecordTime;
diff --git a/chrome/browser/resources/chromeos/camera/src/js/views/camera/review_result.js b/chrome/browser/resources/chromeos/camera/src/js/views/camera/review_result.js index a57c2c39..3d1b807 100644 --- a/chrome/browser/resources/chromeos/camera/src/js/views/camera/review_result.js +++ b/chrome/browser/resources/chromeos/camera/src/js/views/camera/review_result.js
@@ -2,27 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -'use strict'; - -/** - * Namespace for the Camera app. - */ -var cca = cca || {}; - -/** - * Namespace for views. - */ -cca.views = cca.views || {}; - -/** - * Namespace for Camera view. - */ -cca.views.camera = cca.views.camera || {}; +import {assertInstanceof} from '../../chrome_util.js'; +import * as state from '../../state.js'; +import * as util from '../../util.js'; /** * Creates a controller for reviewing intent result in Camera view. */ -cca.views.camera.ReviewResult = class { +export class ReviewResult { /** * @public */ @@ -31,15 +18,15 @@ * @const {!HTMLImageElement} * @private */ - this.reviewPhotoResult_ = /** @type {!HTMLImageElement} */ ( - document.querySelector('#review-photo-result')); + this.reviewPhotoResult_ = assertInstanceof( + document.querySelector('#review-photo-result'), HTMLImageElement); /** * @const {!HTMLVideoElement} * @private */ - this.reviewVideoResult_ = /** @type {!HTMLVideoElement} */ ( - document.querySelector('#review-video-result')); + this.reviewVideoResult_ = assertInstanceof( + document.querySelector('#review-video-result'), HTMLVideoElement); /** * @const {!HTMLButtonElement} @@ -75,7 +62,7 @@ this.reviewVideoResult_.onended = () => { this.reviewVideoResult_.currentTime = 0; - cca.state.set(cca.state.State.PLAYING_RESULT_VIDEO, false); + state.set(state.State.PLAYING_RESULT_VIDEO, false); }; this.confirmResultButton_.addEventListener( @@ -91,10 +78,10 @@ * @private */ playResultVideo_() { - if (cca.state.get(cca.state.State.PLAYING_RESULT_VIDEO)) { + if (state.get(state.State.PLAYING_RESULT_VIDEO)) { return; } - cca.state.set(cca.state.State.PLAYING_RESULT_VIDEO, true); + state.set(state.State.PLAYING_RESULT_VIDEO, true); if (document.activeElement === this.playResultVideoButton_) { this.confirmResultButton_.focus(); } @@ -114,10 +101,10 @@ } const resolve = this.resolveOpen_; this.resolveOpen_ = null; - cca.state.set(cca.state.State.REVIEW_RESULT, false); - cca.state.set(cca.state.State.REVIEW_PHOTO_RESULT, false); - cca.state.set(cca.state.State.REVIEW_VIDEO_RESULT, false); - cca.state.set(cca.state.State.PLAYING_RESULT_VIDEO, false); + state.set(state.State.REVIEW_RESULT, false); + state.set(state.State.REVIEW_PHOTO_RESULT, false); + state.set(state.State.REVIEW_VIDEO_RESULT, false); + state.set(state.State.PLAYING_RESULT_VIDEO, false); this.reviewPhotoResult_.src = ''; this.reviewVideoResult_.src = ''; resolve(confirmed); @@ -130,10 +117,10 @@ * with the photo result. */ async openPhoto(blob) { - const img = await cca.util.blobToImage(blob); + const img = await util.blobToImage(blob); this.reviewPhotoResult_.src = img.src; - cca.state.set(cca.state.State.REVIEW_PHOTO_RESULT, true); - cca.state.set(cca.state.State.REVIEW_RESULT, true); + state.set(state.State.REVIEW_PHOTO_RESULT, true); + state.set(state.State.REVIEW_RESULT, true); this.confirmResultButton_.focus(); return new Promise((resolve) => { @@ -149,12 +136,15 @@ */ async openVideo(fileEntry) { this.reviewVideoResult_.src = fileEntry.toURL(); - cca.state.set(cca.state.State.REVIEW_VIDEO_RESULT, true); - cca.state.set(cca.state.State.REVIEW_RESULT, true); + state.set(state.State.REVIEW_VIDEO_RESULT, true); + state.set(state.State.REVIEW_RESULT, true); this.confirmResultButton_.focus(); return new Promise((resolve) => { this.resolveOpen_ = resolve; }); } -}; +} + +/** @const */ +cca.views.camera.ReviewResult = ReviewResult;
diff --git a/chrome/browser/resources/chromeos/camera/src/js/views/settings.js b/chrome/browser/resources/chromeos/camera/src/js/views/settings.js index 4b04c8c..16ce54a 100644 --- a/chrome/browser/resources/chromeos/camera/src/js/views/settings.js +++ b/chrome/browser/resources/chromeos/camera/src/js/views/settings.js
@@ -2,45 +2,48 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -'use strict'; - -/** - * Namespace for the Camera app. - */ -var cca = cca || {}; - -/** - * Namespace for views. - */ -cca.views = cca.views || {}; +// eslint-disable-next-line no-unused-vars +import {Camera3DeviceInfo} from '../device/camera3_device_info.js'; +import {PhotoConstraintsPreferrer, // eslint-disable-line no-unused-vars + VideoConstraintsPreferrer, // eslint-disable-line no-unused-vars +} from '../device/constraints_preferrer.js'; +// eslint-disable-next-line no-unused-vars +import {DeviceInfoUpdater} from '../device/device_info_updater.js'; +import * as nav from '../nav.js'; +import * as state from '../state.js'; +import {Resolution, // eslint-disable-line no-unused-vars + ResolutionList, // eslint-disable-line no-unused-vars +} from '../type.js'; +import * as util from '../util.js'; +import {View, ViewName} from './view.js'; /* eslint-disable no-unused-vars */ /** * Object of device id, preferred capture resolution and all * available resolutions for a particular video device. - * @typedef {{prefResol: !cca.Resolution, resols: !cca.ResolutionList}} + * @typedef {{prefResol: !Resolution, resols: !ResolutionList}} */ -cca.views.ResolutionConfig; +let ResolutionConfig; /** * Photo and video resolution configuration for a particular video device. * @typedef {{ * deviceId: string, - * photo: !cca.views.ResolutionConfig, - * video: !cca.views.ResolutionConfig, + * photo: !ResolutionConfig, + * video: !ResolutionConfig, * }} */ -cca.views.DeviceSetting; +let DeviceSetting; /* eslint-enable no-unused-vars */ /** - * Creates the base controller of settings view. + * Base controller of settings view. */ -cca.views.BaseSettings = class extends cca.views.View { +export class BaseSettings extends View { /** - * @param {cca.views.ViewName} name Name of the view. + * @param {ViewName} name Name of the view. * @param {!Object<string, !function(Event=)>=} itemHandlers Click-handlers * mapped by element ids. */ @@ -64,38 +67,35 @@ focus() { this.rootElement_.querySelector('[tabindex]').focus(); } + /** * Opens sub-settings. - * @param {cca.views.ViewName} name Name of settings view. + * @param {ViewName} name Name of settings view. * @private */ openSubSettings(name) { // Dismiss master-settings if sub-settings was dismissed by background // click. - cca.nav.open(name).then((cond) => cond && cond.bkgnd && this.leave(cond)); + nav.open(name).then((cond) => cond && cond.bkgnd && this.leave(cond)); } -}; - +} /** - * Creates the controller of master settings view. + * Controller of master settings view. */ -cca.views.MasterSettings = class extends cca.views.BaseSettings { +export class MasterSettings extends BaseSettings { /** * @public */ constructor() { - super(cca.views.ViewName.SETTINGS, { - 'settings-gridtype': () => - this.openSubSettings(cca.views.ViewName.GRID_SETTINGS), - 'settings-timerdur': () => - this.openSubSettings(cca.views.ViewName.TIMER_SETTINGS), + super(ViewName.SETTINGS, { + 'settings-gridtype': () => this.openSubSettings(ViewName.GRID_SETTINGS), + 'settings-timerdur': () => this.openSubSettings(ViewName.TIMER_SETTINGS), 'settings-resolution': () => - this.openSubSettings(cca.views.ViewName.RESOLUTION_SETTINGS), - 'settings-expert': () => - this.openSubSettings(cca.views.ViewName.EXPERT_SETTINGS), + this.openSubSettings(ViewName.RESOLUTION_SETTINGS), + 'settings-expert': () => this.openSubSettings(ViewName.EXPERT_SETTINGS), 'settings-feedback': () => this.openFeedback(), - 'settings-help': () => cca.util.openHelp(), + 'settings-help': () => util.openHelp(), }); } @@ -118,20 +118,20 @@ const id = 'gfdkimpbcpahaombhbimeihdjnejgicl'; // Feedback extension id. chrome.runtime.sendMessage(id, data); } -}; +} /** - * Creates the controller of resolution settings view. + * Controller of resolution settings view. */ -cca.views.ResolutionSettings = class extends cca.views.BaseSettings { +export class ResolutionSettings extends BaseSettings { /** - * @param {!cca.device.DeviceInfoUpdater} infoUpdater - * @param {!cca.device.PhotoConstraintsPreferrer} photoPreferrer - * @param {!cca.device.VideoConstraintsPreferrer} videoPreferrer + * @param {!DeviceInfoUpdater} infoUpdater + * @param {!PhotoConstraintsPreferrer} photoPreferrer + * @param {!VideoConstraintsPreferrer} videoPreferrer */ constructor(infoUpdater, photoPreferrer, videoPreferrer) { /** - * @param {function(): ?cca.views.DeviceSetting} getSetting + * @param {function(): ?DeviceSetting} getSetting * @param {function(): !HTMLElement} getElement * @param {boolean} isPhoto * @return {!function()} @@ -151,7 +151,7 @@ } } }; - super(cca.views.ViewName.RESOLUTION_SETTINGS, { + super(ViewName.RESOLUTION_SETTINGS, { 'settings-front-photores': createOpenMenuHandler( () => this.frontSetting_, () => this.frontPhotoItem_, true), 'settings-front-videores': createOpenMenuHandler( @@ -163,13 +163,13 @@ }); /** - * @type {!cca.device.PhotoConstraintsPreferrer} + * @type {!PhotoConstraintsPreferrer} * @private */ this.photoPreferrer_ = photoPreferrer; /** - * @type {!cca.device.VideoConstraintsPreferrer} + * @type {!VideoConstraintsPreferrer} * @private */ this.videoPreferrer_ = videoPreferrer; @@ -239,21 +239,21 @@ /** * Device setting of front camera. Null if no front camera. - * @type {?cca.views.DeviceSetting} + * @type {?DeviceSetting} * @private */ this.frontSetting_ = null; /** * Device setting of back camera. Null if no front camera. - * @type {?cca.views.DeviceSetting} + * @type {?DeviceSetting} * @private */ this.backSetting_ = null; /** * Device setting of external cameras. - * @type {!Array<!cca.views.DeviceSetting>} + * @type {!Array<!DeviceSetting>} * @private */ this.externalSettings_ = []; @@ -266,10 +266,10 @@ this.openedSettingDeviceId_ = null; infoUpdater.addDeviceChangeListener(async (updater) => { - /** @type {?Array<!cca.device.Camera3DeviceInfo>} */ + /** @type {?Array<!Camera3DeviceInfo>} */ const devices = await updater.getCamera3DevicesInfo(); if (devices === null) { - cca.state.set(cca.state.State.NO_RESOLUTION_SETTINGS, true); + state.set(state.State.NO_RESOLUTION_SETTINGS, true); return; } @@ -277,10 +277,10 @@ this.externalSettings_ = []; devices.forEach(({deviceId, facing, photoResols, videoResols}) => { - const /** !cca.views.DeviceSetting */ deviceSetting = { + const /** !DeviceSetting */ deviceSetting = { deviceId, photo: { - prefResol: /** @type {!cca.Resolution} */ ( + prefResol: /** @type {!Resolution} */ ( photoPreferrer.getPrefResolution(deviceId)), resols: /* Filter out resolutions of megapixels < 0.1 i.e. megapixels @@ -288,7 +288,7 @@ photoResols.filter((r) => r.area >= 100000), }, video: { - prefResol: /** @type {!cca.Resolution} */ ( + prefResol: /** @type {!Resolution} */ ( videoPreferrer.getPrefResolution(deviceId)), resols: videoResols, }, @@ -318,8 +318,8 @@ /** * Template for generating option text from photo resolution width and height. - * @param {!cca.Resolution} r Resolution of text to be generated. - * @param {!cca.ResolutionList} resolutions All available resolutions. + * @param {!Resolution} r Resolution of text to be generated. + * @param {!ResolutionList} resolutions All available resolutions. * @return {string} Text shown on resolution option item. * @private */ @@ -331,7 +331,7 @@ */ const gcd = (a, b) => (a === 0 ? b : gcd(b % a, a)); /** - * @param {!cca.Resolution} r + * @param {!Resolution} r * @return {number} */ const toMegapixel = (r) => Math.round(r.area / 100000) / 10; @@ -351,7 +351,7 @@ /** * Template for generating option text from video resolution width and height. - * @param {!cca.Resolution} r Resolution of text to be generated. + * @param {!Resolution} r Resolution of text to be generated. * @return {string} Text shown on resolution option item. * @private */ @@ -363,7 +363,7 @@ /** * Finds photo and video resolution setting of target device id. * @param {string} deviceId - * @return {?cca.views.DeviceSetting} + * @return {?DeviceSetting} * @private */ getDeviceSetting_(deviceId) { @@ -384,9 +384,8 @@ /** * @param {!HTMLElement} item * @param {string} id - * @param {!cca.views.ResolutionConfig} config - * @param {!function(!cca.Resolution, !cca.ResolutionList): string} - * optTextTempl + * @param {!ResolutionConfig} config + * @param {!function(!Resolution, !ResolutionList): string} optTextTempl */ const prepItem = (item, id, {prefResol, resols}, optTextTempl) => { item.dataset.deviceId = id; @@ -396,8 +395,7 @@ }; // Update front camera setting - cca.state.set( - cca.state.State.HAS_FRONT_CAMERA, this.frontSetting_ !== null); + state.set(state.State.HAS_FRONT_CAMERA, this.frontSetting_ !== null); if (this.frontSetting_) { const {deviceId, photo, video} = this.frontSetting_; prepItem(this.frontPhotoItem_, deviceId, photo, this.photoOptTextTempl_); @@ -405,7 +403,7 @@ } // Update back camera setting - cca.state.set(cca.state.State.HAS_BACK_CAMERA, this.backSetting_ !== null); + state.set(state.State.HAS_BACK_CAMERA, this.backSetting_ !== null); if (this.backSetting_) { const {deviceId, photo, video} = this.backSetting_; prepItem(this.backPhotoItem_, deviceId, photo, this.photoOptTextTempl_); @@ -441,7 +439,7 @@ if (deviceId !== focusedId) { const extItem = /** @type {!HTMLElement} */ ( document.importNode(this.extcamItemTempl_.content, true)); - cca.util.setupI18nElements(extItem); + util.setupI18nElements(extItem); [titleItem, photoItem, videoItem] = /** @type {!NodeList<!HTMLElement>}*/ ( extItem.querySelectorAll('.menu-item')); @@ -477,21 +475,21 @@ prepItem(videoItem, deviceId, config.video, this.videoOptTextTempl_); }); // Force closing opened setting of unplugged device. - if ((cca.state.get(cca.views.ViewName.PHOTO_RESOLUTION_SETTINGS) || - cca.state.get(cca.views.ViewName.VIDEO_RESOLUTION_SETTINGS)) && + if ((state.get(ViewName.PHOTO_RESOLUTION_SETTINGS) || + state.get(ViewName.VIDEO_RESOLUTION_SETTINGS)) && this.openedSettingDeviceId_ !== null && this.getDeviceSetting_(this.openedSettingDeviceId_) === null) { - cca.nav.close( - cca.state.get(cca.views.ViewName.PHOTO_RESOLUTION_SETTINGS) ? - cca.views.ViewName.PHOTO_RESOLUTION_SETTINGS : - cca.views.ViewName.VIDEO_RESOLUTION_SETTINGS); + nav.close( + state.get(ViewName.PHOTO_RESOLUTION_SETTINGS) ? + ViewName.PHOTO_RESOLUTION_SETTINGS : + ViewName.VIDEO_RESOLUTION_SETTINGS); } } /** * Updates current selected photo resolution. * @param {string} deviceId Device id of the selected resolution. - * @param {!cca.Resolution} resolution Selected resolution. + * @param {!Resolution} resolution Selected resolution. * @private */ updateSelectedPhotoResolution_(deviceId, resolution) { @@ -510,7 +508,7 @@ this.photoOptTextTempl_(photo.prefResol, photo.resols); // Update setting option if it's opened. - if (cca.state.get(cca.views.ViewName.PHOTO_RESOLUTION_SETTINGS) && + if (state.get(ViewName.PHOTO_RESOLUTION_SETTINGS) && this.openedSettingDeviceId_ === deviceId) { this.photoResMenu_ .querySelector( @@ -524,7 +522,7 @@ /** * Updates current selected video resolution. * @param {string} deviceId Device id of the selected resolution. - * @param {!cca.Resolution} resolution Selected resolution. + * @param {!Resolution} resolution Selected resolution. * @private */ updateSelectedVideoResolution_(deviceId, resolution) { @@ -543,7 +541,7 @@ this.videoOptTextTempl_(video.prefResol); // Update setting option if it's opened. - if (cca.state.get(cca.views.ViewName.VIDEO_RESOLUTION_SETTINGS) && + if (state.get(ViewName.VIDEO_RESOLUTION_SETTINGS) && this.openedSettingDeviceId_ === deviceId) { this.videoResMenu_ .querySelector( @@ -556,7 +554,7 @@ /** * Opens photo resolution setting view. - * @param {!cca.views.DeviceSetting} Setting of video device to be opened. + * @param {!DeviceSetting} Setting of video device to be opened. * @param {!HTMLElement} resolItem Dom element from upper layer menu item * showing title of the selected resolution. * @private @@ -567,12 +565,12 @@ resolItem, this.photoResMenu_, this.photoOptTextTempl_, (r) => this.photoPreferrer_.changePreferredResolution(deviceId, r), photo.resols, photo.prefResol); - this.openSubSettings(cca.views.ViewName.PHOTO_RESOLUTION_SETTINGS); + this.openSubSettings(ViewName.PHOTO_RESOLUTION_SETTINGS); } /** * Opens video resolution setting view. - * @param {!cca.views.DeviceSetting} Setting of video device to be opened. + * @param {!DeviceSetting} Setting of video device to be opened. * @param {!HTMLElement} resolItem Dom element from upper layer menu item * showing title of the selected resolution. * @private @@ -583,21 +581,21 @@ resolItem, this.videoResMenu_, this.videoOptTextTempl_, (r) => this.videoPreferrer_.changePreferredResolution(deviceId, r), video.resols, video.prefResol); - this.openSubSettings(cca.views.ViewName.VIDEO_RESOLUTION_SETTINGS); + this.openSubSettings(ViewName.VIDEO_RESOLUTION_SETTINGS); } /** * Updates resolution menu with specified resolutions. * @param {!HTMLElement} resolItem DOM element holding selected resolution. * @param {!HTMLElement} menu Menu holding all resolution option elements. - * @param {!function(!cca.Resolution, !cca.ResolutionList): string} - * optTextTempl Template generating text content for each resolution - * option from its width and height. - * @param {!function(!cca.Resolution)} onChange Called when selected option + * @param {!function(!Resolution, !ResolutionList): string} optTextTempl + * Template generating text content for each resolution option from its + * width and height. + * @param {!function(!Resolution)} onChange Called when selected option * changed with resolution of newly selected option. - * @param {!cca.ResolutionList} resolutions Resolutions of its width and - * height to be updated with. - * @param {!cca.Resolution} selectedR Selected resolution. + * @param {!ResolutionList} resolutions Resolutions of its width and height to + * be updated with. + * @param {!Resolution} selectedR Selected resolution. * @private */ updateMenu_(resolItem, menu, optTextTempl, onChange, resolutions, selectedR) { @@ -620,8 +618,8 @@ inputElement.checked = true; } inputElement.addEventListener('click', (event) => { - if (!cca.state.get(cca.state.State.STREAMING) || - cca.state.get(cca.state.State.TAKING)) { + if (!state.get(state.State.STREAMING) || + state.get(state.State.TAKING)) { event.preventDefault(); } }); @@ -634,4 +632,11 @@ menu.appendChild(item); }); } -}; +} + +/** @const */ +cca.views.BaseSettings = BaseSettings; +/** @const */ +cca.views.MasterSettings = MasterSettings; +/** @const */ +cca.views.ResolutionSettings = ResolutionSettings;
diff --git a/chrome/browser/resources/chromeos/camera/src/views/main.html b/chrome/browser/resources/chromeos/camera/src/views/main.html index 10330ae..9152fee 100644 --- a/chrome/browser/resources/chromeos/camera/src/views/main.html +++ b/chrome/browser/resources/chromeos/camera/src/views/main.html
@@ -29,10 +29,10 @@ <script type="module" src="../js/models/filenamer.js"></script> <script defer src="../js/gallerybutton.js"></script> <script type="module" src="../js/models/filesystem.js"></script> - <script defer src="../js/models/result_saver.js"></script> - <script defer src="../js/models/video_saver_interface.js"></script> - <script defer src="../js/models/file_video_saver.js"></script> - <script defer src="../js/models/intent_video_saver.js"></script> + <script type="module" src="../js/models/result_saver.js"></script> + <script type="module" src="../js/models/video_saver_interface.js"></script> + <script type="module" src="../js/models/file_video_saver.js"></script> + <script type="module" src="../js/models/intent_video_saver.js"></script> <script defer src="../js/mojo/mojo_bindings_lite.js"></script> <script defer src="../js/mojo/camera_metadata_tags.mojom-lite.js"></script> <script defer src="../js/mojo/camera_metadata.mojom-lite.js"></script> @@ -49,15 +49,15 @@ <script type="module" src="../js/views/view.js"></script> <script defer src="../js/views/camera.js"></script> <script defer src="../js/views/camera_intent.js"></script> - <script defer src="../js/views/camera/layout.js"></script> - <script defer src="../js/views/camera/options.js"></script> - <script defer src="../js/views/camera/preview.js"></script> - <script defer src="../js/views/camera/recordtime.js"></script> - <script defer src="../js/views/camera/review_result.js"></script> + <script type="module" src="../js/views/camera/layout.js"></script> + <script type="module" src="../js/views/camera/options.js"></script> + <script type="module" src="../js/views/camera/preview.js"></script> + <script type="module" src="../js/views/camera/recordtime.js"></script> + <script type="module" src="../js/views/camera/review_result.js"></script> <script defer src="../js/views/camera/timertick.js"></script> <script defer src="../js/views/camera/modes.js"></script> <script defer src="../js/views/dialog.js"></script> - <script defer src="../js/views/settings.js"></script> + <script type="module" src="../js/views/settings.js"></script> <script defer src="../js/views/warning.js"></script> <script type="module" src="../js/nav.js"></script> <script defer src="../js/main.js"></script>
diff --git a/chrome/browser/resources/print_preview/ui/advanced_settings_dialog.js b/chrome/browser/resources/print_preview/ui/advanced_settings_dialog.js index 9a19fc7d..4648ca1 100644 --- a/chrome/browser/resources/print_preview/ui/advanced_settings_dialog.js +++ b/chrome/browser/resources/print_preview/ui/advanced_settings_dialog.js
@@ -49,11 +49,11 @@ 'keydown': 'onKeydown_', }, - /** @private {!Array<Node>} */ + /** @private {!Array<!Node>} */ highlights_: [], - /** @private {!Array<Node>} */ - bubbles_: [], + /** @private {!Map<!Node, number>} */ + bubbles_: new Map, /** @private {!MetricsContext} */ metrics_: MetricsContext.printSettingsUi(), @@ -109,11 +109,9 @@ } removeHighlights(this.highlights_); - for (const bubble of this.bubbles_) { - bubble.remove(); - } + this.bubbles_.forEach((number, bubble) => bubble.remove()); this.highlights_ = []; - this.bubbles_ = []; + this.bubbles_.clear(); const listItems = this.shadowRoot.querySelectorAll( 'print-preview-advanced-settings-item'); @@ -122,9 +120,8 @@ const matches = item.hasMatch(this.searchQuery_); item.hidden = !matches; hasMatch = hasMatch || matches; - const result = item.updateHighlighting(this.searchQuery_); - this.highlights_.push(...result.highlights); - this.bubbles_.push(...result.bubbles); + this.highlights_.push( + ...item.updateHighlighting(this.searchQuery_, this.bubbles_)); }); return hasMatch; },
diff --git a/chrome/browser/resources/print_preview/ui/advanced_settings_item.js b/chrome/browser/resources/print_preview/ui/advanced_settings_item.js index 2e61762..d32a56e 100644 --- a/chrome/browser/resources/print_preview/ui/advanced_settings_item.js +++ b/chrome/browser/resources/print_preview/ui/advanced_settings_item.js
@@ -15,7 +15,7 @@ import {Destination, VendorCapability, VendorCapabilitySelectOption} from '../data/destination.js'; import {getStringForCurrentLocale} from '../print_preview_utils.js'; -import {HighlightResults, updateHighlights} from './highlight_utils.js'; +import {updateHighlights} from './highlight_utils.js'; import {SettingsBehavior} from './settings_behavior.js'; Polymer({ @@ -208,10 +208,10 @@ /** * @param {?RegExp} query The current search query. - * @return {!HighlightResults} The highlight wrappers and - * search bubbles that were created. + * @param {!Map<!Node, number>} bubbles + * @return {!Array<!Node>} The highlight wrappers and that were created. */ - updateHighlighting: function(query) { - return updateHighlights(this, query); + updateHighlighting: function(query, bubbles) { + return updateHighlights(this, query, bubbles); }, });
diff --git a/chrome/browser/resources/print_preview/ui/destination_list_item.js b/chrome/browser/resources/print_preview/ui/destination_list_item.js index 1e77869..364e0bc8 100644 --- a/chrome/browser/resources/print_preview/ui/destination_list_item.js +++ b/chrome/browser/resources/print_preview/ui/destination_list_item.js
@@ -17,7 +17,7 @@ import {Destination, DestinationOrigin} from '../data/destination.js'; -import {HighlightResults, updateHighlights} from './highlight_utils.js'; +import {updateHighlights} from './highlight_utils.js'; // <if expr="chromeos"> @@ -128,7 +128,7 @@ updateHighlightsAndHint_: function() { this.updateSearchHint_(); removeHighlights(this.highlights_); - this.highlights_ = this.updateHighlighting_().highlights; + this.highlights_ = updateHighlights(this, this.searchQuery, new Map); }, /** @private */ @@ -143,15 +143,6 @@ }, /** - * @return {!HighlightResults} The highlight wrappers and - * search bubbles that were created. - * @private - */ - updateHighlighting_: function() { - return updateHighlights(this, this.searchQuery); - }, - - /** * @return {string} A tooltip for the extension printer icon. * @private */
diff --git a/chrome/browser/resources/print_preview/ui/highlight_utils.js b/chrome/browser/resources/print_preview/ui/highlight_utils.js index a2668db..7a568dc0 100644 --- a/chrome/browser/resources/print_preview/ui/highlight_utils.js +++ b/chrome/browser/resources/print_preview/ui/highlight_utils.js
@@ -3,41 +3,44 @@ // found in the LICENSE file. import {assert} from 'chrome://resources/js/assert.m.js'; -import {highlight, highlightControlWithBubble} from 'chrome://resources/js/search_highlight_utils.m.js'; - -/** - * @typedef {{ - * highlights: !Array<!Node>, - * bubbles: !Array<!Node> - * }} - */ -export let HighlightResults; +import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; +import {createEmptySearchBubble, highlight, Range, stripDiacritics} from 'chrome://resources/js/search_highlight_utils.m.js'; /** * @param {!HTMLElement} element The element to update. Element should have a * shadow root. * @param {?RegExp} query The current search query - * @return {!HighlightResults} The highlight wrappers and - * search bubbles that were created. + * @param {!Map<!Node, number>} bubbles A map of bubbles created / results found + * so far. + * @return {!Array<!Node>} The highlight wrappers that were created. */ -export function updateHighlights(element, query) { - const result = {highlights: [], bubbles: []}; +export function updateHighlights(element, query, bubbles) { + const highlights = []; if (!query) { - return result; + return highlights; } + assert(query.global); + element.shadowRoot.querySelectorAll('.searchable').forEach(childElement => { childElement.childNodes.forEach(node => { if (node.nodeType !== Node.TEXT_NODE) { return; } - const textContent = node.nodeValue.trim(); - if (textContent.length === 0) { + const textContent = node.nodeValue; + if (textContent.trim().length === 0) { return; } - if (query.test(textContent)) { + const strippedText = stripDiacritics(textContent); + /** @type {!Array<!Range>} */ + const ranges = []; + for (let match; match = query.exec(strippedText);) { + ranges.push({start: match.index, length: match[0].length}); + } + + if (ranges.length > 0) { // Don't highlight <select> nodes, yellow rectangles can't be // displayed within an <option>. if (node.parentNode.nodeName === 'OPTION') { @@ -45,17 +48,24 @@ // Note: The bubble's ::after element, a yellow arrow, will not // appear correctly in print preview without SPv175 enabled. See // https://crbug.com/817058. - const bubble = highlightControlWithBubble( - /** @type {!HTMLElement} */ (assert(node.parentNode.parentNode)), - textContent.match(query)[0], /*horizontallyCenter=*/ true); - if (bubble) { - result.bubbles.push(bubble); - } + // TODO(crbug.com/1038464): turn on horizontallyCenter when we fix + // incorrect positioning caused by scrollbar width changing after + // search finishes. + const bubble = createEmptySearchBubble( + /** @type {!Node} */ (assert(node.parentNode.parentNode)), + /* horizontallyCenter= */ false); + const numHits = ranges.length + (bubbles.get(bubble) || 0); + bubbles.set(bubble, numHits); + const msgName = numHits === 1 ? 'searchResultBubbleText' : + 'searchResultsBubbleText'; + bubble.firstChild.textContent = + loadTimeData.getStringF(msgName, numHits); } else { - result.highlights.push(highlight(node, textContent.split(query))); + highlights.push(highlight(node, ranges)); } } }); }); - return result; + + return highlights; }
diff --git a/chrome/browser/resources/print_preview/ui/print_preview_search_box.js b/chrome/browser/resources/print_preview/ui/print_preview_search_box.js index 3c0e569..69d2cd9 100644 --- a/chrome/browser/resources/print_preview/ui/print_preview_search_box.js +++ b/chrome/browser/resources/print_preview/ui/print_preview_search_box.js
@@ -9,6 +9,7 @@ import './print_preview_shared_css.js'; import {CrSearchFieldBehavior} from 'chrome://resources/cr_elements/cr_search_field/cr_search_field_behavior.m.js'; +import {stripDiacritics} from 'chrome://resources/js/search_highlight_utils.m.js'; import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; /** @type {!RegExp} */ @@ -39,7 +40,7 @@ * The last search query. * @private {string} */ - lastString_: '', + lastQuery_: '', /** @return {!CrInputElement} */ getSearchInput: function() { @@ -55,15 +56,15 @@ * @private */ onSearchChanged_: function(e) { - const safeQueryString = e.detail.trim().replace(SANITIZE_REGEX, '\\$&'); - if (safeQueryString === this.lastString_) { + const strippedQuery = stripDiacritics(e.detail.trim()); + const safeQuery = strippedQuery.replace(SANITIZE_REGEX, '\\$&'); + if (safeQuery === this.lastQuery_) { return; } - this.lastString_ = safeQueryString; - this.searchQuery = safeQueryString.length > 0 ? - new RegExp(`(${safeQueryString})`, 'i') : - null; + this.lastQuery_ = safeQuery; + this.searchQuery = + safeQuery.length > 0 ? new RegExp(`(${safeQuery})`, 'ig') : null; }, /** @private */
diff --git a/chrome/browser/resources/settings/lazy_load.html b/chrome/browser/resources/settings/lazy_load.html index 57ed5ea..7800dbf 100644 --- a/chrome/browser/resources/settings/lazy_load.html +++ b/chrome/browser/resources/settings/lazy_load.html
@@ -23,8 +23,8 @@ <if expr="not chromeos"> <link rel="import" href="people_page/manage_profile.html"> - <link rel="import" href="people_page/sync_account_control.html"> </if> + <link rel="import" href="people_page/sync_account_control.html"> <if expr="use_nss_certs"> <link rel="import" href="chrome://resources/cr_components/certificate_manager/certificate_manager.html">
diff --git a/chrome/browser/resources/settings/os_settings_resources.grd b/chrome/browser/resources/settings/os_settings_resources.grd index b1e64154..dcd5335 100644 --- a/chrome/browser/resources/settings/os_settings_resources.grd +++ b/chrome/browser/resources/settings/os_settings_resources.grd
@@ -903,6 +903,7 @@ file="people_page/sync_controls.html" type="chrome_html" preprocess="true" /> + <!-- TODO(jamescook): Remove when SplitSettingsSync is the default. --> <structure name="IDR_OS_SETTINGS_SYNC_PAGE_JS" file="people_page/sync_page.js" type="chrome_html" @@ -911,6 +912,14 @@ file="people_page/sync_page.html" type="chrome_html" preprocess="true" /> + <structure name="IDR_SETTINGS_PEOPLE_PAGE_SYNC_ACCOUNT_CONTROL_HTML" + file="people_page/sync_account_control.html" + type="chrome_html" + flattenhtml="true" + allowexternalscript="true" /> + <structure name="IDR_SETTINGS_PEOPLE_PAGE_SYNC_ACCOUNT_CONTROL_JS" + file="people_page/sync_account_control.js" + type="chrome_html" /> <structure name="IDR_OS_SETTINGS_SYSTEM_PAGE_BROWSER_PROXY_HTML" file="system_page/system_page_browser_proxy.html" type="chrome_html" />
diff --git a/chrome/browser/resources/settings/people_page/BUILD.gn b/chrome/browser/resources/settings/people_page/BUILD.gn index 8d20748..a394ab3 100644 --- a/chrome/browser/resources/settings/people_page/BUILD.gn +++ b/chrome/browser/resources/settings/people_page/BUILD.gn
@@ -9,6 +9,7 @@ ":people_page", ":profile_info_browser_proxy", ":signout_dialog", + ":sync_account_control", ":sync_browser_proxy", ":sync_page", ] @@ -19,7 +20,6 @@ ":import_data_dialog", ":manage_profile", ":manage_profile_browser_proxy", - ":sync_account_control", ] }
diff --git a/chrome/browser/resources/settings/people_page/sync_account_control.html b/chrome/browser/resources/settings/people_page/sync_account_control.html index eb0fb3a6..f115380 100644 --- a/chrome/browser/resources/settings/people_page/sync_account_control.html +++ b/chrome/browser/resources/settings/people_page/sync_account_control.html
@@ -140,6 +140,8 @@ display: block; } </style> + <!-- TODO(jamescook): Show the promo on Chrome OS if the user is signed-in + but has sync disabled. --> <div id="banner" hidden="[[syncStatus.signedIn]]" part="banner"></div> <div class$="settings-box first [[getPromoHeaderClass_(subLabel_)]]" @@ -191,11 +193,14 @@ </div> </div> </div> +<!-- Chrome OS does not allow switching users for sync. --> +<if expr="not chromeos"> <cr-icon-button class="icon-arrow-dropdown" hidden="[[syncStatus.signedIn]]" on-click="onMenuButtonTap_" id="dropdown-arrow" aria-label="$i18n{useAnotherAccount}"> </cr-icon-button> <div class="separator" hidden="[[syncStatus.signedIn]]"></div> +</if> <cr-button id="sync-button" class="action-button" hidden="[[syncStatus.signedIn]]" on-click="onSyncButtonTap_" disabled="[[shouldDisableSyncButton_(showSetupButtons_, @@ -224,6 +229,8 @@ </cr-button> </div> </div> +<!-- Chrome OS does not allow switching users for sync. --> +<if expr="not chromeos"> <template is="dom-if" if="[[!syncStatus.signedIn]]" restamp> <cr-action-menu id="menu" auto-reposition role-description="$i18n{menu}"> @@ -247,6 +254,7 @@ </button> </cr-action-menu> </template> +</if> </template> </template> <script src="sync_account_control.js"></script>
diff --git a/chrome/browser/resources/settings/people_page/sync_browser_proxy.js b/chrome/browser/resources/settings/people_page/sync_browser_proxy.js index 34f3a96..91e7240 100644 --- a/chrome/browser/resources/settings/people_page/sync_browser_proxy.js +++ b/chrome/browser/resources/settings/people_page/sync_browser_proxy.js
@@ -132,6 +132,7 @@ * Invalidates the Sync token without signing the user out. */ pauseSync() {} + // </if> /** * @return {number} the number of times the sync account promo was shown. @@ -143,8 +144,6 @@ */ incrementPromoImpressionCount() {} - // </if> - // <if expr="chromeos"> /** * Signs the user out. @@ -239,6 +238,7 @@ pauseSync() { chrome.send('SyncSetupPauseSync'); } + // </if> /** @override */ getPromoImpressionCount() { @@ -254,7 +254,6 @@ (this.getPromoImpressionCount() + 1).toString()); } - // </if> // <if expr="chromeos"> /** @override */ attemptUserExit() {
diff --git a/chrome/browser/resources/settings/people_page/sync_page.html b/chrome/browser/resources/settings/people_page/sync_page.html index 74b11b8..aa881290 100644 --- a/chrome/browser/resources/settings/people_page/sync_page.html +++ b/chrome/browser/resources/settings/people_page/sync_page.html
@@ -13,6 +13,7 @@ <link rel="import" href="chrome://resources/cr_elements/shared_style_css.html"> <link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html"> <link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html"> +<link rel="import" href="sync_account_control.html"> <link rel="import" href="sync_browser_proxy.html"> <link rel="import" href="../privacy_page/personalization_options.html"> <link rel="import" href="../route.html"> @@ -20,7 +21,6 @@ <link rel="import" href="../settings_vars_css.html"> <if expr="not chromeos"> -<link rel="import" href="sync_account_control.html"> <link rel="import" href="chrome://resources/cr_elements/cr_toast/cr_toast.html"> </if> @@ -81,7 +81,6 @@ width: 40px; } -<if expr="not chromeos"> #toast { left: 0; z-index: 1; @@ -91,9 +90,7 @@ left: auto; right: 0; } -</if> </style> -<if expr="not chromeos"> <template is="dom-if" if="[[shouldShowSyncAccountControl_( syncStatus.syncSystemEnabled, syncStatus.signinAllowed)]]"> <settings-sync-account-control embedded-in-subpage @@ -105,7 +102,6 @@ on-sync-setup-done="onSyncSetupDone_"> </settings-sync-account-control> </template> -</if> <div class="settings-box first" hidden="[[!syncDisabledByAdmin_]]"> <iron-icon id="disabled-by-admin-icon" icon="cr20:domain"></iron-icon> <div class="middle settings-box-text">
diff --git a/chrome/browser/resources/settings/people_page/sync_page.js b/chrome/browser/resources/settings/people_page/sync_page.js index 7497011..80b678c 100644 --- a/chrome/browser/resources/settings/people_page/sync_page.js +++ b/chrome/browser/resources/settings/people_page/sync_page.js
@@ -562,16 +562,19 @@ return this.syncPrefs.encryptAllData ? 'three-line' : 'two-line'; }, - // <if expr="not chromeos"> /** * @return {boolean} * @private */ shouldShowSyncAccountControl_: function() { + // <if expr="chromeos"> + if (!loadTimeData.getBoolean('splitSettingsSyncEnabled')) { + return false; + } + // </if> return this.syncStatus !== undefined && !!this.syncStatus.syncSystemEnabled && !!this.syncStatus.signinAllowed; }, - // </if> /** * @return {boolean}
diff --git a/chrome/browser/resources/settings/search_settings.js b/chrome/browser/resources/settings/search_settings.js index 24c584b..e2e5c8f 100644 --- a/chrome/browser/resources/settings/search_settings.js +++ b/chrome/browser/resources/settings/search_settings.js
@@ -54,12 +54,12 @@ * * @param {!settings.SearchRequest} request * @param {!Node} root The root of the sub-tree to be searched + * @return {boolean} Whether or not matches were found. * @private */ function findAndHighlightMatches_(request, root) { let foundMatches = false; const highlights = []; - const bubbles = []; function doSearch(node) { // NOTE: For subpage wrappers <template route-path="..."> when |no-search| @@ -91,17 +91,22 @@ } if (node.nodeType == Node.TEXT_NODE) { - const textContent = node.nodeValue.trim(); - if (textContent.length == 0) { + const textContent = node.nodeValue; + if (textContent.trim().length === 0) { return; } - if (request.regExp.test(textContent)) { + const strippedText = + cr.search_highlight_utils.stripDiacritics(textContent); + const ranges = []; + for (let match; match = request.regExp.exec(strippedText);) { + ranges.push({start: match.index, length: match[0].length}); + } + + if (ranges.length > 0) { foundMatches = true; - const bubble = revealParentSection_(node, request.rawQuery_); - if (bubble) { - bubbles.push(bubble); - } + revealParentSection_( + node, /*numResults=*/ ranges.length, request.bubbles); if (node.parentNode.nodeName === 'OPTION') { const select = node.parentNode.parentNode; @@ -116,18 +121,15 @@ return; } - const bubble = cr.search_highlight_utils.highlightControlWithBubble( - select, textContent.match(request.regExp)[0], + showBubble_( + select, /*numResults=*/ ranges.length, request.bubbles, /*horizontallyCenter=*/ true); - if (bubble) { - bubbles.push(bubble); - } } else { request.addTextObserver(node); - highlights.push(cr.search_highlight_utils.highlight( - node, textContent.split(request.regExp))); + highlights.push(cr.search_highlight_utils.highlight(node, ranges)); } } + // Returning early since TEXT_NODE nodes never have children. return; } @@ -148,20 +150,20 @@ } doSearch(root); - request.addHighlightsAndBubbles(highlights, bubbles); + request.addHighlights(highlights); return foundMatches; } /** * Finds and makes visible the <settings-section> parent of |node|. * @param {!Node} node - * @param {string} rawQuery - * @return {?Node} The search bubble created while revealing the section, if - * any. + * @param {number} numResults + * @param {!Map<!Node, number>} bubbles A map of bubbles created so far. * @private */ - function revealParentSection_(node, rawQuery) { + function revealParentSection_(node, numResults, bubbles) { let associatedControl = null; + // Find corresponding SETTINGS-SECTION parent and make it visible. let parent = node; while (parent.nodeName !== 'SETTINGS-SECTION') { @@ -170,7 +172,7 @@ parent.parentNode; if (!parent) { // |node| wasn't inside a SETTINGS-SECTION. - return null; + return; } if (parent.nodeName == 'SETTINGS-SUBPAGE') { // TODO(dpapad): Cast to SettingsSubpageElement here. @@ -185,10 +187,26 @@ // Need to add the search bubble after the parent SETTINGS-SECTION has // become visible, otherwise |offsetWidth| returns zero. if (associatedControl) { - return cr.search_highlight_utils.highlightControlWithBubble( - associatedControl, rawQuery); + showBubble_( + associatedControl, numResults, bubbles, + /* horizontallyCenter= */ false); } - return null; + } + + /** + * @param {!Node} control + * @param {number} numResults + * @param {!Map<!Node, number>} bubbles + * @param {boolean} horizontallyCenter + */ + function showBubble_(control, numResults, bubbles, horizontallyCenter) { + const bubble = cr.search_highlight_utils.createEmptySearchBubble( + control, horizontallyCenter); + const numHits = numResults + (bubbles.get(bubble) || 0); + bubbles.set(bubble, numHits); + const msgName = + numHits === 1 ? 'searchResultBubbleText' : 'searchResultsBubbleText'; + bubble.firstChild.textContent = loadTimeData.getStringF(msgName, numHits); } /** @abstract */ @@ -437,17 +455,13 @@ /** @private {!Array<!Node>} */ this.highlights_ = []; - /** @private {!Array<!Node>} */ - this.bubbles_ = []; + /** @type {!Map<!Node, number>} */ + this.bubbles = new Map; } - /** - * @param {!Array<!Node>} highlights The highlight wrappers to add - * @param {!Array<!Node>} bubbles The search bubbles to add. - */ - addHighlightsAndBubbles(highlights, bubbles) { + /** @param {!Array<!Node>} highlights The highlight wrappers to add */ + addHighlights(highlights) { this.highlights_.push(...highlights); - this.bubbles_.push(...bubbles); } removeAllTextObservers() { @@ -459,11 +473,9 @@ removeAllHighlightsAndBubbles() { cr.search_highlight_utils.removeHighlights(this.highlights_); - for (const bubble of this.bubbles_) { - bubble.remove(); - } + this.bubbles.forEach((count, bubble) => bubble.remove()); this.highlights_ = []; - this.bubbles_ = []; + this.bubbles.clear(); } /** @param {!Node} textNode */ @@ -497,14 +509,14 @@ */ generateRegExp_() { let regExp = null; - // Generate search text by escaping any characters that would be // problematic for regular expressions. - const searchText = this.rawQuery_.trim().replace(SANITIZE_REGEX, '\\$&'); - if (searchText.length > 0) { - regExp = new RegExp(`(${searchText})`, 'i'); + const strippedQuery = + cr.search_highlight_utils.stripDiacritics(this.rawQuery_.trim()); + const sanitizedQuery = strippedQuery.replace(SANITIZE_REGEX, '\\$&'); + if (sanitizedQuery.length > 0) { + regExp = new RegExp(`(${sanitizedQuery})`, 'ig'); } - return regExp; }
diff --git a/chrome/browser/resources/settings/settings_resources.grd b/chrome/browser/resources/settings/settings_resources.grd index 3dd4233..b992a9e 100644 --- a/chrome/browser/resources/settings/settings_resources.grd +++ b/chrome/browser/resources/settings/settings_resources.grd
@@ -710,15 +710,15 @@ file="people_page/people_page.js" type="chrome_html" preprocess="true" /> + <structure name="IDR_SETTINGS_PEOPLE_PAGE_SYNC_ACCOUNT_CONTROL_HTML" + file="people_page/sync_account_control.html" + type="chrome_html" + flattenhtml="true" + allowexternalscript="true" /> + <structure name="IDR_SETTINGS_PEOPLE_PAGE_SYNC_ACCOUNT_CONTROL_JS" + file="people_page/sync_account_control.js" + type="chrome_html" /> <if expr="not chromeos"> - <structure name="IDR_SETTINGS_PEOPLE_PAGE_SYNC_ACCOUNT_CONTROL_HTML" - file="people_page/sync_account_control.html" - type="chrome_html" - flattenhtml="true" - allowexternalscript="true" /> - <structure name="IDR_SETTINGS_PEOPLE_PAGE_SYNC_ACCOUNT_CONTROL_JS" - file="people_page/sync_account_control.js" - type="chrome_html" /> <structure name="IDR_SETTINGS_PEOPLE_PAGE_IMPORT_DATA_DIALOG_HTML" file="people_page/import_data_dialog.html" type="chrome_html" />
diff --git a/chrome/browser/sharing/sharing_message_sender.cc b/chrome/browser/sharing/sharing_message_sender.cc index f141b02..cd7441b 100644 --- a/chrome/browser/sharing/sharing_message_sender.cc +++ b/chrome/browser/sharing/sharing_message_sender.cc
@@ -36,14 +36,14 @@ send_message_callbacks_.emplace(message_guid, std::move(callback)); chrome_browser_sharing::MessageType message_type = SharingPayloadCaseToMessageType(message.payload_case()); - - receiver_device_platform_.emplace( - message_guid, sync_prefs_->GetDevicePlatform(device.guid())); + SharingDevicePlatform receiver_device_platform = + sync_prefs_->GetDevicePlatform(device.guid()); base::PostDelayedTask( FROM_HERE, {base::TaskPriority::USER_VISIBLE, content::BrowserThread::UI}, base::BindOnce(&SharingMessageSender::InvokeSendMessageCallback, weak_ptr_factory_.GetWeakPtr(), message_guid, message_type, + receiver_device_platform, SharingSendMessageResult::kAckTimeout, /*response=*/nullptr), response_timeout); @@ -55,6 +55,7 @@ auto target_info = sync_prefs_->GetTargetInfo(device.guid()); if (!target_info) { InvokeSendMessageCallback(message_guid, message_type, + receiver_device_platform, SharingSendMessageResult::kDeviceNotFound, /*response=*/nullptr); return; @@ -64,6 +65,7 @@ local_device_info_provider_->GetLocalDeviceInfo(); if (!local_device_info) { InvokeSendMessageCallback(message_guid, message_type, + receiver_device_platform, SharingSendMessageResult::kInternalError, /*response=*/nullptr); return; @@ -73,6 +75,7 @@ sync_prefs_->GetLocalSharingInfo(local_device_info); if (!sharing_info) { InvokeSendMessageCallback(message_guid, message_type, + receiver_device_platform, SharingSendMessageResult::kInternalError, /*response=*/nullptr); return; @@ -97,50 +100,61 @@ std::move(message), base::BindOnce(&SharingMessageSender::OnMessageSent, weak_ptr_factory_.GetWeakPtr(), base::TimeTicks::Now(), - message_guid, message_type)); + message_guid, message_type, receiver_device_platform)); } void SharingMessageSender::OnMessageSent( base::TimeTicks start_time, const std::string& message_guid, chrome_browser_sharing::MessageType message_type, + SharingDevicePlatform receiver_device_platform, SharingSendMessageResult result, base::Optional<std::string> message_id) { if (result != SharingSendMessageResult::kSuccessful) { - InvokeSendMessageCallback(message_guid, message_type, result, + InvokeSendMessageCallback(message_guid, message_type, + receiver_device_platform, result, /*response=*/nullptr); return; } send_message_times_.emplace(*message_id, start_time); message_guids_.emplace(*message_id, message_guid); + receiver_device_platform_.emplace(*message_id, receiver_device_platform); } void SharingMessageSender::OnAckReceived( chrome_browser_sharing::MessageType message_type, const std::string& message_id, std::unique_ptr<chrome_browser_sharing::ResponseMessage> response) { - auto times_iter = send_message_times_.find(message_id); - if (times_iter != send_message_times_.end()) { - LogSharingMessageAckTime(message_type, - base::TimeTicks::Now() - times_iter->second); - send_message_times_.erase(times_iter); - } - - auto iter = message_guids_.find(message_id); - if (iter == message_guids_.end()) + auto guid_iter = message_guids_.find(message_id); + if (guid_iter == message_guids_.end()) return; - std::string message_guid = std::move(iter->second); - message_guids_.erase(iter); - InvokeSendMessageCallback(message_guid, message_type, - SharingSendMessageResult::kSuccessful, - std::move(response)); + std::string message_guid = std::move(guid_iter->second); + message_guids_.erase(guid_iter); + + auto times_iter = send_message_times_.find(message_id); + DCHECK(times_iter != send_message_times_.end()); + + auto device_platform_iter = receiver_device_platform_.find(message_id); + DCHECK(device_platform_iter != receiver_device_platform_.end()); + + SharingDevicePlatform receiver_device_platform = device_platform_iter->second; + receiver_device_platform_.erase(device_platform_iter); + + LogSharingMessageAckTime(message_type, receiver_device_platform, + base::TimeTicks::Now() - times_iter->second); + send_message_times_.erase(times_iter); + + InvokeSendMessageCallback( + message_guid, message_type, receiver_device_platform, + SharingSendMessageResult::kSuccessful, std::move(response)); } void SharingMessageSender::InvokeSendMessageCallback( const std::string& message_guid, chrome_browser_sharing::MessageType message_type, + SharingDevicePlatform receiver_device_platform, SharingSendMessageResult result, std::unique_ptr<chrome_browser_sharing::ResponseMessage> response) { auto iter = send_message_callbacks_.find(message_guid); @@ -151,11 +165,5 @@ send_message_callbacks_.erase(iter); std::move(callback).Run(result, std::move(response)); - auto device_platform_iter = receiver_device_platform_.find(message_guid); - DCHECK(device_platform_iter != receiver_device_platform_.end()); - - SharingDevicePlatform device_platform = device_platform_iter->second; - receiver_device_platform_.erase(device_platform_iter); - - LogSendSharingMessageResult(message_type, device_platform, result); + LogSendSharingMessageResult(message_type, receiver_device_platform, result); }
diff --git a/chrome/browser/sharing/sharing_message_sender.h b/chrome/browser/sharing/sharing_message_sender.h index 0d5b7691..2886a4d 100644 --- a/chrome/browser/sharing/sharing_message_sender.h +++ b/chrome/browser/sharing/sharing_message_sender.h
@@ -58,12 +58,14 @@ void OnMessageSent(base::TimeTicks start_time, const std::string& message_guid, chrome_browser_sharing::MessageType message_type, + SharingDevicePlatform receiver_device_platform, SharingSendMessageResult result, base::Optional<std::string> message_id); void InvokeSendMessageCallback( const std::string& message_guid, chrome_browser_sharing::MessageType message_type, + SharingDevicePlatform receiver_device_platform, SharingSendMessageResult result, std::unique_ptr<chrome_browser_sharing::ResponseMessage> response); @@ -77,7 +79,7 @@ std::map<std::string, base::TimeTicks> send_message_times_; // Map of FCM message_id to random GUID. std::map<std::string, std::string> message_guids_; - // Map of random message guid to platform of receiver device for metrics. + // Map of FCM message_id to platform of receiver device for metrics. std::map<std::string, SharingDevicePlatform> receiver_device_platform_; base::WeakPtrFactory<SharingMessageSender> weak_ptr_factory_{this};
diff --git a/chrome/browser/sharing/sharing_metrics.cc b/chrome/browser/sharing/sharing_metrics.cc index 73537bd..d491d43 100644 --- a/chrome/browser/sharing/sharing_metrics.cc +++ b/chrome/browser/sharing/sharing_metrics.cc
@@ -199,15 +199,21 @@ } void LogSharingMessageAckTime(chrome_browser_sharing::MessageType message_type, + SharingDevicePlatform receiver_device_platform, base::TimeDelta time) { std::string suffixed_name = base::StrCat( {"Sharing.MessageAckTime.", MessageTypeToMessageSuffix(message_type)}); + std::string platform_suffixed_name = + base::StrCat({"Sharing.MessageAckTime.", + DevicePlatformToString(receiver_device_platform), ".", + MessageTypeToMessageSuffix(message_type)}); switch (message_type) { case chrome_browser_sharing::MessageType::UNKNOWN_MESSAGE: case chrome_browser_sharing::MessageType::PING_MESSAGE: case chrome_browser_sharing::MessageType::CLICK_TO_CALL_MESSAGE: case chrome_browser_sharing::MessageType::SHARED_CLIPBOARD_MESSAGE: base::UmaHistogramMediumTimes(suffixed_name, time); + base::UmaHistogramMediumTimes(platform_suffixed_name, time); break; case chrome_browser_sharing::MessageType::SMS_FETCH_REQUEST: base::UmaHistogramCustomTimes(
diff --git a/chrome/browser/sharing/sharing_metrics.h b/chrome/browser/sharing/sharing_metrics.h index 97a98b349..a7f3204 100644 --- a/chrome/browser/sharing/sharing_metrics.h +++ b/chrome/browser/sharing/sharing_metrics.h
@@ -103,6 +103,7 @@ // Logs to UMA the time from sending a FCM message from the Sharing service // until an ack message is received for it. void LogSharingMessageAckTime(chrome_browser_sharing::MessageType message_type, + SharingDevicePlatform receiver_device_platform, base::TimeDelta time); // Logs to UMA the number of hours since the target device timestamp was last
diff --git a/chrome/browser/ui/app_list/arc/arc_app_unittest.cc b/chrome/browser/ui/app_list/arc/arc_app_unittest.cc index 4b0d584..81738ed 100644 --- a/chrome/browser/ui/app_list/arc/arc_app_unittest.cc +++ b/chrome/browser/ui/app_list/arc/arc_app_unittest.cc
@@ -625,6 +625,8 @@ arc::FakeAppInstance* app_instance() { return arc_test_.app_instance(); } + FakeAppListModelUpdater* model_updater() { return model_updater_.get(); } + private: ArcAppTest arc_test_; std::unique_ptr<FakeAppListModelUpdater> model_updater_; @@ -2140,16 +2142,23 @@ EXPECT_EQ(delegate.update_image_count(), 1U); } -// https://crbug.com/1030009 -TEST_P(ArcAppModelBuilderTest, DISABLED_IconLoader) { +TEST_P(ArcAppModelBuilderTest, IconLoader) { const arc::mojom::AppInfo& app = fake_apps()[0]; const std::string app_id = ArcAppTest::GetAppId(app); ArcAppListPrefs* prefs = ArcAppListPrefs::Get(profile_.get()); ASSERT_NE(nullptr, prefs); - SendRefreshAppList(std::vector<arc::mojom::AppInfo>(fake_apps().begin(), - fake_apps().begin() + 1)); + const std::vector<ui::ScaleFactor>& scale_factors = + ui::GetSupportedScaleFactors(); + + app_instance()->SendRefreshAppList(std::vector<arc::mojom::AppInfo>( + fake_apps().begin(), fake_apps().begin() + 1)); + + // Wait AppServiceAppItem to finish loading icon, otherwise, the test result + // could be flaky, because the update image count could include the icon + // updates by AppServiceAppItem. + model_updater()->WaitForIconUpdates(1 + scale_factors.size()); FakeAppIconLoaderDelegate delegate; ArcAppIconLoader icon_loader( @@ -2163,8 +2172,6 @@ // Validate default image. ValidateIcon(delegate.image()); - const std::vector<ui::ScaleFactor>& scale_factors = - ui::GetSupportedScaleFactors(); AppServiceAppItem* app_item = FindArcItem(app_id); for (auto& scale_factor : scale_factors) { // Force the icon to be loaded.
diff --git a/chrome/browser/ui/app_list/test/fake_app_list_model_updater.cc b/chrome/browser/ui/app_list/test/fake_app_list_model_updater.cc index 4ce990f..31ec4c2 100644 --- a/chrome/browser/ui/app_list/test/fake_app_list_model_updater.cc +++ b/chrome/browser/ui/app_list/test/fake_app_list_model_updater.cc
@@ -7,6 +7,7 @@ #include <utility> #include "base/containers/flat_map.h" +#include "base/run_loop.h" #include "chrome/browser/ui/app_list/chrome_app_list_item.h" #include "extensions/common/constants.h" @@ -64,6 +65,15 @@ } } +void FakeAppListModelUpdater::SetItemIcon(const std::string& id, + const gfx::ImageSkia& icon) { + ++update_image_count_; + if (update_image_count_ == expected_update_image_count_ && + !icon_updated_callback_.is_null()) { + std::move(icon_updated_callback_).Run(); + } +} + void FakeAppListModelUpdater::SetSearchEngineIsGoogle(bool is_google) { search_engine_is_google_ = is_google; } @@ -233,3 +243,10 @@ AppListModelUpdaterObserver* observer) { observers_.RemoveObserver(observer); } + +void FakeAppListModelUpdater::WaitForIconUpdates(size_t expected_updates) { + base::RunLoop run_loop; + expected_update_image_count_ = expected_updates + update_image_count_; + icon_updated_callback_ = run_loop.QuitClosure(); + run_loop.Run(); +}
diff --git a/chrome/browser/ui/app_list/test/fake_app_list_model_updater.h b/chrome/browser/ui/app_list/test/fake_app_list_model_updater.h index 50ad427..d6219ce 100644 --- a/chrome/browser/ui/app_list/test/fake_app_list_model_updater.h +++ b/chrome/browser/ui/app_list/test/fake_app_list_model_updater.h
@@ -38,6 +38,7 @@ void RemoveUninstalledItem(const std::string& id) override; void MoveItemToFolder(const std::string& id, const std::string& folder_id) override; + void SetItemIcon(const std::string& id, const gfx::ImageSkia& icon) override; // For SearchModel: void SetSearchEngineIsGoogle(bool is_google) override; void PublishSearchResults( @@ -74,6 +75,8 @@ void AddObserver(AppListModelUpdaterObserver* observer) override; void RemoveObserver(AppListModelUpdaterObserver* observer) override; + void WaitForIconUpdates(size_t expected_updates); + private: bool search_engine_is_google_ = false; std::vector<std::unique_ptr<ChromeAppListItem>> items_; @@ -81,6 +84,10 @@ base::ObserverList<AppListModelUpdaterObserver> observers_; Profile* profile_; + size_t update_image_count_ = 0; + size_t expected_update_image_count_ = 0; + base::OnceClosure icon_updated_callback_; + void FindOrCreateOemFolder( const std::string& oem_folder_name, const syncer::StringOrdinal& preferred_oem_position);
diff --git a/chrome/browser/ui/ash/launcher/app_service/app_service_app_window_crostini_tracker.cc b/chrome/browser/ui/ash/launcher/app_service/app_service_app_window_crostini_tracker.cc index cbf38d98..9a04fc7 100644 --- a/chrome/browser/ui/ash/launcher/app_service/app_service_app_window_crostini_tracker.cc +++ b/chrome/browser/ui/ash/launcher/app_service/app_service_app_window_crostini_tracker.cc
@@ -10,6 +10,7 @@ #include "base/time/time.h" #include "chrome/browser/apps/app_service/app_service_proxy.h" #include "chrome/browser/apps/app_service/app_service_proxy_factory.h" +#include "chrome/browser/chromeos/crostini/crostini_features.h" #include "chrome/browser/chromeos/crostini/crostini_force_close_watcher.h" #include "chrome/browser/chromeos/crostini/crostini_registry_service.h" #include "chrome/browser/chromeos/crostini/crostini_registry_service_factory.h" @@ -208,6 +209,12 @@ std::string AppServiceAppWindowCrostiniTracker::GetShelfAppId( aura::Window* window) const { + // Only handle the app associated with the primary user. + if (!crostini::CrostiniFeatures::Get()->IsUIAllowed( + app_service_controller_->owner()->profile())) { + return std::string(); + } + // Transient windows are set up after window init, so remove them here. // Crostini shouldn't need to know about ARC app windows. if (wm::GetTransientParent(window) ||
diff --git a/chrome/browser/ui/browser_navigator.cc b/chrome/browser/ui/browser_navigator.cc index 9b572f4..be0266d2 100644 --- a/chrome/browser/ui/browser_navigator.cc +++ b/chrome/browser/ui/browser_navigator.cc
@@ -52,7 +52,6 @@ #include "ash/public/cpp/multi_user_window_manager.h" #include "chrome/browser/ui/ash/multi_user/multi_user_window_manager_helper.h" #include "chrome/browser/ui/settings_window_manager_chromeos.h" -#include "chromeos/constants/chromeos_features.h" #include "components/account_id/account_id.h" #endif @@ -528,8 +527,7 @@ if (source_browser) { // If OS Settings is accessed in any means other than explicitly typing the // URL into the URL bar, open OS Settings in its own standalone surface. - if (chromeos::features::IsSplitSettingsEnabled() && - params->url.host() == chrome::kChromeUIOSSettingsHost && + if (params->url.host() == chrome::kChromeUIOSSettingsHost && !PageTransitionCoreTypeIs(params->transition, ui::PageTransition::PAGE_TRANSITION_TYPED)) { chrome::SettingsWindowManager* settings_window_manager =
diff --git a/chrome/browser/ui/extensions/extension_message_bubble_bridge.cc b/chrome/browser/ui/extensions/extension_message_bubble_bridge.cc index b4d88a8..0a71e49 100644 --- a/chrome/browser/ui/extensions/extension_message_bubble_bridge.cc +++ b/chrome/browser/ui/extensions/extension_message_bubble_bridge.cc
@@ -11,6 +11,8 @@ #include "chrome/grit/generated_resources.h" #include "components/vector_icons/vector_icons.h" #include "extensions/browser/extension_registry.h" +#include "extensions/common/extension.h" +#include "extensions/common/extension_id.h" #include "ui/base/l10n/l10n_util.h" ExtensionMessageBubbleBridge::ExtensionMessageBubbleBridge(
diff --git a/chrome/browser/ui/extensions/extension_message_bubble_bridge_unittest.cc b/chrome/browser/ui/extensions/extension_message_bubble_bridge_unittest.cc index cf4a6fbe..471ddf8 100644 --- a/chrome/browser/ui/extensions/extension_message_bubble_bridge_unittest.cc +++ b/chrome/browser/ui/extensions/extension_message_bubble_bridge_unittest.cc
@@ -31,7 +31,9 @@ #include "extensions/browser/disable_reason.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" +#include "extensions/common/extension.h" #include "extensions/common/extension_builder.h" +#include "extensions/common/extension_id.h" #include "extensions/common/manifest.h" #include "extensions/common/value_builder.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/ui/toolbar/toolbar_actions_model_unittest.cc b/chrome/browser/ui/toolbar/toolbar_actions_model_unittest.cc index 6f529533..f7b9969 100644 --- a/chrome/browser/ui/toolbar/toolbar_actions_model_unittest.cc +++ b/chrome/browser/ui/toolbar/toolbar_actions_model_unittest.cc
@@ -43,6 +43,7 @@ #include "extensions/browser/uninstall_reason.h" #include "extensions/common/extension.h" #include "extensions/common/extension_builder.h" +#include "extensions/common/extension_id.h" #include "extensions/common/manifest.h" #include "extensions/common/value_builder.h" #include "extensions/test/test_extension_dir.h"
diff --git a/chrome/browser/ui/views/autofill/payments/local_card_migration_icon_view.cc b/chrome/browser/ui/views/autofill/payments/local_card_migration_icon_view.cc index aea9b9e..a63d959 100644 --- a/chrome/browser/ui/views/autofill/payments/local_card_migration_icon_view.cc +++ b/chrome/browser/ui/views/autofill/payments/local_card_migration_icon_view.cc
@@ -140,6 +140,10 @@ return gfx::kNoneIcon; } +const char* LocalCardMigrationIconView::GetClassName() const { + return "LocalCardMigrationIconView"; +} + base::string16 LocalCardMigrationIconView::GetTextForTooltipAndAccessibleName() const { return l10n_util::GetStringUTF16(IDS_TOOLTIP_MIGRATE_LOCAL_CARD);
diff --git a/chrome/browser/ui/views/autofill/payments/local_card_migration_icon_view.h b/chrome/browser/ui/views/autofill/payments/local_card_migration_icon_view.h index 877e7d3..90212b6f 100644 --- a/chrome/browser/ui/views/autofill/payments/local_card_migration_icon_view.h +++ b/chrome/browser/ui/views/autofill/payments/local_card_migration_icon_view.h
@@ -34,6 +34,7 @@ void OnExecuting(PageActionIconView::ExecuteSource execute_source) override; const gfx::VectorIcon& GetVectorIcon() const override; const gfx::VectorIcon& GetVectorIconBadge() const override; + const char* GetClassName() const override; private: ManageMigrationUiController* GetController() const;
diff --git a/chrome/browser/ui/views/autofill/payments/save_card_icon_view.cc b/chrome/browser/ui/views/autofill/payments/save_card_icon_view.cc index 5dae0121..1823b3c 100644 --- a/chrome/browser/ui/views/autofill/payments/save_card_icon_view.cc +++ b/chrome/browser/ui/views/autofill/payments/save_card_icon_view.cc
@@ -86,14 +86,23 @@ return gfx::kNoneIcon; } -base::string16 SaveCardIconView::GetTextForTooltipAndAccessibleName() const { - SaveCardBubbleController* controller = GetController(); - if (!controller) { - // The controller can be null in unit tests only. - return base::string16(); - } +const char* SaveCardIconView::GetClassName() const { + return "SaveCardIconView"; +} - return controller->GetSaveCardIconTooltipText(); +base::string16 SaveCardIconView::GetTextForTooltipAndAccessibleName() const { + base::string16 text; + + SaveCardBubbleController* const controller = GetController(); + if (controller) + text = controller->GetSaveCardIconTooltipText(); + + // Because the card icon is in an animated container, it is still briefly + // visible as it's disappearing. Since our test infrastructure does not allow + // views to have empty tooltip text when they are visible, we instead return + // the default text. + return text.empty() ? l10n_util::GetStringUTF16(IDS_TOOLTIP_SAVE_CREDIT_CARD) + : text; } SaveCardBubbleController* SaveCardIconView::GetController() const {
diff --git a/chrome/browser/ui/views/autofill/payments/save_card_icon_view.h b/chrome/browser/ui/views/autofill/payments/save_card_icon_view.h index 601d1a7..bf37f2b 100644 --- a/chrome/browser/ui/views/autofill/payments/save_card_icon_view.h +++ b/chrome/browser/ui/views/autofill/payments/save_card_icon_view.h
@@ -34,6 +34,7 @@ void OnExecuting(PageActionIconView::ExecuteSource execute_source) override; const gfx::VectorIcon& GetVectorIcon() const override; const gfx::VectorIcon& GetVectorIconBadge() const override; + const char* GetClassName() const override; private: SaveCardBubbleController* GetController() const;
diff --git a/chrome/browser/ui/views/location_bar/cookie_controls_icon_view.cc b/chrome/browser/ui/views/location_bar/cookie_controls_icon_view.cc index 1e25fe7..307a8b99 100644 --- a/chrome/browser/ui/views/location_bar/cookie_controls_icon_view.cc +++ b/chrome/browser/ui/views/location_bar/cookie_controls_icon_view.cc
@@ -109,6 +109,10 @@ return kEyeCrossedIcon; } +const char* CookieControlsIconView::GetClassName() const { + return "CookieControlsIconView"; +} + base::string16 CookieControlsIconView::GetTextForTooltipAndAccessibleName() const { return l10n_util::GetStringUTF16(IDS_COOKIE_CONTROLS_TOOLTIP);
diff --git a/chrome/browser/ui/views/location_bar/cookie_controls_icon_view.h b/chrome/browser/ui/views/location_bar/cookie_controls_icon_view.h index 3803f5e..379c8283 100644 --- a/chrome/browser/ui/views/location_bar/cookie_controls_icon_view.h +++ b/chrome/browser/ui/views/location_bar/cookie_controls_icon_view.h
@@ -35,6 +35,7 @@ protected: void OnExecuting(PageActionIconView::ExecuteSource source) override; const gfx::VectorIcon& GetVectorIcon() const override; + const char* GetClassName() const override; private: bool HasAssociatedBubble() const;
diff --git a/chrome/browser/ui/views/location_bar/find_bar_icon.cc b/chrome/browser/ui/views/location_bar/find_bar_icon.cc index 588b57cb..cb6caafb 100644 --- a/chrome/browser/ui/views/location_bar/find_bar_icon.cc +++ b/chrome/browser/ui/views/location_bar/find_bar_icon.cc
@@ -45,6 +45,10 @@ return l10n_util::GetStringUTF16(IDS_TOOLTIP_FIND); } +const char* FindBarIcon::GetClassName() const { + return "FindBarIcon"; +} + void FindBarIcon::OnExecuting(ExecuteSource execute_source) {} views::BubbleDialogDelegateView* FindBarIcon::GetBubble() const {
diff --git a/chrome/browser/ui/views/location_bar/find_bar_icon.h b/chrome/browser/ui/views/location_bar/find_bar_icon.h index 96be5e3..ab5daf3 100644 --- a/chrome/browser/ui/views/location_bar/find_bar_icon.h +++ b/chrome/browser/ui/views/location_bar/find_bar_icon.h
@@ -27,6 +27,7 @@ views::BubbleDialogDelegateView* GetBubble() const override; const gfx::VectorIcon& GetVectorIcon() const override; base::string16 GetTextForTooltipAndAccessibleName() const override; + const char* GetClassName() const override; private: DISALLOW_COPY_AND_ASSIGN(FindBarIcon);
diff --git a/chrome/browser/ui/views/location_bar/intent_picker_view.cc b/chrome/browser/ui/views/location_bar/intent_picker_view.cc index 608a886..7a8c645 100644 --- a/chrome/browser/ui/views/location_bar/intent_picker_view.cc +++ b/chrome/browser/ui/views/location_bar/intent_picker_view.cc
@@ -107,3 +107,7 @@ base::string16 IntentPickerView::GetTextForTooltipAndAccessibleName() const { return l10n_util::GetStringUTF16(IDS_TOOLTIP_INTENT_PICKER_ICON); } + +const char* IntentPickerView::GetClassName() const { + return "IntentPickerView"; +}
diff --git a/chrome/browser/ui/views/location_bar/intent_picker_view.h b/chrome/browser/ui/views/location_bar/intent_picker_view.h index edd90cd..5528499 100644 --- a/chrome/browser/ui/views/location_bar/intent_picker_view.h +++ b/chrome/browser/ui/views/location_bar/intent_picker_view.h
@@ -26,6 +26,7 @@ views::BubbleDialogDelegateView* GetBubble() const override; const gfx::VectorIcon& GetVectorIcon() const override; base::string16 GetTextForTooltipAndAccessibleName() const override; + const char* GetClassName() const override; private: bool IsIncognitoMode() const;
diff --git a/chrome/browser/ui/views/location_bar/star_view.cc b/chrome/browser/ui/views/location_bar/star_view.cc index 8559616..60d3bbe54 100644 --- a/chrome/browser/ui/views/location_bar/star_view.cc +++ b/chrome/browser/ui/views/location_bar/star_view.cc
@@ -128,6 +128,10 @@ : IDS_TOOLTIP_STAR); } +const char* StarView::GetClassName() const { + return "StarView"; +} + SkColor StarView::GetInkDropBaseColor() const { return bookmark_promo_observer_.IsObservingSources() ? GetNativeTheme()->GetSystemColor(
diff --git a/chrome/browser/ui/views/location_bar/star_view.h b/chrome/browser/ui/views/location_bar/star_view.h index bb242fe..97cacc82 100644 --- a/chrome/browser/ui/views/location_bar/star_view.h +++ b/chrome/browser/ui/views/location_bar/star_view.h
@@ -40,6 +40,7 @@ SkColor GetInkDropBaseColor() const override; const gfx::VectorIcon& GetVectorIcon() const override; base::string16 GetTextForTooltipAndAccessibleName() const override; + const char* GetClassName() const override; // views::WidgetObserver: void OnWidgetDestroying(views::Widget* widget) override;
diff --git a/chrome/browser/ui/views/native_file_system/native_file_system_access_icon_view.cc b/chrome/browser/ui/views/native_file_system/native_file_system_access_icon_view.cc index 72654fdf..4c3d08f 100644 --- a/chrome/browser/ui/views/native_file_system/native_file_system_access_icon_view.cc +++ b/chrome/browser/ui/views/native_file_system/native_file_system_access_icon_view.cc
@@ -105,3 +105,7 @@ return has_write_access_ ? kSaveOriginalFileIcon : vector_icons::kInsertDriveFileOutlineIcon; } + +const char* NativeFileSystemAccessIconView::GetClassName() const { + return "NativeFileSystemAccessIconView"; +}
diff --git a/chrome/browser/ui/views/native_file_system/native_file_system_access_icon_view.h b/chrome/browser/ui/views/native_file_system/native_file_system_access_icon_view.h index 69ba98f5..5a9a125 100644 --- a/chrome/browser/ui/views/native_file_system/native_file_system_access_icon_view.h +++ b/chrome/browser/ui/views/native_file_system/native_file_system_access_icon_view.h
@@ -22,6 +22,7 @@ base::string16 GetTextForTooltipAndAccessibleName() const override; void OnExecuting(ExecuteSource execute_source) override; const gfx::VectorIcon& GetVectorIcon() const override; + const char* GetClassName() const override; private: bool has_write_access_ = false;
diff --git a/chrome/browser/ui/views/page_action/page_action_icon_view.cc b/chrome/browser/ui/views/page_action/page_action_icon_view.cc index 998ac0a..db8a8fb 100644 --- a/chrome/browser/ui/views/page_action/page_action_icon_view.cc +++ b/chrome/browser/ui/views/page_action/page_action_icon_view.cc
@@ -94,11 +94,6 @@ node_data->role = ax::mojom::Role::kButton; const base::string16 name_text = GetTextForTooltipAndAccessibleName(); node_data->SetName(name_text); - // TODO(crbug/1038567): This shouldn't be necessary and suggests a bug in how - // we deconstruct icons as we're fading them out. In the interim let's make - // sure interactive uitests don't crash as they're trying to hide a button. - if (name_text.empty()) - node_data->SetNameExplicitlyEmpty(); } base::string16 PageActionIconView::GetTooltipText(const gfx::Point& p) const { @@ -192,6 +187,10 @@ PreferredSizeChanged(); } +const char* PageActionIconView::GetClassName() const { + return "PageActionIconView"; +} + void PageActionIconView::SetIconColor(SkColor icon_color) { icon_color_ = icon_color; UpdateIconImage();
diff --git a/chrome/browser/ui/views/page_action/page_action_icon_view.h b/chrome/browser/ui/views/page_action/page_action_icon_view.h index 42c3a4d..65ab854e 100644 --- a/chrome/browser/ui/views/page_action/page_action_icon_view.h +++ b/chrome/browser/ui/views/page_action/page_action_icon_view.h
@@ -137,6 +137,7 @@ // IconLabelBubbleView: void OnBoundsChanged(const gfx::Rect& previous_bounds) override; void OnTouchUiChanged() override; + const char* GetClassName() const override; // Updates the icon image after some state has changed. virtual void UpdateIconImage();
diff --git a/chrome/browser/ui/views/page_action/pwa_install_view.cc b/chrome/browser/ui/views/page_action/pwa_install_view.cc index 069001a4..bdb8d442 100644 --- a/chrome/browser/ui/views/page_action/pwa_install_view.cc +++ b/chrome/browser/ui/views/page_action/pwa_install_view.cc
@@ -75,3 +75,7 @@ IDS_OMNIBOX_PWA_INSTALL_ICON_TOOLTIP, banners::AppBannerManager::GetInstallableWebAppName(web_contents)); } + +const char* PwaInstallView::GetClassName() const { + return "PwaInstallView"; +}
diff --git a/chrome/browser/ui/views/page_action/pwa_install_view.h b/chrome/browser/ui/views/page_action/pwa_install_view.h index 6d634a5..ccc8d31 100644 --- a/chrome/browser/ui/views/page_action/pwa_install_view.h +++ b/chrome/browser/ui/views/page_action/pwa_install_view.h
@@ -25,6 +25,7 @@ views::BubbleDialogDelegateView* GetBubble() const override; const gfx::VectorIcon& GetVectorIcon() const override; base::string16 GetTextForTooltipAndAccessibleName() const override; + const char* GetClassName() const override; private: DISALLOW_COPY_AND_ASSIGN(PwaInstallView);
diff --git a/chrome/browser/ui/views/page_action/zoom_view.cc b/chrome/browser/ui/views/page_action/zoom_view.cc index 78a9e20..e4969b4 100644 --- a/chrome/browser/ui/views/page_action/zoom_view.cc +++ b/chrome/browser/ui/views/page_action/zoom_view.cc
@@ -112,3 +112,7 @@ return l10n_util::GetStringFUTF16(IDS_TOOLTIP_ZOOM, base::FormatPercent(current_zoom_percent_)); } + +const char* ZoomView::GetClassName() const { + return "ZoomView"; +}
diff --git a/chrome/browser/ui/views/page_action/zoom_view.h b/chrome/browser/ui/views/page_action/zoom_view.h index 632b284..4a7b75c 100644 --- a/chrome/browser/ui/views/page_action/zoom_view.h +++ b/chrome/browser/ui/views/page_action/zoom_view.h
@@ -30,6 +30,7 @@ views::BubbleDialogDelegateView* GetBubble() const override; const gfx::VectorIcon& GetVectorIcon() const override; base::string16 GetTextForTooltipAndAccessibleName() const override; + const char* GetClassName() const override; private: bool ShouldBeVisible(bool can_show_bubble) const;
diff --git a/chrome/browser/ui/views/passwords/password_bubble_interactive_uitest.cc b/chrome/browser/ui/views/passwords/password_bubble_interactive_uitest.cc index 3fba8b5..9259a5e 100644 --- a/chrome/browser/ui/views/passwords/password_bubble_interactive_uitest.cc +++ b/chrome/browser/ui/views/passwords/password_bubble_interactive_uitest.cc
@@ -218,8 +218,7 @@ ->GetFocusManager() ->GetFocusedView()); ui_test_utils::ClickOnView(browser(), VIEW_ID_TAB_CONTAINER); - EXPECT_EQ(IsBubbleShowing(), base::FeatureList::IsEnabled( - password_manager::features::kStickyBubble)); + EXPECT_TRUE(IsBubbleShowing()); } IN_PROC_BROWSER_TEST_F(PasswordBubbleInteractiveUiTest, CloseOnEsc) { @@ -227,8 +226,7 @@ EXPECT_TRUE(IsBubbleShowing()); ASSERT_TRUE(ui_test_utils::SendKeyPressSync(browser(), ui::VKEY_ESCAPE, false, false, false, false)); - EXPECT_EQ(IsBubbleShowing(), base::FeatureList::IsEnabled( - password_manager::features::kStickyBubble)); + EXPECT_TRUE(IsBubbleShowing()); } IN_PROC_BROWSER_TEST_F(PasswordBubbleInteractiveUiTest, CloseOnKey) { @@ -250,8 +248,7 @@ EXPECT_TRUE(web_contents->IsFocusedElementEditable()); ASSERT_TRUE(ui_test_utils::SendKeyPressSync(browser(), ui::VKEY_K, false, false, false, false)); - EXPECT_EQ(IsBubbleShowing(), base::FeatureList::IsEnabled( - password_manager::features::kStickyBubble)); + EXPECT_TRUE(IsBubbleShowing()); } IN_PROC_BROWSER_TEST_F(PasswordBubbleInteractiveUiTest,
diff --git a/chrome/browser/ui/views/passwords/password_bubble_view_base.cc b/chrome/browser/ui/views/passwords/password_bubble_view_base.cc index 84737a69..cf5364d 100644 --- a/chrome/browser/ui/views/passwords/password_bubble_view_base.cc +++ b/chrome/browser/ui/views/passwords/password_bubble_view_base.cc
@@ -117,9 +117,7 @@ // happens outside of the bubble. By this the bubble becomes // 'easily-dissmisable' and this behavior can be enforced by the // corresponding flag. - if (!base::FeatureList::IsEnabled( - password_manager::features::kStickyBubble) || - easily_dismissable) { + if (easily_dismissable) { mouse_handler_ = std::make_unique<WebContentMouseHandler>(this, web_contents); }
diff --git a/chrome/browser/ui/views/qrcode_generator/qrcode_generator_icon_view.cc b/chrome/browser/ui/views/qrcode_generator/qrcode_generator_icon_view.cc index 894ef83..44e6fa5 100644 --- a/chrome/browser/ui/views/qrcode_generator/qrcode_generator_icon_view.cc +++ b/chrome/browser/ui/views/qrcode_generator/qrcode_generator_icon_view.cc
@@ -67,6 +67,10 @@ return kQrcodeGeneratorIcon; } +const char* QRCodeGeneratorIconView::GetClassName() const { + return "QRCodeGeneratorIconView"; +} + SkColor QRCodeGeneratorIconView::GetForegroundColor() const { return GetOmniboxColor(GetThemeProvider(), OmniboxPart::LOCATION_BAR_TEXT_DEFAULT);
diff --git a/chrome/browser/ui/views/qrcode_generator/qrcode_generator_icon_view.h b/chrome/browser/ui/views/qrcode_generator/qrcode_generator_icon_view.h index 07106ed..91f5512 100644 --- a/chrome/browser/ui/views/qrcode_generator/qrcode_generator_icon_view.h +++ b/chrome/browser/ui/views/qrcode_generator/qrcode_generator_icon_view.h
@@ -32,6 +32,7 @@ // PageActionIconView: void OnExecuting(PageActionIconView::ExecuteSource execute_source) override; const gfx::VectorIcon& GetVectorIcon() const override; + const char* GetClassName() const override; private: DISALLOW_COPY_AND_ASSIGN(QRCodeGeneratorIconView);
diff --git a/chrome/browser/ui/views/reader_mode/reader_mode_icon_view.cc b/chrome/browser/ui/views/reader_mode/reader_mode_icon_view.cc index 222b201..f168e57 100644 --- a/chrome/browser/ui/views/reader_mode/reader_mode_icon_view.cc +++ b/chrome/browser/ui/views/reader_mode/reader_mode_icon_view.cc
@@ -60,6 +60,10 @@ return l10n_util::GetStringUTF16(IDS_DISTILL_PAGE); } +const char* ReaderModeIconView::GetClassName() const { + return "ReaderModeIconView"; +} + // TODO(gilmanmh): Consider displaying a bubble the first time a user // activates the icon to explain what Reader Mode is. views::BubbleDialogDelegateView* ReaderModeIconView::GetBubble() const {
diff --git a/chrome/browser/ui/views/reader_mode/reader_mode_icon_view.h b/chrome/browser/ui/views/reader_mode/reader_mode_icon_view.h index f4361dd6..54cadcf 100644 --- a/chrome/browser/ui/views/reader_mode/reader_mode_icon_view.h +++ b/chrome/browser/ui/views/reader_mode/reader_mode_icon_view.h
@@ -39,6 +39,7 @@ void UpdateImpl() override; const gfx::VectorIcon& GetVectorIcon() const override; base::string16 GetTextForTooltipAndAccessibleName() const override; + const char* GetClassName() const override; // GetBubble() is required by PageActionIconView; however, the icon // intentionally does not display a bubble when activated.
diff --git a/chrome/browser/ui/views/relaunch_notification/relaunch_recommended_bubble_view.cc b/chrome/browser/ui/views/relaunch_notification/relaunch_recommended_bubble_view.cc index bb9cf1d3..2b57f18 100644 --- a/chrome/browser/ui/views/relaunch_notification/relaunch_recommended_bubble_view.cc +++ b/chrome/browser/ui/views/relaunch_notification/relaunch_recommended_bubble_view.cc
@@ -90,9 +90,9 @@ } gfx::ImageSkia RelaunchRecommendedBubbleView::GetWindowIcon() { - return gfx::CreateVectorIcon(gfx::IconDescription( - vector_icons::kBusinessIcon, kTitleIconSize, gfx::kChromeIconGrey, - base::TimeDelta(), gfx::kNoneIcon)); + return gfx::CreateVectorIcon( + gfx::IconDescription(vector_icons::kBusinessIcon, kTitleIconSize, + gfx::kChromeIconGrey, gfx::kNoneIcon)); } bool RelaunchRecommendedBubbleView::ShouldShowWindowIcon() const {
diff --git a/chrome/browser/ui/views/relaunch_notification/relaunch_required_dialog_view.cc b/chrome/browser/ui/views/relaunch_notification/relaunch_required_dialog_view.cc index b64162e..241a8f7 100644 --- a/chrome/browser/ui/views/relaunch_notification/relaunch_required_dialog_view.cc +++ b/chrome/browser/ui/views/relaunch_notification/relaunch_required_dialog_view.cc
@@ -87,9 +87,9 @@ } gfx::ImageSkia RelaunchRequiredDialogView::GetWindowIcon() { - return gfx::CreateVectorIcon(gfx::IconDescription( - vector_icons::kBusinessIcon, kTitleIconSize, gfx::kChromeIconGrey, - base::TimeDelta(), gfx::kNoneIcon)); + return gfx::CreateVectorIcon( + gfx::IconDescription(vector_icons::kBusinessIcon, kTitleIconSize, + gfx::kChromeIconGrey, gfx::kNoneIcon)); } bool RelaunchRequiredDialogView::ShouldShowWindowIcon() const {
diff --git a/chrome/browser/ui/views/screen_capture_notification_ui_views.cc b/chrome/browser/ui/views/screen_capture_notification_ui_views.cc index 49363ff..afea3a0 100644 --- a/chrome/browser/ui/views/screen_capture_notification_ui_views.cc +++ b/chrome/browser/ui/views/screen_capture_notification_ui_views.cc
@@ -115,9 +115,9 @@ NotificationBarClientView* client_view_ = nullptr; views::ImageView* gripper_ = nullptr; views::Label* label_ = nullptr; - views::Button* source_button_ = nullptr; - views::Button* stop_button_ = nullptr; - views::Link* hide_link_ = nullptr; + views::View* source_button_ = nullptr; + views::View* stop_button_ = nullptr; + views::View* hide_link_ = nullptr; const base::string16 text_; DISALLOW_COPY_AND_ASSIGN(ScreenCaptureNotificationUIViews); @@ -151,10 +151,8 @@ views::MdTextButton::CreateSecondaryUiBlueButton(this, stop_text); stop_button_ = AddChildView(std::move(stop_button)); - // TODO(jiayl): IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON is used for the need to - // merge to M34. Change it to a new IDS_ after the merge. auto hide_link = std::make_unique<views::Link>( - l10n_util::GetStringUTF16(IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON)); + l10n_util::GetStringUTF16(IDS_MEDIA_SCREEN_CAPTURE_NOTIFICATION_HIDE)); hide_link->set_listener(this); hide_link->SetUnderline(false); hide_link_ = AddChildView(std::move(hide_link));
diff --git a/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_icon_view.cc b/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_icon_view.cc index 5fdf6d1..cd92b27 100644 --- a/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_icon_view.cc +++ b/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_icon_view.cc
@@ -85,6 +85,10 @@ return kSendTabToSelfIcon; } +const char* SendTabToSelfIconView::GetClassName() const { + return "SendTabToSelfIconView"; +} + SkColor SendTabToSelfIconView::GetForegroundColor() const { return GetOmniboxColor(GetThemeProvider(), OmniboxPart::LOCATION_BAR_TEXT_DEFAULT);
diff --git a/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_icon_view.h b/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_icon_view.h index 319bfea..8d6c5cd 100644 --- a/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_icon_view.h +++ b/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_icon_view.h
@@ -37,6 +37,7 @@ // PageActionIconView: void OnExecuting(PageActionIconView::ExecuteSource execute_source) override; const gfx::VectorIcon& GetVectorIcon() const override; + const char* GetClassName() const override; private: enum class AnimationState { kNotShown, kShowing, kShown };
diff --git a/chrome/browser/ui/views/sharing/sharing_icon_view.cc b/chrome/browser/ui/views/sharing/sharing_icon_view.cc index 00fe3f1..5b6579e9 100644 --- a/chrome/browser/ui/views/sharing/sharing_icon_view.cc +++ b/chrome/browser/ui/views/sharing/sharing_icon_view.cc
@@ -169,3 +169,7 @@ return controller ? controller->GetTextForTooltipAndAccessibleName() : base::string16(); } + +const char* SharingIconView::GetClassName() const { + return "SharingIconView"; +}
diff --git a/chrome/browser/ui/views/sharing/sharing_icon_view.h b/chrome/browser/ui/views/sharing/sharing_icon_view.h index 7bcff96..188e4115 100644 --- a/chrome/browser/ui/views/sharing/sharing_icon_view.h +++ b/chrome/browser/ui/views/sharing/sharing_icon_view.h
@@ -37,6 +37,7 @@ void UpdateImpl() override; const gfx::VectorIcon& GetVectorIcon() const override; base::string16 GetTextForTooltipAndAccessibleName() const override; + const char* GetClassName() const override; // gfx::AnimationDelegate: void AnimationProgressed(const gfx::Animation* animation) override;
diff --git a/chrome/browser/ui/views/sync/profile_signin_confirmation_dialog_views.cc b/chrome/browser/ui/views/sync/profile_signin_confirmation_dialog_views.cc index 0091dd1..9194fa3 100644 --- a/chrome/browser/ui/views/sync/profile_signin_confirmation_dialog_views.cc +++ b/chrome/browser/ui/views/sync/profile_signin_confirmation_dialog_views.cc
@@ -149,9 +149,9 @@ // Create business icon. int business_icon_size = 20; auto business_icon = std::make_unique<views::ImageView>(); - business_icon->SetImage(gfx::CreateVectorIcon(gfx::IconDescription( - vector_icons::kBusinessIcon, business_icon_size, gfx::kChromeIconGrey, - base::TimeDelta(), gfx::kNoneIcon))); + business_icon->SetImage(gfx::CreateVectorIcon( + gfx::IconDescription(vector_icons::kBusinessIcon, business_icon_size, + gfx::kChromeIconGrey, gfx::kNoneIcon))); // Create the prompt label. size_t offset;
diff --git a/chrome/browser/ui/views/translate/translate_icon_view.cc b/chrome/browser/ui/views/translate/translate_icon_view.cc index 9c94a701..8118a598 100644 --- a/chrome/browser/ui/views/translate/translate_icon_view.cc +++ b/chrome/browser/ui/views/translate/translate_icon_view.cc
@@ -67,3 +67,7 @@ base::string16 TranslateIconView::GetTextForTooltipAndAccessibleName() const { return l10n_util::GetStringUTF16(IDS_TOOLTIP_TRANSLATE); } + +const char* TranslateIconView::GetClassName() const { + return "TranslateIconView"; +}
diff --git a/chrome/browser/ui/views/translate/translate_icon_view.h b/chrome/browser/ui/views/translate/translate_icon_view.h index 541f8a3a..be8a314 100644 --- a/chrome/browser/ui/views/translate/translate_icon_view.h +++ b/chrome/browser/ui/views/translate/translate_icon_view.h
@@ -29,6 +29,7 @@ void OnPressed(bool activated) override; const gfx::VectorIcon& GetVectorIcon() const override; base::string16 GetTextForTooltipAndAccessibleName() const override; + const char* GetClassName() const override; private: DISALLOW_COPY_AND_ASSIGN(TranslateIconView);
diff --git a/chrome/browser/ui/views/webauthn/authenticator_request_sheet_view.cc b/chrome/browser/ui/views/webauthn/authenticator_request_sheet_view.cc index bb780d6..4081696f 100644 --- a/chrome/browser/ui/views/webauthn/authenticator_request_sheet_view.cc +++ b/chrome/browser/ui/views/webauthn/authenticator_request_sheet_view.cc
@@ -207,7 +207,6 @@ model()->GetStepIllustration(GetNativeTheme()->ShouldUseDarkColors() ? ImageColorScheme::kDark : ImageColorScheme::kLight), - 0 /* automatic dip_size */, SK_ColorBLACK, base::TimeDelta(), - gfx::kNoneIcon); + 0 /* automatic dip_size */, SK_ColorBLACK, gfx::kNoneIcon); step_illustration_->SetImage(gfx::CreateVectorIcon(icon_description)); }
diff --git a/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.cc b/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.cc index 3691bb4..69d0ad4 100644 --- a/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.cc +++ b/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.cc
@@ -12,7 +12,6 @@ #include "base/stl_util.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/views/chrome_web_dialog_view.h" -#include "chromeos/constants/chromeos_features.h" #include "components/session_manager/core/session_manager.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/host_zoom_map.h" @@ -173,17 +172,15 @@ void SystemWebDialogDelegate::OnDialogShown(content::WebUI* webui) { webui_ = webui; - if (features::IsSplitSettingsEnabled()) { - // System dialogs don't use the browser's default page zoom. Their contents - // stay at 100% to match the size of app list, shelf, status area, etc. - auto* web_contents = webui_->GetWebContents(); - auto* rvh = web_contents->GetRenderViewHost(); - auto* zoom_map = content::HostZoomMap::GetForWebContents(web_contents); - // Temporary means the lifetime of the WebContents. - zoom_map->SetTemporaryZoomLevel(rvh->GetProcess()->GetID(), - rvh->GetRoutingID(), - blink::PageZoomFactorToZoomLevel(1.0)); - } + // System dialogs don't use the browser's default page zoom. Their contents + // stay at 100% to match the size of app list, shelf, status area, etc. + auto* web_contents = webui_->GetWebContents(); + auto* rvh = web_contents->GetRenderViewHost(); + auto* zoom_map = content::HostZoomMap::GetForWebContents(web_contents); + // Temporary means the lifetime of the WebContents. + zoom_map->SetTemporaryZoomLevel(rvh->GetProcess()->GetID(), + rvh->GetRoutingID(), + blink::PageZoomFactorToZoomLevel(1.0)); } void SystemWebDialogDelegate::OnDialogClosed(const std::string& json_retval) {
diff --git a/chrome/browser/ui/webui/print_preview/print_preview_ui.cc b/chrome/browser/ui/webui/print_preview/print_preview_ui.cc index 852c366..ed2914c 100644 --- a/chrome/browser/ui/webui/print_preview/print_preview_ui.cc +++ b/chrome/browser/ui/webui/print_preview/print_preview_ui.cc
@@ -280,6 +280,8 @@ {"scalingInstruction", IDS_PRINT_PREVIEW_SCALING_INSTRUCTION}, {"scalingLabel", IDS_PRINT_PREVIEW_SCALING_LABEL}, {"searchBoxPlaceholder", IDS_PRINT_PREVIEW_SEARCH_BOX_PLACEHOLDER}, + {"searchResultBubbleText", IDS_SEARCH_RESULT_BUBBLE_TEXT}, + {"searchResultsBubbleText", IDS_SEARCH_RESULTS_BUBBLE_TEXT}, {"selectButton", IDS_PRINT_PREVIEW_BUTTON_SELECT}, {"seeMore", IDS_PRINT_PREVIEW_SEE_MORE}, {"seeMoreDestinationsLabel", IDS_PRINT_PREVIEW_SEE_MORE_DESTINATIONS_LABEL},
diff --git a/chrome/browser/ui/webui/settings/people_handler.cc b/chrome/browser/ui/webui/settings/people_handler.cc index 9a7f179..6d5442f 100644 --- a/chrome/browser/ui/webui/settings/people_handler.cc +++ b/chrome/browser/ui/webui/settings/people_handler.cc
@@ -18,6 +18,7 @@ #include "build/build_config.h" #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/profiles/profile_avatar_icon_util.h" #include "chrome/browser/profiles/profile_metrics.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/signin/signin_error_controller_factory.h" @@ -51,8 +52,10 @@ #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_delegate.h" #include "google_apis/gaia/gaia_auth_util.h" +#include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/webui/web_ui_util.h" +#include "ui/gfx/image/image.h" #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/login/quick_unlock/pin_backend.h" @@ -63,10 +66,7 @@ #endif #if BUILDFLAG(ENABLE_DICE_SUPPORT) -#include "chrome/browser/profiles/profile_avatar_icon_util.h" #include "chrome/browser/signin/account_consistency_mode_manager.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "ui/gfx/image/image.h" #endif using content::WebContents; @@ -187,7 +187,6 @@ } } -#if BUILDFLAG(ENABLE_DICE_SUPPORT) // Returns the base::Value associated with the account, to use in the stored // accounts list. base::Value GetAccountValue(const AccountInfo& account) { @@ -203,7 +202,6 @@ } return dictionary; } -#endif // BUILDFLAG(ENABLE_DICE_SUPPORT) base::string16 GetEnterPassphraseBody(syncer::PassphraseType passphrase_type, base::Time passphrase_time) { @@ -328,7 +326,6 @@ base::BindRepeating(&PeopleHandler::HandleStartSignin, base::Unretained(this))); #endif -#if BUILDFLAG(ENABLE_DICE_SUPPORT) web_ui()->RegisterMessageCallback( "SyncSetupGetStoredAccounts", base::BindRepeating(&PeopleHandler::HandleGetStoredAccounts, @@ -337,7 +334,6 @@ "SyncSetupStartSyncingWithEmail", base::BindRepeating(&PeopleHandler::HandleStartSyncingWithEmail, base::Unretained(this))); -#endif web_ui()->RegisterMessageCallback( "SyncStartKeyRetrieval", base::BindRepeating(&PeopleHandler::HandleStartKeyRetrieval, @@ -478,7 +474,6 @@ ProfileMetrics::LogProfileSyncInfo(ProfileMetrics::SYNC_CHOOSE); } -#if BUILDFLAG(ENABLE_DICE_SUPPORT) void PeopleHandler::HandleGetStoredAccounts(const base::ListValue* args) { CHECK_EQ(1U, args->GetSize()); const base::Value* callback_id; @@ -497,30 +492,28 @@ base::Value PeopleHandler::GetStoredAccountsList() { base::Value accounts(base::Value::Type::LIST); - const bool dice_enabled = - AccountConsistencyModeManager::IsDiceEnabledForProfile(profile_); - - if (dice_enabled) { +#if BUILDFLAG(ENABLE_DICE_SUPPORT) + if (AccountConsistencyModeManager::IsDiceEnabledForProfile(profile_)) { // If dice is enabled, show all the accounts. for (auto const& account : signin_ui_util::GetAccountsForDicePromos(profile_)) { accounts.Append(GetAccountValue(account)); } - } else { - // If dice is disabled (and unified consent enabled), show only the primary - // account. - auto* identity_manager = IdentityManagerFactory::GetForProfile(profile_); - base::Optional<AccountInfo> primary_account_info = - identity_manager->FindExtendedAccountInfoForAccountWithRefreshToken( - identity_manager->GetPrimaryAccountInfo()); - if (primary_account_info.has_value()) - accounts.Append(GetAccountValue(primary_account_info.value())); + return accounts; } - +#endif + // If dice is disabled or unsupported, show only the primary account. + auto* identity_manager = IdentityManagerFactory::GetForProfile(profile_); + base::Optional<AccountInfo> primary_account_info = + identity_manager->FindExtendedAccountInfoForAccountWithRefreshToken( + identity_manager->GetPrimaryAccountInfo()); + if (primary_account_info.has_value()) + accounts.Append(GetAccountValue(primary_account_info.value())); return accounts; } void PeopleHandler::HandleStartSyncingWithEmail(const base::ListValue* args) { +#if BUILDFLAG(ENABLE_DICE_SUPPORT) DCHECK(AccountConsistencyModeManager::IsDiceEnabledForProfile(profile_)); const base::Value* email; const base::Value* is_default_promo_account; @@ -540,8 +533,11 @@ maybe_account.has_value() ? maybe_account.value() : AccountInfo(), signin_metrics::AccessPoint::ACCESS_POINT_SETTINGS, is_default_promo_account->GetBool()); -} +#else + // TODO(jamescook): Enable sync on non-DICE platforms (e.g. Chrome OS). + NOTIMPLEMENTED(); #endif +} void PeopleHandler::HandleSetEncryption(const base::ListValue* args) { SyncConfigInfo configuration; @@ -931,6 +927,9 @@ sync_status->SetBoolean( "disabled", !service || disallowed_by_policy || !service->GetUserSettings()->IsSyncAllowedByPlatform()); + // TODO(jamescook): This is always true on Chrome OS, but the WebUI uses + // false to mean that the user has sync turned off. We need to distinguish + // between the two cases. sync_status->SetBoolean("signedIn", identity_manager->HasPrimaryAccount()); sync_status->SetString("signedInUsername", signin_ui_util::GetAuthenticatedUsername(profile_));
diff --git a/chrome/browser/ui/webui/settings/people_handler.h b/chrome/browser/ui/webui/settings/people_handler.h index 2b8cd56..89822fc 100644 --- a/chrome/browser/ui/webui/settings/people_handler.h +++ b/chrome/browser/ui/webui/settings/people_handler.h
@@ -128,10 +128,8 @@ const CoreAccountInfo& primary_account_info) override; void OnPrimaryAccountCleared( const CoreAccountInfo& previous_primary_account_info) override; -#if BUILDFLAG(ENABLE_DICE_SUPPORT) void OnExtendedAccountInfoUpdated(const AccountInfo& info) override; void OnExtendedAccountInfoRemoved(const AccountInfo& info) override; -#endif // syncer::SyncServiceObserver implementation. void OnStateChanged(syncer::SyncService* sync) override; @@ -183,11 +181,9 @@ void OnPinLoginAvailable(bool is_available); #endif -#if BUILDFLAG(ENABLE_DICE_SUPPORT) void HandleGetStoredAccounts(const base::ListValue* args); void HandleStartSyncingWithEmail(const base::ListValue* args); base::Value GetStoredAccountsList(); -#endif // Pushes the updated sync prefs to JavaScript. void PushSyncPrefs();
diff --git a/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc b/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc index 20872cad..f8757106 100644 --- a/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc +++ b/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc
@@ -185,6 +185,8 @@ #endif {"retry", IDS_SETTINGS_RETRY}, {"save", IDS_SAVE}, + {"searchResultBubbleText", IDS_SEARCH_RESULT_BUBBLE_TEXT}, + {"searchResultsBubbleText", IDS_SEARCH_RESULTS_BUBBLE_TEXT}, {"settings", IDS_SETTINGS_SETTINGS}, {"settingsAltPageTitle", IDS_SETTINGS_ALT_PAGE_TITLE}, {"subpageArrowRoleDescription", IDS_SETTINGS_SUBPAGE_BUTTON}, @@ -2142,17 +2144,15 @@ IDS_SETTINGS_WIFI_CONFIGURATIONS_CHECKBOX_LABEL}, {"wallpaperCheckboxLabel", IDS_OS_SETTINGS_WALLPAPER_CHECKBOX_LABEL}, #else // !defined(OS_CHROMEOS) - {"domainManagedProfile", IDS_SETTINGS_PEOPLE_DOMAIN_MANAGED_PROFILE}, {"editPerson", IDS_SETTINGS_EDIT_PERSON}, {"profileNameAndPicture", IDS_SETTINGS_PROFILE_NAME_AND_PICTURE}, {"showShortcutLabel", IDS_SETTINGS_PROFILE_SHORTCUT_TOGGLE_LABEL}, +#endif // defined(OS_CHROMEOS) {"syncWillStart", IDS_SETTINGS_SYNC_WILL_START}, {"syncSettingsSavedToast", IDS_SETTINGS_SYNC_SETTINGS_SAVED_TOAST_LABEL}, {"cancelSync", IDS_SETTINGS_SYNC_SETTINGS_CANCEL_SYNC}, {"syncSetupCancelDialogTitle", IDS_SETTINGS_SYNC_SETUP_CANCEL_DIALOG_TITLE}, {"syncSetupCancelDialogBody", IDS_SETTINGS_SYNC_SETUP_CANCEL_DIALOG_BODY}, -#endif // defined(OS_CHROMEOS) -#if BUILDFLAG(ENABLE_DICE_SUPPORT) {"peopleSignIn", IDS_PROFILES_DICE_SIGNIN_BUTTON}, {"peopleSignOut", IDS_SETTINGS_PEOPLE_SIGN_OUT}, {"peopleSignInPrompt", IDS_SETTINGS_PEOPLE_SIGN_IN_PROMPT}, @@ -2171,7 +2171,6 @@ IDS_SETTINGS_SYNC_SIGN_IN_PROMPT_WITH_ACCOUNT}, {"syncSignInPromptWithNoAccount", IDS_SETTINGS_SYNC_SIGN_IN_PROMPT_WITH_NO_ACCOUNT}, -#endif {"syncOverview", IDS_SETTINGS_SYNC_OVERVIEW}, {"syncDisabled", IDS_PROFILES_DICE_SYNC_DISABLED_TITLE}, {"syncDisabledByAdministrator", IDS_SIGNED_IN_WITH_SYNC_DISABLED_BY_POLICY},
diff --git a/chrome/browser/ui/webui/settings/settings_ui.cc b/chrome/browser/ui/webui/settings/settings_ui.cc index 86d7c98..35519e71 100644 --- a/chrome/browser/ui/webui/settings/settings_ui.cc +++ b/chrome/browser/ui/webui/settings/settings_ui.cc
@@ -279,6 +279,8 @@ html_source->AddBoolean( "showParentalControls", chromeos::settings::ShouldShowParentalControls(profile)); + html_source->AddBoolean("splitSettingsSyncEnabled", + chromeos::features::IsSplitSettingsSyncEnabled()); #endif #if defined(OS_CHROMEOS)
diff --git a/chrome/test/data/webui/print_preview/advanced_dialog_test.js b/chrome/test/data/webui/print_preview/advanced_dialog_test.js index bc3e1a0..abd229c47 100644 --- a/chrome/test/data/webui/print_preview/advanced_dialog_test.js +++ b/chrome/test/data/webui/print_preview/advanced_dialog_test.js
@@ -208,18 +208,18 @@ assertTrue(noMatchHint.hidden); // Searching for Watermark should show only the watermark setting. - searchBox.searchQuery = /(Watermark)/i; + searchBox.searchQuery = /(Watermark)/ig; items.forEach((item, index) => assertEquals(index != 2, item.hidden)); assertTrue(noMatchHint.hidden); // Searching for A4 should show only the print area setting. - searchBox.searchQuery = /(A4)/i; + searchBox.searchQuery = /(A4)/ig; items.forEach((item, index) => assertEquals(index != 0, item.hidden)); assertTrue(noMatchHint.hidden); // Searching for WXYZ should show no settings and display the "no match" // hint. - searchBox.searchQuery = /(WXYZ)/i; + searchBox.searchQuery = /(WXYZ)/ig; items.forEach(item => assertTrue(item.hidden)); assertFalse(noMatchHint.hidden); });
diff --git a/chrome/test/data/webui/print_preview/advanced_item_test.js b/chrome/test/data/webui/print_preview/advanced_item_test.js index 917dc16..4197bfac 100644 --- a/chrome/test/data/webui/print_preview/advanced_item_test.js +++ b/chrome/test/data/webui/print_preview/advanced_item_test.js
@@ -150,9 +150,9 @@ // Test that the setting is displayed correctly when the search query // matches its display name. test(assert(advanced_item_test.TestNames.QueryName), function() { - const query = /(Type)/i; + const query = /(Type)/ig; assertTrue(item.hasMatch(query)); - item.updateHighlighting(query); + item.updateHighlighting(query, new Map); const label = item.$$('.label'); assertEquals( @@ -173,9 +173,9 @@ // Test that the setting is displayed correctly when the search query // matches one of the select options. test(assert(advanced_item_test.TestNames.QueryOption), function() { - const query = /(cycle)/i; + const query = /(cycle)/ig; assertTrue(item.hasMatch(query)); - item.updateHighlighting(query); + item.updateHighlighting(query, new Map); const label = item.$$('.label'); assertEquals('Paper Type', label.textContent); @@ -188,6 +188,6 @@ assertEquals(0, control.querySelectorAll('.search-highlight-hit').length); const searchBubbleHits = control.querySelectorAll('.search-bubble'); assertEquals(1, searchBubbleHits.length); - assertEquals('cycle', searchBubbleHits[0].textContent); + assertEquals('1 result', searchBubbleHits[0].textContent); }); });
diff --git a/chrome/test/data/webui/print_preview/destination_item_test.js b/chrome/test/data/webui/print_preview/destination_item_test.js index 3d91fcb..133ed99e 100644 --- a/chrome/test/data/webui/print_preview/destination_item_test.js +++ b/chrome/test/data/webui/print_preview/destination_item_test.js
@@ -100,7 +100,7 @@ // Test that the destination is displayed correctly when the search query // matches its display name. test(assert(destination_item_test.TestNames.QueryName), function() { - item.searchQuery = /(Foo)/i; + item.searchQuery = /(Foo)/ig; const name = item.$$('.name'); assertEquals(printerName + printerName, name.textContent); @@ -124,7 +124,7 @@ item.destination = new Destination( printerId, DestinationType.GOOGLE, DestinationOrigin.COOKIES, printerName, DestinationConnectionStatus.ONLINE, params); - item.searchQuery = /(ABC)/i; + item.searchQuery = /(ABC)/ig; // No highlighting on name. const name = item.$$('.name');
diff --git a/chrome/test/data/webui/print_preview/destination_list_test.js b/chrome/test/data/webui/print_preview/destination_list_test.js index c032cc2..8e6faa65 100644 --- a/chrome/test/data/webui/print_preview/destination_list_test.js +++ b/chrome/test/data/webui/print_preview/destination_list_test.js
@@ -69,7 +69,7 @@ assertTrue(noMatchHint.hidden); // Searching for "e" should show "One", "Three", and "Five". - list.searchQuery = /(e)/i; + list.searchQuery = /(e)/ig; flush(); assertEquals(undefined, Array.from(items).find(item => { return !item.hidden && @@ -79,7 +79,7 @@ assertTrue(noMatchHint.hidden); // Searching for "ABC" should show "One" and "Three". - list.searchQuery = /(ABC)/i; + list.searchQuery = /(ABC)/ig; flush(); assertEquals(undefined, Array.from(items).find(item => { return !item.hidden && item.destination.displayName != 'One' && @@ -88,7 +88,7 @@ assertTrue(noMatchHint.hidden); // Searching for "F" should show "Four" and "Five" - list.searchQuery = /(F)/i; + list.searchQuery = /(F)/ig; flush(); assertEquals(undefined, Array.from(items).find(item => { return !item.hidden && item.destination.displayName != 'Four' && @@ -98,13 +98,13 @@ // Searching for UVW should show no destinations and display the "no // match" hint. - list.searchQuery = /(UVW)/i; + list.searchQuery = /(UVW)/ig; flush(); items.forEach(item => assertTrue(item.hidden)); assertFalse(noMatchHint.hidden); // Searching for 123 should show destinations "Three", "Four", and "Five". - list.searchQuery = /(123)/i; + list.searchQuery = /(123)/ig; flush(); assertEquals(undefined, Array.from(items).find(item => { return !item.hidden && @@ -114,7 +114,7 @@ assertTrue(noMatchHint.hidden); // Clearing the query restores the original state. - list.searchQuery = /()/i; + list.searchQuery = null; flush(); items.forEach(item => assertFalse(item.hidden)); assertTrue(noMatchHint.hidden);
diff --git a/chrome/test/data/webui/settings/cr_settings_browsertest.js b/chrome/test/data/webui/settings/cr_settings_browsertest.js index fc3709f9..2d9e41a 100644 --- a/chrome/test/data/webui/settings/cr_settings_browsertest.js +++ b/chrome/test/data/webui/settings/cr_settings_browsertest.js
@@ -466,7 +466,6 @@ mocha.run(); }); -GEN('#if !defined(OS_CHROMEOS)'); /** * Test fixture for * chrome/browser/resources/settings/people_page/sync_account_control.html. @@ -494,8 +493,6 @@ mocha.run(); }); -GEN('#endif // !defined(OS_CHROMEOS)'); - /** * Test fixture for * chrome/browser/resources/settings/people_page/sync_controls.html.
diff --git a/chrome/test/data/webui/settings/search_settings_test.js b/chrome/test/data/webui/settings/search_settings_test.js index 297f72f..1721e6e 100644 --- a/chrome/test/data/webui/settings/search_settings_test.js +++ b/chrome/test/data/webui/settings/search_settings_test.js
@@ -11,6 +11,8 @@ suiteSetup(function() { if (!window.settings || !settings.getSearchManager) { return Promise.all([ + PolymerTest.loadScript('chrome://resources/js/load_time_data.js'), + PolymerTest.loadScript('chrome://settings/strings.js'), PolymerTest.loadScript( 'chrome://resources/js/search_highlight_utils.js'), PolymerTest.loadScript('chrome://settings/search_settings.js'), @@ -284,5 +286,55 @@ assertEquals(1, document.querySelectorAll('.search-bubble').length); }); + + test('bubble result count', async () => { + document.body.innerHTML = ` + <settings-section> + <select> + <option>nohello</option> + <option>hello dolly!</option> + <option>hello to you, too!</option> + <option>you say goodbye, I say hello!</option> + </select> + + <button></button> + <settings-subpage> + hello there! + </settings-subpage> + </setting-section>`; + + const subpage = document.querySelector('settings-subpage'); + subpage.associatedControl = document.querySelector('button'); + + await searchManager.search('hello', document.body); + + const bubbles = document.querySelectorAll('.search-bubble'); + assertEquals(2, bubbles.length); + assertEquals('4 results', bubbles[1].textContent); + assertEquals('1 result', bubbles[0].textContent); + }); + + test('diacritics', async () => { + document.body.innerHTML = ` + <settings-section> + <select> + <option>año de oro</option> + </select> + <button></button> + <settings-subpage> + malibu cañon + </settings-subpage> + danger zone + </setting-section>`; + + const subpage = document.querySelector('settings-subpage'); + subpage.associatedControl = document.querySelector('button'); + + await searchManager.search('an', document.body); + + const highlights = document.querySelectorAll('.search-highlight-wrapper'); + assertEquals(2, highlights.length); + assertEquals(2, document.querySelectorAll('.search-bubble').length); + }); }); });
diff --git a/chrome/test/data/webui/settings/sync_account_control_test.js b/chrome/test/data/webui/settings/sync_account_control_test.js index fd2adb5c..c9255b78 100644 --- a/chrome/test/data/webui/settings/sync_account_control_test.js +++ b/chrome/test/data/webui/settings/sync_account_control_test.js
@@ -128,7 +128,10 @@ assertVisible(testElement.$$('#promo-header'), true); assertVisible(testElement.$$('#avatar-row'), false); - assertVisible(testElement.$$('#menu'), false); + // Chrome OS does not use the account switch menu. + if (!cr.isChromeOS) { + assertVisible(testElement.$$('#menu'), false); + } assertVisible(testElement.$$('#sign-in'), true); testElement.$$('#sign-in').click(); @@ -136,6 +139,10 @@ }); test('not signed in but has stored accounts', function() { + // Chrome OS users are always signed in. + if (cr.isChromeOS) { + return; + } testElement.syncStatus = { firstSetupInProgress: false, signedIn: false, @@ -241,11 +248,14 @@ Polymer.dom.flush(); assertVisible(testElement.$$('#avatar-row'), true); - assertVisible(testElement.$$('cr-icon-button'), false); assertVisible(testElement.$$('#promo-header'), false); assertFalse(testElement.$$('#sync-icon-container').hidden); - assertFalse(!!testElement.$$('#menu')); + // Chrome OS does not use the account switch menu. + if (!cr.isChromeOS) { + assertVisible(testElement.$$('cr-icon-button'), false); + assertFalse(!!testElement.$$('#menu')); + } const userInfo = testElement.$$('#user-info'); assertTrue(userInfo.textContent.includes('barName'));
diff --git a/chromecast/media/audio/BUILD.gn b/chromecast/media/audio/BUILD.gn index 8e145dd..17dc915 100644 --- a/chromecast/media/audio/BUILD.gn +++ b/chromecast/media/audio/BUILD.gn
@@ -46,24 +46,6 @@ cflags = [ "-ffast-math" ] } -cast_source_set("audio_resampler") { - sources = [ - "audio_resampler.cc", - "audio_resampler.h", - ] - - deps = [ - "//base", - "//chromecast/media/cma/base", - "//media", - ] - - # Use fastest possible float math. - configs -= [ "//build/config/compiler:default_optimization" ] - configs += [ "//build/config/compiler:optimize_speed" ] - cflags = [ "-ffast-math" ] -} - cast_source_set("audio") { sources = [ "cast_audio_input_stream.cc",
diff --git a/chromecast/media/audio/audio_clock_simulator.cc b/chromecast/media/audio/audio_clock_simulator.cc index 7ba1eae5..f11f6ca7 100644 --- a/chromecast/media/audio/audio_clock_simulator.cc +++ b/chromecast/media/audio/audio_clock_simulator.cc
@@ -13,14 +13,6 @@ namespace chromecast { namespace media { -namespace { - -int64_t FramesToTime(int64_t frames, int sample_rate) { - return frames * 1000000 / sample_rate; -} - -} // namespace - constexpr int AudioClockSimulator::kInterpolateWindow; constexpr double AudioClockSimulator::kMaxRate; constexpr double AudioClockSimulator::kMinRate; @@ -53,9 +45,11 @@ double AudioClockSimulator::SetRate(double rate) { rate = std::max(kMinRate, std::min(rate, kMaxRate)); - clock_rate_ = rate; - input_frames_ = 0; - output_frames_ = 0; + if (clock_rate_ != rate) { + clock_rate_ = rate; + input_frames_ = 0; + output_frames_ = 0; + } return rate; } @@ -66,6 +60,14 @@ return 0; } +void AudioClockSimulator::SetSampleRate(int sample_rate) { + sample_rate_ = sample_rate; +} + +void AudioClockSimulator::SetPlaybackRate(double playback_rate) { + playback_rate_ = playback_rate; +} + int AudioClockSimulator::FillFrames(int num_frames, int64_t playout_timestamp, float* const* channel_data) { @@ -107,7 +109,7 @@ for (size_t c = 0; c < num_channels_; ++c) { channels[c] = channel_data[c] + filled; } - int64_t timestamp = playout_timestamp + FramesToTime(filled, sample_rate_); + int64_t timestamp = playout_timestamp + FramesToMicroseconds(filled); int desired = std::min(num_frames - filled, kInterpolateWindow); int provided = provider_->FillFrames(desired, timestamp, channels); input_frames_ += provided; @@ -148,7 +150,7 @@ // index 1. channels[c] = scratch_buffer_->channel(c) + 1; } - int64_t timestamp = playout_timestamp + FramesToTime(offset, sample_rate_); + int64_t timestamp = playout_timestamp + FramesToMicroseconds(offset); int provided = provider_->FillFrames(desired_fill, timestamp, channels); input_frames_ += provided; InterpolateLonger(provided, channel_data, offset); @@ -213,7 +215,7 @@ for (size_t c = 0; c < num_channels_; ++c) { channels[c] = scratch_buffer_->channel(c) + fill_offset; } - int64_t timestamp = playout_timestamp + FramesToTime(offset, sample_rate_); + int64_t timestamp = playout_timestamp + FramesToMicroseconds(offset); int provided = provider_->FillFrames(desired_fill, timestamp, channels); if (provided == 0) { return {false, 0}; @@ -260,5 +262,9 @@ } } +int64_t AudioClockSimulator::FramesToMicroseconds(int64_t frames) { + return frames * 1000000 / (sample_rate_ * playback_rate_); +} + } // namespace media } // namespace chromecast
diff --git a/chromecast/media/audio/audio_clock_simulator.h b/chromecast/media/audio/audio_clock_simulator.h index 4fdbe4e..9755b04f 100644 --- a/chromecast/media/audio/audio_clock_simulator.h +++ b/chromecast/media/audio/audio_clock_simulator.h
@@ -53,6 +53,13 @@ // internally. Will always return 0 or 1. int DelayFrames() const; + // Sets a new playback sample rate. Needed to calculate timestamps correctly. + void SetSampleRate(int sample_rate); + + // Sets the playback rate (rate at which samples are played out relative to + // the sample rate). Needed to calculate timestamps correctly. + void SetPlaybackRate(double playback_rate); + // AudioProvider implementation: int FillFrames(int num_frames, int64_t playout_timestamp, @@ -87,9 +94,12 @@ float* const* channel_data, int offset); + int64_t FramesToMicroseconds(int64_t frames); + AudioProvider* const provider_; - const int sample_rate_; + int sample_rate_; const size_t num_channels_; + double playback_rate_ = 1.0; double clock_rate_ = 1.0; int64_t input_frames_ = 0;
diff --git a/chromecast/media/audio/audio_resampler.cc b/chromecast/media/audio/audio_resampler.cc deleted file mode 100644 index 52d6ec97..0000000 --- a/chromecast/media/audio/audio_resampler.cc +++ /dev/null
@@ -1,132 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/audio_resampler.h" - -#include <algorithm> - -#include "base/logging.h" -#include "base/memory/ref_counted.h" -#include "chromecast/media/cma/base/decoder_buffer_adapter.h" -#include "chromecast/media/cma/base/decoder_buffer_base.h" -#include "media/base/decoder_buffer.h" - -namespace chromecast { -namespace media { - -namespace { -constexpr size_t kMaxChannels = 8; -} // namespace - -AudioResampler::AudioResampler(size_t channel_count) - : channel_count_(channel_count) { - DCHECK_LE(channel_count_, kMaxChannels); -} - -scoped_refptr<media::DecoderBufferBase> AudioResampler::ResampleBuffer( - scoped_refptr<media::DecoderBufferBase> buffer) { - DCHECK(buffer); - const int num_frames = buffer->data_size() / (channel_count_ * sizeof(float)); - input_frames_for_clock_rate_ += num_frames; - int64_t expected_output_frames = output_frames_for_clock_rate_ + num_frames; - int64_t desired_output_frames = - input_frames_for_clock_rate_ / media_clock_rate_; - - if (expected_output_frames > desired_output_frames) { - output_frames_for_clock_rate_ += num_frames - 1; - return ShortenBuffer(std::move(buffer)); - } else if (expected_output_frames < desired_output_frames) { - output_frames_for_clock_rate_ += num_frames + 1; - return LengthenBuffer(std::move(buffer)); - } - output_frames_for_clock_rate_ += num_frames; - return buffer; -} - -double AudioResampler::SetMediaClockRate(double rate) { - // We are only allowed to deviate from 1.0x playback rate by this much, - // because we only add/remove 1 frame each buffer. The buffers are typically - // 1024 frames, and even if they're not, we limit to this rate anyway, - // because bigger changes may start being perceptible. - double max_deviation = 1.0 / 1024.0; - - rate = std::min(rate, 1.0 + max_deviation); - rate = std::max(rate, 1.0 - max_deviation); - - media_clock_rate_ = rate; - input_frames_for_clock_rate_ = 0; - output_frames_for_clock_rate_ = 0; - return rate; -} - -scoped_refptr<media::DecoderBufferBase> AudioResampler::LengthenBuffer( - scoped_refptr<media::DecoderBufferBase> buffer) { - const int num_frames = buffer->data_size() / (channel_count_ * sizeof(float)); - const int new_num_frames = num_frames + 1; - auto delayed_buffer = base::MakeRefCounted<::media::DecoderBuffer>( - new_num_frames * (channel_count_ * sizeof(float))); - - delayed_buffer->set_timestamp( - base::TimeDelta::FromMicroseconds(buffer->timestamp())); - - const float* old_channels[kMaxChannels]; - float* new_channels[kMaxChannels]; - for (size_t c = 0; c < channel_count_; ++c) { - old_channels[c] = - reinterpret_cast<const float*>(buffer->data()) + c * num_frames; - new_channels[c] = - reinterpret_cast<float*>(delayed_buffer->writable_data()) + - c * new_num_frames; - } - - for (size_t c = 0; c < channel_count_; ++c) { - new_channels[c][0] = old_channels[c][0]; - // Linearly interpolate between all n input samples to produce (n - 1) - // samples, plus the first and last sample = (n + 1) output samples. - for (int s = 1; s < num_frames; ++s) { - new_channels[c][s] = - (old_channels[c][s - 1] * s + old_channels[c][s] * (num_frames - s)) / - num_frames; - } - new_channels[c][num_frames] = old_channels[c][num_frames - 1]; - } - - return base::MakeRefCounted<media::DecoderBufferAdapter>(delayed_buffer); -} - -scoped_refptr<media::DecoderBufferBase> AudioResampler::ShortenBuffer( - scoped_refptr<media::DecoderBufferBase> buffer) { - const int num_frames = buffer->data_size() / (channel_count_ * sizeof(float)); - - const int new_num_frames = num_frames - 1; - auto cut_buffer = base::MakeRefCounted<::media::DecoderBuffer>( - new_num_frames * (channel_count_ * sizeof(float))); - - cut_buffer->set_timestamp( - base::TimeDelta::FromMicroseconds(buffer->timestamp())); - - const float* old_channels[kMaxChannels]; - float* new_channels[kMaxChannels]; - for (size_t c = 0; c < channel_count_; ++c) { - old_channels[c] = - reinterpret_cast<const float*>(buffer->data()) + c * num_frames; - new_channels[c] = reinterpret_cast<float*>(cut_buffer->writable_data()) + - c * new_num_frames; - } - - DCHECK_GE(num_frames, 2); - for (size_t c = 0; c < channel_count_; ++c) { - // Linearly interpolate between all n input samples to produce (n - 1) - // output samples. - for (int s = 0; s < new_num_frames; ++s) { - new_channels[c][s] = (old_channels[c][s] * (num_frames - (s + 1)) + - old_channels[c][s + 1] * (s + 1)) / - num_frames; - } - } - return base::MakeRefCounted<media::DecoderBufferAdapter>(cut_buffer); -} - -} // namespace media -} // namespace chromecast
diff --git a/chromecast/media/audio/audio_resampler.h b/chromecast/media/audio/audio_resampler.h deleted file mode 100644 index ede35a5..0000000 --- a/chromecast/media/audio/audio_resampler.h +++ /dev/null
@@ -1,53 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_AUDIO_RESAMPLER_H_ -#define CHROMECAST_MEDIA_AUDIO_AUDIO_RESAMPLER_H_ - -#include <stdint.h> - -#include "base/macros.h" -#include "base/memory/ref_counted.h" - -namespace chromecast { -namespace media { -class DecoderBufferBase; - -// The audio resampler allows us to apply small changes to the rate of audio -// playback via (supposedly) imperceptible changes. -// -// Note: only works for planar float data. -class AudioResampler { - public: - explicit AudioResampler(size_t channel_count); - - // Sets the effective media clock rate. - double SetMediaClockRate(double rate); - - // Resamples a buffer, adding or dropping frames as necessary to match the - // media clock rate. - scoped_refptr<media::DecoderBufferBase> ResampleBuffer( - scoped_refptr<media::DecoderBufferBase> buffer); - - private: - // Adds a frame to a buffer. - scoped_refptr<media::DecoderBufferBase> LengthenBuffer( - scoped_refptr<media::DecoderBufferBase> buffer); - - // Cuts a frame from a buffer. - scoped_refptr<media::DecoderBufferBase> ShortenBuffer( - scoped_refptr<media::DecoderBufferBase> buffer); - - const size_t channel_count_; - double media_clock_rate_ = 1.0; - int64_t input_frames_for_clock_rate_ = 0; - int64_t output_frames_for_clock_rate_ = 0; - - DISALLOW_COPY_AND_ASSIGN(AudioResampler); -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_AUDIO_RESAMPLER_H_
diff --git a/chromecast/media/audio/mixer_service/mixer_service.proto b/chromecast/media/audio/mixer_service/mixer_service.proto index 633844d..9eb7f86 100644 --- a/chromecast/media/audio/mixer_service/mixer_service.proto +++ b/chromecast/media/audio/mixer_service/mixer_service.proto
@@ -87,6 +87,12 @@ optional bool paused = 1; } +// Sets (or simulates setting) the audio clock rate. If the provided rate is +// not supported, the rate will be clamped to the supported range. +message SetAudioClockRate { + optional double rate = 1; +} + // Indicates that previously pushed audio data has been queued for playback, // and the next audio data that is pushed to the mixer will start playing at // |next_playback_timestamp|. @@ -225,4 +231,5 @@ optional Error error = 20; optional NumOutputChannels set_num_output_channels = 21; optional StreamInterruption stream_interruption = 22; + optional SetAudioClockRate set_audio_clock_rate = 23; }
diff --git a/chromecast/media/audio/mixer_service/output_stream_connection.cc b/chromecast/media/audio/mixer_service/output_stream_connection.cc index f47173a4..4a5cfcc9 100644 --- a/chromecast/media/audio/mixer_service/output_stream_connection.cc +++ b/chromecast/media/audio/mixer_service/output_stream_connection.cc
@@ -113,6 +113,15 @@ } } +void OutputStreamConnection::SetAudioClockRate(double rate) { + audio_clock_rate_ = rate; + if (socket_) { + Generic message; + message.mutable_set_audio_clock_rate()->set_rate(rate); + socket_->SendProto(message); + } +} + void OutputStreamConnection::Pause() { paused_ = true; if (socket_) { @@ -145,6 +154,9 @@ if (playback_rate_ != 1.0f) { message.mutable_set_playback_rate()->set_playback_rate(playback_rate_); } + if (audio_clock_rate_ != 1.0) { + message.mutable_set_audio_clock_rate()->set_rate(audio_clock_rate_); + } if (volume_multiplier_ != 1.0f) { message.mutable_set_stream_volume()->set_volume(volume_multiplier_); }
diff --git a/chromecast/media/audio/mixer_service/output_stream_connection.h b/chromecast/media/audio/mixer_service/output_stream_connection.h index d4e2a141..7d16c74f 100644 --- a/chromecast/media/audio/mixer_service/output_stream_connection.h +++ b/chromecast/media/audio/mixer_service/output_stream_connection.h
@@ -90,6 +90,10 @@ // 2.0 / sample_rate seconds. void SetPlaybackRate(float playback_rate); + // Changes the audio output clock rate. If the provided |rate| is outside of + // the supported range, the rate will be clamped to the supported range. + void SetAudioClockRate(double rate); + // Pauses playback. void Pause(); @@ -120,6 +124,7 @@ int64_t start_pts_ = INT64_MIN; float playback_rate_ = 1.0f; + double audio_clock_rate_ = 1.0; bool paused_ = false; bool sent_eos_ = false;
diff --git a/chromecast/media/cma/backend/BUILD.gn b/chromecast/media/cma/backend/BUILD.gn index b1980839..51a7c7f 100644 --- a/chromecast/media/cma/backend/BUILD.gn +++ b/chromecast/media/cma/backend/BUILD.gn
@@ -166,7 +166,6 @@ ":volume_map", "//base", "//chromecast/base", - "//chromecast/media/audio:audio_resampler", "//chromecast/media/audio:processing", "//chromecast/media/audio/mixer_service:common", "//chromecast/media/audio/mixer_service:control_connection",
diff --git a/chromecast/media/cma/backend/audio_decoder_for_mixer.cc b/chromecast/media/cma/backend/audio_decoder_for_mixer.cc index 8bd6e85..96eca87f 100644 --- a/chromecast/media/cma/backend/audio_decoder_for_mixer.cc +++ b/chromecast/media/cma/backend/audio_decoder_for_mixer.cc
@@ -15,7 +15,7 @@ #include "build/build_config.h" #include "chromecast/base/chromecast_switches.h" #include "chromecast/base/task_runner_impl.h" -#include "chromecast/media/audio/audio_resampler.h" +#include "chromecast/media/audio/audio_clock_simulator.h" #include "chromecast/media/audio/mixer_service/conversions.h" #include "chromecast/media/audio/mixer_service/mixer_service.pb.h" #include "chromecast/media/audio/mixer_service/mixer_socket.h" @@ -175,9 +175,6 @@ CreateBufferPool(config, buffer_pool_frames_); DCHECK_GT(buffer_pool_frames_, 0); - audio_resampler_ = std::make_unique<AudioResampler>(config.channel_number); - audio_resampler_->SetMediaClockRate(av_sync_clock_rate_); - mixer_service::OutputStreamParams params; params.set_stream_type( backend_->Primary() @@ -202,6 +199,7 @@ std::make_unique<mixer_service::OutputStreamConnection>(this, params); mixer_input_->Connect(); mixer_input_->SetVolumeMultiplier(volume_multiplier_); + mixer_input_->SetAudioClockRate(av_sync_clock_rate_); } void AudioDecoderForMixer::StartPlaybackAt(int64_t playback_start_timestamp) { @@ -268,12 +266,12 @@ return rate; } -float AudioDecoderForMixer::SetAvSyncPlaybackRate(float rate) { - av_sync_clock_rate_ = rate; - if (audio_resampler_) { - return audio_resampler_->SetMediaClockRate(rate); - } - return rate; +double AudioDecoderForMixer::SetAvSyncPlaybackRate(double rate) { + av_sync_clock_rate_ = std::max(AudioClockSimulator::kMinRate, + std::min(rate, AudioClockSimulator::kMaxRate)); + if (mixer_input_) + mixer_input_->SetAudioClockRate(av_sync_clock_rate_); + return av_sync_clock_rate_; } bool AudioDecoderForMixer::GetTimestampedPts(int64_t* timestamp, @@ -534,18 +532,7 @@ return; } - // TODO(kmackay) This could be made more efficient by reducing memory - // allocations and copies. For example we would resample (and maybe decode) - // directly into an IOBuffer. - DCHECK(audio_resampler_); - scoped_refptr<DecoderBufferBase> resampled = - (original_frame_count > 1 - ? audio_resampler_->ResampleBuffer(std::move(buffer)) - : std::move(buffer)); - - const int frame_count = resampled->data_size() / frame_size; - // We only resample if there was more than 1 frame, and the resampler only - // subtracts at most 1 frame. + const int frame_count = buffer->data_size() / frame_size; DCHECK_GT(frame_count, 0); if (frame_count > buffer_pool_frames_) { @@ -553,12 +540,12 @@ } auto io_buffer = buffer_pool_->GetBuffer(); - memcpy(io_buffer->data() + kAudioMessageHeaderSize, resampled->data(), - resampled->data_size()); + memcpy(io_buffer->data() + kAudioMessageHeaderSize, buffer->data(), + buffer->data_size()); pending_buffer_complete_ = true; mixer_input_->SendAudioBuffer(std::move(io_buffer), frame_count, - resampled->timestamp()); + buffer->timestamp()); } void AudioDecoderForMixer::FillNextBuffer(void* buffer,
diff --git a/chromecast/media/cma/backend/audio_decoder_for_mixer.h b/chromecast/media/cma/backend/audio_decoder_for_mixer.h index 02704ff..cd65c86 100644 --- a/chromecast/media/cma/backend/audio_decoder_for_mixer.h +++ b/chromecast/media/cma/backend/audio_decoder_for_mixer.h
@@ -26,7 +26,6 @@ class IOBufferPool; namespace media { -class AudioResampler; class DecoderBufferBase; class MediaPipelineBackendForMixer; @@ -60,7 +59,7 @@ // This allows for very small changes in the rate of audio playback that are // (supposedly) imperceptible. - float SetAvSyncPlaybackRate(float rate); + double SetAvSyncPlaybackRate(double rate); void RestartPlaybackAt(int64_t pts, int64_t timestamp); RenderingDelay GetMixerRenderingDelay(); @@ -110,8 +109,7 @@ AudioConfig config_; std::unique_ptr<CastAudioDecoder> decoder_; - std::unique_ptr<AudioResampler> audio_resampler_; - float av_sync_clock_rate_ = 1.0f; + double av_sync_clock_rate_ = 1.0; std::unique_ptr<mixer_service::OutputStreamConnection> mixer_input_;
diff --git a/chromecast/media/cma/backend/mixer/mixer_input_connection.cc b/chromecast/media/cma/backend/mixer/mixer_input_connection.cc index 2921706f..2e1626e 100644 --- a/chromecast/media/cma/backend/mixer/mixer_input_connection.cc +++ b/chromecast/media/cma/backend/mixer/mixer_input_connection.cc
@@ -179,6 +179,7 @@ kDefaultFadeTime, input_samples_per_second_), 1.0 /* playback_rate */), + audio_clock_simulator_(&fader_), use_start_timestamp_(params.use_start_timestamp()), playback_start_timestamp_(use_start_timestamp_ ? INT64_MAX : INT64_MIN), audio_buffer_pool_( @@ -254,6 +255,9 @@ if (message.has_set_playback_rate()) { SetMediaPlaybackRate(message.set_playback_rate().playback_rate()); } + if (message.has_set_audio_clock_rate()) { + SetAudioClockRate(message.set_audio_clock_rate().rate()); + } if (message.has_set_paused()) { SetPaused(message.set_paused().paused()); } @@ -448,6 +452,13 @@ } } +void MixerInputConnection::SetAudioClockRate(double rate) { + DCHECK(io_task_runner_->RunsTasksInCurrentSequence()); + + base::AutoLock lock(lock_); + audio_clock_simulator_.SetRate(rate); +} + void MixerInputConnection::SetPaused(bool paused) { DCHECK(io_task_runner_->RunsTasksInCurrentSequence()); LOG(INFO) << (paused ? "Pausing " : "Unpausing ") << this; @@ -573,8 +584,9 @@ // |extra_delay_frames_|). // * Queued data in |queue_|. // * Data in the rate shifter, if any. - double extra_delay_frames = - extra_delay_frames_ + queued_frames_ / playback_rate_; + double extra_delay_frames = extra_delay_frames_ + + queued_frames_ / playback_rate_ + + audio_clock_simulator_.DelayFrames(); if (rate_shifter_) { double rate_shifter_delay = static_cast<double>(rate_shifter_input_frames_) / playback_rate_ -
diff --git a/chromecast/media/cma/backend/mixer/mixer_input_connection.h b/chromecast/media/cma/backend/mixer/mixer_input_connection.h index 2b5421a..d3ce733 100644 --- a/chromecast/media/cma/backend/mixer/mixer_input_connection.h +++ b/chromecast/media/cma/backend/mixer/mixer_input_connection.h
@@ -16,6 +16,7 @@ #include "base/synchronization/lock.h" #include "base/thread_annotations.h" #include "base/timer/timer.h" +#include "chromecast/media/audio/audio_clock_simulator.h" #include "chromecast/media/audio/audio_fader.h" #include "chromecast/media/audio/audio_provider.h" #include "chromecast/media/audio/mixer_service/mixer_service.pb.h" @@ -90,6 +91,7 @@ void OnInactivityTimeout(); void RestartPlaybackAt(int64_t timestamp, int64_t pts); void SetMediaPlaybackRate(double rate); + void SetAudioClockRate(double rate); void SetPaused(bool paused); // MixerInput::Source implementation: @@ -175,6 +177,7 @@ int extra_delay_frames_ GUARDED_BY(lock_) = 0; int current_buffer_offset_ GUARDED_BY(lock_) = 0; AudioFader fader_ GUARDED_BY(lock_); + AudioClockSimulator audio_clock_simulator_ GUARDED_BY(lock_); bool zero_fader_frames_ GUARDED_BY(lock_) = false; bool started_ GUARDED_BY(lock_) = false; double playback_rate_ GUARDED_BY(lock_) = 1.0;
diff --git a/chromeos/constants/chromeos_features.cc b/chromeos/constants/chromeos_features.cc index 05f0c88..de92ece 100644 --- a/chromeos/constants/chromeos_features.cc +++ b/chromeos/constants/chromeos_features.cc
@@ -311,11 +311,6 @@ return base::FeatureList::IsEnabled(kQuickAnswers); } -bool IsSplitSettingsEnabled() { - // TODO(dpapad): Remove all calls to this function. - return true; -} - bool IsSplitSettingsSyncEnabled() { return base::FeatureList::IsEnabled(kSplitSettingsSync); }
diff --git a/chromeos/constants/chromeos_features.h b/chromeos/constants/chromeos_features.h index b8e69b14..d6f845a 100644 --- a/chromeos/constants/chromeos_features.h +++ b/chromeos/constants/chromeos_features.h
@@ -139,7 +139,6 @@ bool IsInstantTetheringBackgroundAdvertisingSupported(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsParentalControlsSettingsEnabled(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsQuickAnswersEnabled(); -COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsSplitSettingsEnabled(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsSplitSettingsSyncEnabled(); // TODO(michaelpg): Remove after M71 branch to re-enable Play Store by default.
diff --git a/chromeos/network/proxy/ui_proxy_config_service.cc b/chromeos/network/proxy/ui_proxy_config_service.cc index ab5f961..03c3aa3 100644 --- a/chromeos/network/proxy/ui_proxy_config_service.cc +++ b/chromeos/network/proxy/ui_proxy_config_service.cc
@@ -115,11 +115,9 @@ const std::string& source, const net::ProxyList& for_http, const net::ProxyList& for_https, - const net::ProxyList& for_ftp, const net::ProxyList& fallback, const net::ProxyBypassRules& bypass_rules) { - if (for_http.IsEmpty() && for_https.IsEmpty() && for_ftp.IsEmpty() && - fallback.IsEmpty()) { + if (for_http.IsEmpty() && for_https.IsEmpty() && fallback.IsEmpty()) { return base::Value(); } base::Value result = OncValueWithMode(source, ::onc::proxy::kManual); @@ -128,7 +126,6 @@ ::onc::proxy::kManual, base::Value(base::Value::Type::DICTIONARY)); SetManualProxy(manual, source, ::onc::proxy::kHttp, for_http); SetManualProxy(manual, source, ::onc::proxy::kHttps, for_https); - SetManualProxy(manual, source, ::onc::proxy::kFtp, for_ftp); SetManualProxy(manual, source, ::onc::proxy::kSocks, fallback); base::Value exclude_domains(base::Value::Type::LIST); @@ -171,13 +168,11 @@ net_config.proxy_rules().single_proxies, net_config.proxy_rules().single_proxies, net_config.proxy_rules().single_proxies, - net_config.proxy_rules().single_proxies, net_config.proxy_rules().bypass_rules); case net::ProxyConfig::ProxyRules::Type::PROXY_LIST_PER_SCHEME: return OncValueForManualProxyList( source, net_config.proxy_rules().proxies_for_http, net_config.proxy_rules().proxies_for_https, - net_config.proxy_rules().proxies_for_ftp, net_config.proxy_rules().fallback_proxies, net_config.proxy_rules().bypass_rules); }
diff --git a/chromeos/network/proxy/ui_proxy_config_service_unittest.cc b/chromeos/network/proxy/ui_proxy_config_service_unittest.cc index b5d458de..974ad834 100644 --- a/chromeos/network/proxy/ui_proxy_config_service_unittest.cc +++ b/chromeos/network/proxy/ui_proxy_config_service_unittest.cc
@@ -316,8 +316,7 @@ std::unique_ptr<UIProxyConfigService> service = CreateServiceForUser(); base::Value policy_prefs_config = ProxyConfigDictionary::CreateFixedServers( - "http=proxy1:81;https=proxy2:81;ftp=proxy3:81;socks=proxy4:81", - "localhost"); + "http=proxy1:81;https=proxy2:81;socks=proxy3:81", "localhost"); user_prefs_.SetManagedPref( proxy_config::prefs::kProxy, base::Value::ToUniquePtrValue(std::move(policy_prefs_config))); @@ -328,17 +327,15 @@ std::string expected_json = base::ReplaceStringPlaceholders( R"({"Type": $1, "Manual": { - "HTTPProxy": {"Host": $2, "Port": $6}, - "SecureHTTPProxy": {"Host": $3, "Port": $6}, - "FTPProxy": {"Host": $4, "Port": $6}, - "SOCKS": {"Host": $5, "Port": $6} + "HTTPProxy": {"Host": $2, "Port": $5}, + "SecureHTTPProxy": {"Host": $3, "Port": $5}, + "SOCKS": {"Host": $4, "Port": $5} }, - "ExcludeDomains": $7 + "ExcludeDomains": $6 })", {UserPolicyOncValue(R"("Manual")"), UserPolicyOncValue(R"("proxy1")"), UserPolicyOncValue(R"("proxy2")"), UserPolicyOncValue(R"("proxy3")"), - UserPolicyOncValue(R"("proxy4")"), UserPolicyOncValue("81"), - UserPolicyOncValue(R"(["localhost"])")}, + UserPolicyOncValue("81"), UserPolicyOncValue(R"(["localhost"])")}, nullptr); std::unique_ptr<base::Value> expected = base::JSONReader::ReadDeprecated(expected_json); @@ -349,8 +346,8 @@ TEST_F(UIProxyConfigServiceTest, PartialManualPolicyPref) { std::unique_ptr<UIProxyConfigService> service = CreateServiceForUser(); - base::Value policy_prefs_config = ProxyConfigDictionary::CreateFixedServers( - "http=proxy1:81;ftp=proxy3:83;", ""); + base::Value policy_prefs_config = + ProxyConfigDictionary::CreateFixedServers("http=proxy1:81;", ""); user_prefs_.SetManagedPref( proxy_config::prefs::kProxy, base::Value::ToUniquePtrValue(std::move(policy_prefs_config))); @@ -362,15 +359,13 @@ R"({"Type": $1, "Manual": { "HTTPProxy": {"Host": $2, "Port": $3}, - "FTPProxy": {"Host": $4, "Port": $5}, - "SecureHTTPProxy": {"Host": $6, "Port": $7}, - "SOCKS": {"Host": $6, "Port": $7} + "SecureHTTPProxy": {"Host": $4, "Port": $5}, + "SOCKS": {"Host": $4, "Port": $5} }, - "ExcludeDomains": $8 + "ExcludeDomains": $6 })", {UserPolicyOncValue(R"("Manual")"), UserPolicyOncValue(R"("proxy1")"), - UserPolicyOncValue("81"), UserPolicyOncValue(R"("proxy3")"), - UserPolicyOncValue("83"), UserPolicyOncValue(R"("")"), + UserPolicyOncValue("81"), UserPolicyOncValue(R"("")"), UserPolicyOncValue("0"), UserPolicyOncValue("[]")}, nullptr); std::unique_ptr<base::Value> expected = @@ -383,7 +378,7 @@ std::unique_ptr<UIProxyConfigService> service = CreateServiceForUser(); base::Value policy_prefs_config = ProxyConfigDictionary::CreateFixedServers( - "http=proxy:80;https=proxy:80;ftp=proxy:80;socks=proxy:80", "localhost"); + "http=proxy:80;https=proxy:80;socks=proxy:80", "localhost"); user_prefs_.SetManagedPref( proxy_config::prefs::kProxy, base::Value::ToUniquePtrValue(std::move(policy_prefs_config))); @@ -405,7 +400,6 @@ "Manual": { "HTTPProxy": {"Host": $2, "Port": $3}, "SecureHTTPProxy": {"Host": $2, "Port": $3}, - "FTPProxy": {"Host": $2, "Port": $3}, "SOCKS": {"Host": $2, "Port": $3} }, "PAC": $4, @@ -489,8 +483,7 @@ base::Value extension_prefs_config = ProxyConfigDictionary::CreateFixedServers( - "http=proxy1:81;https=proxy2:82;ftp=proxy3:83;socks=proxy4:81", - "localhost"); + "http=proxy1:81;https=proxy2:82;socks=proxy3:81", "localhost"); user_prefs_.SetExtensionPref( proxy_config::prefs::kProxy, base::Value::ToUniquePtrValue(std::move(extension_prefs_config))); @@ -503,10 +496,9 @@ "Manual": { "HTTPProxy": {"Host": $2, "Port": $3}, "SecureHTTPProxy": {"Host": $4, "Port": $5}, - "FTPProxy": {"Host": $6, "Port": $7}, - "SOCKS": {"Host": $8, "Port": $3} + "SOCKS": {"Host": $6, "Port": $3} }, - "ExcludeDomains": $9 + "ExcludeDomains": $7 })", {ExtensionControlledOncValue(R"("Manual")"), ExtensionControlledOncValue(R"("proxy1")"), @@ -514,8 +506,6 @@ ExtensionControlledOncValue(R"("proxy2")"), ExtensionControlledOncValue("82"), ExtensionControlledOncValue(R"("proxy3")"), - ExtensionControlledOncValue("83"), - ExtensionControlledOncValue(R"("proxy4")"), ExtensionControlledOncValue(R"(["localhost"])")}, nullptr); std::unique_ptr<base::Value> expected = @@ -723,8 +713,7 @@ "Manual": { "HTTPProxy": {"Host": "proxy1", "Port": 81}, "SecureHTTPProxy": {"Host": "proxy2", "Port": 82}, - "FTPProxy": {"Host": "proxy3", "Port": 83}, - "SOCKS": {"Host": "proxy4", "Port": 83}}}}])", + "SOCKS": {"Host": "proxy3", "Port": 83}}}}])", {kTestUserWifiGuid}, nullptr); user_prefs_.SetManagedPref(::onc::prefs::kOpenNetworkConfiguration, base::JSONReader::ReadDeprecated(onc_config)); @@ -737,15 +726,14 @@ "Manual": { "HTTPProxy": {"Host": $2, "Port": $3}, "SecureHTTPProxy": {"Host": $4, "Port": $5}, - "FTPProxy": {"Host": $6, "Port": $7}, - "SOCKS": {"Host": $8, "Port": $7} + "SOCKS": {"Host": $7, "Port": $6} }, - "ExcludeDomains": $9 + "ExcludeDomains": $8 })", {UserPolicyOncValue(R"("Manual")"), UserPolicyOncValue(R"("proxy1")"), UserPolicyOncValue("81"), UserPolicyOncValue(R"("proxy2")"), - UserPolicyOncValue("82"), UserPolicyOncValue(R"("proxy3")"), - UserPolicyOncValue("83"), UserPolicyOncValue(R"("proxy4")"), + UserPolicyOncValue("82"), UserPolicyOncValue("83"), + UserPolicyOncValue(R"("proxy3")"), UserPolicyOncValue(R"(["foo.test", "localhost"])")}, nullptr); std::unique_ptr<base::Value> expected = @@ -775,8 +763,7 @@ "Manual": { "HTTPProxy": {"Host": $2, "Port": $3}, "SOCKS": {"Host": $4, "Port": $5}, - "SecureHTTPProxy": {"Host": $6, "Port": $7}, - "FTPProxy": {"Host": $6, "Port": $7} + "SecureHTTPProxy": {"Host": $6, "Port": $7} }, "ExcludeDomains": $8 })",
diff --git a/components/background_task_scheduler/BUILD.gn b/components/background_task_scheduler/BUILD.gn index 552b453d..d2fa8da 100644 --- a/components/background_task_scheduler/BUILD.gn +++ b/components/background_task_scheduler/BUILD.gn
@@ -70,7 +70,6 @@ testonly = true sources = [ - "android/javatests/src/org/chromium/components/background_task_scheduler/BackgroundTaskBroadcastReceiverTest.java", "android/javatests/src/org/chromium/components/background_task_scheduler/BackgroundTaskSchedulerImplWithMockTest.java", "android/javatests/src/org/chromium/components/background_task_scheduler/BackgroundTaskSchedulerJobServiceTest.java", "android/javatests/src/org/chromium/components/background_task_scheduler/BundleToPersistableBundleConverterTest.java", @@ -101,6 +100,7 @@ "android/junit/src/org/chromium/components/background_task_scheduler/BackgroundTaskSchedulerImplTest.java", "android/junit/src/org/chromium/components/background_task_scheduler/BackgroundTaskSchedulerPrefsTest.java", "android/junit/src/org/chromium/components/background_task_scheduler/BackgroundTaskSchedulerUmaTest.java", + "android/junit/src/org/chromium/components/background_task_scheduler/BroadcastReceiverRobolectricTest.java", "android/junit/src/org/chromium/components/background_task_scheduler/ExtrasToProtoConverterTest.java", "android/junit/src/org/chromium/components/background_task_scheduler/ShadowGcmNetworkManager.java", "android/junit/src/org/chromium/components/background_task_scheduler/TaskInfoTest.java",
diff --git a/components/background_task_scheduler/android/java/src/org/chromium/components/background_task_scheduler/BackgroundTaskBroadcastReceiver.java b/components/background_task_scheduler/android/java/src/org/chromium/components/background_task_scheduler/BackgroundTaskBroadcastReceiver.java index 76bac5e..60c850c 100644 --- a/components/background_task_scheduler/android/java/src/org/chromium/components/background_task_scheduler/BackgroundTaskBroadcastReceiver.java +++ b/components/background_task_scheduler/android/java/src/org/chromium/components/background_task_scheduler/BackgroundTaskBroadcastReceiver.java
@@ -7,6 +7,12 @@ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; +import android.content.IntentFilter; +import android.net.ConnectivityManager; +import android.net.Network; +import android.net.NetworkInfo; +import android.os.BatteryManager; +import android.os.Build; import android.os.PowerManager; import android.text.format.DateUtils; @@ -18,8 +24,6 @@ /** * Starts running the BackgroundTask at the specified triggering time. - * TODO (crbug.com/970160): Check that the requirements set for the BackgroundTask are met before - * starting it. * * Receives the information through a broadcast, which is synchronous in the Main thread. The * execution of the task will be detached to a best effort task. @@ -96,8 +100,33 @@ return; } + int taskId = taskParams.getTaskId(); + ScheduledTaskProto.ScheduledTask scheduledTask = + BackgroundTaskSchedulerPrefs.getScheduledTask(taskId); + if (scheduledTask == null) { + Log.e(TAG, "Cannot get information about task with task ID " + taskId); + return; + } + + // Only continue if network requirements match network status. + if (!networkRequirementsMet(context, taskId, + convertToTaskInfoNetworkType(scheduledTask.getRequiredNetworkType()))) { + Log.w(TAG, + "Failed to start task. Network requirements not satisfied for task with task ID" + + taskId); + return; + } + + // Check if battery requirements match. + if (!batteryRequirementsMet(context, taskId, scheduledTask.getRequiresCharging())) { + Log.w(TAG, + "Failed to start task. Battery requirements not satisfied for task with task ID" + + taskId); + return; + } + final BackgroundTask backgroundTask = - BackgroundTaskSchedulerFactory.getBackgroundTaskFromTaskId(taskParams.getTaskId()); + BackgroundTaskSchedulerFactory.getBackgroundTaskFromTaskId(taskId); if (backgroundTask == null) { Log.w(TAG, "Failed to start task. Could not instantiate BackgroundTask class."); // Cancel task if the BackgroundTask class is not found anymore. We assume this means @@ -116,4 +145,52 @@ TaskExecutor taskExecutor = new TaskExecutor(context, wakeLock, taskParams, backgroundTask); PostTask.postTask(UiThreadTaskTraits.BEST_EFFORT, taskExecutor::execute); } + + private boolean networkRequirementsMet(Context context, int taskId, int requiredNetworkType) { + if (requiredNetworkType == TaskInfo.NetworkType.NONE) return true; + + ConnectivityManager connectivityManager = + (ConnectivityManager) context.getApplicationContext().getSystemService( + Context.CONNECTIVITY_SERVICE); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + Network network = connectivityManager.getActiveNetwork(); + if (requiredNetworkType == TaskInfo.NetworkType.ANY) return (network != null); + } else { + NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); + if (requiredNetworkType == TaskInfo.NetworkType.ANY) return (networkInfo != null); + } + + return (!connectivityManager.isActiveNetworkMetered()); + } + + private boolean batteryRequirementsMet(Context context, int taskId, boolean requiresCharging) { + if (!requiresCharging) return true; + BatteryManager batteryManager = + (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE); + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + return batteryManager.isCharging(); + } + + IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); + Intent batteryStatus = context.registerReceiver(null, intentFilter); + int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1); + return status == BatteryManager.BATTERY_STATUS_CHARGING + || status == BatteryManager.BATTERY_STATUS_FULL; + } + + private @TaskInfo.NetworkType int convertToTaskInfoNetworkType( + ScheduledTaskProto.ScheduledTask.RequiredNetworkType networkType) { + switch (networkType) { + case NONE: + return TaskInfo.NetworkType.NONE; + case ANY: + return TaskInfo.NetworkType.ANY; + case UNMETERED: + return TaskInfo.NetworkType.UNMETERED; + default: + assert false : "Incorrect value of RequiredNetworkType"; + return -1; + } + } }
diff --git a/components/background_task_scheduler/android/java/src/org/chromium/components/background_task_scheduler/BackgroundTaskSchedulerAlarmManager.java b/components/background_task_scheduler/android/java/src/org/chromium/components/background_task_scheduler/BackgroundTaskSchedulerAlarmManager.java index 7b14235..77514aa 100644 --- a/components/background_task_scheduler/android/java/src/org/chromium/components/background_task_scheduler/BackgroundTaskSchedulerAlarmManager.java +++ b/components/background_task_scheduler/android/java/src/org/chromium/components/background_task_scheduler/BackgroundTaskSchedulerAlarmManager.java
@@ -40,6 +40,7 @@ ScheduledTaskProto.ScheduledTask scheduledTask = BackgroundTaskSchedulerPrefs.getScheduledTask(taskId); + if (scheduledTask == null) { Log.e(TAG, "Cannot get information about task with task ID " + taskId); return null;
diff --git a/components/background_task_scheduler/android/java/src/org/chromium/components/background_task_scheduler/BackgroundTaskSchedulerPrefs.java b/components/background_task_scheduler/android/java/src/org/chromium/components/background_task_scheduler/BackgroundTaskSchedulerPrefs.java index 5da57ec..d0e36ef 100644 --- a/components/background_task_scheduler/android/java/src/org/chromium/components/background_task_scheduler/BackgroundTaskSchedulerPrefs.java +++ b/components/background_task_scheduler/android/java/src/org/chromium/components/background_task_scheduler/BackgroundTaskSchedulerPrefs.java
@@ -109,7 +109,8 @@ public static void addScheduledTask(TaskInfo taskInfo) { try (TraceEvent te = TraceEvent.scoped("BackgroundTaskSchedulerPrefs.addScheduledTask", Integer.toString(taskInfo.getTaskId()))) { - ScheduledTaskProtoVisitor visitor = new ScheduledTaskProtoVisitor(taskInfo.getExtras()); + ScheduledTaskProtoVisitor visitor = new ScheduledTaskProtoVisitor(taskInfo.getExtras(), + taskInfo.getRequiredNetworkType(), taskInfo.requiresCharging()); taskInfo.getTimingInfo().accept(visitor); getSharedPreferences() @@ -123,9 +124,15 @@ private static class ScheduledTaskProtoVisitor implements TaskInfo.TimingInfoVisitor { private String mSerializedScheduledTask; private final Bundle mExtras; + @TaskInfo.NetworkType + private final int mRequiredNetworkType; + private final boolean mRequiresCharging; - ScheduledTaskProtoVisitor(Bundle extras) { + ScheduledTaskProtoVisitor(Bundle extras, @TaskInfo.NetworkType int requiredNetworkType, + boolean requiresCharging) { mExtras = extras; + mRequiredNetworkType = requiredNetworkType; + mRequiresCharging = requiresCharging; } // Only valid after a TimingInfo object was visited. @@ -159,6 +166,9 @@ ScheduledTaskProto.ScheduledTask.newBuilder() .setType(ScheduledTaskProto.ScheduledTask.Type.EXACT) .setTriggerMs(exactInfo.getTriggerAtMs()) + .setRequiredNetworkType( + convertToRequiredNetworkType(mRequiredNetworkType)) + .setRequiresCharging(mRequiresCharging) .addAllExtras( ExtrasToProtoConverter.convertExtrasToProtoExtras(mExtras)) .build(); @@ -283,4 +293,19 @@ .apply(); } } + + private static ScheduledTaskProto.ScheduledTask.RequiredNetworkType + convertToRequiredNetworkType(@TaskInfo.NetworkType int networkType) { + switch (networkType) { + case TaskInfo.NetworkType.NONE: + return ScheduledTaskProto.ScheduledTask.RequiredNetworkType.NONE; + case TaskInfo.NetworkType.ANY: + return ScheduledTaskProto.ScheduledTask.RequiredNetworkType.ANY; + case TaskInfo.NetworkType.UNMETERED: + return ScheduledTaskProto.ScheduledTask.RequiredNetworkType.UNMETERED; + default: + assert false : "Incorrect value of TaskInfo.NetworkType"; + return ScheduledTaskProto.ScheduledTask.RequiredNetworkType.NONE; + } + } } \ No newline at end of file
diff --git a/components/background_task_scheduler/android/java/src/org/chromium/components/background_task_scheduler/scheduled_task.proto b/components/background_task_scheduler/android/java/src/org/chromium/components/background_task_scheduler/scheduled_task.proto index 4020735..d80e72c 100644 --- a/components/background_task_scheduler/android/java/src/org/chromium/components/background_task_scheduler/scheduled_task.proto +++ b/components/background_task_scheduler/android/java/src/org/chromium/components/background_task_scheduler/scheduled_task.proto
@@ -18,6 +18,12 @@ EXACT = 2; } + enum RequiredNetworkType { + NONE = 0; + ANY = 1; + UNMETERED = 2; + } + // The type of the scheduled task. Type type = 1; @@ -62,4 +68,14 @@ // PeriodicTask objects store their extras through their scheduling backend // (JobScheduler and GcmNetworkManager). repeated ExtraItem extras = 3; + + // Required network type, stored for an ExactTask. OneOffTask and PeriodicTask + // objects store their required network type through their scheduling backend + // (JobScheduler and GCMNetworkManager). + RequiredNetworkType required_network_type = 4; + + // Bool representing whether the task requires charging. Stored for an + // ExactTask. OneOffTask and PeriodicTask objects store this info through + // their scheduling backend (JobScheduler and GCMNetworkManager). + bool requires_charging = 5; } \ No newline at end of file
diff --git a/components/background_task_scheduler/android/javatests/src/org/chromium/components/background_task_scheduler/BackgroundTaskBroadcastReceiverTest.java b/components/background_task_scheduler/android/javatests/src/org/chromium/components/background_task_scheduler/BackgroundTaskBroadcastReceiverTest.java deleted file mode 100644 index 48b3367..0000000 --- a/components/background_task_scheduler/android/javatests/src/org/chromium/components/background_task_scheduler/BackgroundTaskBroadcastReceiverTest.java +++ /dev/null
@@ -1,99 +0,0 @@ -// Copyright 2019 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.components.background_task_scheduler; - -import static org.junit.Assert.assertEquals; - -import android.content.Context; -import android.content.Intent; -import android.support.test.filters.MediumTest; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.chromium.base.ContextUtils; -import org.chromium.base.ThreadUtils; -import org.chromium.base.test.BaseJUnit4ClassRunner; -import org.chromium.content_public.browser.test.util.CriteriaHelper; - -import java.util.concurrent.Callable; -import java.util.concurrent.TimeUnit; - -/** Tests for {@link BackgroundTaskBroadcastReceiver}. */ -@RunWith(BaseJUnit4ClassRunner.class) -public class BackgroundTaskBroadcastReceiverTest { - class TestBackgroundTask implements BackgroundTask { - public TestBackgroundTask() {} - - @Override - public boolean onStartTask( - Context context, TaskParameters taskParameters, TaskFinishedCallback callback) { - ThreadUtils.assertOnUiThread(); - mScheduled++; - return false; - } - - @Override - public boolean onStopTask(Context context, TaskParameters taskParameters) { - ThreadUtils.assertOnUiThread(); - mStopped++; - return false; - } - - @Override - public void reschedule(Context context) { - ThreadUtils.assertOnUiThread(); - mRescheduled++; - } - } - - class TestBackgroundTaskFactory implements BackgroundTaskFactory { - @Override - public BackgroundTask getBackgroundTaskFromTaskId(int taskId) { - if (taskId == TaskIds.TEST) { - return new TestBackgroundTask(); - } - return null; - } - } - - private int mScheduled; - private int mStopped; - private int mRescheduled; - - @Before - public void setUp() { - mScheduled = 0; - mStopped = 0; - mRescheduled = 0; - - BackgroundTaskSchedulerFactory.setBackgroundTaskFactory(new TestBackgroundTaskFactory()); - } - - @Test - @MediumTest - public void testStartExact() { - TaskInfo.TimingInfo exactInfo = - TaskInfo.ExactInfo.create().setTriggerAtMs(System.currentTimeMillis()).build(); - TaskInfo exactTask = TaskInfo.createTask(TaskIds.TEST, exactInfo).build(); - BackgroundTaskSchedulerPrefs.addScheduledTask(exactTask); - - Intent intent = new Intent( - ContextUtils.getApplicationContext(), BackgroundTaskBroadcastReceiver.class) - .putExtra(BackgroundTaskSchedulerDelegate.BACKGROUND_TASK_ID_KEY, - TaskIds.TEST); - - BackgroundTaskBroadcastReceiver receiver = new BackgroundTaskBroadcastReceiver(); - receiver.onReceive(ContextUtils.getApplicationContext(), intent); - - Callable<Boolean> hasScheduled = () -> mScheduled == 1; - CriteriaHelper.pollUiThread(hasScheduled, "Failed to schedule task", - /*maxTimeoutMs=*/TimeUnit.MINUTES.toMillis(2), /*checkIntervalMs=*/50); - - assertEquals(0, mStopped); - assertEquals(0, mRescheduled); - } -}
diff --git a/components/background_task_scheduler/android/junit/src/org/chromium/components/background_task_scheduler/BroadcastReceiverRobolectricTest.java b/components/background_task_scheduler/android/junit/src/org/chromium/components/background_task_scheduler/BroadcastReceiverRobolectricTest.java new file mode 100644 index 0000000..f4924f7 --- /dev/null +++ b/components/background_task_scheduler/android/junit/src/org/chromium/components/background_task_scheduler/BroadcastReceiverRobolectricTest.java
@@ -0,0 +1,270 @@ +// Copyright 2019 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.components.background_task_scheduler; + +import static org.junit.Assert.assertEquals; +import static org.robolectric.Shadows.shadowOf; + +import android.content.Context; +import android.content.Intent; +import android.net.ConnectivityManager; +import android.os.BatteryManager; +import android.os.Build; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; +import org.robolectric.shadows.ShadowBatteryManager; +import org.robolectric.shadows.ShadowConnectivityManager; + +import org.chromium.base.ContextUtils; +import org.chromium.base.ThreadUtils; +import org.chromium.base.test.BaseRobolectricTestRunner; +import org.chromium.base.test.util.Feature; +import org.chromium.base.test.util.MinAndroidSdkLevel; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** Robolectric tests for BackgroundTaskBroadcastReceiver. */ +@RunWith(BaseRobolectricTestRunner.class) +@Config(manifest = Config.NONE, + shadows = {ShadowBatteryManager.class, ShadowConnectivityManager.class}) +public final class BroadcastReceiverRobolectricTest { + private static final long WAIT_TIME_MS = 10; + private CountDownLatch mScheduleLatch; + private int mStopped; + private int mRescheduled; + + private BatteryManager mBatteryManager; + private ShadowBatteryManager mShadowBatteryManager; + private ConnectivityManager mConnectivityManager; + private ShadowConnectivityManager mShadowConnectivityManager; + + class TestBackgroundTask implements BackgroundTask { + public TestBackgroundTask() {} + + @Override + public boolean onStartTask( + Context context, TaskParameters taskParameters, TaskFinishedCallback callback) { + ThreadUtils.assertOnUiThread(); + mScheduleLatch.countDown(); + return false; + } + + @Override + public boolean onStopTask(Context context, TaskParameters taskParameters) { + ThreadUtils.assertOnUiThread(); + mStopped++; + return false; + } + + @Override + public void reschedule(Context context) { + ThreadUtils.assertOnUiThread(); + mRescheduled++; + } + } + + class TestBackgroundTaskFactory implements BackgroundTaskFactory { + @Override + public BackgroundTask getBackgroundTaskFromTaskId(int taskId) { + if (taskId == TaskIds.TEST) { + return new TestBackgroundTask(); + } + return null; + } + } + + @Before + public void setUp() { + mScheduleLatch = new CountDownLatch(1); + mStopped = 0; + mRescheduled = 0; + + BackgroundTaskSchedulerFactory.setBackgroundTaskFactory(new TestBackgroundTaskFactory()); + + mBatteryManager = (BatteryManager) ContextUtils.getApplicationContext().getSystemService( + Context.BATTERY_SERVICE); + mShadowBatteryManager = shadowOf(mBatteryManager); + + mConnectivityManager = + (ConnectivityManager) ContextUtils.getApplicationContext().getSystemService( + Context.CONNECTIVITY_SERVICE); + mShadowConnectivityManager = shadowOf(mConnectivityManager); + } + + @Test + @Feature({"BackgroundTaskScheduler"}) + public void testStartExact() throws InterruptedException { + TaskInfo.TimingInfo exactInfo = + TaskInfo.ExactInfo.create().setTriggerAtMs(System.currentTimeMillis()).build(); + TaskInfo exactTask = TaskInfo.createTask(TaskIds.TEST, exactInfo).build(); + BackgroundTaskSchedulerPrefs.addScheduledTask(exactTask); + + Intent intent = new Intent( + ContextUtils.getApplicationContext(), BackgroundTaskBroadcastReceiver.class) + .putExtra(BackgroundTaskSchedulerDelegate.BACKGROUND_TASK_ID_KEY, + TaskIds.TEST); + + BackgroundTaskBroadcastReceiver receiver = new BackgroundTaskBroadcastReceiver(); + receiver.onReceive(ContextUtils.getApplicationContext(), intent); + + Assert.assertTrue(mScheduleLatch.await(WAIT_TIME_MS, TimeUnit.MILLISECONDS)); + assertEquals(0, mStopped); + assertEquals(0, mRescheduled); + } + + @Test + @Feature({"BackgroundTaskScheduler"}) + public void noChargingRequired() throws InterruptedException { + TaskInfo.TimingInfo exactInfo = + TaskInfo.ExactInfo.create().setTriggerAtMs(System.currentTimeMillis()).build(); + TaskInfo exactTask = + TaskInfo.createTask(TaskIds.TEST, exactInfo).setRequiresCharging(false).build(); + BackgroundTaskSchedulerPrefs.addScheduledTask(exactTask); + + Intent intent = new Intent( + ContextUtils.getApplicationContext(), BackgroundTaskBroadcastReceiver.class) + .putExtra(BackgroundTaskSchedulerDelegate.BACKGROUND_TASK_ID_KEY, + TaskIds.TEST); + + BackgroundTaskBroadcastReceiver receiver = new BackgroundTaskBroadcastReceiver(); + receiver.onReceive(ContextUtils.getApplicationContext(), intent); + + Assert.assertTrue(mScheduleLatch.await(WAIT_TIME_MS, TimeUnit.MILLISECONDS)); + assertEquals(0, mStopped); + assertEquals(0, mRescheduled); + } + + @Test + @MinAndroidSdkLevel(Build.VERSION_CODES.M) + @Feature({"BackgroundTaskScheduler"}) + public void withChargingRequired() throws InterruptedException { + // Set device in charging mode + mShadowBatteryManager.setIsCharging(true); + Assert.assertTrue(mBatteryManager.isCharging()); + + TaskInfo.TimingInfo exactInfo = + TaskInfo.ExactInfo.create().setTriggerAtMs(System.currentTimeMillis()).build(); + TaskInfo exactTask = + TaskInfo.createTask(TaskIds.TEST, exactInfo).setRequiresCharging(true).build(); + BackgroundTaskSchedulerPrefs.addScheduledTask(exactTask); + + Intent intent = new Intent( + ContextUtils.getApplicationContext(), BackgroundTaskBroadcastReceiver.class) + .putExtra(BackgroundTaskSchedulerDelegate.BACKGROUND_TASK_ID_KEY, + TaskIds.TEST); + + BackgroundTaskBroadcastReceiver receiver = new BackgroundTaskBroadcastReceiver(); + receiver.onReceive(ContextUtils.getApplicationContext(), intent); + + Assert.assertTrue(mScheduleLatch.await(WAIT_TIME_MS, TimeUnit.MILLISECONDS)); + assertEquals(0, mStopped); + assertEquals(0, mRescheduled); + } + + @Test + @Feature({"BackgroundTaskScheduler"}) + public void noNetworkRequirements() throws InterruptedException { + TaskInfo.TimingInfo exactInfo = + TaskInfo.ExactInfo.create().setTriggerAtMs(System.currentTimeMillis()).build(); + TaskInfo exactTask = TaskInfo.createTask(TaskIds.TEST, exactInfo) + .setRequiredNetworkType(TaskInfo.NetworkType.NONE) + .build(); + BackgroundTaskSchedulerPrefs.addScheduledTask(exactTask); + + Intent intent = new Intent( + ContextUtils.getApplicationContext(), BackgroundTaskBroadcastReceiver.class) + .putExtra(BackgroundTaskSchedulerDelegate.BACKGROUND_TASK_ID_KEY, + TaskIds.TEST); + + BackgroundTaskBroadcastReceiver receiver = new BackgroundTaskBroadcastReceiver(); + receiver.onReceive(ContextUtils.getApplicationContext(), intent); + + Assert.assertTrue(mScheduleLatch.await(WAIT_TIME_MS, TimeUnit.MILLISECONDS)); + assertEquals(0, mStopped); + assertEquals(0, mRescheduled); + } + + @Test + @MinAndroidSdkLevel(Build.VERSION_CODES.L) + @Feature({"BackgroundTaskScheduler"}) + public void withAnyNetworkRequired() throws InterruptedException { + mShadowConnectivityManager.setDefaultNetworkActive(true); + TaskInfo.TimingInfo exactInfo = + TaskInfo.ExactInfo.create().setTriggerAtMs(System.currentTimeMillis()).build(); + TaskInfo exactTask = TaskInfo.createTask(TaskIds.TEST, exactInfo) + .setRequiredNetworkType(TaskInfo.NetworkType.ANY) + .build(); + BackgroundTaskSchedulerPrefs.addScheduledTask(exactTask); + + Intent intent = new Intent( + ContextUtils.getApplicationContext(), BackgroundTaskBroadcastReceiver.class) + .putExtra(BackgroundTaskSchedulerDelegate.BACKGROUND_TASK_ID_KEY, + TaskIds.TEST); + + BackgroundTaskBroadcastReceiver receiver = new BackgroundTaskBroadcastReceiver(); + receiver.onReceive(ContextUtils.getApplicationContext(), intent); + + Assert.assertTrue(mScheduleLatch.await(WAIT_TIME_MS, TimeUnit.MILLISECONDS)); + assertEquals(0, mStopped); + assertEquals(0, mRescheduled); + } + + @Test + @MinAndroidSdkLevel(Build.VERSION_CODES.M) + @Feature({"BackgroundTaskScheduler"}) + public void withAnyNetworkRequiredButNoConnectivity() throws InterruptedException { + mShadowConnectivityManager.setDefaultNetworkActive(false); + + TaskInfo.TimingInfo exactInfo = + TaskInfo.ExactInfo.create().setTriggerAtMs(System.currentTimeMillis()).build(); + TaskInfo exactTask = TaskInfo.createTask(TaskIds.TEST, exactInfo) + .setRequiredNetworkType(TaskInfo.NetworkType.ANY) + .build(); + BackgroundTaskSchedulerPrefs.addScheduledTask(exactTask); + + Intent intent = new Intent( + ContextUtils.getApplicationContext(), BackgroundTaskBroadcastReceiver.class) + .putExtra(BackgroundTaskSchedulerDelegate.BACKGROUND_TASK_ID_KEY, + TaskIds.TEST); + + BackgroundTaskBroadcastReceiver receiver = new BackgroundTaskBroadcastReceiver(); + receiver.onReceive(ContextUtils.getApplicationContext(), intent); + + // TODO(crbug.com/1964613): Explore ways to avoid waiting for WAIT_TIME_MS here. + Assert.assertFalse(mScheduleLatch.await(WAIT_TIME_MS, TimeUnit.MILLISECONDS)); + assertEquals(0, mStopped); + assertEquals(0, mRescheduled); + } + + @Test + @Feature({"BackgroundTaskScheduler"}) + public void withUnmeteredNetworkRequired() throws InterruptedException { + mShadowConnectivityManager.setActiveNetworkInfo( + mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)); + TaskInfo.TimingInfo exactInfo = + TaskInfo.ExactInfo.create().setTriggerAtMs(System.currentTimeMillis()).build(); + TaskInfo exactTask = TaskInfo.createTask(TaskIds.TEST, exactInfo) + .setRequiredNetworkType(TaskInfo.NetworkType.UNMETERED) + .build(); + BackgroundTaskSchedulerPrefs.addScheduledTask(exactTask); + + Intent intent = new Intent( + ContextUtils.getApplicationContext(), BackgroundTaskBroadcastReceiver.class) + .putExtra(BackgroundTaskSchedulerDelegate.BACKGROUND_TASK_ID_KEY, + TaskIds.TEST); + + BackgroundTaskBroadcastReceiver receiver = new BackgroundTaskBroadcastReceiver(); + receiver.onReceive(ContextUtils.getApplicationContext(), intent); + + Assert.assertTrue(mScheduleLatch.await(WAIT_TIME_MS, TimeUnit.MILLISECONDS)); + assertEquals(0, mStopped); + assertEquals(0, mRescheduled); + } +}
diff --git a/components/onc/docs/onc_spec.md b/components/onc/docs/onc_spec.md index 4dbad07..740e12b 100644 --- a/components/onc/docs/onc_spec.md +++ b/components/onc/docs/onc_spec.md
@@ -1131,7 +1131,7 @@ * (optional) - [ProxyLocation](#ProxyLocation-type) * settings for secure HTTP proxy. -* **FTPProxy** +* **FTPProxy (Unsupported)** * (optional) - [ProxyLocation](#ProxyLocation-type) * settings for FTP proxy
diff --git a/components/optimization_guide/hints_processing_util.cc b/components/optimization_guide/hints_processing_util.cc index ca31e5c5..6f1f3d0 100644 --- a/components/optimization_guide/hints_processing_util.cc +++ b/components/optimization_guide/hints_processing_util.cc
@@ -36,6 +36,8 @@ return "DeferAllScript"; case proto::OptimizationType::PERFORMANCE_HINTS: return "PerformanceHints"; + case proto::OptimizationType::LITE_PAGE: + return "LitePage"; } NOTREACHED(); return std::string();
diff --git a/components/optimization_guide/proto/hints.proto b/components/optimization_guide/proto/hints.proto index 5b641d9..2df1867 100644 --- a/components/optimization_guide/proto/hints.proto +++ b/components/optimization_guide/proto/hints.proto
@@ -123,6 +123,9 @@ // This optimization is used to provide aggregated performance information // about the page and pages it links to. PERFORMANCE_HINTS = 6; + // This optimization allows page loads going through the data reduction + // proxy to be transformed by the proxy. + LITE_PAGE = 7; } // Presents semantics for how page load URLs should be matched.
diff --git a/components/password_manager/core/common/password_manager_features.cc b/components/password_manager/core/common/password_manager_features.cc index 74e0c58..c1689a6 100644 --- a/components/password_manager/core/common/password_manager_features.cc +++ b/components/password_manager/core/common/password_manager_features.cc
@@ -83,10 +83,6 @@ const base::Feature kUsernameFirstFlow = {"UsernameFirstFlow", base::FEATURE_DISABLED_BY_DEFAULT}; -// Makes the password managaer save/update bubble sticky. -const base::Feature kStickyBubble{"PasswordManagerStickyBubble", - base::FEATURE_DISABLED_BY_DEFAULT}; - // Field trial identifier for password generation requirements. const char kGenerationRequirementsFieldTrial[] = "PasswordGenerationRequirements";
diff --git a/components/password_manager/core/common/password_manager_features.h b/components/password_manager/core/common/password_manager_features.h index 242feb2b..bd33e391 100644 --- a/components/password_manager/core/common/password_manager_features.h +++ b/components/password_manager/core/common/password_manager_features.h
@@ -33,7 +33,6 @@ extern const base::Feature kPasswordManagerOnboardingAndroid; extern const base::Feature kPasswordSaveIllustration; extern const base::Feature kUsernameFirstFlow; -extern const base::Feature kStickyBubble; // Field trial and corresponding parameters. // To manually override this, start Chrome with the following parameters:
diff --git a/components/viz/service/display_embedder/skia_output_device_buffer_queue.cc b/components/viz/service/display_embedder/skia_output_device_buffer_queue.cc index 57bf523..2659a335 100644 --- a/components/viz/service/display_embedder/skia_output_device_buffer_queue.cc +++ b/components/viz/service/display_embedder/skia_output_device_buffer_queue.cc
@@ -113,10 +113,13 @@ std::vector<GrBackendSemaphore> begin_semaphores; SkSurfaceProps surface_props{0, kUnknown_SkPixelGeometry}; + // Buffer queue is internal to GPU proc and handles texture initialization, + // so allow uncleared access. // TODO(vasilyt): Props and MSAA scoped_write_access_ = skia_representation_->BeginScopedWriteAccess( 0 /* final_msaa_count */, surface_props, &begin_semaphores, - &end_semaphores_); + &end_semaphores_, + gpu::SharedImageRepresentation::AllowUnclearedAccess::kYes); DCHECK(scoped_write_access_); if (!begin_semaphores.empty()) { scoped_write_access_->surface()->wait(begin_semaphores.size(), @@ -137,13 +140,18 @@ SkSurface::BackendSurfaceAccess::kNoAccess, flush_info); scoped_write_access_.reset(); end_semaphores_.clear(); + + // SkiaRenderer always draws the full frame. + skia_representation_->SetCleared(); } void SkiaOutputDeviceBufferQueue::Image::BeginPresent() { DCHECK(!scoped_write_access_); DCHECK(!scoped_read_access_); scoped_read_access_ = gl_representation_->BeginScopedAccess( - GL_SHARED_IMAGE_ACCESS_MODE_READ_CHROMIUM); + GL_SHARED_IMAGE_ACCESS_MODE_READ_CHROMIUM, + gpu::SharedImageRepresentation::AllowUnclearedAccess::kNo); + DCHECK(scoped_read_access_); } void SkiaOutputDeviceBufferQueue::Image::EndPresent() { @@ -457,10 +465,7 @@ const gfx::ColorSpace& color_space, bool has_alpha, gfx::OverlayTransform transform) { - gl::GLSurface::ColorSpace surface_color_space = - gl::ColorSpaceUtils::GetGLSurfaceColorSpace(color_space); - if (!gl_surface_->Resize(size, device_scale_factor, surface_color_space, - has_alpha)) { + if (!gl_surface_->Resize(size, device_scale_factor, color_space, has_alpha)) { DLOG(ERROR) << "Failed to resize."; return false; }
diff --git a/components/viz/service/display_embedder/skia_output_device_buffer_queue_unittest.cc b/components/viz/service/display_embedder/skia_output_device_buffer_queue_unittest.cc index 19ab3df..adf4e82e 100644 --- a/components/viz/service/display_embedder/skia_output_device_buffer_queue_unittest.cc +++ b/components/viz/service/display_embedder/skia_output_device_buffer_queue_unittest.cc
@@ -251,7 +251,13 @@ EXPECT_EQ(images.size(), (size_t)CountBuffers()); } - Image* GetCurrentImage() { return output_device_->GetCurrentImage(); } + Image* GetCurrentImage() { + // Call Begin/EndPaint to ensusre the image is initialized before use. + output_device_->BeginPaint(); + GrBackendSemaphore semaphore; + output_device_->EndPaint(semaphore); + return output_device_->GetCurrentImage(); + } void SwapBuffers() { auto present_callback =
diff --git a/components/viz/service/display_embedder/skia_output_device_gl.cc b/components/viz/service/display_embedder/skia_output_device_gl.cc index 89a56ddd..d39c02b 100644 --- a/components/viz/service/display_embedder/skia_output_device_gl.cc +++ b/components/viz/service/display_embedder/skia_output_device_gl.cc
@@ -98,10 +98,7 @@ gfx::OverlayTransform transform) { DCHECK_EQ(transform, gfx::OVERLAY_TRANSFORM_NONE); - gl::GLSurface::ColorSpace surface_color_space = - gl::ColorSpaceUtils::GetGLSurfaceColorSpace(color_space); - if (!gl_surface_->Resize(size, device_scale_factor, surface_color_space, - has_alpha)) { + if (!gl_surface_->Resize(size, device_scale_factor, color_space, has_alpha)) { DLOG(ERROR) << "Failed to resize."; return false; }
diff --git a/components/viz/test/fake_output_surface.cc b/components/viz/test/fake_output_surface.cc index 19d8bf2f..775a8d2f 100644 --- a/components/viz/test/fake_output_surface.cc +++ b/components/viz/test/fake_output_surface.cc
@@ -11,6 +11,7 @@ #include "components/viz/test/begin_frame_args_test.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/presentation_feedback.h" +#include "ui/gfx/swap_result.h" #include "ui/gl/color_space_utils.h" namespace viz {
diff --git a/content/browser/compositor/test/test_image_transport_factory.cc b/content/browser/compositor/test/test_image_transport_factory.cc index 33f50ec..314487e1 100644 --- a/content/browser/compositor/test/test_image_transport_factory.cc +++ b/content/browser/compositor/test/test_image_transport_factory.cc
@@ -7,11 +7,6 @@ #include <limits> #include <utility> -#include "components/viz/common/features.h" -#include "components/viz/service/display_embedder/server_shared_bitmap_manager.h" -#include "components/viz/service/frame_sinks/frame_sink_manager_impl.h" -#include "components/viz/test/test_frame_sink_manager.h" -#include "content/browser/compositor/surface_utils.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "ui/compositor/test/in_process_context_provider.h" @@ -25,46 +20,31 @@ } // namespace TestImageTransportFactory::TestImageTransportFactory() - : enable_viz_(features::IsVizDisplayCompositorEnabled()), - frame_sink_id_allocator_(kDefaultClientId) { - if (enable_viz_) { - test_frame_sink_manager_impl_ = - std::make_unique<viz::TestFrameSinkManagerImpl>(); + : frame_sink_id_allocator_(kDefaultClientId) { + mojo::PendingRemote<viz::mojom::FrameSinkManager> frame_sink_manager; + mojo::PendingReceiver<viz::mojom::FrameSinkManager> + frame_sink_manager_receiver = + frame_sink_manager.InitWithNewPipeAndPassReceiver(); + mojo::PendingRemote<viz::mojom::FrameSinkManagerClient> + frame_sink_manager_client; + mojo::PendingReceiver<viz::mojom::FrameSinkManagerClient> + frame_sink_manager_client_receiver = + frame_sink_manager_client.InitWithNewPipeAndPassReceiver(); - mojo::PendingRemote<viz::mojom::FrameSinkManager> frame_sink_manager; - mojo::PendingReceiver<viz::mojom::FrameSinkManager> - frame_sink_manager_receiver = - frame_sink_manager.InitWithNewPipeAndPassReceiver(); - mojo::PendingRemote<viz::mojom::FrameSinkManagerClient> - frame_sink_manager_client; - mojo::PendingReceiver<viz::mojom::FrameSinkManagerClient> - frame_sink_manager_client_receiver = - frame_sink_manager_client.InitWithNewPipeAndPassReceiver(); + // Bind endpoints in HostFrameSinkManager. + host_frame_sink_manager_.BindAndSetManager( + std::move(frame_sink_manager_client_receiver), nullptr, + std::move(frame_sink_manager)); - // Bind endpoints in HostFrameSinkManager. - host_frame_sink_manager_.BindAndSetManager( - std::move(frame_sink_manager_client_receiver), nullptr, - std::move(frame_sink_manager)); - - // Bind endpoints in TestFrameSinkManagerImpl. For non-tests there would be - // a FrameSinkManagerImpl running in another process and these interface - // endpoints would be bound there. - test_frame_sink_manager_impl_->BindReceiver( - std::move(frame_sink_manager_receiver), - std::move(frame_sink_manager_client)); - } else { - shared_bitmap_manager_ = std::make_unique<viz::ServerSharedBitmapManager>(); - frame_sink_manager_impl_ = std::make_unique<viz::FrameSinkManagerImpl>( - shared_bitmap_manager_.get()); - surface_utils::ConnectWithLocalFrameSinkManager( - &host_frame_sink_manager_, frame_sink_manager_impl_.get()); - } + // Bind endpoints in TestFrameSinkManagerImpl. For non-tests there would be + // a FrameSinkManagerImpl running in another process and these interface + // endpoints would be bound there. + test_frame_sink_manager_impl_.BindReceiver( + std::move(frame_sink_manager_receiver), + std::move(frame_sink_manager_client)); } -TestImageTransportFactory::~TestImageTransportFactory() { - for (auto& observer : observer_list_) - observer.OnLostSharedContext(); -} +TestImageTransportFactory::~TestImageTransportFactory() = default; void TestImageTransportFactory::CreateLayerTreeFrameSink( base::WeakPtr<ui::Compositor> compositor) { @@ -103,16 +83,6 @@ return &task_graph_runner_; } -void TestImageTransportFactory::AddObserver( - ui::ContextFactoryObserver* observer) { - observer_list_.AddObserver(observer); -} - -void TestImageTransportFactory::RemoveObserver( - ui::ContextFactoryObserver* observer) { - observer_list_.RemoveObserver(observer); -} - viz::FrameSinkId TestImageTransportFactory::AllocateFrameSinkId() { return frame_sink_id_allocator_.NextFrameSinkId(); }
diff --git a/content/browser/compositor/test/test_image_transport_factory.h b/content/browser/compositor/test/test_image_transport_factory.h index 14b8119..47dc849 100644 --- a/content/browser/compositor/test/test_image_transport_factory.h +++ b/content/browser/compositor/test/test_image_transport_factory.h
@@ -8,13 +8,13 @@ #include <memory> #include "base/macros.h" -#include "base/observer_list.h" #include "build/build_config.h" #include "cc/test/fake_layer_tree_frame_sink.h" #include "cc/test/test_task_graph_runner.h" #include "components/viz/common/display/renderer_settings.h" #include "components/viz/common/surfaces/frame_sink_id_allocator.h" #include "components/viz/host/host_frame_sink_manager.h" +#include "components/viz/test/test_frame_sink_manager.h" #include "components/viz/test/test_gpu_memory_buffer_manager.h" #include "components/viz/test/test_image_factory.h" #include "content/browser/compositor/image_transport_factory.h" @@ -22,12 +22,6 @@ #include "services/viz/privileged/mojom/compositing/vsync_parameter_observer.mojom.h" #include "ui/compositor/compositor.h" -namespace viz { -class FrameSinkManagerImpl; -class ServerSharedBitmapManager; -class TestFrameSinkManagerImpl; -} // namespace viz - namespace content { // Test implementation of ImageTransportFactory, ContextFactory and @@ -47,12 +41,11 @@ override; scoped_refptr<viz::RasterContextProvider> SharedMainThreadRasterContextProvider() override; - void RemoveCompositor(ui::Compositor* compositor) override {} gpu::GpuMemoryBufferManager* GetGpuMemoryBufferManager() override; cc::TaskGraphRunner* GetTaskGraphRunner() override; - void AddObserver(ui::ContextFactoryObserver* observer) override; - void RemoveObserver(ui::ContextFactoryObserver* observer) override; + void AddObserver(ui::ContextFactoryObserver* observer) override {} + void RemoveObserver(ui::ContextFactoryObserver* observer) override {} // ui::ContextFactoryPrivate implementation. viz::FrameSinkId AllocateFrameSinkId() override; @@ -86,23 +79,14 @@ ui::ContextFactoryPrivate* GetContextFactoryPrivate() override; private: - const bool enable_viz_; - cc::TestTaskGraphRunner task_graph_runner_; viz::TestImageFactory image_factory_; viz::TestGpuMemoryBufferManager gpu_memory_buffer_manager_; viz::RendererSettings renderer_settings_; viz::FrameSinkIdAllocator frame_sink_id_allocator_; scoped_refptr<viz::ContextProvider> shared_main_context_provider_; - base::ObserverList<ui::ContextFactoryObserver>::Unchecked observer_list_; viz::HostFrameSinkManager host_frame_sink_manager_; - - // Objects that exist if |enable_viz_| is false. - std::unique_ptr<viz::ServerSharedBitmapManager> shared_bitmap_manager_; - std::unique_ptr<viz::FrameSinkManagerImpl> frame_sink_manager_impl_; - - // Objects that exist if |enable_viz_| is true. - std::unique_ptr<viz::TestFrameSinkManagerImpl> test_frame_sink_manager_impl_; + viz::TestFrameSinkManagerImpl test_frame_sink_manager_impl_; DISALLOW_COPY_AND_ASSIGN(TestImageTransportFactory); };
diff --git a/content/browser/cross_origin_opener_policy_browsertest.cc b/content/browser/cross_origin_opener_policy_browsertest.cc index 0c07e74..b86feda4 100644 --- a/content/browser/cross_origin_opener_policy_browsertest.cc +++ b/content/browser/cross_origin_opener_policy_browsertest.cc
@@ -117,4 +117,47 @@ network::mojom::CrossOriginOpenerPolicy::kUnsafeNone); } +IN_PROC_BROWSER_TEST_F( + CrossOriginOpenerPolicyBrowserTest, + NewPopupCOOP_SameOriginPolicyAndCrossOriginIframeSetsNoopener) { + GURL starting_page(embedded_test_server()->GetURL( + "a.com", "/cross_site_iframe_factory.html?a(b)")); + EXPECT_TRUE(NavigateToURL(shell(), starting_page)); + + RenderFrameHostImpl* main_frame = current_frame_host(); + main_frame->SetCrossOriginOriginOpenerPolicyForTesting( + network::mojom::CrossOriginOpenerPolicy::kSameOrigin); + + ShellAddedObserver new_shell_observer; + RenderFrameHostImpl* iframe = main_frame->child_at(0)->current_frame_host(); + EXPECT_TRUE(ExecJs(iframe, "window.open('about:blank')")); + + Shell* new_shell = new_shell_observer.GetShell(); + RenderFrameHostImpl* popup_frame = + static_cast<WebContentsImpl*>(new_shell->web_contents()) + ->GetFrameTree() + ->root() + ->current_frame_host(); + + scoped_refptr<SiteInstance> main_frame_site_instance( + main_frame->GetSiteInstance()); + scoped_refptr<SiteInstance> iframe_site_instance(iframe->GetSiteInstance()); + scoped_refptr<SiteInstance> popup_site_instance( + popup_frame->GetSiteInstance()); + + ASSERT_TRUE(main_frame_site_instance); + ASSERT_TRUE(iframe_site_instance); + ASSERT_TRUE(popup_site_instance); + EXPECT_FALSE(main_frame_site_instance->IsRelatedSiteInstance( + popup_site_instance.get())); + EXPECT_FALSE( + iframe_site_instance->IsRelatedSiteInstance(popup_site_instance.get())); + + // Check that `window.opener` is not set. + bool success = false; + EXPECT_TRUE(ExecuteScriptAndExtractBool( + new_shell, "window.domAutomationController.send(window.opener == null);", + &success)); + EXPECT_TRUE(success) << "window.opener is set"; +} } // namespace content
diff --git a/content/browser/form_controls_browsertest.cc b/content/browser/form_controls_browsertest.cc new file mode 100644 index 0000000..051421ca --- /dev/null +++ b/content/browser/form_controls_browsertest.cc
@@ -0,0 +1,172 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/path_service.h" +#include "base/run_loop.h" +#include "base/test/scoped_feature_list.h" +#include "base/threading/thread_restrictions.h" +#include "build/build_config.h" +#include "cc/test/pixel_comparator.h" +#include "cc/test/pixel_test_utils.h" +#include "content/browser/renderer_host/render_widget_host_impl.h" +#include "content/public/common/content_paths.h" +#include "content/public/test/browser_test_utils.h" +#include "content/public/test/content_browser_test.h" +#include "content/public/test/content_browser_test_utils.h" +#include "content/public/test/test_utils.h" +#include "content/shell/browser/shell.h" +#include "ui/base/ui_base_features.h" +#include "ui/display/display_switches.h" +#include "ui/gfx/image/image.h" +#include "ui/gfx/skbitmap_operations.h" + +// To rebaseline this test on android: +// 1. Run a CQ+1 dry run +// 2. Click the failing android bot +// 3. Find the failing content_browsertests step +// 4. Click the "Deterministic failure" link for the failing test case +// 5. Copy the "Actual pixels" data url and paste into browser +// 6. Save the image into your chromium checkout in content/test/data/forms/ + +namespace content { + +class FormControlsBrowserTest : public ContentBrowserTest { + public: + FormControlsBrowserTest() = default; + + void SetUp() override { + EnablePixelOutput(); + ContentBrowserTest::SetUp(); + } + + void SetUpCommandLine(base::CommandLine* command_line) override { + ContentBrowserTest::SetUpCommandLine(command_line); + // The --force-device-scale-factor flag helps make the pixel output of + // different android trybots more similar. + command_line->AppendSwitchASCII(switches::kForceDeviceScaleFactor, "1.0"); + feature_list_ = std::make_unique<base::test::ScopedFeatureList>(); + feature_list_->InitWithFeatures({features::kFormControlsRefresh}, {}); + } + + void TearDown() override { feature_list_.reset(); } + + void AsyncSnapshotCallback(const gfx::Image& image) { + got_snapshot_ = true; + snapshot_ = image; + } + + void RunFormControlsTest(const std::string& expected_filename, + const std::string& body_html, + int screenshot_width, + int screenshot_height) { + base::ScopedAllowBlockingForTesting allow_blocking; + ASSERT_TRUE(features::IsFormControlsRefreshEnabled()); + + std::string url = + "data:text/html,<!DOCTYPE html>" + "<head>" + // The <meta name=viewport> tag helps make the pixel output of + // different android trybots more similar. + " <meta name=\"viewport\" content=\"width=640, initial-scale=1, " + " maximum-scale=1, minimum-scale=1\">" + "</head>" + "<body>" + + body_html + "</body>"; + ASSERT_TRUE(NavigateToURL(shell(), GURL(url))); + + RenderWidgetHostImpl* const rwh = + RenderWidgetHostImpl::From(shell() + ->web_contents() + ->GetRenderWidgetHostView() + ->GetRenderWidgetHost()); + CHECK(rwh); + rwh->GetSnapshotFromBrowser( + base::BindOnce(&FormControlsBrowserTest::AsyncSnapshotCallback, + base::Unretained(this)), + /* from_surface */ true); + while (!got_snapshot_) + base::RunLoop().RunUntilIdle(); + SkBitmap bitmap = SkBitmapOperations::CreateTiledBitmap( + *snapshot_.ToSkBitmap(), /* src_x */ 0, /* src_y */ 0, screenshot_width, + screenshot_height); + + base::FilePath dir_test_data; + ASSERT_TRUE(base::PathService::Get(DIR_TEST_DATA, &dir_test_data)); + std::string filename_with_extension = expected_filename; +#if defined(OS_ANDROID) + filename_with_extension += "_android"; +#endif + filename_with_extension += ".png"; + base::FilePath expected_path = + dir_test_data.AppendASCII("forms").AppendASCII(filename_with_extension); + SkBitmap expected_bitmap; + ASSERT_TRUE(cc::ReadPNGFile(expected_path, &expected_bitmap)); + + EXPECT_TRUE(cc::MatchesBitmap( + bitmap, expected_bitmap, +#if defined(OS_MACOSX) + // The Mac 10.12 trybot has more significant subpixel rendering + // differences which we accommodate for here with a large avg/max + // per-pixel error limit. + // TODO(crbug.com/1037971): Remove this special case for mac once this + // bug is resolved. + cc::FuzzyPixelComparator(/* discard_alpha */ true, + /* error_pixels_percentage_limit */ 7.f, + /* small_error_pixels_percentage_limit */ 0.f, + /* avg_abs_error_limit */ 16.f, + /* max_abs_error_limit */ 79.f, + /* small_error_threshold */ 0))); +#else + // We use a fuzzy comparator to accommodate for slight + // differences between the kitkat and marshmallow trybots that aren't + // visible to the human eye. We use a very low error limit because the + // pixels that are different are very similar shades of color. + cc::FuzzyPixelComparator(/* discard_alpha */ true, + /* error_pixels_percentage_limit */ 6.f, + /* small_error_pixels_percentage_limit */ 0.f, + /* avg_abs_error_limit */ 4.f, + /* max_abs_error_limit */ 4.f, + /* small_error_threshold */ 0))); +#endif + } + + bool got_snapshot_ = false; + gfx::Image snapshot_; + std::unique_ptr<base::test::ScopedFeatureList> feature_list_; +}; + +IN_PROC_BROWSER_TEST_F(FormControlsBrowserTest, Checkbox) { + RunFormControlsTest( + "form_controls_browsertest_checkbox", + "<input type=checkbox>" + "<input type=checkbox checked>" + "<input type=checkbox disabled>" + "<input type=checkbox checked disabled>" + "<input type=checkbox id=\"indeterminate\">" + "<script>" + " document.getElementById('indeterminate').indeterminate = true" + "</script>", + /* screenshot_width */ 130, + /* screenshot_height */ 40); +} + +IN_PROC_BROWSER_TEST_F(FormControlsBrowserTest, Radio) { + RunFormControlsTest( + "form_controls_browsertest_radio", + "<input type=radio>" + "<input type=radio checked>" + "<input type=radio disabled>" + "<input type=radio checked disabled>" + "<input type=radio id=\"indeterminate\">" + "<script>" + " document.getElementById('indeterminate').indeterminate = true" + "</script>", + /* screenshot_width */ 140, + /* screenshot_height */ 40); +} + +// TODO(jarhar): Add tests for other elements from +// https://concrete-hardboard.glitch.me + +} // namespace content
diff --git a/content/browser/frame_host/render_frame_host_impl.cc b/content/browser/frame_host/render_frame_host_impl.cc index 89f00d47..ad457144 100644 --- a/content/browser/frame_host/render_frame_host_impl.cc +++ b/content/browser/frame_host/render_frame_host_impl.cc
@@ -4431,11 +4431,18 @@ while (top_level_opener->GetParent()) { top_level_opener = top_level_opener->GetParent(); } - // Verify that they are same origin. Otherwise leave it to default - // unsafe-none. + // Verify that they are same origin. if (top_level_opener->GetLastCommittedOrigin().IsSameOriginWith( GetLastCommittedOrigin())) { popup_coop = top_level_opener->cross_origin_opener_policy(); + } else { + // The documents are cross origin, leave COOP of the popup to the default + // unsafe-none. + // Then set the popup to noopener if the top level COOP is same origin. + if (top_level_opener->cross_origin_opener_policy() == + network::mojom::CrossOriginOpenerPolicy::kSameOrigin) { + params->opener_suppressed = true; + } } } @@ -4444,8 +4451,6 @@ // means the current renderer process will not be able to route messages to // it. Because of this, we will immediately show and navigate the window // in OnCreateNewWindowOnUI, using the params provided here. - // TODO(pmeuleman): Switch BrowsingInstance when Cross-Origin-Opener-Policy of - // the main document and the opened document are incompatible. bool is_new_browsing_instance = params->opener_suppressed || no_javascript_access;
diff --git a/content/child/runtime_features.cc b/content/child/runtime_features.cc index adfcfa3..82d85ba 100644 --- a/content/child/runtime_features.cc +++ b/content/child/runtime_features.cc
@@ -334,8 +334,6 @@ // function and using feature string name with EnableFeatureFromString. const RuntimeFeatureToChromiumFeatureMap<const char*> runtimeFeatureNameToChromiumFeatureMapping[] = { - {"FastBorderRadius", blink::features::kFastBorderRadius, - kUseFeatureState}, {"FontSrcLocalMatching", features::kFontSrcLocalMatching, kUseFeatureState}, {"LegacyWindowsDWriteFontFallback", @@ -547,7 +545,6 @@ WebRuntimeFeatures::EnableNetInfoDownlinkMax(true); WebRuntimeFeatures::EnableFetchMetadata(true); WebRuntimeFeatures::EnableFetchMetadataDestination(true); - WebRuntimeFeatures::EnableFeatureFromString("FastBorderRadius", true); WebRuntimeFeatures::EnableDisplayLocking(true); }
diff --git a/content/public/android/java/src/org/chromium/content/browser/androidoverlay/DialogOverlayCore.java b/content/public/android/java/src/org/chromium/content/browser/androidoverlay/DialogOverlayCore.java index 38f2e485..19185d6 100644 --- a/content/public/android/java/src/org/chromium/content/browser/androidoverlay/DialogOverlayCore.java +++ b/content/public/android/java/src/org/chromium/content/browser/androidoverlay/DialogOverlayCore.java
@@ -171,8 +171,8 @@ // since we're blocking the UI thread. To avoid that, we just give up on synchronous // shutdown and hope for the best. // - // We only allow it on P, though, since that's the only place it should be observed. - if (Build.VERSION.SDK_INT != Build.VERSION_CODES.P) { + // We only allow it on P and later, since it's observed on both P and Q. + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) { assertProperThread(); } else if (mLooper != Looper.myLooper()) { Log.e(TAG, "surfaceDestroyed called on wrong thread. Avoiding proper shutdown.");
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index b0a4f31..dfcea04bb 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -872,6 +872,7 @@ "../browser/file_system/fileapi_browsertest.cc", "../browser/find_request_manager_browsertest.cc", "../browser/font_unique_name_lookup/font_unique_name_browsertest.cc", + "../browser/form_controls_browsertest.cc", "../browser/frame_host/ancestor_throttle_browsertest.cc", "../browser/frame_host/back_forward_cache_metrics_browsertest.cc", "../browser/frame_host/blocked_scheme_navigation_browsertest.cc",
diff --git a/content/test/data/forms/form_controls_browsertest_checkbox.png b/content/test/data/forms/form_controls_browsertest_checkbox.png new file mode 100644 index 0000000..20b1656 --- /dev/null +++ b/content/test/data/forms/form_controls_browsertest_checkbox.png Binary files differ
diff --git a/content/test/data/forms/form_controls_browsertest_checkbox_android.png b/content/test/data/forms/form_controls_browsertest_checkbox_android.png new file mode 100644 index 0000000..07eef94d --- /dev/null +++ b/content/test/data/forms/form_controls_browsertest_checkbox_android.png Binary files differ
diff --git a/content/test/data/forms/form_controls_browsertest_radio.png b/content/test/data/forms/form_controls_browsertest_radio.png new file mode 100644 index 0000000..cbc21ab2 --- /dev/null +++ b/content/test/data/forms/form_controls_browsertest_radio.png Binary files differ
diff --git a/content/test/data/forms/form_controls_browsertest_radio_android.png b/content/test/data/forms/form_controls_browsertest_radio_android.png new file mode 100644 index 0000000..0126008 --- /dev/null +++ b/content/test/data/forms/form_controls_browsertest_radio_android.png Binary files differ
diff --git a/extensions/browser/event_router.cc b/extensions/browser/event_router.cc index 96b9ab85..3f57d5c 100644 --- a/extensions/browser/event_router.cc +++ b/extensions/browser/event_router.cc
@@ -60,14 +60,13 @@ // Sends a notification about an event to the API activity monitor and the // ExtensionHost for |extension_id| on the UI thread. Can be called from any // thread. -void NotifyEventDispatched(void* browser_context_id, +void NotifyEventDispatched(content::BrowserContext* browser_context, const std::string& extension_id, const std::string& event_name, const base::ListValue& args) { // Notify the ApiActivityMonitor about the event dispatch. - BrowserContext* context = static_cast<BrowserContext*>(browser_context_id); - activity_monitor::OnApiEventDispatched(context, extension_id, event_name, - args); + activity_monitor::OnApiEventDispatched(browser_context, extension_id, + event_name, args); } LazyContextId LazyContextIdForBrowserContext(BrowserContext* browser_context, @@ -93,17 +92,17 @@ "serviceworkerevents"; // static -void EventRouter::DispatchExtensionMessage(IPC::Sender* ipc_sender, - int worker_thread_id, - void* browser_context_id, - const std::string& extension_id, - int event_id, - const std::string& event_name, - ListValue* event_args, - UserGestureState user_gesture, - const EventFilteringInfo& info) { - NotifyEventDispatched(browser_context_id, extension_id, event_name, - *event_args); +void EventRouter::DispatchExtensionMessage( + IPC::Sender* ipc_sender, + int worker_thread_id, + content::BrowserContext* browser_context, + const std::string& extension_id, + int event_id, + const std::string& event_name, + ListValue* event_args, + UserGestureState user_gesture, + const EventFilteringInfo& info) { + NotifyEventDispatched(browser_context, extension_id, event_name, *event_args); ExtensionMsg_DispatchEvent_Params params; params.worker_thread_id = worker_thread_id; params.extension_id = extension_id; @@ -127,24 +126,25 @@ } // static -void EventRouter::DispatchEventToSender(IPC::Sender* ipc_sender, - void* browser_context_id, - const std::string& extension_id, - events::HistogramValue histogram_value, - const std::string& event_name, - int render_process_id, - int worker_thread_id, - int64_t service_worker_version_id, - std::unique_ptr<ListValue> event_args, - const EventFilteringInfo& info) { +void EventRouter::DispatchEventToSender( + IPC::Sender* ipc_sender, + content::BrowserContext* browser_context, + const std::string& extension_id, + events::HistogramValue histogram_value, + const std::string& event_name, + int render_process_id, + int worker_thread_id, + int64_t service_worker_version_id, + std::unique_ptr<ListValue> event_args, + const EventFilteringInfo& info) { DCHECK_CURRENTLY_ON(BrowserThread::UI); int event_id = g_extension_event_id.GetNext(); - DoDispatchEventToSenderBookkeepingOnUI( - browser_context_id, extension_id, event_id, render_process_id, + DoDispatchEventToSenderBookkeeping( + browser_context, extension_id, event_id, render_process_id, service_worker_version_id, histogram_value, event_name); - DispatchExtensionMessage(ipc_sender, worker_thread_id, browser_context_id, + DispatchExtensionMessage(ipc_sender, worker_thread_id, browser_context, extension_id, event_id, event_name, event_args.get(), UserGestureState::USER_GESTURE_UNKNOWN, info); } @@ -693,8 +693,8 @@ } // static -void EventRouter::DoDispatchEventToSenderBookkeepingOnUI( - void* browser_context_id, +void EventRouter::DoDispatchEventToSenderBookkeeping( + content::BrowserContext* browser_context, const std::string& extension_id, int event_id, int render_process_id, @@ -702,8 +702,6 @@ events::HistogramValue histogram_value, const std::string& event_name) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - BrowserContext* browser_context = - reinterpret_cast<BrowserContext*>(browser_context_id); // TODO(https://crbug.com/897946): Remove after investigating the bug. if (ExtensionsBrowserClient::Get()->IsShuttingDown()) { LOG(ERROR)
diff --git a/extensions/browser/event_router.h b/extensions/browser/event_router.h index 3b1f759..154348e 100644 --- a/extensions/browser/event_router.h +++ b/extensions/browser/event_router.h
@@ -107,7 +107,7 @@ // Note that this method will dispatch the event with // UserGestureState:USER_GESTURE_UNKNOWN. static void DispatchEventToSender(IPC::Sender* ipc_sender, - void* browser_context_id, + content::BrowserContext* browser_context, const std::string& extension_id, events::HistogramValue histogram_value, const std::string& event_name, @@ -277,7 +277,7 @@ static void DispatchExtensionMessage( IPC::Sender* ipc_sender, int worker_thread_id, - void* browser_context_id, + content::BrowserContext* browser_context, const std::string& extension_id, int event_id, const std::string& event_name, @@ -350,8 +350,8 @@ int64_t service_worker_version_id); // static - static void DoDispatchEventToSenderBookkeepingOnUI( - void* browser_context_id, + static void DoDispatchEventToSenderBookkeeping( + content::BrowserContext* context, const std::string& extension_id, int event_id, int render_process_id,
diff --git a/extensions/browser/extension_function_dispatcher.cc b/extensions/browser/extension_function_dispatcher.cc index 4246752..0ea26e0 100644 --- a/extensions/browser/extension_function_dispatcher.cc +++ b/extensions/browser/extension_function_dispatcher.cc
@@ -67,41 +67,12 @@ blink::mojom::kInvalidServiceWorkerVersionId; } -void CommonResponseCallback(IPC::Sender* ipc_sender, - int routing_id, - int worker_thread_id, - int request_id, - ExtensionFunction::ResponseType type, - const base::ListValue& results, - const std::string& error) { - DCHECK(ipc_sender); - - if (type == ExtensionFunction::BAD_MESSAGE) { - // The renderer will be shut down from ExtensionFunction::SetBadMessage(). - return; - } - - if (routing_id != MSG_ROUTING_NONE) { - DCHECK_EQ(kMainThreadId, worker_thread_id); - ipc_sender->Send(new ExtensionMsg_Response( - routing_id, request_id, type == ExtensionFunction::SUCCEEDED, results, - error)); - } else { - DCHECK_NE(kMainThreadId, worker_thread_id); - ipc_sender->Send(new ExtensionMsg_ResponseWorker( - worker_thread_id, request_id, type == ExtensionFunction::SUCCEEDED, - results, error)); - } -} - } // namespace -// TODO(http://crbug.com/980774): Simplify this or change the name now that -// IOThreadExtensionFunction is gone. -class ExtensionFunctionDispatcher::UIThreadResponseCallbackWrapper +class ExtensionFunctionDispatcher::ResponseCallbackWrapper : public content::WebContentsObserver { public: - UIThreadResponseCallbackWrapper( + ResponseCallbackWrapper( const base::WeakPtr<ExtensionFunctionDispatcher>& dispatcher, content::RenderFrameHost* render_frame_host) : content::WebContentsObserver( @@ -109,26 +80,22 @@ dispatcher_(dispatcher), render_frame_host_(render_frame_host) {} - ~UIThreadResponseCallbackWrapper() override {} + ~ResponseCallbackWrapper() override = default; // content::WebContentsObserver overrides. void RenderFrameDeleted( content::RenderFrameHost* render_frame_host) override { - DCHECK_CURRENTLY_ON(BrowserThread::UI); if (render_frame_host != render_frame_host_) return; if (dispatcher_.get()) { - dispatcher_->ui_thread_response_callback_wrappers_ - .erase(render_frame_host); + dispatcher_->response_callback_wrappers_.erase(render_frame_host); } } ExtensionFunction::ResponseCallback CreateCallback(int request_id) { - return base::Bind( - &UIThreadResponseCallbackWrapper::OnExtensionFunctionCompleted, - weak_ptr_factory_.GetWeakPtr(), - request_id); + return base::Bind(&ResponseCallbackWrapper::OnExtensionFunctionCompleted, + weak_ptr_factory_.GetWeakPtr(), request_id); } private: @@ -136,22 +103,27 @@ ExtensionFunction::ResponseType type, const base::ListValue& results, const std::string& error) { - CommonResponseCallback(render_frame_host_, - render_frame_host_->GetRoutingID(), kMainThreadId, - request_id, type, results, error); + if (type == ExtensionFunction::BAD_MESSAGE) { + // The renderer will be shut down from ExtensionFunction::SetBadMessage(). + return; + } + + render_frame_host_->Send(new ExtensionMsg_Response( + render_frame_host_->GetRoutingID(), request_id, + type == ExtensionFunction::SUCCEEDED, results, error)); } base::WeakPtr<ExtensionFunctionDispatcher> dispatcher_; content::RenderFrameHost* render_frame_host_; - base::WeakPtrFactory<UIThreadResponseCallbackWrapper> weak_ptr_factory_{this}; + base::WeakPtrFactory<ResponseCallbackWrapper> weak_ptr_factory_{this}; - DISALLOW_COPY_AND_ASSIGN(UIThreadResponseCallbackWrapper); + DISALLOW_COPY_AND_ASSIGN(ResponseCallbackWrapper); }; -class ExtensionFunctionDispatcher::UIThreadWorkerResponseCallbackWrapper +class ExtensionFunctionDispatcher::WorkerResponseCallbackWrapper : public content::RenderProcessHostObserver { public: - UIThreadWorkerResponseCallbackWrapper( + WorkerResponseCallbackWrapper( const base::WeakPtr<ExtensionFunctionDispatcher>& dispatcher, content::RenderProcessHost* render_process_host, int worker_thread_id) @@ -164,7 +136,7 @@ ->ExtensionAPIEnabledInExtensionServiceWorkers()); } - ~UIThreadWorkerResponseCallbackWrapper() override {} + ~WorkerResponseCallbackWrapper() override = default; // content::RenderProcessHostObserver override. void RenderProcessExited( @@ -181,13 +153,12 @@ ExtensionFunction::ResponseCallback CreateCallback(int request_id, int worker_thread_id) { return base::Bind( - &UIThreadWorkerResponseCallbackWrapper::OnExtensionFunctionCompleted, + &WorkerResponseCallbackWrapper::OnExtensionFunctionCompleted, weak_ptr_factory_.GetWeakPtr(), request_id, worker_thread_id); } private: void CleanUp() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); if (dispatcher_) { dispatcher_->RemoveWorkerCallbacksForProcess( render_process_host_->GetID()); @@ -213,10 +184,9 @@ ScopedObserver<content::RenderProcessHost, content::RenderProcessHostObserver> observer_{this}; content::RenderProcessHost* const render_process_host_; - base::WeakPtrFactory<UIThreadWorkerResponseCallbackWrapper> weak_ptr_factory_{ - this}; + base::WeakPtrFactory<WorkerResponseCallbackWrapper> weak_ptr_factory_{this}; - DISALLOW_COPY_AND_ASSIGN(UIThreadWorkerResponseCallbackWrapper); + DISALLOW_COPY_AND_ASSIGN(WorkerResponseCallbackWrapper); }; struct ExtensionFunctionDispatcher::WorkerResponseCallbackMapKey { @@ -273,13 +243,13 @@ if (render_frame_host) { // Extension API from a non Service Worker context, e.g. extension page, // background page, content script. - UIThreadResponseCallbackWrapperMap::const_iterator iter = - ui_thread_response_callback_wrappers_.find(render_frame_host); - UIThreadResponseCallbackWrapper* callback_wrapper = nullptr; - if (iter == ui_thread_response_callback_wrappers_.end()) { + ResponseCallbackWrapperMap::const_iterator iter = + response_callback_wrappers_.find(render_frame_host); + ResponseCallbackWrapper* callback_wrapper = nullptr; + if (iter == response_callback_wrappers_.end()) { callback_wrapper = - new UIThreadResponseCallbackWrapper(AsWeakPtr(), render_frame_host); - ui_thread_response_callback_wrappers_[render_frame_host] = + new ResponseCallbackWrapper(AsWeakPtr(), render_frame_host); + response_callback_wrappers_[render_frame_host] = base::WrapUnique(callback_wrapper); } else { callback_wrapper = iter->second.get(); @@ -290,8 +260,7 @@ } else { content::RenderProcessHost* rph = content::RenderProcessHost::FromID(render_process_id); - // UIThreadWorkerResponseCallbackWrapper requires render process host to be - // around. + // WorkerResponseCallbackWrapper requires render process host to be around. if (!rph) return; @@ -304,13 +273,13 @@ WorkerResponseCallbackMapKey key(render_process_id, params.service_worker_version_id); - UIThreadWorkerResponseCallbackWrapperMap::const_iterator iter = - ui_thread_response_callback_wrappers_for_worker_.find(key); - UIThreadWorkerResponseCallbackWrapper* callback_wrapper = nullptr; - if (iter == ui_thread_response_callback_wrappers_for_worker_.end()) { - callback_wrapper = new UIThreadWorkerResponseCallbackWrapper( + WorkerResponseCallbackWrapperMap::const_iterator iter = + response_callback_wrappers_for_worker_.find(key); + WorkerResponseCallbackWrapper* callback_wrapper = nullptr; + if (iter == response_callback_wrappers_for_worker_.end()) { + callback_wrapper = new WorkerResponseCallbackWrapper( AsWeakPtr(), rph, params.worker_thread_id); - ui_thread_response_callback_wrappers_for_worker_[key] = + response_callback_wrappers_for_worker_[key] = base::WrapUnique(callback_wrapper); } else { callback_wrapper = iter->second.get(); @@ -435,8 +404,8 @@ void ExtensionFunctionDispatcher::RemoveWorkerCallbacksForProcess( int render_process_id) { - UIThreadWorkerResponseCallbackWrapperMap& map = - ui_thread_response_callback_wrappers_for_worker_; + WorkerResponseCallbackWrapperMap& map = + response_callback_wrappers_for_worker_; for (auto it = map.begin(); it != map.end();) { if (it->first.render_process_id == render_process_id) { it = map.erase(it);
diff --git a/extensions/browser/extension_function_dispatcher.h b/extensions/browser/extension_function_dispatcher.h index 6721cee..44d5385 100644 --- a/extensions/browser/extension_function_dispatcher.h +++ b/extensions/browser/extension_function_dispatcher.h
@@ -98,19 +98,19 @@ void set_delegate(Delegate* delegate) { delegate_ = delegate; } private: - // For a given RenderFrameHost instance, UIThreadResponseCallbackWrapper + // For a given RenderFrameHost instance, ResponseCallbackWrapper // creates ExtensionFunction::ResponseCallback instances which send responses // to the corresponding render view in ExtensionMsg_Response messages. // This class tracks the lifespan of the RenderFrameHost instance, and will be // destroyed automatically when it goes away. - class UIThreadResponseCallbackWrapper; + class ResponseCallbackWrapper; - // Same as UIThreadResponseCallbackWrapper above, but applies to an extension + // Same as ResponseCallbackWrapper above, but applies to an extension // function from an extension Service Worker. - class UIThreadWorkerResponseCallbackWrapper; + class WorkerResponseCallbackWrapper; - // Key used to store UIThreadWorkerResponseCallbackWrapper in the map - // |ui_thread_response_callback_wrappers_for_worker_|. + // Key used to store WorkerResponseCallbackWrapper in the map + // |response_callback_wrappers_for_worker_|. struct WorkerResponseCallbackMapKey; // Helper to check whether an ExtensionFunction has the required permissions. @@ -155,17 +155,16 @@ // instance goes away, the corresponding entry in this map (if exists) will be // removed. typedef std::map<content::RenderFrameHost*, - std::unique_ptr<UIThreadResponseCallbackWrapper>> - UIThreadResponseCallbackWrapperMap; - UIThreadResponseCallbackWrapperMap ui_thread_response_callback_wrappers_; + std::unique_ptr<ResponseCallbackWrapper>> + ResponseCallbackWrapperMap; + ResponseCallbackWrapperMap response_callback_wrappers_; - using UIThreadWorkerResponseCallbackWrapperMap = + using WorkerResponseCallbackWrapperMap = std::map<WorkerResponseCallbackMapKey, - std::unique_ptr<UIThreadWorkerResponseCallbackWrapper>>; + std::unique_ptr<WorkerResponseCallbackWrapper>>; // TODO(lazyboy): The map entries are cleared upon RenderProcessHost shutown, // we should really be clearing it on service worker shutdown. - UIThreadWorkerResponseCallbackWrapperMap - ui_thread_response_callback_wrappers_for_worker_; + WorkerResponseCallbackWrapperMap response_callback_wrappers_for_worker_; }; } // namespace extensions
diff --git a/extensions/common/extension.h b/extensions/common/extension.h index a43d767e..56c7e5a 100644 --- a/extensions/common/extension.h +++ b/extensions/common/extension.h
@@ -474,7 +474,6 @@ typedef std::vector<scoped_refptr<const Extension> > ExtensionList; typedef std::set<ExtensionId> ExtensionIdSet; -typedef std::vector<ExtensionId> ExtensionIdList; // Handy struct to pass core extension info around. struct ExtensionInfo {
diff --git a/extensions/common/extension_id.h b/extensions/common/extension_id.h index bace9c16..7d8573e2 100644 --- a/extensions/common/extension_id.h +++ b/extensions/common/extension_id.h
@@ -6,6 +6,7 @@ #define EXTENSIONS_COMMON_EXTENSION_ID_H_ #include <string> +#include <vector> namespace extensions { @@ -13,6 +14,8 @@ // alphabet 'a'-'p'. using ExtensionId = std::string; +using ExtensionIdList = std::vector<ExtensionId>; + } // namespace extensions #endif // EXTENSIONS_COMMON_EXTENSION_ID_H_
diff --git a/gpu/BUILD.gn b/gpu/BUILD.gn index 04bf17c..acc467ab 100644 --- a/gpu/BUILD.gn +++ b/gpu/BUILD.gn
@@ -295,6 +295,7 @@ "command_buffer/service/shared_image_backing_factory_gl_texture_unittest.cc", "command_buffer/service/shared_image_factory_unittest.cc", "command_buffer/service/shared_image_manager_unittest.cc", + "command_buffer/service/shared_image_representation_unittest.cc", "command_buffer/service/shared_image_test_utils.cc", "command_buffer/service/shared_image_test_utils.h", "command_buffer/tests/compressed_texture_test.cc",
diff --git a/gpu/command_buffer/service/external_vk_image_dawn_representation.cc b/gpu/command_buffer/service/external_vk_image_dawn_representation.cc index f7f0427..be4d292 100644 --- a/gpu/command_buffer/service/external_vk_image_dawn_representation.cc +++ b/gpu/command_buffer/service/external_vk_image_dawn_representation.cc
@@ -93,7 +93,7 @@ // the result. // TODO(cwallez@chromium.org): This is incorrect and allows reading // uninitialized data. When !IsCleared we should tell dawn_native to - // consider the texture lazy-cleared. + // consider the texture lazy-cleared. crbug.com/1036080 SetCleared(); }
diff --git a/gpu/command_buffer/service/gl_surface_mock.h b/gpu/command_buffer/service/gl_surface_mock.h index 7812ab7..0c9ed3b 100644 --- a/gpu/command_buffer/service/gl_surface_mock.h +++ b/gpu/command_buffer/service/gl_surface_mock.h
@@ -21,7 +21,7 @@ MOCK_METHOD4(Resize, bool(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool alpha)); MOCK_METHOD0(IsOffscreen, bool()); MOCK_METHOD1(SwapBuffers, gfx::SwapResult(PresentationCallback callback));
diff --git a/gpu/command_buffer/service/gles2_cmd_decoder.cc b/gpu/command_buffer/service/gles2_cmd_decoder.cc index f340164..c45d86a 100644 --- a/gpu/command_buffer/service/gles2_cmd_decoder.cc +++ b/gpu/command_buffer/service/gles2_cmd_decoder.cc
@@ -98,6 +98,7 @@ #include "ui/gfx/ipc/color/gfx_param_traits.h" #include "ui/gfx/transform.h" #include "ui/gl/ca_renderer_layer_params.h" +#include "ui/gl/color_space_utils.h" #include "ui/gl/dc_renderer_layer_params.h" #include "ui/gl/gl_bindings.h" #include "ui/gl/gl_context.h" @@ -5863,7 +5864,8 @@ GLuint width = static_cast<GLuint>(c.width); GLuint height = static_cast<GLuint>(c.height); GLfloat scale_factor = c.scale_factor; - GLenum color_space = c.color_space; + gfx::ColorSpace color_space = + gl::ColorSpaceUtils::GetColorSpace(c.color_space); GLboolean has_alpha = c.alpha; TRACE_EVENT2("gpu", "glResizeChromium", "width", width, "height", height); @@ -5874,29 +5876,6 @@ width = base::ClampToRange(width, 1U, kMaxDimension); height = base::ClampToRange(height, 1U, kMaxDimension); - gl::GLSurface::ColorSpace surface_color_space = - gl::GLSurface::ColorSpace::UNSPECIFIED; - switch (color_space) { - case GL_COLOR_SPACE_UNSPECIFIED_CHROMIUM: - surface_color_space = gl::GLSurface::ColorSpace::UNSPECIFIED; - break; - case GL_COLOR_SPACE_SCRGB_LINEAR_CHROMIUM: - surface_color_space = gl::GLSurface::ColorSpace::SCRGB_LINEAR; - break; - case GL_COLOR_SPACE_HDR10_CHROMIUM: - surface_color_space = gl::GLSurface::ColorSpace::HDR10; - break; - case GL_COLOR_SPACE_SRGB_CHROMIUM: - surface_color_space = gl::GLSurface::ColorSpace::SRGB; - break; - case GL_COLOR_SPACE_DISPLAY_P3_CHROMIUM: - surface_color_space = gl::GLSurface::ColorSpace::DISPLAY_P3; - break; - default: - LOG(ERROR) << "GLES2DecoderImpl: Context lost because specified color" - << "space was invalid."; - return error::kLostContext; - } bool is_offscreen = !!offscreen_target_frame_buffer_.get(); if (is_offscreen) { if (!ResizeOffscreenFramebuffer(gfx::Size(width, height))) { @@ -5905,8 +5884,8 @@ return error::kLostContext; } } else { - if (!surface_->Resize(gfx::Size(width, height), scale_factor, - surface_color_space, !!has_alpha)) { + if (!surface_->Resize(gfx::Size(width, height), scale_factor, color_space, + !!has_alpha)) { LOG(ERROR) << "GLES2DecoderImpl: Context lost because resize failed."; return error::kLostContext; }
diff --git a/gpu/command_buffer/service/gles2_cmd_decoder_passthrough.cc b/gpu/command_buffer/service/gles2_cmd_decoder_passthrough.cc index a876c06a..00965e3d 100644 --- a/gpu/command_buffer/service/gles2_cmd_decoder_passthrough.cc +++ b/gpu/command_buffer/service/gles2_cmd_decoder_passthrough.cc
@@ -391,7 +391,10 @@ bool PassthroughResources::SharedImageData::BeginAccess(GLenum mode, gl::GLApi* api) { DCHECK(!is_being_accessed()); - scoped_access_ = representation_->BeginScopedAccess(mode); + // When importing a texture for use in passthrough cmd decoder, always allow + // uncleared access. We ensure the texture is cleared below. + scoped_access_ = representation_->BeginScopedAccess( + mode, SharedImageRepresentation::AllowUnclearedAccess::kYes); if (!scoped_access_) { return false; }
diff --git a/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_doers.cc b/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_doers.cc index 374f070..243cb35 100644 --- a/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_doers.cc +++ b/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_doers.cc
@@ -21,6 +21,7 @@ #include "gpu/command_buffer/service/shared_image_representation.h" #include "ui/gfx/geometry/rect_conversions.h" #include "ui/gl/ca_renderer_layer_params.h" +#include "ui/gl/color_space_utils.h" #include "ui/gl/dc_renderer_layer_params.h" #include "ui/gl/gl_version_info.h" @@ -3914,30 +3915,8 @@ return error::kLostContext; } } else { - gl::GLSurface::ColorSpace surface_color_space = - gl::GLSurface::ColorSpace::UNSPECIFIED; - switch (color_space) { - case GL_COLOR_SPACE_UNSPECIFIED_CHROMIUM: - surface_color_space = gl::GLSurface::ColorSpace::UNSPECIFIED; - break; - case GL_COLOR_SPACE_SCRGB_LINEAR_CHROMIUM: - surface_color_space = gl::GLSurface::ColorSpace::SCRGB_LINEAR; - break; - case GL_COLOR_SPACE_HDR10_CHROMIUM: - surface_color_space = gl::GLSurface::ColorSpace::HDR10; - break; - case GL_COLOR_SPACE_SRGB_CHROMIUM: - surface_color_space = gl::GLSurface::ColorSpace::SRGB; - break; - case GL_COLOR_SPACE_DISPLAY_P3_CHROMIUM: - surface_color_space = gl::GLSurface::ColorSpace::DISPLAY_P3; - break; - default: - LOG(ERROR) << "GLES2DecoderPassthroughImpl: Context lost because " - "specified color space was invalid."; - return error::kLostContext; - } - if (!surface_->Resize(safe_size, scale_factor, surface_color_space, + if (!surface_->Resize(safe_size, scale_factor, + gl::ColorSpaceUtils::GetColorSpace(color_space), !!alpha)) { LOG(ERROR) << "GLES2DecoderPassthroughImpl: Context lost because resize failed.";
diff --git a/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_unittest_textures.cc b/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_unittest_textures.cc index 9069424..f2fffe2c 100644 --- a/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_unittest_textures.cc +++ b/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_unittest_textures.cc
@@ -166,17 +166,10 @@ EXPECT_EQ(GL_NO_ERROR, GetGLError()); cmds::EndSharedImageAccessDirectCHROMIUM readwrite_end_cmd; readwrite_end_cmd.Init(client_id); - // EXPECT_EQ(error::kNoError, ExecuteCmd(readwrite_end_cmd)); - // EXPECT_EQ(GL_NO_ERROR, GetGLError()); - } - - for (int i = 20; i > 10; --i) { - cmds::EndSharedImageAccessDirectCHROMIUM readwrite_end_cmd; - readwrite_end_cmd.Init(kNewClientId + i); EXPECT_EQ(error::kNoError, ExecuteCmd(readwrite_end_cmd)); EXPECT_EQ(GL_NO_ERROR, GetGLError()); - DoDeleteTexture(kNewClientId + i); - fprintf(stderr, "EEEE DoDeleteTexture() i=%d\n", i); + + DoDeleteTexture(client_id); } // Cleanup
diff --git a/gpu/command_buffer/service/raster_decoder.cc b/gpu/command_buffer/service/raster_decoder.cc index 6ab2f00..c333429c 100644 --- a/gpu/command_buffer/service/raster_decoder.cc +++ b/gpu/command_buffer/service/raster_decoder.cc
@@ -1796,16 +1796,19 @@ std::unique_ptr<SharedImageRepresentationGLTexturePassthrough::ScopedAccess> source_access = source_shared_image->BeginScopedAccess( - GL_SHARED_IMAGE_ACCESS_MODE_READ_CHROMIUM); + GL_SHARED_IMAGE_ACCESS_MODE_READ_CHROMIUM, + SharedImageRepresentation::AllowUnclearedAccess::kNo); if (!source_access) { LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "glCopySubTexture", "unable to access source for read"); return; } + // Allow uncleared access, as we manually handle clear tracking. std::unique_ptr<SharedImageRepresentationGLTexturePassthrough::ScopedAccess> dest_access = dest_shared_image->BeginScopedAccess( - GL_SHARED_IMAGE_ACCESS_MODE_READWRITE_CHROMIUM); + GL_SHARED_IMAGE_ACCESS_MODE_READWRITE_CHROMIUM, + SharedImageRepresentation::AllowUnclearedAccess::kYes); if (!dest_access) { LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "glCopySubTexture", "unable to access destination for write"); @@ -1872,7 +1875,8 @@ std::unique_ptr<SharedImageRepresentationGLTexture::ScopedAccess> source_access = source_shared_image->BeginScopedAccess( - GL_SHARED_IMAGE_ACCESS_MODE_READ_CHROMIUM); + GL_SHARED_IMAGE_ACCESS_MODE_READ_CHROMIUM, + SharedImageRepresentation::AllowUnclearedAccess::kNo); if (!source_access) { LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "glCopySubTexture", "unable to access source for read"); @@ -1891,9 +1895,11 @@ return; } + // Allow uncleared access, as we manually handle clear tracking. std::unique_ptr<SharedImageRepresentationGLTexture::ScopedAccess> dest_access = dest_shared_image->BeginScopedAccess( - GL_SHARED_IMAGE_ACCESS_MODE_READWRITE_CHROMIUM); + GL_SHARED_IMAGE_ACCESS_MODE_READWRITE_CHROMIUM, + SharedImageRepresentation::AllowUnclearedAccess::kYes); if (!dest_access) { LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "glCopySubTexture", "unable to access destination for write"); @@ -2116,9 +2122,11 @@ std::vector<GrBackendSemaphore> begin_semaphores; std::vector<GrBackendSemaphore> end_semaphores; + // Allow uncleared access, as we manually handle clear tracking. std::unique_ptr<SharedImageRepresentationSkia::ScopedWriteAccess> dest_scoped_access = dest_shared_image->BeginScopedWriteAccess( - &begin_semaphores, &end_semaphores); + &begin_semaphores, &end_semaphores, + SharedImageRepresentation::AllowUnclearedAccess::kYes); if (!dest_scoped_access) { LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "glCopySubTexture", "Dest shared image is not writable"); @@ -2336,8 +2344,11 @@ std::vector<GrBackendSemaphore> begin_semaphores; DCHECK(end_semaphores_.empty()); DCHECK(!scoped_shared_image_write_); + // Allow uncleared access, as raster specifically handles uncleared images by + // clearing them before writing. scoped_shared_image_write_ = shared_image_->BeginScopedWriteAccess( - final_msaa_count, surface_props, &begin_semaphores, &end_semaphores_); + final_msaa_count, surface_props, &begin_semaphores, &end_semaphores_, + SharedImageRepresentation::AllowUnclearedAccess::kYes); if (!scoped_shared_image_write_) { LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "glBeginRasterCHROMIUM", "failed to create surface");
diff --git a/gpu/command_buffer/service/raster_decoder_unittest.cc b/gpu/command_buffer/service/raster_decoder_unittest.cc index b6fc328e..0ac91df5 100644 --- a/gpu/command_buffer/service/raster_decoder_unittest.cc +++ b/gpu/command_buffer/service/raster_decoder_unittest.cc
@@ -298,6 +298,11 @@ init.extensions.push_back("GL_EXT_texture_rg"); InitDecoder(init); + // Recreate |client_texture_mailbox_| as a cleared mailbox. + client_texture_mailbox_ = CreateFakeTexture( + kServiceTextureId, viz::ResourceFormat::RGBA_8888, /*width=*/2, + /*height=*/2, /*cleared=*/true); + // Create dest texture. gpu::Mailbox dest_texture_mailbox = CreateFakeTexture(kNewServiceId, viz::ResourceFormat::RED_8,
diff --git a/gpu/command_buffer/service/shared_image_backing_egl_image.cc b/gpu/command_buffer/service/shared_image_backing_egl_image.cc index 71803a0c..6f93bfe 100644 --- a/gpu/command_buffer/service/shared_image_backing_egl_image.cc +++ b/gpu/command_buffer/service/shared_image_backing_egl_image.cc
@@ -59,11 +59,6 @@ egl_backing()->EndRead(this, std::move(egl_fence)); } else if (mode_ == RepresentationAccessMode::kWrite) { egl_backing()->EndWrite(std::move(egl_fence)); - - if (texture_) { - if (texture_->IsLevelCleared(texture_->target(), 0)) - backing()->SetCleared(); - } } else { NOTREACHED(); }
diff --git a/gpu/command_buffer/service/shared_image_backing_factory_ahardwarebuffer.cc b/gpu/command_buffer/service/shared_image_backing_factory_ahardwarebuffer.cc index 183dcdd..d280ca7 100644 --- a/gpu/command_buffer/service/shared_image_backing_factory_ahardwarebuffer.cc +++ b/gpu/command_buffer/service/shared_image_backing_factory_ahardwarebuffer.cc
@@ -234,11 +234,6 @@ ahb_backing()->EndRead(this, std::move(sync_fd)); } else if (mode_ == RepresentationAccessMode::kWrite) { ahb_backing()->EndWrite(std::move(sync_fd)); - - if (texture_) { - if (texture_->IsLevelCleared(texture_->target(), 0)) - backing()->SetCleared(); - } } mode_ = RepresentationAccessMode::kNone; @@ -921,6 +916,11 @@ auto backing = std::make_unique<SharedImageBackingAHB>( mailbox, format, size, color_space, usage, std::move(handle), estimated_size, is_thread_safe, std::move(initial_upload_fd)); + + // If we uploaded initial data, set the backing as cleared. + if (!pixel_data.empty()) + backing->SetCleared(); + return backing; }
diff --git a/gpu/command_buffer/service/shared_image_backing_factory_ahardwarebuffer_unittest.cc b/gpu/command_buffer/service/shared_image_backing_factory_ahardwarebuffer_unittest.cc index 4e4a2529..ed7e983 100644 --- a/gpu/command_buffer/service/shared_image_backing_factory_ahardwarebuffer_unittest.cc +++ b/gpu/command_buffer/service/shared_image_backing_factory_ahardwarebuffer_unittest.cc
@@ -127,7 +127,8 @@ std::unique_ptr<SharedImageRepresentationSkia::ScopedWriteAccess> scoped_write_access; scoped_write_access = skia_representation->BeginScopedWriteAccess( - &begin_semaphores, &end_semaphores); + &begin_semaphores, &end_semaphores, + SharedImageRepresentation::AllowUnclearedAccess::kYes); EXPECT_TRUE(scoped_write_access); auto* surface = scoped_write_access->surface(); EXPECT_TRUE(surface); @@ -197,6 +198,9 @@ // Set the clear color to green. api->glClearColorFn(0.0f, 1.0f, 0.0f, 1.0f); api->glClearFn(GL_COLOR_BUFFER_BIT); + + // Mark the representation as cleared. + gl_representation->SetCleared(); gl_representation.reset(); auto dst_pixels = ReadPixels(mailbox, size, context_state_.get(), @@ -325,7 +329,8 @@ std::unique_ptr<SharedImageRepresentationSkia::ScopedWriteAccess> scoped_write_access; scoped_write_access = skia_representation->BeginScopedWriteAccess( - &begin_semaphores, &end_semaphores); + &begin_semaphores, &end_semaphores, + SharedImageRepresentation::AllowUnclearedAccess::kYes); EXPECT_TRUE(scoped_write_access); EXPECT_EQ(0u, begin_semaphores.size()); EXPECT_EQ(0u, end_semaphores.size()); @@ -337,7 +342,8 @@ std::unique_ptr<SharedImageRepresentationSkia::ScopedWriteAccess> scoped_write_access2; scoped_write_access2 = skia_representation2->BeginScopedWriteAccess( - &begin_semaphores2, &end_semaphores2); + &begin_semaphores2, &end_semaphores2, + SharedImageRepresentation::AllowUnclearedAccess::kYes); EXPECT_FALSE(scoped_write_access); EXPECT_EQ(0u, begin_semaphores2.size()); EXPECT_EQ(0u, end_semaphores2.size()); @@ -419,7 +425,8 @@ std::unique_ptr<SharedImageRepresentationSkia::ScopedWriteAccess> scoped_write_access; scoped_write_access = skia_representation2->BeginScopedWriteAccess( - &begin_semaphores2, &end_semaphores2); + &begin_semaphores2, &end_semaphores2, + SharedImageRepresentation::AllowUnclearedAccess::kYes); EXPECT_FALSE(scoped_write_access); EXPECT_EQ(0u, begin_semaphores2.size()); EXPECT_EQ(0u, end_semaphores2.size()); @@ -446,7 +453,8 @@ std::unique_ptr<SharedImageRepresentationSkia::ScopedWriteAccess> scoped_write_access; scoped_write_access = skia_representation->BeginScopedWriteAccess( - &begin_semaphores, &end_semaphores); + &begin_semaphores, &end_semaphores, + SharedImageRepresentation::AllowUnclearedAccess::kYes); EXPECT_TRUE(scoped_write_access); EXPECT_EQ(0u, begin_semaphores.size()); EXPECT_EQ(0u, end_semaphores.size());
diff --git a/gpu/command_buffer/service/shared_image_backing_factory_d3d.cc b/gpu/command_buffer/service/shared_image_backing_factory_d3d.cc index 9308011d..4b55763 100644 --- a/gpu/command_buffer/service/shared_image_backing_factory_d3d.cc +++ b/gpu/command_buffer/service/shared_image_backing_factory_d3d.cc
@@ -460,7 +460,7 @@ // the result. // TODO(cwallez@chromium.org): This is incorrect and allows reading // uninitialized data. When !IsCleared we should tell dawn_native to - // consider the texture lazy-cleared. + // consider the texture lazy-cleared. crbug.com/1036080 SetCleared(); } else { d3d_image_backing->EndAccessD3D12();
diff --git a/gpu/command_buffer/service/shared_image_backing_factory_d3d_unittest.cc b/gpu/command_buffer/service/shared_image_backing_factory_d3d_unittest.cc index 2165650..a8e4214 100644 --- a/gpu/command_buffer/service/shared_image_backing_factory_d3d_unittest.cc +++ b/gpu/command_buffer/service/shared_image_backing_factory_d3d_unittest.cc
@@ -514,7 +514,8 @@ std::unique_ptr<SharedImageRepresentationGLTexturePassthrough::ScopedAccess> scoped_access = gl_representation->BeginScopedAccess( - GL_SHARED_IMAGE_ACCESS_MODE_READWRITE_CHROMIUM); + GL_SHARED_IMAGE_ACCESS_MODE_READWRITE_CHROMIUM, + SharedImageRepresentation::AllowUnclearedAccess::kYes); EXPECT_TRUE(scoped_access); // Create an FBO. @@ -584,7 +585,8 @@ ASSERT_TRUE(dawn_representation); auto scoped_access = dawn_representation->BeginScopedAccess( - WGPUTextureUsage_OutputAttachment); + WGPUTextureUsage_OutputAttachment, + SharedImageRepresentation::AllowUnclearedAccess::kNo); ASSERT_TRUE(scoped_access); wgpu::Texture texture = wgpu::Texture::Acquire(scoped_access->texture());
diff --git a/gpu/command_buffer/service/shared_image_backing_factory_gl_texture_unittest.cc b/gpu/command_buffer/service/shared_image_backing_factory_gl_texture_unittest.cc index 8e97860..751ee24 100644 --- a/gpu/command_buffer/service/shared_image_backing_factory_gl_texture_unittest.cc +++ b/gpu/command_buffer/service/shared_image_backing_factory_gl_texture_unittest.cc
@@ -270,7 +270,8 @@ std::unique_ptr<SharedImageRepresentationSkia::ScopedWriteAccess> scoped_write_access; scoped_write_access = skia_representation->BeginScopedWriteAccess( - &begin_semaphores, &end_semaphores); + &begin_semaphores, &end_semaphores, + SharedImageRepresentation::AllowUnclearedAccess::kYes); auto* surface = scoped_write_access->surface(); EXPECT_TRUE(surface); EXPECT_EQ(size.width(), surface->width()); @@ -381,7 +382,8 @@ std::unique_ptr<SharedImageRepresentationSkia::ScopedWriteAccess> scoped_write_access; scoped_write_access = skia_representation->BeginScopedWriteAccess( - &begin_semaphores, &end_semaphores); + &begin_semaphores, &end_semaphores, + SharedImageRepresentation::AllowUnclearedAccess::kYes); auto* surface = scoped_write_access->surface(); EXPECT_TRUE(surface); EXPECT_EQ(size.width(), surface->width()); @@ -884,7 +886,8 @@ // Begin writing to the underlying texture of the backing via ScopedAccess. std::unique_ptr<SharedImageRepresentationGLTexture::ScopedAccess> writer_scoped_access = gl_representation->BeginScopedAccess( - GL_SHARED_IMAGE_ACCESS_MODE_READ_CHROMIUM); + GL_SHARED_IMAGE_ACCESS_MODE_READ_CHROMIUM, + SharedImageRepresentation::AllowUnclearedAccess::kNo); DCHECK(writer_scoped_access); @@ -903,6 +906,8 @@ // Set the clear color to green. api->glClearColorFn(0.0f, 1.0f, 0.0f, 1.0f); api->glClearFn(GL_COLOR_BUFFER_BIT); + gl_representation->GetTexture()->SetLevelCleared( + gl_representation->GetTexture()->target(), 0, true); // End writing. writer_scoped_access.reset(); @@ -991,7 +996,8 @@ std::unique_ptr<SharedImageRepresentationSkia::ScopedWriteAccess> scoped_write_access; scoped_write_access = skia_representation->BeginScopedWriteAccess( - &begin_semaphores, &end_semaphores); + &begin_semaphores, &end_semaphores, + SharedImageRepresentation::AllowUnclearedAccess::kNo); auto* surface = scoped_write_access->surface(); EXPECT_TRUE(surface); EXPECT_EQ(size_.width(), surface->width());
diff --git a/gpu/command_buffer/service/shared_image_backing_factory_iosurface.mm b/gpu/command_buffer/service/shared_image_backing_factory_iosurface.mm index 31afb13..b460c93 100644 --- a/gpu/command_buffer/service/shared_image_backing_factory_iosurface.mm +++ b/gpu/command_buffer/service/shared_image_backing_factory_iosurface.mm
@@ -304,7 +304,7 @@ // the result. // TODO(cwallez@chromium.org): This is incorrect and allows reading // uninitialized data. When !IsCleared we should tell dawn_native to - // consider the texture lazy-cleared. + // consider the texture lazy-cleared. crbug.com/1036080 SetCleared(); }
diff --git a/gpu/command_buffer/service/shared_image_backing_factory_iosurface_unittest.cc b/gpu/command_buffer/service/shared_image_backing_factory_iosurface_unittest.cc index 245f841..19e87966 100644 --- a/gpu/command_buffer/service/shared_image_backing_factory_iosurface_unittest.cc +++ b/gpu/command_buffer/service/shared_image_backing_factory_iosurface_unittest.cc
@@ -143,7 +143,8 @@ scoped_write_access; scoped_write_access = skia_representation->BeginScopedWriteAccess( - &begin_semaphores, &end_semaphores); + &begin_semaphores, &end_semaphores, + SharedImageRepresentation::AllowUnclearedAccess::kYes); auto* surface = scoped_write_access->surface(); EXPECT_TRUE(surface); EXPECT_EQ(size.width(), surface->width()); @@ -189,27 +190,36 @@ memory_type_tracker_.get()); // Create a SharedImageRepresentationGLTexture. - auto gl_representation = - shared_image_representation_factory_->ProduceGLTexture(mailbox); - EXPECT_TRUE(gl_representation); - EXPECT_EQ(expected_target, gl_representation->GetTexture()->target()); + { + auto gl_representation = + shared_image_representation_factory_->ProduceGLTexture(mailbox); + EXPECT_TRUE(gl_representation); + EXPECT_EQ(expected_target, gl_representation->GetTexture()->target()); - // Create an FBO. - GLuint fbo = 0; - gl::GLApi* api = gl::g_current_gl_context; - api->glGenFramebuffersEXTFn(1, &fbo); - api->glBindFramebufferEXTFn(GL_FRAMEBUFFER, fbo); + // Access the SharedImageRepresentationGLTexutre + auto scoped_write_access = gl_representation->BeginScopedAccess( + GL_SHARED_IMAGE_ACCESS_MODE_READWRITE_CHROMIUM, + SharedImageRepresentation::AllowUnclearedAccess::kYes); - // Attach the texture to FBO. - api->glFramebufferTexture2DEXTFn( - GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, - gl_representation->GetTexture()->target(), - gl_representation->GetTexture()->service_id(), 0); + // Create an FBO. + GLuint fbo = 0; + gl::GLApi* api = gl::g_current_gl_context; + api->glGenFramebuffersEXTFn(1, &fbo); + api->glBindFramebufferEXTFn(GL_FRAMEBUFFER, fbo); - // Set the clear color to green. - api->glClearColorFn(0.0f, 1.0f, 0.0f, 1.0f); - api->glClearFn(GL_COLOR_BUFFER_BIT); - gl_representation.reset(); + // Attach the texture to FBO. + api->glFramebufferTexture2DEXTFn( + GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, + gl_representation->GetTexture()->target(), + gl_representation->GetTexture()->service_id(), 0); + + // Set the clear color to green. + api->glClearColorFn(0.0f, 1.0f, 0.0f, 1.0f); + api->glClearFn(GL_COLOR_BUFFER_BIT); + + gl_representation->GetTexture()->SetLevelCleared( + gl_representation->GetTexture()->target(), 0, true); + } // Next create a SharedImageRepresentationSkia to read back the texture data. auto skia_representation = shared_image_representation_factory_->ProduceSkia( @@ -353,7 +363,8 @@ // Clear the shared image to green using Dawn. { auto scoped_access = dawn_representation->BeginScopedAccess( - WGPUTextureUsage_OutputAttachment); + WGPUTextureUsage_OutputAttachment, + SharedImageRepresentation::AllowUnclearedAccess::kYes); ASSERT_TRUE(scoped_access); wgpu::Texture texture = wgpu::Texture::Acquire(scoped_access->texture());
diff --git a/gpu/command_buffer/service/shared_image_representation.cc b/gpu/command_buffer/service/shared_image_representation.cc index 7234e590..5a42baba 100644 --- a/gpu/command_buffer/service/shared_image_representation.cc +++ b/gpu/command_buffer/service/shared_image_representation.cc
@@ -4,6 +4,7 @@ #include "gpu/command_buffer/service/shared_image_representation.h" +#include "gpu/command_buffer/service/texture_manager.h" #include "third_party/skia/include/core/SkPromiseImageTexture.h" namespace gpu { @@ -22,7 +23,14 @@ } std::unique_ptr<SharedImageRepresentationGLTexture::ScopedAccess> -SharedImageRepresentationGLTextureBase::BeginScopedAccess(GLenum mode) { +SharedImageRepresentationGLTextureBase::BeginScopedAccess( + GLenum mode, + AllowUnclearedAccess allow_uncleared) { + if (allow_uncleared != AllowUnclearedAccess::kYes && !IsCleared()) { + LOG(ERROR) << "Attempt to access an uninitialized ShardImage"; + return nullptr; + } + if (!BeginAccess(mode)) return nullptr; @@ -44,6 +52,15 @@ return false; } +void SharedImageRepresentationGLTexture::UpdateClearedStateOnEndAccess() { + auto* texture = GetTexture(); + // Operations on the gles2::Texture may have cleared or uncleared it. Make + // sure this state is reflected back in the SharedImage. + gfx::Rect cleared_rect = texture->GetLevelClearedRect(texture->target(), 0); + if (cleared_rect != ClearedRect()) + SetClearedRect(cleared_rect); +} + SharedImageRepresentationSkia::ScopedWriteAccess::ScopedWriteAccess( util::PassKey<SharedImageRepresentationSkia> /* pass_key */, SharedImageRepresentationSkia* representation, @@ -59,7 +76,13 @@ int final_msaa_count, const SkSurfaceProps& surface_props, std::vector<GrBackendSemaphore>* begin_semaphores, - std::vector<GrBackendSemaphore>* end_semaphores) { + std::vector<GrBackendSemaphore>* end_semaphores, + AllowUnclearedAccess allow_uncleared) { + if (allow_uncleared != AllowUnclearedAccess::kYes && !IsCleared()) { + LOG(ERROR) << "Attempt to write to an uninitialized ShardImage"; + return nullptr; + } + sk_sp<SkSurface> surface = BeginWriteAccess(final_msaa_count, surface_props, begin_semaphores, end_semaphores); if (!surface) @@ -72,11 +95,12 @@ std::unique_ptr<SharedImageRepresentationSkia::ScopedWriteAccess> SharedImageRepresentationSkia::BeginScopedWriteAccess( std::vector<GrBackendSemaphore>* begin_semaphores, - std::vector<GrBackendSemaphore>* end_semaphores) { + std::vector<GrBackendSemaphore>* end_semaphores, + AllowUnclearedAccess allow_uncleared) { return BeginScopedWriteAccess( 0 /* final_msaa_count */, SkSurfaceProps(0 /* flags */, kUnknown_SkPixelGeometry), begin_semaphores, - end_semaphores); + end_semaphores, allow_uncleared); } SharedImageRepresentationSkia::ScopedReadAccess::ScopedReadAccess( @@ -94,6 +118,11 @@ SharedImageRepresentationSkia::BeginScopedReadAccess( std::vector<GrBackendSemaphore>* begin_semaphores, std::vector<GrBackendSemaphore>* end_semaphores) { + if (!IsCleared()) { + LOG(ERROR) << "Attempt to read from an uninitialized ShardImage"; + return nullptr; + } + sk_sp<SkPromiseImageTexture> promise_image_texture = BeginReadAccess(begin_semaphores, end_semaphores); if (!promise_image_texture) @@ -106,6 +135,11 @@ std::unique_ptr<SharedImageRepresentationOverlay::ScopedReadAccess> SharedImageRepresentationOverlay::BeginScopedReadAccess(bool needs_gl_image) { + if (!IsCleared()) { + LOG(ERROR) << "Attempt to read from an uninitialized ShardImage"; + return nullptr; + } + BeginReadAccess(); return std::make_unique<ScopedReadAccess>( util::PassKey<SharedImageRepresentationOverlay>(), this, @@ -123,7 +157,14 @@ } std::unique_ptr<SharedImageRepresentationDawn::ScopedAccess> -SharedImageRepresentationDawn::BeginScopedAccess(WGPUTextureUsage usage) { +SharedImageRepresentationDawn::BeginScopedAccess( + WGPUTextureUsage usage, + AllowUnclearedAccess allow_uncleared) { + if (allow_uncleared != AllowUnclearedAccess::kYes && !IsCleared()) { + LOG(ERROR) << "Attempt to access an uninitialized ShardImage"; + return nullptr; + } + WGPUTexture texture = BeginAccess(usage); if (!texture) return nullptr;
diff --git a/gpu/command_buffer/service/shared_image_representation.h b/gpu/command_buffer/service/shared_image_representation.h index 96699f1..da832e8 100644 --- a/gpu/command_buffer/service/shared_image_representation.h +++ b/gpu/command_buffer/service/shared_image_representation.h
@@ -44,6 +44,9 @@ // api. class GPU_GLES2_EXPORT SharedImageRepresentation { public: + // Used by derived classes. + enum class AllowUnclearedAccess { kYes, kNo }; + SharedImageRepresentation(SharedImageManager* manager, SharedImageBacking* backing, MemoryTypeTracker* tracker); @@ -106,7 +109,10 @@ ScopedAccess(util::PassKey<SharedImageRepresentationGLTextureBase> pass_key, SharedImageRepresentationGLTextureBase* representation) : representation_(representation) {} - ~ScopedAccess() { representation_->EndAccess(); } + ~ScopedAccess() { + representation_->UpdateClearedStateOnEndAccess(); + representation_->EndAccess(); + } private: SharedImageRepresentationGLTextureBase* representation_ = nullptr; @@ -119,11 +125,16 @@ MemoryTypeTracker* tracker) : SharedImageRepresentation(manager, backing, tracker) {} - std::unique_ptr<ScopedAccess> BeginScopedAccess(GLenum mode); + std::unique_ptr<ScopedAccess> BeginScopedAccess( + GLenum mode, + AllowUnclearedAccess allow_uncleared); protected: friend class SharedImageRepresentationSkiaGL; + // Can be overridden to handle clear state tracking when GL access ends. + virtual void UpdateClearedStateOnEndAccess() {} + // TODO(ericrk): Make these pure virtual and ensure real implementations // exist. virtual bool BeginAccess(GLenum mode); @@ -140,6 +151,9 @@ // TODO(ericrk): Move this to the ScopedAccess object. crbug.com/1003686 virtual gles2::Texture* GetTexture() = 0; + + protected: + void UpdateClearedStateOnEndAccess() override; }; class GPU_GLES2_EXPORT SharedImageRepresentationGLTexturePassthrough @@ -203,10 +217,13 @@ int final_msaa_count, const SkSurfaceProps& surface_props, std::vector<GrBackendSemaphore>* begin_semaphores, - std::vector<GrBackendSemaphore>* end_semaphores); + std::vector<GrBackendSemaphore>* end_semaphores, + AllowUnclearedAccess allow_uncleared); + std::unique_ptr<ScopedWriteAccess> BeginScopedWriteAccess( std::vector<GrBackendSemaphore>* begin_semaphores, - std::vector<GrBackendSemaphore>* end_semaphores); + std::vector<GrBackendSemaphore>* end_semaphores, + AllowUnclearedAccess allow_uncleared); // Note: See BeginReadAccess below for a description of the semaphore // parameters. @@ -271,7 +288,9 @@ // Calls BeginAccess and returns a ScopedAccess object which will EndAccess // when it goes out of scope. The Representation must outlive the returned // ScopedAccess. - std::unique_ptr<ScopedAccess> BeginScopedAccess(WGPUTextureUsage usage); + std::unique_ptr<ScopedAccess> BeginScopedAccess( + WGPUTextureUsage usage, + AllowUnclearedAccess allow_uncleared); private: // This can return null in case of a Dawn validation error, for example if
diff --git a/gpu/command_buffer/service/shared_image_representation_dawn_ozone.cc b/gpu/command_buffer/service/shared_image_representation_dawn_ozone.cc index 1b7d95f..df4a9d4 100644 --- a/gpu/command_buffer/service/shared_image_representation_dawn_ozone.cc +++ b/gpu/command_buffer/service/shared_image_representation_dawn_ozone.cc
@@ -90,7 +90,7 @@ // the result. // TODO(cwallez@chromium.org): This is incorrect and allows reading // uninitialized data. When !IsCleared we should tell dawn_native to - // consider the texture lazy-cleared. + // consider the texture lazy-cleared. crbug.com/1036080 SetCleared(); } else { close(fd);
diff --git a/gpu/command_buffer/service/shared_image_representation_unittest.cc b/gpu/command_buffer/service/shared_image_representation_unittest.cc new file mode 100644 index 0000000..81c6055 --- /dev/null +++ b/gpu/command_buffer/service/shared_image_representation_unittest.cc
@@ -0,0 +1,235 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "gpu/command_buffer/service/shared_image_representation.h" + +#include "components/viz/common/resources/resource_format_utils.h" +#include "gpu/command_buffer/common/mailbox.h" +#include "gpu/command_buffer/common/shared_image_usage.h" +#include "gpu/command_buffer/service/shared_context_state.h" +#include "gpu/command_buffer/service/shared_image_backing.h" +#include "gpu/command_buffer/service/shared_image_representation.h" +#include "gpu/command_buffer/service/test_shared_image_backing.h" +#include "gpu/command_buffer/service/texture_manager.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/skia/include/core/SkPromiseImageTexture.h" +#include "third_party/skia/include/gpu/GrBackendSurface.h" + +namespace gpu { + +class SharedImageRepresentationTest : public ::testing::Test { + public: + void SetUp() override { + tracker_ = std::make_unique<MemoryTypeTracker>(nullptr); + mailbox_ = Mailbox::GenerateForSharedImage(); + auto format = viz::ResourceFormat::RGBA_8888; + gfx::Size size(256, 256); + auto color_space = gfx::ColorSpace::CreateSRGB(); + uint32_t usage = SHARED_IMAGE_USAGE_GLES2; + + auto backing = std::make_unique<TestSharedImageBacking>( + mailbox_, format, size, color_space, usage, 0 /* estimated_size */); + factory_ref_ = manager_.Register(std::move(backing), tracker_.get()); + } + + protected: + gpu::Mailbox mailbox_; + SharedImageManager manager_; + std::unique_ptr<MemoryTypeTracker> tracker_; + std::unique_ptr<SharedImageRepresentationFactoryRef> factory_ref_; +}; + +TEST_F(SharedImageRepresentationTest, GLTextureClearing) { + auto representation = manager_.ProduceGLTexture(mailbox_, tracker_.get()); + EXPECT_FALSE(representation->IsCleared()); + + // We should not be able to begin access when |allow_uncleared| is false. + { + auto scoped_access = representation->BeginScopedAccess( + GL_SHARED_IMAGE_ACCESS_MODE_READWRITE_CHROMIUM, + SharedImageRepresentation::AllowUnclearedAccess::kNo); + EXPECT_FALSE(scoped_access); + } + EXPECT_FALSE(representation->IsCleared()); + + // Begin/End access should not modify clear status on its own. + { + auto scoped_access = representation->BeginScopedAccess( + GL_SHARED_IMAGE_ACCESS_MODE_READWRITE_CHROMIUM, + SharedImageRepresentation::AllowUnclearedAccess::kYes); + EXPECT_TRUE(scoped_access); + } + EXPECT_FALSE(representation->IsCleared()); + + // Clearing underlying GL texture should clear the SharedImage. + { + auto scoped_access = representation->BeginScopedAccess( + GL_SHARED_IMAGE_ACCESS_MODE_READWRITE_CHROMIUM, + SharedImageRepresentation::AllowUnclearedAccess::kYes); + ASSERT_TRUE(scoped_access); + representation->GetTexture()->SetLevelCleared(GL_TEXTURE_2D, 0, + true /* cleared */); + } + EXPECT_TRUE(representation->IsCleared()); + + // We can now begin accdess with |allow_uncleared| == false. + { + auto scoped_access = representation->BeginScopedAccess( + GL_SHARED_IMAGE_ACCESS_MODE_READWRITE_CHROMIUM, + SharedImageRepresentation::AllowUnclearedAccess::kNo); + EXPECT_TRUE(scoped_access); + } +} + +TEST_F(SharedImageRepresentationTest, GLTexturePassthroughClearing) { + auto representation = + manager_.ProduceGLTexturePassthrough(mailbox_, tracker_.get()); + EXPECT_FALSE(representation->IsCleared()); + + // We should not be able to begin access when |allow_uncleared| is false. + { + auto scoped_access = representation->BeginScopedAccess( + GL_SHARED_IMAGE_ACCESS_MODE_READWRITE_CHROMIUM, + SharedImageRepresentation::AllowUnclearedAccess::kNo); + EXPECT_FALSE(scoped_access); + } + EXPECT_FALSE(representation->IsCleared()); + + // Begin/End access will not clear the representation on its own. + { + auto scoped_access = representation->BeginScopedAccess( + GL_SHARED_IMAGE_ACCESS_MODE_READWRITE_CHROMIUM, + SharedImageRepresentation::AllowUnclearedAccess::kYes); + EXPECT_TRUE(scoped_access); + } + EXPECT_FALSE(representation->IsCleared()); + + // Clear the SharedImage. + representation->SetCleared(); + EXPECT_TRUE(representation->IsCleared()); + + // We can now begin accdess with |allow_uncleared| == false. + { + auto scoped_access = representation->BeginScopedAccess( + GL_SHARED_IMAGE_ACCESS_MODE_READWRITE_CHROMIUM, + SharedImageRepresentation::AllowUnclearedAccess::kNo); + EXPECT_TRUE(scoped_access); + } +} + +TEST_F(SharedImageRepresentationTest, SkiaClearing) { + auto representation = manager_.ProduceSkia(mailbox_, tracker_.get(), nullptr); + EXPECT_FALSE(representation->IsCleared()); + + // We should not be able to begin read access. + { + auto scoped_access = + representation->BeginScopedReadAccess(nullptr, nullptr); + EXPECT_FALSE(scoped_access); + } + EXPECT_FALSE(representation->IsCleared()); + + // We should not be able to begin write access when |allow_uncleared| is + // false. + { + auto scoped_access = representation->BeginScopedWriteAccess( + nullptr, nullptr, SharedImageRepresentation::AllowUnclearedAccess::kNo); + EXPECT_FALSE(scoped_access); + } + EXPECT_FALSE(representation->IsCleared()); + + // We can begin write access when |allow_uncleared| is true. + { + auto scoped_access = representation->BeginScopedWriteAccess( + nullptr, nullptr, + SharedImageRepresentation::AllowUnclearedAccess::kYes); + EXPECT_TRUE(scoped_access); + } + EXPECT_FALSE(representation->IsCleared()); + + // Clear the SharedImage. + representation->SetCleared(); + EXPECT_TRUE(representation->IsCleared()); + + // We can now begin read access. + { + auto scoped_access = + representation->BeginScopedReadAccess(nullptr, nullptr); + EXPECT_TRUE(scoped_access); + } + EXPECT_TRUE(representation->IsCleared()); + + // We can also begin write access with |allow_uncleared| == false. + { + auto scoped_access = representation->BeginScopedWriteAccess( + nullptr, nullptr, SharedImageRepresentation::AllowUnclearedAccess::kNo); + EXPECT_TRUE(scoped_access); + } + EXPECT_TRUE(representation->IsCleared()); +} + +TEST_F(SharedImageRepresentationTest, DawnClearing) { + auto representation = + manager_.ProduceDawn(mailbox_, tracker_.get(), nullptr /* device */); + EXPECT_FALSE(representation->IsCleared()); + + // We should not be able to begin access with |allow_uncleared| == false. + { + auto scoped_access = representation->BeginScopedAccess( + WGPUTextureUsage_None, + SharedImageRepresentation::AllowUnclearedAccess::kNo); + EXPECT_FALSE(scoped_access); + } + EXPECT_FALSE(representation->IsCleared()); + + // We can begin access when |allow_uncleared| is true. + { + auto scoped_access = representation->BeginScopedAccess( + WGPUTextureUsage_None, + SharedImageRepresentation::AllowUnclearedAccess::kYes); + EXPECT_TRUE(scoped_access); + } + EXPECT_FALSE(representation->IsCleared()); + + // Clear the SharedImage. + representation->SetCleared(); + EXPECT_TRUE(representation->IsCleared()); + + // We can also begin access with |allow_uncleared| == false. + { + auto scoped_access = representation->BeginScopedAccess( + WGPUTextureUsage_None, + SharedImageRepresentation::AllowUnclearedAccess::kNo); + EXPECT_TRUE(scoped_access); + } + EXPECT_TRUE(representation->IsCleared()); +} + +TEST_F(SharedImageRepresentationTest, OverlayClearing) { + auto representation = manager_.ProduceOverlay(mailbox_, tracker_.get()); + EXPECT_FALSE(representation->IsCleared()); + + // We should not be able to begin read ccess. + { + auto scoped_access = + representation->BeginScopedReadAccess(false /* needs_gl_image */); + EXPECT_FALSE(scoped_access); + } + EXPECT_FALSE(representation->IsCleared()); + + // Clear the SharedImage. + representation->SetCleared(); + EXPECT_TRUE(representation->IsCleared()); + + // We can now begin read access. + { + auto scoped_access = + representation->BeginScopedReadAccess(false /* needs_gl_image */); + EXPECT_TRUE(scoped_access); + } + EXPECT_TRUE(representation->IsCleared()); +} + +} // namespace gpu
diff --git a/gpu/command_buffer/service/test_shared_image_backing.cc b/gpu/command_buffer/service/test_shared_image_backing.cc index 62fac229..3427f341a 100644 --- a/gpu/command_buffer/service/test_shared_image_backing.cc +++ b/gpu/command_buffer/service/test_shared_image_backing.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include "gpu/command_buffer/service/test_shared_image_backing.h" +#include "build/build_config.h" #include "components/viz/common/resources/resource_format_utils.h" #include "gpu/command_buffer/service/shared_context_state.h" #include "third_party/skia/include/core/SkPromiseImageTexture.h" @@ -55,6 +56,75 @@ const scoped_refptr<gles2::TexturePassthrough> texture_; }; +class TestSharedImageRepresentationSkia : public SharedImageRepresentationSkia { + public: + TestSharedImageRepresentationSkia(SharedImageManager* manager, + SharedImageBacking* backing, + MemoryTypeTracker* tracker) + : SharedImageRepresentationSkia(manager, backing, tracker) {} + + protected: + sk_sp<SkSurface> BeginWriteAccess( + int final_msaa_count, + const SkSurfaceProps& surface_props, + std::vector<GrBackendSemaphore>* begin_semaphores, + std::vector<GrBackendSemaphore>* end_semaphores) override { + if (!static_cast<TestSharedImageBacking*>(backing())->can_access()) { + return nullptr; + } + return SkSurface::MakeRasterN32Premul(size().width(), size().height()); + } + void EndWriteAccess(sk_sp<SkSurface> surface) override {} + sk_sp<SkPromiseImageTexture> BeginReadAccess( + std::vector<GrBackendSemaphore>* begin_semaphores, + std::vector<GrBackendSemaphore>* end_semaphores) override { + if (!static_cast<TestSharedImageBacking*>(backing())->can_access()) { + return nullptr; + } + GrBackendTexture backend_tex(size().width(), size().height(), + GrMipMapped::kNo, GrMockTextureInfo()); + return SkPromiseImageTexture::Make(backend_tex); + } + void EndReadAccess() override {} +}; + +class TestSharedImageRepresentationDawn : public SharedImageRepresentationDawn { + public: + TestSharedImageRepresentationDawn(SharedImageManager* manager, + SharedImageBacking* backing, + MemoryTypeTracker* tracker) + : SharedImageRepresentationDawn(manager, backing, tracker) {} + + WGPUTexture BeginAccess(WGPUTextureUsage usage) override { + if (!static_cast<TestSharedImageBacking*>(backing())->can_access()) { + return nullptr; + } + + // Return a dummy value. + return reinterpret_cast<WGPUTexture>(203); + } + + void EndAccess() override {} +}; + +class TestSharedImageRepresentationOverlay + : public SharedImageRepresentationOverlay { + public: + TestSharedImageRepresentationOverlay(SharedImageManager* manager, + SharedImageBacking* backing, + MemoryTypeTracker* tracker) + : SharedImageRepresentationOverlay(manager, backing, tracker) {} + + void BeginReadAccess() override {} + void EndReadAccess() override {} + gl::GLImage* GetGLImage() override { return nullptr; } + +#if defined(OS_ANDROID) + void NotifyOverlayPromotion(bool promotion, + const gfx::Rect& bounds) override {} +#endif +}; + } // namespace TestSharedImageBacking::TestSharedImageBacking( @@ -146,4 +216,28 @@ manager, this, tracker, texture_passthrough_); } +std::unique_ptr<SharedImageRepresentationSkia> +TestSharedImageBacking::ProduceSkia( + SharedImageManager* manager, + MemoryTypeTracker* tracker, + scoped_refptr<SharedContextState> context_state) { + return std::make_unique<TestSharedImageRepresentationSkia>(manager, this, + tracker); +} + +std::unique_ptr<SharedImageRepresentationDawn> +TestSharedImageBacking::ProduceDawn(SharedImageManager* manager, + MemoryTypeTracker* tracker, + WGPUDevice device) { + return std::make_unique<TestSharedImageRepresentationDawn>(manager, this, + tracker); +} + +std::unique_ptr<SharedImageRepresentationOverlay> +TestSharedImageBacking::ProduceOverlay(SharedImageManager* manager, + MemoryTypeTracker* tracker) { + return std::make_unique<TestSharedImageRepresentationOverlay>(manager, this, + tracker); +} + } // namespace gpu
diff --git a/gpu/command_buffer/service/test_shared_image_backing.h b/gpu/command_buffer/service/test_shared_image_backing.h index 93540b8..14d3654 100644 --- a/gpu/command_buffer/service/test_shared_image_backing.h +++ b/gpu/command_buffer/service/test_shared_image_backing.h
@@ -52,6 +52,20 @@ ProduceGLTexturePassthrough(SharedImageManager* manager, MemoryTypeTracker* tracker) override; + // ProduceSkia/Dawn/Overlay all create dummy representations that + // don't link up to a real texture. + std::unique_ptr<SharedImageRepresentationSkia> ProduceSkia( + SharedImageManager* manager, + MemoryTypeTracker* tracker, + scoped_refptr<SharedContextState> context_state) override; + std::unique_ptr<SharedImageRepresentationDawn> ProduceDawn( + SharedImageManager* manager, + MemoryTypeTracker* tracker, + WGPUDevice device) override; + std::unique_ptr<SharedImageRepresentationOverlay> ProduceOverlay( + SharedImageManager* manager, + MemoryTypeTracker* tracker) override; + private: const GLuint service_id_ = 0; gles2::Texture* texture_ = nullptr;
diff --git a/gpu/command_buffer/service/texture_manager.cc b/gpu/command_buffer/service/texture_manager.cc index 4ca4a0a..b889041 100644 --- a/gpu/command_buffer/service/texture_manager.cc +++ b/gpu/command_buffer/service/texture_manager.cc
@@ -2106,15 +2106,27 @@ } bool TextureRef::BeginAccessSharedImage(GLenum mode) { - shared_image_scoped_access_ = shared_image_->BeginScopedAccess(mode); + // When accessing through TextureManager, we are using legacy GL logic which + // tracks clearning internally. Always allow access to uncleared + // SharedImages. + shared_image_scoped_access_ = shared_image_->BeginScopedAccess( + mode, SharedImageRepresentation::AllowUnclearedAccess::kYes); if (!shared_image_scoped_access_) { return false; } + // After beginning access, the returned gles2::Texture's cleared status + // should match the SharedImage's. + DCHECK_EQ(shared_image_->ClearedRect(), + texture_->GetLevelClearedRect(texture_->target(), 0)); return true; } void TextureRef::EndAccessSharedImage() { shared_image_scoped_access_.reset(); + // After ending access, the SharedImages cleared rect should be synchronized + // with |texture_|'s. + DCHECK_EQ(shared_image_->ClearedRect(), + texture_->GetLevelClearedRect(texture_->target(), 0)); } void TextureRef::ForceContextLost() {
diff --git a/gpu/command_buffer/service/webgpu_decoder_impl.cc b/gpu/command_buffer/service/webgpu_decoder_impl.cc index adb00ed1..343088a3 100644 --- a/gpu/command_buffer/service/webgpu_decoder_impl.cc +++ b/gpu/command_buffer/service/webgpu_decoder_impl.cc
@@ -836,8 +836,12 @@ return error::kInvalidArguments; } + // TODO(cwallez@chromium.org): Handle texture clearing. We should either + // pre-clear textures, or implement a way to detect whether DAWN has cleared + // a texture. crbug.com/1036080 std::unique_ptr<SharedImageRepresentationDawn::ScopedAccess> - shared_image_access = shared_image->BeginScopedAccess(wgpu_usage); + shared_image_access = shared_image->BeginScopedAccess( + wgpu_usage, SharedImageRepresentation::AllowUnclearedAccess::kYes); if (!shared_image_access) { DLOG(ERROR) << "AssociateMailbox: Couldn't begin shared image access"; return error::kInvalidArguments;
diff --git a/gpu/command_buffer/service/wrapped_sk_image.cc b/gpu/command_buffer/service/wrapped_sk_image.cc index 528b8f9..d8c46b23f 100644 --- a/gpu/command_buffer/service/wrapped_sk_image.cc +++ b/gpu/command_buffer/service/wrapped_sk_image.cc
@@ -157,6 +157,7 @@ if (!image_) return false; + SetCleared(); OnWriteSucceeded(); } else { // Initializing to bright green makes it obvious if the pixels are not
diff --git a/gpu/ipc/service/gpu_channel_manager.cc b/gpu/ipc/service/gpu_channel_manager.cc index 1808acd..f05e29f9 100644 --- a/gpu/ipc/service/gpu_channel_manager.cc +++ b/gpu/ipc/service/gpu_channel_manager.cc
@@ -67,12 +67,19 @@ void GpuChannelManager::GpuPeakMemoryMonitor::StartGpuMemoryTracking( uint32_t sequence_num) { + TRACE_EVENT_ASYNC_BEGIN1("gpu", "PeakMemoryTracking", sequence_num, "start", + current_memory_); sequence_trackers_.emplace(sequence_num, current_memory_); } void GpuChannelManager::GpuPeakMemoryMonitor::StopGpuMemoryTracking( uint32_t sequence_num) { - sequence_trackers_.erase(sequence_num); + auto sequence = sequence_trackers_.find(sequence_num); + if (sequence != sequence_trackers_.end()) { + TRACE_EVENT_ASYNC_END1("gpu", "PeakMemoryTracking", sequence_num, "peak", + sequence->second); + sequence_trackers_.erase(sequence); + } } void GpuChannelManager::GpuPeakMemoryMonitor::OnMemoryAllocatedChange( @@ -89,8 +96,14 @@ // |peak_since_last_sequence_update_| on the the memory changes. Then only // update the sequences with a new one is added, or the peak is requested. for (auto& sequence : sequence_trackers_) { - if (current_memory_ > sequence.second) + if (current_memory_ > sequence.second) { sequence.second = current_memory_; + for (auto& sequence : sequence_trackers_) { + TRACE_EVENT_ASYNC_STEP_INTO1("gpu", "PeakMemoryTracking", + sequence.first, "Peak", "peak", + current_memory_); + } + } } } }
diff --git a/gpu/ipc/service/image_transport_surface_overlay_mac.h b/gpu/ipc/service/image_transport_surface_overlay_mac.h index f65ad035..a298747 100644 --- a/gpu/ipc/service/image_transport_surface_overlay_mac.h +++ b/gpu/ipc/service/image_transport_surface_overlay_mac.h
@@ -53,7 +53,7 @@ void PrepareToDestroy(bool have_context) override; bool Resize(const gfx::Size& size, float scale_factor, - gl::GLSurface::ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) override; bool IsOffscreen() override; gfx::SwapResult SwapBuffers(
diff --git a/gpu/ipc/service/image_transport_surface_overlay_mac.mm b/gpu/ipc/service/image_transport_surface_overlay_mac.mm index c1af03a..eb46993b 100644 --- a/gpu/ipc/service/image_transport_surface_overlay_mac.mm +++ b/gpu/ipc/service/image_transport_surface_overlay_mac.mm
@@ -307,7 +307,7 @@ bool ImageTransportSurfaceOverlayMacBase<BaseClass>::Resize( const gfx::Size& pixel_size, float scale_factor, - gl::GLSurface::ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) { pixel_size_ = pixel_size; scale_factor_ = scale_factor;
diff --git a/ios/chrome/browser/overlays/BUILD.gn b/ios/chrome/browser/overlays/BUILD.gn index b71f6709..e8e58d5 100644 --- a/ios/chrome/browser/overlays/BUILD.gn +++ b/ios/chrome/browser/overlays/BUILD.gn
@@ -4,10 +4,9 @@ source_set("overlays") { public = [ - "public/aggregate_overlay_request_support.h", "public/overlay_callback_manager.h", "public/overlay_dismissal_callback.h", - "public/overlay_dispatch_callback_storage.h", + "public/overlay_dispatch_callback.h", "public/overlay_modality.h", "public/overlay_presentation_callback.h", "public/overlay_presentation_context.h", @@ -16,24 +15,27 @@ "public/overlay_presenter_observer.h", "public/overlay_presenter_observer_bridge.h", "public/overlay_request.h", + "public/overlay_request_callback_installer.h", "public/overlay_request_cancel_handler.h", "public/overlay_request_config.h", "public/overlay_request_queue.h", "public/overlay_request_support.h", "public/overlay_response.h", + "public/overlay_response_info.h", + "public/overlay_response_support.h", "public/overlay_user_data.h", ] sources = [ - "aggregate_overlay_request_support.cc", "default_overlay_request_cancel_handler.h", "default_overlay_request_cancel_handler.mm", "overlay_callback_manager_impl.cc", "overlay_callback_manager_impl.h", - "overlay_dispatch_callback_storage.cc", + "overlay_dispatch_callback.cc", "overlay_presenter_impl.h", "overlay_presenter_impl.mm", "overlay_presenter_observer.cc", "overlay_presenter_observer_bridge.mm", + "overlay_request_callback_installer.cc", "overlay_request_cancel_handler.mm", "overlay_request_impl.cc", "overlay_request_impl.h", @@ -42,6 +44,7 @@ "overlay_request_support.cc", "overlay_response_impl.cc", "overlay_response_impl.h", + "overlay_response_support.cc", ] configs += [ "//build/config/compiler:enable_arc" ] @@ -59,15 +62,17 @@ source_set("unit_tests") { testonly = true sources = [ - "aggregate_overlay_request_support_unittest.cc", "default_overlay_request_cancel_handler_unittest.mm", "overlay_callback_manager_impl_unittest.cc", + "overlay_dispatch_callback_unittest.cc", "overlay_presenter_impl_unittest.mm", "overlay_presenter_observer_bridge_unittest.mm", + "overlay_request_callback_installer_unittest.cc", "overlay_request_impl_unittest.cc", "overlay_request_queue_impl_unittest.mm", "overlay_request_support_unittest.cc", "overlay_request_unittest.cc", + "overlay_response_support_unittest.cc", "overlay_response_unittest.cc", ]
diff --git a/ios/chrome/browser/overlays/aggregate_overlay_request_support.cc b/ios/chrome/browser/overlays/aggregate_overlay_request_support.cc deleted file mode 100644 index 4e7c69ad..0000000 --- a/ios/chrome/browser/overlays/aggregate_overlay_request_support.cc +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright 2019 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/overlays/public/aggregate_overlay_request_support.h" - -#include "base/logging.h" - -AggregateOverlayRequestSupport::AggregateOverlayRequestSupport( - const std::vector<const OverlayRequestSupport*>& supports) - : aggregated_supports_(supports) { - DCHECK(!aggregated_supports_.empty()); -} - -AggregateOverlayRequestSupport::~AggregateOverlayRequestSupport() = default; - -bool AggregateOverlayRequestSupport::IsRequestSupported( - OverlayRequest* request) const { - for (const OverlayRequestSupport* support : aggregated_supports_) { - if (support->IsRequestSupported(request)) - return true; - } - return false; -}
diff --git a/ios/chrome/browser/overlays/aggregate_overlay_request_support_unittest.cc b/ios/chrome/browser/overlays/aggregate_overlay_request_support_unittest.cc deleted file mode 100644 index a3ca9129..0000000 --- a/ios/chrome/browser/overlays/aggregate_overlay_request_support_unittest.cc +++ /dev/null
@@ -1,39 +0,0 @@ -// Copyright 2019 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/overlays/public/aggregate_overlay_request_support.h" - -#include "ios/chrome/browser/overlays/public/overlay_request.h" -#include "ios/chrome/browser/overlays/public/overlay_request_config.h" -#include "ios/chrome/browser/overlays/test/overlay_test_macros.h" -#include "testing/platform_test.h" - -namespace { -// Fake request config types. -DEFINE_TEST_OVERLAY_REQUEST_CONFIG(FirstConfig); -DEFINE_TEST_OVERLAY_REQUEST_CONFIG(SecondConfig); -DEFINE_TEST_OVERLAY_REQUEST_CONFIG(ThirdConfig); -} // namespace - -using AggregateOverlayRequestSupportTest = PlatformTest; - -// Tests that support is correctly aggregated. -TEST_F(AggregateOverlayRequestSupportTest, AggregateSupport) { - // Create an AggregateOverlayRequestSupport that supports requests for - // FirstConfig and SecondConfig. - const std::vector<const OverlayRequestSupport*> support_list = { - FirstConfig::RequestSupport(), SecondConfig::RequestSupport()}; - const AggregateOverlayRequestSupport aggregate_support(support_list); - - // Verify that requests created with FirstConfig and SecondConfig are - // supported. - EXPECT_TRUE(aggregate_support.IsRequestSupported( - OverlayRequest::CreateWithConfig<FirstConfig>().get())); - EXPECT_TRUE(aggregate_support.IsRequestSupported( - OverlayRequest::CreateWithConfig<SecondConfig>().get())); - - // Verify that requests created with ThirdConfig are not supported. - EXPECT_FALSE(aggregate_support.IsRequestSupported( - OverlayRequest::CreateWithConfig<ThirdConfig>().get())); -}
diff --git a/ios/chrome/browser/overlays/overlay_callback_manager_impl.cc b/ios/chrome/browser/overlays/overlay_callback_manager_impl.cc index 474dda4..11ee6776 100644 --- a/ios/chrome/browser/overlays/overlay_callback_manager_impl.cc +++ b/ios/chrome/browser/overlays/overlay_callback_manager_impl.cc
@@ -39,10 +39,12 @@ void OverlayCallbackManagerImpl::DispatchResponse( std::unique_ptr<OverlayResponse> response) { DCHECK(response); - dispatch_callback_storage_.DispatchResponse(response.get()); + for (auto& callback : dispatch_callbacks_) { + callback.Run(response.get()); + } } -OverlayDispatchCallbackStorage* -OverlayCallbackManagerImpl::GetDispatchCallbackStorage() { - return &dispatch_callback_storage_; +void OverlayCallbackManagerImpl::AddDispatchCallback( + OverlayDispatchCallback callback) { + dispatch_callbacks_.emplace_back(std::move(callback)); }
diff --git a/ios/chrome/browser/overlays/overlay_callback_manager_impl.h b/ios/chrome/browser/overlays/overlay_callback_manager_impl.h index 17d3efe..d504688 100644 --- a/ios/chrome/browser/overlays/overlay_callback_manager_impl.h +++ b/ios/chrome/browser/overlays/overlay_callback_manager_impl.h
@@ -8,7 +8,6 @@ #include <vector> #include "ios/chrome/browser/overlays/public/overlay_callback_manager.h" -#include "ios/chrome/browser/overlays/public/overlay_dispatch_callback_storage.h" #include "ios/chrome/browser/overlays/public/overlay_response.h" // Implementation of OverlayCallbackManager. @@ -27,14 +26,12 @@ OverlayResponse* GetCompletionResponse() const override; void AddCompletionCallback(OverlayCompletionCallback callback) override; void DispatchResponse(std::unique_ptr<OverlayResponse> response) override; - OverlayDispatchCallbackStorage* GetDispatchCallbackStorage() override; + void AddDispatchCallback(OverlayDispatchCallback callback) override; private: - // The completion response and callbacks. std::unique_ptr<OverlayResponse> completion_response_; std::vector<OverlayCompletionCallback> completion_callbacks_; - // The storage holding OverlayDispatchCallbacks. - OverlayDispatchCallbackStorage dispatch_callback_storage_; + std::vector<OverlayDispatchCallback> dispatch_callbacks_; }; #endif // IOS_CHROME_BROWSER_OVERLAYS_OVERLAY_CALLBACK_MANAGER_IMPL_H_
diff --git a/ios/chrome/browser/overlays/overlay_callback_manager_impl_unittest.cc b/ios/chrome/browser/overlays/overlay_callback_manager_impl_unittest.cc index d3548742..fb7eae4b 100644 --- a/ios/chrome/browser/overlays/overlay_callback_manager_impl_unittest.cc +++ b/ios/chrome/browser/overlays/overlay_callback_manager_impl_unittest.cc
@@ -67,10 +67,12 @@ ^(OverlayResponse* response) { ++second_execution_count; }; - manager.AddDispatchCallback<FirstResponseInfo>( - base::BindRepeating(base::RetainBlock(first_callback_block))); - manager.AddDispatchCallback<SecondResponseInfo>( - base::BindRepeating(base::RetainBlock(second_callback_block))); + manager.AddDispatchCallback(OverlayDispatchCallback( + base::BindRepeating(base::RetainBlock(first_callback_block)), + FirstResponseInfo::ResponseSupport())); + manager.AddDispatchCallback(OverlayDispatchCallback( + base::BindRepeating(base::RetainBlock(second_callback_block)), + SecondResponseInfo::ResponseSupport())); ASSERT_EQ(0U, first_execution_count); ASSERT_EQ(0U, second_execution_count);
diff --git a/ios/chrome/browser/overlays/overlay_dispatch_callback.cc b/ios/chrome/browser/overlays/overlay_dispatch_callback.cc new file mode 100644 index 0000000..1abee57b --- /dev/null +++ b/ios/chrome/browser/overlays/overlay_dispatch_callback.cc
@@ -0,0 +1,28 @@ +// Copyright 2020 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/overlays/public/overlay_dispatch_callback.h" + +#include "base/logging.h" +#include "ios/chrome/browser/overlays/public/overlay_response_support.h" + +OverlayDispatchCallback::OverlayDispatchCallback( + base::RepeatingCallback<void(OverlayResponse* response)> callback, + const OverlayResponseSupport* support) + : callback_(std::move(callback)), response_support_(support) { + DCHECK(!callback_.is_null()); + DCHECK(response_support_); +} + +OverlayDispatchCallback::OverlayDispatchCallback( + OverlayDispatchCallback&& other) + : callback_(std::move(other.callback_)), + response_support_(other.response_support_) {} + +OverlayDispatchCallback::~OverlayDispatchCallback() = default; + +void OverlayDispatchCallback::Run(OverlayResponse* response) { + if (response_support_->IsResponseSupported(response)) + callback_.Run(response); +}
diff --git a/ios/chrome/browser/overlays/overlay_dispatch_callback_storage.cc b/ios/chrome/browser/overlays/overlay_dispatch_callback_storage.cc deleted file mode 100644 index 8246a342..0000000 --- a/ios/chrome/browser/overlays/overlay_dispatch_callback_storage.cc +++ /dev/null
@@ -1,39 +0,0 @@ -// Copyright 2019 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/overlays/public/overlay_dispatch_callback_storage.h" - -#pragma mark - OverlayDispatchCallbackStorage - -OverlayDispatchCallbackStorage::OverlayDispatchCallbackStorage() = default; - -OverlayDispatchCallbackStorage::~OverlayDispatchCallbackStorage() = default; - -void OverlayDispatchCallbackStorage::DispatchResponse( - OverlayResponse* response) { - for (auto& list_pair : callback_lists_) { - list_pair.second->ExecuteCallbacks(response); - } -} - -#pragma mark - OverlayDispatchCallbackStorage::CallbackList - -OverlayDispatchCallbackStorage::CallbackList::CallbackList() = default; - -OverlayDispatchCallbackStorage::CallbackList::~CallbackList() = default; - -void OverlayDispatchCallbackStorage::CallbackList::AddCallback( - OverlayDispatchCallback callback) { - DCHECK(!callback.is_null()); - callbacks_.emplace_back(std::move(callback)); -} - -void OverlayDispatchCallbackStorage::CallbackList::ExecuteCallbacks( - OverlayResponse* response) { - if (!ShouldExecuteForResponse(response)) - return; - for (auto& callback : callbacks_) { - callback.Run(response); - } -}
diff --git a/ios/chrome/browser/overlays/overlay_dispatch_callback_unittest.cc b/ios/chrome/browser/overlays/overlay_dispatch_callback_unittest.cc new file mode 100644 index 0000000..d160f9a --- /dev/null +++ b/ios/chrome/browser/overlays/overlay_dispatch_callback_unittest.cc
@@ -0,0 +1,58 @@ +// Copyright 2020 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/overlays/public/overlay_dispatch_callback.h" + +#include "base/bind.h" +#include "ios/chrome/browser/overlays/public/overlay_response.h" +#include "ios/chrome/browser/overlays/test/overlay_test_macros.h" +#include "testing/platform_test.h" + +namespace { +// Response info types used in tests. +DEFINE_TEST_OVERLAY_RESPONSE_INFO(FirstInfo); +DEFINE_TEST_OVERLAY_RESPONSE_INFO(SecondInfo); +} // namespace + +// Test fixture for OverlayDispatchCallback. +class OverlayDispatchCallbackTest : public PlatformTest { + public: + // Test function to be used as a dispatch callback. Counts number of times + // function was called and exposes that count via execution_count(). + void TestDispatchCallback(OverlayResponse* response) { ++execution_count_; } + + // Returns the number of times TestCompletionCallback() has been executed. + size_t execution_count() const { return execution_count_; } + + private: + size_t execution_count_ = 0; +}; + +// Tests that the OverlayDispatchCallbacks constructed with a specified +// OverlaySupport is executed when run with a supported response type. +TEST_F(OverlayDispatchCallbackTest, SupportedResponse) { + OverlayDispatchCallback callback( + base::BindRepeating(&OverlayDispatchCallbackTest::TestDispatchCallback, + base::Unretained(this)), + FirstInfo::ResponseSupport()); + std::unique_ptr<OverlayResponse> supported_response = + OverlayResponse::CreateWithInfo<FirstInfo>(); + callback.Run(supported_response.get()); + callback.Run(supported_response.get()); + EXPECT_EQ(2U, execution_count()); +} + +// Tests that the OverlayDispatchCallbacks constructed with a specified +// OverlaySupport no-ops when run with an unsupported response type. +TEST_F(OverlayDispatchCallbackTest, UnsupportedResponse) { + OverlayDispatchCallback callback( + base::BindRepeating(&OverlayDispatchCallbackTest::TestDispatchCallback, + base::Unretained(this)), + FirstInfo::ResponseSupport()); + std::unique_ptr<OverlayResponse> unsupported_response = + OverlayResponse::CreateWithInfo<SecondInfo>(); + callback.Run(unsupported_response.get()); + callback.Run(unsupported_response.get()); + EXPECT_EQ(0U, execution_count()); +}
diff --git a/ios/chrome/browser/overlays/overlay_request_callback_installer.cc b/ios/chrome/browser/overlays/overlay_request_callback_installer.cc new file mode 100644 index 0000000..7818251 --- /dev/null +++ b/ios/chrome/browser/overlays/overlay_request_callback_installer.cc
@@ -0,0 +1,47 @@ +// Copyright 2019 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/overlays/public/overlay_request_callback_installer.h" + +#include "base/bind.h" +#include "ios/chrome/browser/overlays/public/overlay_callback_manager.h" +#include "ios/chrome/browser/overlays/public/overlay_request.h" +#include "ios/chrome/browser/overlays/public/overlay_request_support.h" + +OverlayRequestCallbackInstaller::OverlayRequestCallbackInstaller() = default; + +OverlayRequestCallbackInstaller::~OverlayRequestCallbackInstaller() = default; + +void OverlayRequestCallbackInstaller::InstallCallbacks( + OverlayRequest* request) { + // Early return if |request| is unsupported or if callbacks have already been + // installed. + if (!GetRequestSupport()->IsRequestSupported(request) || + requests_.find(request) != requests_.end()) { + return; + } + requests_.insert(request); + + // Add the completion callback to remove the request from |requests_|. + request->GetCallbackManager()->AddCompletionCallback( + base::BindOnce(&OverlayRequestCallbackInstaller::OverlayCompleted, + weak_factory_.GetWeakPtr(), request)); + + // Allow subclasses to install their own callbacks. + InstallCallbacksInternal(request); +} + +const OverlayRequestSupport* +OverlayRequestCallbackInstaller::GetRequestSupport() const { + return OverlayRequestSupport::All(); +} + +void OverlayRequestCallbackInstaller::InstallCallbacksInternal( + OverlayRequest* request) {} + +void OverlayRequestCallbackInstaller::OverlayCompleted( + OverlayRequest* request, + OverlayResponse* response) { + requests_.erase(request); +}
diff --git a/ios/chrome/browser/overlays/overlay_request_callback_installer_unittest.cc b/ios/chrome/browser/overlays/overlay_request_callback_installer_unittest.cc new file mode 100644 index 0000000..243c2a3 --- /dev/null +++ b/ios/chrome/browser/overlays/overlay_request_callback_installer_unittest.cc
@@ -0,0 +1,119 @@ +// Copyright 2019 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/overlays/public/overlay_request_callback_installer.h" + +#include "ios/chrome/browser/overlays/public/overlay_callback_manager.h" +#include "ios/chrome/browser/overlays/public/overlay_request.h" +#include "ios/chrome/browser/overlays/public/overlay_response.h" +#include "ios/chrome/browser/overlays/test/fake_overlay_request_callback_installer.h" +#include "ios/chrome/browser/overlays/test/overlay_test_macros.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/platform_test.h" + +namespace { +// Request configs used in tests. +DEFINE_TEST_OVERLAY_REQUEST_CONFIG(SupportedConfig); +DEFINE_TEST_OVERLAY_REQUEST_CONFIG(UnsupportedConfig); +DEFINE_TEST_OVERLAY_RESPONSE_INFO(DispatchInfo); +DEFINE_TEST_OVERLAY_RESPONSE_INFO(CompletionInfo); + +// Mock callback receiver. +class MockCallbackReceiver : public FakeOverlayRequestCallbackReceiver { + public: + MockCallbackReceiver() = default; + ~MockCallbackReceiver() = default; + + MOCK_METHOD2(CompletionCallback, + void(OverlayRequest* request, OverlayResponse* response)); + MOCK_METHOD3(DispatchCallback, + void(OverlayRequest* request, + const OverlayResponseSupport* response_support, + OverlayResponse* response)); +}; +} // namespace + +// Test fixture for OverlayRequestCallbackInstaller. +class OverlayRequestCallbackInstallerTest : public PlatformTest { + public: + OverlayRequestCallbackInstallerTest() : installer_(&mock_receiver_) { + installer_.SetRequestSupport(SupportedConfig::RequestSupport()); + installer_.StartInstallingDispatchCallbacksWithSupport( + DispatchInfo::ResponseSupport()); + } + ~OverlayRequestCallbackInstallerTest() override = default; + + // Dispatches an OverlayResponse created with DispatchInfo through |request|'s + // callback manager. The mock callback receiver will be notified to expect + // callback execution if |expect_callback_execution| is true. + void DispatchResponse(OverlayRequest* request, + bool expect_callback_execution) { + std::unique_ptr<OverlayResponse> response = + OverlayResponse::CreateWithInfo<DispatchInfo>(); + if (expect_callback_execution) { + EXPECT_CALL(mock_receiver_, + DispatchCallback(request, DispatchInfo::ResponseSupport(), + response.get())); + } + request->GetCallbackManager()->DispatchResponse(std::move(response)); + } + + protected: + testing::StrictMock<MockCallbackReceiver> mock_receiver_; + FakeOverlayRequestCallbackInstaller installer_; +}; + +// Tests that callbacks are successfully installed for supported requests. +TEST_F(OverlayRequestCallbackInstallerTest, InstallCallbacks) { + std::unique_ptr<OverlayRequest> request = + OverlayRequest::CreateWithConfig<SupportedConfig>(); + installer_.InstallCallbacks(request.get()); + + // Dispatch responses with DispatchInfo, verifying that the mock dispatch + // callback was executed for each. + DispatchResponse(request.get(), /*expect_callback_execution=*/true); + DispatchResponse(request.get(), /*expect_callback_execution=*/true); + + // Destroy the request and verify that the completion callback was executed. + std::unique_ptr<OverlayResponse> completion_response = + OverlayResponse::CreateWithInfo<CompletionInfo>(); + EXPECT_CALL(mock_receiver_, + CompletionCallback(request.get(), completion_response.get())); + request->GetCallbackManager()->SetCompletionResponse( + std::move(completion_response)); + request = nullptr; +} + +// Tests that callbacks are not installed for unsupported requests. +TEST_F(OverlayRequestCallbackInstallerTest, UnsupportedRequest) { + std::unique_ptr<OverlayRequest> request = + OverlayRequest::CreateWithConfig<UnsupportedConfig>(); + installer_.InstallCallbacks(request.get()); + + // Dispatch a response with DispatchInfo, verifying that the mock dispatch + // callback was not executed. + DispatchResponse(request.get(), /*expect_callback_execution=*/false); + + // Destroy the request, verifying that the mock completion was not executed. + request = nullptr; +} + +// Tests that InstallCallbacks() only installs the installer's callbacks once, +// even if called multiple times. +TEST_F(OverlayRequestCallbackInstallerTest, Idempotency) { + std::unique_ptr<OverlayRequest> request = + OverlayRequest::CreateWithConfig<SupportedConfig>(); + + // Attempt to install callbacks twice on the same request. + installer_.InstallCallbacks(request.get()); + installer_.InstallCallbacks(request.get()); + + // Dispatch a single response with DispatchInfo verifying that the callback + // was only executed once. + DispatchResponse(request.get(), /*expect_callback_execution=*/true); + + // Expect the completion callback to be executed upon destruction of + // |request|. + EXPECT_CALL(mock_receiver_, CompletionCallback(request.get(), nullptr)); +}
diff --git a/ios/chrome/browser/overlays/overlay_request_support.cc b/ios/chrome/browser/overlays/overlay_request_support.cc index 7a15e64..e89ce71 100644 --- a/ios/chrome/browser/overlays/overlay_request_support.cc +++ b/ios/chrome/browser/overlays/overlay_request_support.cc
@@ -8,40 +8,51 @@ #include "base/no_destructor.h" namespace { -// OverlayRequestSupport that returns a constant value for IsRequestSupported() -// regardless of the request type. -class ConstantOverlayRequestSupport : public OverlayRequestSupport { +// OverlayRequestSupport that always returns true for IsRequestSupported(). +class UniversalOverlayRequestSupport : public OverlayRequestSupport { public: - ConstantOverlayRequestSupport(bool should_support) - : supports_requests_(should_support) {} - bool IsRequestSupported(OverlayRequest* request) const override { - return supports_requests_; + return true; } - - private: - // Whether requests should be supported. - bool supports_requests_ = false; +}; +// OverlayRequestSupport that always returns false for IsRequestSupported(). +class DisabledOverlayRequestSupport : public OverlayRequestSupport { + public: + bool IsRequestSupported(OverlayRequest* request) const override { + return false; + } }; } // namespace +OverlayRequestSupport::OverlayRequestSupport( + const std::vector<const OverlayRequestSupport*>& supports) + : aggregated_support_(supports) { + DCHECK(aggregated_support_.size()); +} + OverlayRequestSupport::OverlayRequestSupport() = default; OverlayRequestSupport::~OverlayRequestSupport() = default; bool OverlayRequestSupport::IsRequestSupported(OverlayRequest* request) const { - NOTREACHED() << "Subclasses implement."; + DCHECK(aggregated_support_.size()) + << "Default implementation is only for aggregated support. Subclasses " + "using the default constructor must implement IsRequestSupported()."; + for (const OverlayRequestSupport* support : aggregated_support_) { + if (support->IsRequestSupported(request)) + return true; + } return false; } // static const OverlayRequestSupport* OverlayRequestSupport::All() { - static base::NoDestructor<ConstantOverlayRequestSupport> support_all(true); - return support_all.get(); + static base::NoDestructor<UniversalOverlayRequestSupport> support; + return support.get(); } // static const OverlayRequestSupport* OverlayRequestSupport::None() { - static base::NoDestructor<ConstantOverlayRequestSupport> support_none(false); - return support_none.get(); + static base::NoDestructor<DisabledOverlayRequestSupport> support; + return support.get(); }
diff --git a/ios/chrome/browser/overlays/overlay_request_support_unittest.cc b/ios/chrome/browser/overlays/overlay_request_support_unittest.cc index 2908ad04..f4f31c7 100644 --- a/ios/chrome/browser/overlays/overlay_request_support_unittest.cc +++ b/ios/chrome/browser/overlays/overlay_request_support_unittest.cc
@@ -4,23 +4,24 @@ #include "ios/chrome/browser/overlays/public/overlay_request_support.h" -#include "ios/chrome/browser/overlays/test/fake_overlay_user_data.h" #include "ios/chrome/browser/overlays/test/overlay_test_macros.h" #include "testing/platform_test.h" namespace { -// Fake request config type for use in tests. -DEFINE_TEST_OVERLAY_REQUEST_CONFIG(FakeConfig); +// Fake request config types for use in tests. +DEFINE_TEST_OVERLAY_REQUEST_CONFIG(FirstConfig); +DEFINE_TEST_OVERLAY_REQUEST_CONFIG(SecondConfig); +DEFINE_TEST_OVERLAY_REQUEST_CONFIG(ThirdConfig); } // namespace -using SupportsOverlayRequestTest = PlatformTest; +using OverlayRequestSupportTest = PlatformTest; -// Tests that OverlayRequestSupport::All() supports arbitrary config types. -TEST_F(SupportsOverlayRequestTest, SupportAll) { +// Tests that OverlayRequestSupport::All() supports arbitrary requests. +TEST_F(OverlayRequestSupportTest, SupportAll) { std::unique_ptr<OverlayRequest> first_request = - OverlayRequest::CreateWithConfig<FakeOverlayUserData>(); + OverlayRequest::CreateWithConfig<FirstConfig>(); std::unique_ptr<OverlayRequest> second_request = - OverlayRequest::CreateWithConfig<FakeConfig>(); + OverlayRequest::CreateWithConfig<SecondConfig>(); const OverlayRequestSupport* support = OverlayRequestSupport::All(); EXPECT_TRUE(support->IsRequestSupported(first_request.get())); @@ -28,31 +29,51 @@ } // Tests that OverlayRequestSupport::None() does not support config types. -TEST_F(SupportsOverlayRequestTest, SupportNone) { +TEST_F(OverlayRequestSupportTest, SupportNone) { std::unique_ptr<OverlayRequest> first_request = - OverlayRequest::CreateWithConfig<FakeOverlayUserData>(); + OverlayRequest::CreateWithConfig<FirstConfig>(); std::unique_ptr<OverlayRequest> second_request = - OverlayRequest::CreateWithConfig<FakeConfig>(); + OverlayRequest::CreateWithConfig<SecondConfig>(); const OverlayRequestSupport* support = OverlayRequestSupport::None(); EXPECT_FALSE(support->IsRequestSupported(first_request.get())); EXPECT_FALSE(support->IsRequestSupported(second_request.get())); } -// Tests that the SupportsOverlayRequest template returns true when +// Tests that the SupportsOverlayRequest template returns true only when // IsRequestSupported() is called with a request with the config type used to // create the template specialization. -TEST_F(SupportsOverlayRequestTest, SupportsRequestTemplate) { +TEST_F(OverlayRequestSupportTest, SupportsRequestTemplate) { std::unique_ptr<OverlayRequestSupport> support = - std::make_unique<SupportsOverlayRequest<FakeConfig>>(); + std::make_unique<SupportsOverlayRequest<FirstConfig>>(); - // Verify that FakeOverlayUserData requests aren't supported. - std::unique_ptr<OverlayRequest> unsupported_request = - OverlayRequest::CreateWithConfig<FakeOverlayUserData>(); - EXPECT_FALSE(support->IsRequestSupported(unsupported_request.get())); - - // Verify that FakeConfig requests are supported. + // Verify that FirstConfig requests are supported. std::unique_ptr<OverlayRequest> supported_request = - OverlayRequest::CreateWithConfig<FakeConfig>(); + OverlayRequest::CreateWithConfig<FirstConfig>(); EXPECT_TRUE(support->IsRequestSupported(supported_request.get())); + + // Verify that SecondConfig requests are not supported. + std::unique_ptr<OverlayRequest> unsupported_request = + OverlayRequest::CreateWithConfig<SecondConfig>(); + EXPECT_FALSE(support->IsRequestSupported(unsupported_request.get())); +} + +// Tests that the vector constructor aggregates support. +TEST_F(OverlayRequestSupportTest, AggregateSupport) { + // Create an aggregate request support for FirstConfig and SecondConfig, then + // verify that OverlayResponses created with these two configs are supported. + OverlayRequestSupport support( + {FirstConfig::RequestSupport(), SecondConfig::RequestSupport()}); + std::unique_ptr<OverlayRequest> first_request = + OverlayRequest::CreateWithConfig<FirstConfig>(); + EXPECT_TRUE(support.IsRequestSupported(first_request.get())); + std::unique_ptr<OverlayRequest> second_request = + OverlayRequest::CreateWithConfig<SecondConfig>(); + EXPECT_TRUE(support.IsRequestSupported(second_request.get())); + + // Check that OverlayResponses created with a different config are not + // supported. + std::unique_ptr<OverlayRequest> unsupported_request = + OverlayRequest::CreateWithConfig<ThirdConfig>(); + EXPECT_FALSE(support.IsRequestSupported(unsupported_request.get())); }
diff --git a/ios/chrome/browser/overlays/overlay_response_support.cc b/ios/chrome/browser/overlays/overlay_response_support.cc new file mode 100644 index 0000000..1b5b42c --- /dev/null +++ b/ios/chrome/browser/overlays/overlay_response_support.cc
@@ -0,0 +1,59 @@ +// Copyright 2020 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/overlays/public/overlay_response_support.h" + +#include "base/logging.h" +#include "base/no_destructor.h" + +namespace { +// OverlayResponseSupport that always returns true for IsRequestSupported(). +class UniversalOverlayResponseSupport : public OverlayResponseSupport { + public: + bool IsResponseSupported(OverlayResponse* response) const override { + return true; + } +}; +// OverlayResponseSupport that always returns false for IsRequestSupported(). +class DisabledOverlayResponseSupport : public OverlayResponseSupport { + public: + bool IsResponseSupported(OverlayResponse* response) const override { + return false; + } +}; +} // namespace + +OverlayResponseSupport::OverlayResponseSupport( + const std::vector<const OverlayResponseSupport*>& supports) + : aggregated_support_(supports) { + DCHECK(aggregated_support_.size()); +} + +OverlayResponseSupport::OverlayResponseSupport() = default; + +OverlayResponseSupport::~OverlayResponseSupport() = default; + +bool OverlayResponseSupport::IsResponseSupported( + OverlayResponse* response) const { + DCHECK(aggregated_support_.size()) + << "Default implementation is only for aggregated support. Subclasses " + "using the default constructor must implement IsResponseSupported()."; + for (const OverlayResponseSupport* support : aggregated_support_) { + if (support->IsResponseSupported(response)) + return true; + } + return false; +} + +// static +const OverlayResponseSupport* OverlayResponseSupport::All() { + static base::NoDestructor<UniversalOverlayResponseSupport> support; + return support.get(); +} + +// static +const OverlayResponseSupport* OverlayResponseSupport::None() { + static base::NoDestructor<DisabledOverlayResponseSupport> support; + return support.get(); +}
diff --git a/ios/chrome/browser/overlays/overlay_response_support_unittest.cc b/ios/chrome/browser/overlays/overlay_response_support_unittest.cc new file mode 100644 index 0000000..3a589db --- /dev/null +++ b/ios/chrome/browser/overlays/overlay_response_support_unittest.cc
@@ -0,0 +1,80 @@ +// Copyright 2020 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/overlays/public/overlay_response_support.h" + +#include "ios/chrome/browser/overlays/test/overlay_test_macros.h" +#include "testing/platform_test.h" + +namespace { +// Fake response info types for use in tests. +DEFINE_TEST_OVERLAY_RESPONSE_INFO(FirstInfo); +DEFINE_TEST_OVERLAY_RESPONSE_INFO(SecondInfo); +DEFINE_TEST_OVERLAY_RESPONSE_INFO(ThirdInfo); +} // namespace + +using OverlayResponseSupportTest = PlatformTest; + +// Tests that OverlayResponseSupport::All() supports arbitrary responses. +TEST_F(OverlayResponseSupportTest, SupportAll) { + std::unique_ptr<OverlayResponse> first_response = + OverlayResponse::CreateWithInfo<FirstInfo>(); + std::unique_ptr<OverlayResponse> second_response = + OverlayResponse::CreateWithInfo<SecondInfo>(); + + const OverlayResponseSupport* support = OverlayResponseSupport::All(); + EXPECT_TRUE(support->IsResponseSupported(first_response.get())); + EXPECT_TRUE(support->IsResponseSupported(second_response.get())); +} + +// Tests that OverlayResponseSupport::None() does not support arbitrary +// responses. +TEST_F(OverlayResponseSupportTest, SupportNone) { + std::unique_ptr<OverlayResponse> first_response = + OverlayResponse::CreateWithInfo<FirstInfo>(); + std::unique_ptr<OverlayResponse> second_response = + OverlayResponse::CreateWithInfo<SecondInfo>(); + + const OverlayResponseSupport* support = OverlayResponseSupport::None(); + EXPECT_FALSE(support->IsResponseSupported(first_response.get())); + EXPECT_FALSE(support->IsResponseSupported(second_response.get())); +} + +// Tests that the SupportsOverlayResponse template returns true only when +// IsResponseSupported() is called with a response with the config type used to +// create the template specialization. +TEST_F(OverlayResponseSupportTest, SupportsResponseTemplate) { + std::unique_ptr<OverlayResponseSupport> support = + std::make_unique<SupportsOverlayResponse<FirstInfo>>(); + + // Verify that FirstInfo responses are supported. + std::unique_ptr<OverlayResponse> supported_response = + OverlayResponse::CreateWithInfo<FirstInfo>(); + EXPECT_TRUE(support->IsResponseSupported(supported_response.get())); + + // Verify that SecondInfo responses are not supported. + std::unique_ptr<OverlayResponse> unsupported_response = + OverlayResponse::CreateWithInfo<SecondInfo>(); + EXPECT_FALSE(support->IsResponseSupported(unsupported_response.get())); +} + +// Tests that the vector constructor aggregates support. +TEST_F(OverlayResponseSupportTest, AggregateSupport) { + // Create an aggregate support for FirstInfo and SecondInfo, then verify that + // OverlayResponses created with these infos are supported. + OverlayResponseSupport support( + {FirstInfo::ResponseSupport(), SecondInfo::ResponseSupport()}); + std::unique_ptr<OverlayResponse> first_response = + OverlayResponse::CreateWithInfo<FirstInfo>(); + EXPECT_TRUE(support.IsResponseSupported(first_response.get())); + std::unique_ptr<OverlayResponse> second_response = + OverlayResponse::CreateWithInfo<SecondInfo>(); + EXPECT_TRUE(support.IsResponseSupported(second_response.get())); + + // Verify that OveralyResponses created with an unsupported info type are not + // supported. + std::unique_ptr<OverlayResponse> unsupported_response = + OverlayResponse::CreateWithInfo<ThirdInfo>(); + EXPECT_FALSE(support.IsResponseSupported(unsupported_response.get())); +}
diff --git a/ios/chrome/browser/overlays/public/aggregate_overlay_request_support.h b/ios/chrome/browser/overlays/public/aggregate_overlay_request_support.h deleted file mode 100644 index aac3c6ead..0000000 --- a/ios/chrome/browser/overlays/public/aggregate_overlay_request_support.h +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2019 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_OVERLAYS_PUBLIC_AGGREGATE_OVERLAY_REQUEST_SUPPORT_H_ -#define IOS_CHROME_BROWSER_OVERLAYS_PUBLIC_AGGREGATE_OVERLAY_REQUEST_SUPPORT_H_ - -#include <vector> - -#include "ios/chrome/browser/overlays/public/overlay_request_support.h" - -// Helper object that aggregates the request support for a list of -// OverlayRequestSupports. -class AggregateOverlayRequestSupport : public OverlayRequestSupport { - public: - // Constructor for an OverlayRequestSupport that supports requests that are - // supported by at least one OverlayRequestSupport in |supports|. |supports| - // is expected to be non-empty. - explicit AggregateOverlayRequestSupport( - const std::vector<const OverlayRequestSupport*>& supports); - ~AggregateOverlayRequestSupport() override; - - // OverlayRequestSupport: - bool IsRequestSupported(OverlayRequest* request) const override; - - private: - // The OverlayRequestSupport instances whose functionality is being - // aggregated. - const std::vector<const OverlayRequestSupport*> aggregated_supports_; -}; - -#endif // IOS_CHROME_BROWSER_OVERLAYS_PUBLIC_AGGREGATE_OVERLAY_REQUEST_SUPPORT_H_
diff --git a/ios/chrome/browser/overlays/public/overlay_callback_manager.h b/ios/chrome/browser/overlays/public/overlay_callback_manager.h index 1fed74f8..afb8b85 100644 --- a/ios/chrome/browser/overlays/public/overlay_callback_manager.h +++ b/ios/chrome/browser/overlays/public/overlay_callback_manager.h
@@ -7,12 +7,10 @@ #include <memory> -#include "base/callback.h" -#include "ios/chrome/browser/overlays/public/overlay_dispatch_callback_storage.h" +#include "ios/chrome/browser/overlays/public/overlay_dispatch_callback.h" #include "ios/chrome/browser/overlays/public/overlay_user_data.h" class OverlayResponse; - // Completion callback for OverlayRequests. If an overlay requires a completion // block to be executed after its UI is dismissed, OverlayPresenter clients can // provide a callback that uses the OverlayResponse provided to the request. @@ -46,18 +44,10 @@ // requester for ongoing overlay UI. virtual void DispatchResponse(std::unique_ptr<OverlayResponse> response) = 0; - // Adds |callback| to be executed for dispatched responses with InfoType. The - // provided callbacks are not guaranteed to be called, as there is no - // guarantee that an InfoType response will be sent for the overlay. - template <class InfoType> - void AddDispatchCallback(OverlayDispatchCallback callback) { - DCHECK(!callback.is_null()); - GetDispatchCallbackStorage()->AddDispatchCallback<InfoType>(callback); - } - - protected: - // Returns the dispatch callback storage. - virtual OverlayDispatchCallbackStorage* GetDispatchCallbackStorage() = 0; + // Adds |callback| to be executed for dispatched responses. The provided + // callbacks are not guaranteed to be called, as there is no guarantee that a + // supported response will be sent for the overlay. + virtual void AddDispatchCallback(OverlayDispatchCallback callback) = 0; }; #endif // IOS_CHROME_BROWSER_OVERLAYS_PUBLIC_OVERLAY_CALLBACK_MANAGER_H_
diff --git a/ios/chrome/browser/overlays/public/overlay_dispatch_callback.h b/ios/chrome/browser/overlays/public/overlay_dispatch_callback.h new file mode 100644 index 0000000..8db55db --- /dev/null +++ b/ios/chrome/browser/overlays/public/overlay_dispatch_callback.h
@@ -0,0 +1,38 @@ +// Copyright 2020 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_OVERLAYS_PUBLIC_OVERLAY_DISPATCH_CALLBACK_H_ +#define IOS_CHROME_BROWSER_OVERLAYS_PUBLIC_OVERLAY_DISPATCH_CALLBACK_H_ + +#include "base/callback.h" + +class OverlayResponseSupport; +class OverlayResponse; + +// Callback for OverlayResponses dispatched for user interaction events +// occurring in an ongoing overlay. +class OverlayDispatchCallback { + public: + // Constructor for a dispatch callback that executes |callback| with + // OverlayResponses that are supported by |support|. |callback| and |support| + // must be non-null. + OverlayDispatchCallback( + base::RepeatingCallback<void(OverlayResponse* response)> callback, + const OverlayResponseSupport* support); + OverlayDispatchCallback(OverlayDispatchCallback&& other); + ~OverlayDispatchCallback(); + + // Runs |callback_| with |response| iff the response is supported by + // |request_support_|. + void Run(OverlayResponse* response); + + private: + // The callback to be executed. + base::RepeatingCallback<void(OverlayResponse* response)> callback_; + // The OverlayResponseSupport determining which dispatch responses can be + // handled by the callback. + const OverlayResponseSupport* response_support_ = nullptr; +}; + +#endif // IOS_CHROME_BROWSER_OVERLAYS_PUBLIC_OVERLAY_DISPATCH_CALLBACK_H_
diff --git a/ios/chrome/browser/overlays/public/overlay_dispatch_callback_storage.h b/ios/chrome/browser/overlays/public/overlay_dispatch_callback_storage.h deleted file mode 100644 index a706fd6..0000000 --- a/ios/chrome/browser/overlays/public/overlay_dispatch_callback_storage.h +++ /dev/null
@@ -1,90 +0,0 @@ -// Copyright 2019 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_OVERLAYS_PUBLIC_OVERLAY_DISPATCH_CALLBACK_STORAGE_H_ -#define IOS_CHROME_BROWSER_OVERLAYS_PUBLIC_OVERLAY_DISPATCH_CALLBACK_STORAGE_H_ - -#include <map> -#include <vector> - -#include "base/callback.h" -#include "base/logging.h" -#include "ios/chrome/browser/overlays/public/overlay_response.h" - -// Callback for OverlayResponses dispatched for user interaction events -// occurring in an ongoing overlay. -typedef base::RepeatingCallback<void(OverlayResponse* response)> - OverlayDispatchCallback; - -// Storage object used to hold OverlayDispatchCallbacks and execute them for -// dispatched responses. -class OverlayDispatchCallbackStorage { - public: - OverlayDispatchCallbackStorage(); - ~OverlayDispatchCallbackStorage(); - - // Adds |callback| to the storage to be executed whenever DispatchResponse() - // is called with an OverlayResponse created with InfoType. - template <class InfoType> - void AddDispatchCallback(OverlayDispatchCallback callback) { - DCHECK(!callback.is_null()); - GetCallbackList<InfoType>()->AddCallback(std::move(callback)); - } - - // Executes the added callbacks for |response|. - void DispatchResponse(OverlayResponse* response); - - protected: - // Helper object that stores OverlayDispatchCallbacks for OverlayResponses - // created with a specific info type. - class CallbackList { - public: - CallbackList(); - virtual ~CallbackList(); - - // Adds the callback to the list. - void AddCallback(OverlayDispatchCallback callback); - // Executes the callbacks with |response| if it's supported. - void ExecuteCallbacks(OverlayResponse* response); - - protected: - // Returns whether the callbacks in the list have been registered for - // |response|'s info type. - virtual bool ShouldExecuteForResponse(OverlayResponse* response) = 0; - - // The callbacks stored in this list. - std::vector<OverlayDispatchCallback> callbacks_; - }; - - // Template used to create CallbackList instantiations for a specific info - // type. - template <class InfoType> - class CallbackListImpl : public CallbackList { - public: - CallbackListImpl() = default; - ~CallbackListImpl() override = default; - - private: - // CallbackList: - bool ShouldExecuteForResponse(OverlayResponse* response) override { - return !!response->GetInfo<InfoType>(); - } - }; - - // Returns the CallbackList for OverlayRequests created with InfoType, - // creating one if necessary. - template <class InfoType> - CallbackList* GetCallbackList() { - auto& callback_list = callback_lists_[InfoType::UserDataKey()]; - if (!callback_list) - callback_list = std::make_unique<CallbackListImpl<InfoType>>(); - return callback_list.get(); - } - - // Map storing the CallbackList under the user data key for each supported - // OverlayRequest info type. - std::map<const void*, std::unique_ptr<CallbackList>> callback_lists_; -}; - -#endif // IOS_CHROME_BROWSER_OVERLAYS_PUBLIC_OVERLAY_DISPATCH_CALLBACK_STORAGE_H_
diff --git a/ios/chrome/browser/overlays/public/overlay_presenter_observer_bridge.h b/ios/chrome/browser/overlays/public/overlay_presenter_observer_bridge.h index 1d6336c..1be2d51 100644 --- a/ios/chrome/browser/overlays/public/overlay_presenter_observer_bridge.h +++ b/ios/chrome/browser/overlays/public/overlay_presenter_observer_bridge.h
@@ -17,7 +17,7 @@ @protocol OverlayPresenterObserving <NSObject> @optional -// Invoked by OverlayPresenterObserver::GetRequestSupport(). +// Invoked by OverlayPresenterObserver::GetOverlayRequestSupport(). - (const OverlayRequestSupport*)overlayRequestSupportForPresenter: (OverlayPresenter*)presenter;
diff --git a/ios/chrome/browser/overlays/public/overlay_request_callback_installer.h b/ios/chrome/browser/overlays/public/overlay_request_callback_installer.h new file mode 100644 index 0000000..f4991be --- /dev/null +++ b/ios/chrome/browser/overlays/public/overlay_request_callback_installer.h
@@ -0,0 +1,51 @@ +// Copyright 2019 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_OVERLAYS_PUBLIC_OVERLAY_REQUEST_CALLBACK_INSTALLER_H_ +#define IOS_CHROME_BROWSER_OVERLAYS_PUBLIC_OVERLAY_REQUEST_CALLBACK_INSTALLER_H_ + +#include <set> + +#include "base/memory/weak_ptr.h" + +class OverlayRequest; +class OverlayResponse; +class OverlayRequestSupport; + +// Helper object, intended to be subclassed, that installs callbacks for +// OverlayRequests the first time their UI is presented. +class OverlayRequestCallbackInstaller { + public: + OverlayRequestCallbackInstaller(); + virtual ~OverlayRequestCallbackInstaller(); + + // Installs callbacks for |request|. Will only install callbacks once per + // supported request if called more than once. |request| must be non-null. + void InstallCallbacks(OverlayRequest* request); + + protected: + // Returns the request support for this installer. InstallCallbacksInternal() + // will only be called for supported requests. By default, all requests are + // supported. + virtual const OverlayRequestSupport* GetRequestSupport() const; + + // Called from InstallCallbacks() if |request| is supported by + // GetRequestSupport(). Subclasses should override to supply callbacks for a + // specific kind of request. Does nothing by default. + virtual void InstallCallbacksInternal(OverlayRequest* request); + + private: + // Called as a completion callback for |request| to remove the completed + // request from |requests_|. + void OverlayCompleted(OverlayRequest* request, OverlayResponse* response); + + // Set containing the requests for which callbacks have already been + // installed. Requests are removed from the set when their completion + // callbacks are executed. + std::set<OverlayRequest*> requests_; + + base::WeakPtrFactory<OverlayRequestCallbackInstaller> weak_factory_{this}; +}; + +#endif // IOS_CHROME_BROWSER_OVERLAYS_PUBLIC_OVERLAY_REQUEST_CALLBACK_INSTALLER_H_
diff --git a/ios/chrome/browser/overlays/public/overlay_request_config.h b/ios/chrome/browser/overlays/public/overlay_request_config.h index 9bec9f09..0b865a9 100644 --- a/ios/chrome/browser/overlays/public/overlay_request_config.h +++ b/ios/chrome/browser/overlays/public/overlay_request_config.h
@@ -13,7 +13,8 @@ template <class ConfigType> class OverlayRequestConfig : public OverlayUserData<ConfigType> { public: - // Returns an OverlayRequestSupport that only supports this config. + // Returns an OverlayRequestSupport that only supports requests created with + // ConfigType. static const OverlayRequestSupport* RequestSupport() { static base::NoDestructor<SupportsOverlayRequest<ConfigType>> kSupport; return kSupport.get();
diff --git a/ios/chrome/browser/overlays/public/overlay_request_support.h b/ios/chrome/browser/overlays/public/overlay_request_support.h index e4019ca..a515526c 100644 --- a/ios/chrome/browser/overlays/public/overlay_request_support.h +++ b/ios/chrome/browser/overlays/public/overlay_request_support.h
@@ -5,15 +5,26 @@ #ifndef IOS_CHROME_BROWSER_OVERLAYS_PUBLIC_OVERLAY_REQUEST_SUPPORT_H_ #define IOS_CHROME_BROWSER_OVERLAYS_PUBLIC_OVERLAY_REQUEST_SUPPORT_H_ +#include <vector> + #include "ios/chrome/browser/overlays/public/overlay_request.h" -// Helper object that allows objects to specify a subset of OverlayRequest types -// that are supported by the object. +// Helper object that allows objects to specify support for a subset of +// OverlayRequest types. class OverlayRequestSupport { public: + // Creates an OverlayResponseSupport that aggregates the request support from + // the OverlayRequestSupports in |supports|. |supports| must be non-empty. + // Instances created with this constructor will return true from + // IsRequestSupported() if any of the OverlayRequestSupports in |supports| + // returns true from IsRequestSupport() for the same request. + OverlayRequestSupport( + const std::vector<const OverlayRequestSupport*>& supports); virtual ~OverlayRequestSupport(); - // Whether |request| is supported by this instance. + // Whether |request| is supported by this instance. The default + // implementation returns true is any OverlayRequestSupport in + // |aggregated_support_| returns true. virtual bool IsRequestSupported(OverlayRequest* request) const; // Returns an OverlayRequestSupport that supports all requests. @@ -24,9 +35,14 @@ protected: OverlayRequestSupport(); + + // The OverlayRequestSupports to aggregate. Empty for OverlayRequestSupports + // created with the default constructor. + const std::vector<const OverlayRequestSupport*> aggregated_support_; }; -// Template used to create OverlayRequestSupports for a specific ConfigType. +// Template used to create OverlayRequestSupports that only support +// OverlayRequests created with a specific ConfigType. template <class ConfigType> class SupportsOverlayRequest : public OverlayRequestSupport { public:
diff --git a/ios/chrome/browser/overlays/public/overlay_response_info.h b/ios/chrome/browser/overlays/public/overlay_response_info.h new file mode 100644 index 0000000..5965b7d --- /dev/null +++ b/ios/chrome/browser/overlays/public/overlay_response_info.h
@@ -0,0 +1,24 @@ +// Copyright 2020 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_OVERLAYS_PUBLIC_OVERLAY_RESPONSE_INFO_H_ +#define IOS_CHROME_BROWSER_OVERLAYS_PUBLIC_OVERLAY_RESPONSE_INFO_H_ + +#include "base/no_destructor.h" +#include "ios/chrome/browser/overlays/public/overlay_response_support.h" +#include "ios/chrome/browser/overlays/public/overlay_user_data.h" + +// Template for OverlayUserData used to create OverlayResponses. +template <class InfoType> +class OverlayResponseInfo : public OverlayUserData<InfoType> { + public: + // Returns an OverlayResponseSupport that only supports responses created with + // InfoType. + static const OverlayResponseSupport* ResponseSupport() { + static base::NoDestructor<SupportsOverlayResponse<InfoType>> kSupport; + return kSupport.get(); + } +}; + +#endif // IOS_CHROME_BROWSER_OVERLAYS_PUBLIC_OVERLAY_RESPONSE_INFO_H_
diff --git a/ios/chrome/browser/overlays/public/overlay_response_support.h b/ios/chrome/browser/overlays/public/overlay_response_support.h new file mode 100644 index 0000000..19e1111 --- /dev/null +++ b/ios/chrome/browser/overlays/public/overlay_response_support.h
@@ -0,0 +1,53 @@ +// Copyright 2020 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_OVERLAYS_PUBLIC_OVERLAY_RESPONSE_SUPPORT_H_ +#define IOS_CHROME_BROWSER_OVERLAYS_PUBLIC_OVERLAY_RESPONSE_SUPPORT_H_ + +#include <vector> + +#include "ios/chrome/browser/overlays/public/overlay_response.h" + +// Helper object that allows objects to specify support for a subset of +// OverlayResponse types. +class OverlayResponseSupport { + public: + // Creates an OverlayResponseSupport that aggregates the support from + // the OverlayRequestSupports in |supports|. |supports| must be non-empty. + // Instances created with this constructor will return true from + // IsResponseSupported() if any of the OverlayRequestSupports in |supports| + // returns true from IsResponseSupported() for the same response. + OverlayResponseSupport( + const std::vector<const OverlayResponseSupport*>& supports); + virtual ~OverlayResponseSupport(); + + // Whether |response| is supported by this instance. + virtual bool IsResponseSupported(OverlayResponse* response) const; + + // Returns an OverlayResponseSupport that supports all responses. + static const OverlayResponseSupport* All(); + + // Returns an OverlayResponseSupport that does not support any responses. + static const OverlayResponseSupport* None(); + + protected: + OverlayResponseSupport(); + + // The OverlayResponseSupports to aggregate. Empty for + // OverlayResponseSupports created with the default constructor. + const std::vector<const OverlayResponseSupport*> aggregated_support_; +}; + +// Template used to create OverlayResponseSupports that only support +// OverlayResponses created with a specific InfoType. +template <class InfoType> +class SupportsOverlayResponse : public OverlayResponseSupport { + public: + SupportsOverlayResponse() = default; + bool IsResponseSupported(OverlayResponse* response) const override { + return !!response->GetInfo<InfoType>(); + } +}; + +#endif // IOS_CHROME_BROWSER_OVERLAYS_PUBLIC_OVERLAY_RESPONSE_SUPPORT_H_
diff --git a/ios/chrome/browser/overlays/public/web_content_area/app_launcher_alert_overlay.h b/ios/chrome/browser/overlays/public/web_content_area/app_launcher_alert_overlay.h index 9d5d0d4f..ed2a633 100644 --- a/ios/chrome/browser/overlays/public/web_content_area/app_launcher_alert_overlay.h +++ b/ios/chrome/browser/overlays/public/web_content_area/app_launcher_alert_overlay.h
@@ -6,7 +6,7 @@ #define IOS_CHROME_BROWSER_OVERLAYS_PUBLIC_WEB_CONTENT_AREA_APP_LAUNCHER_ALERT_OVERLAY_H_ #include "ios/chrome/browser/overlays/public/overlay_request_config.h" -#include "ios/chrome/browser/overlays/public/overlay_user_data.h" +#include "ios/chrome/browser/overlays/public/overlay_response_info.h" // Configuration object for OverlayRequests for alerts notifying the user that // a navigation will open another app. @@ -27,7 +27,7 @@ // User interaction info for OverlayResponses for app launcher alerts. class AppLauncherAlertOverlayResponseInfo - : public OverlayUserData<AppLauncherAlertOverlayResponseInfo> { + : public OverlayResponseInfo<AppLauncherAlertOverlayResponseInfo> { public: ~AppLauncherAlertOverlayResponseInfo() override;
diff --git a/ios/chrome/browser/overlays/public/web_content_area/http_auth_overlay.h b/ios/chrome/browser/overlays/public/web_content_area/http_auth_overlay.h index 5fa5c02..cfa20205 100644 --- a/ios/chrome/browser/overlays/public/web_content_area/http_auth_overlay.h +++ b/ios/chrome/browser/overlays/public/web_content_area/http_auth_overlay.h
@@ -6,7 +6,7 @@ #define IOS_CHROME_BROWSER_OVERLAYS_PUBLIC_WEB_CONTENT_AREA_HTTP_AUTH_OVERLAY_H_ #include "ios/chrome/browser/overlays/public/overlay_request_config.h" -#include "ios/chrome/browser/overlays/public/overlay_user_data.h" +#include "ios/chrome/browser/overlays/public/overlay_response_info.h" // Configuration object for OverlayRequests for HTTP authentication challenges. class HTTPAuthOverlayRequestConfig @@ -30,7 +30,7 @@ // User interaction info for OverlayResponses for HTTP authentication dialogs. class HTTPAuthOverlayResponseInfo - : public OverlayUserData<HTTPAuthOverlayResponseInfo> { + : public OverlayResponseInfo<HTTPAuthOverlayResponseInfo> { public: ~HTTPAuthOverlayResponseInfo() override;
diff --git a/ios/chrome/browser/overlays/public/web_content_area/java_script_alert_overlay.h b/ios/chrome/browser/overlays/public/web_content_area/java_script_alert_overlay.h index 11bcea4..576c3ba 100644 --- a/ios/chrome/browser/overlays/public/web_content_area/java_script_alert_overlay.h +++ b/ios/chrome/browser/overlays/public/web_content_area/java_script_alert_overlay.h
@@ -6,7 +6,6 @@ #define IOS_CHROME_BROWSER_OVERLAYS_PUBLIC_WEB_CONTENT_AREA_JAVA_SCRIPT_ALERT_OVERLAY_H_ #include "ios/chrome/browser/overlays/public/overlay_request_config.h" -#include "ios/chrome/browser/overlays/public/overlay_user_data.h" #include "ios/chrome/browser/overlays/public/web_content_area/java_script_dialog_source.h" // Configuration object for OverlayRequests for JavaScript alert() calls.
diff --git a/ios/chrome/browser/overlays/public/web_content_area/java_script_confirmation_overlay.h b/ios/chrome/browser/overlays/public/web_content_area/java_script_confirmation_overlay.h index 98f2aec..b143f78a9 100644 --- a/ios/chrome/browser/overlays/public/web_content_area/java_script_confirmation_overlay.h +++ b/ios/chrome/browser/overlays/public/web_content_area/java_script_confirmation_overlay.h
@@ -6,7 +6,7 @@ #define IOS_CHROME_BROWSER_OVERLAYS_PUBLIC_WEB_CONTENT_AREA_JAVA_SCRIPT_CONFIRMATION_OVERLAY_H_ #include "ios/chrome/browser/overlays/public/overlay_request_config.h" -#include "ios/chrome/browser/overlays/public/overlay_user_data.h" +#include "ios/chrome/browser/overlays/public/overlay_response_info.h" #include "ios/chrome/browser/overlays/public/web_content_area/java_script_dialog_source.h" // Configuration object for OverlayRequests for JavaScript confirm() calls. @@ -32,7 +32,7 @@ // User interaction info for OverlayResponses for JavaScript confirm() calls. class JavaScriptConfirmationOverlayResponseInfo - : public OverlayUserData<JavaScriptConfirmationOverlayResponseInfo> { + : public OverlayResponseInfo<JavaScriptConfirmationOverlayResponseInfo> { public: ~JavaScriptConfirmationOverlayResponseInfo() override;
diff --git a/ios/chrome/browser/overlays/public/web_content_area/java_script_prompt_overlay.h b/ios/chrome/browser/overlays/public/web_content_area/java_script_prompt_overlay.h index 8e96559..022f9a61 100644 --- a/ios/chrome/browser/overlays/public/web_content_area/java_script_prompt_overlay.h +++ b/ios/chrome/browser/overlays/public/web_content_area/java_script_prompt_overlay.h
@@ -6,7 +6,7 @@ #define IOS_CHROME_BROWSER_OVERLAYS_PUBLIC_WEB_CONTENT_AREA_JAVA_SCRIPT_PROMPT_OVERLAY_H_ #include "ios/chrome/browser/overlays/public/overlay_request_config.h" -#include "ios/chrome/browser/overlays/public/overlay_user_data.h" +#include "ios/chrome/browser/overlays/public/overlay_response_info.h" #include "ios/chrome/browser/overlays/public/web_content_area/java_script_dialog_source.h" // Configuration object for OverlayRequests for JavaScript prompt() calls. @@ -37,7 +37,7 @@ // User interaction info for OverlayResponses for JavaScript prompt() calls. class JavaScriptPromptOverlayResponseInfo - : public OverlayUserData<JavaScriptPromptOverlayResponseInfo> { + : public OverlayResponseInfo<JavaScriptPromptOverlayResponseInfo> { public: ~JavaScriptPromptOverlayResponseInfo() override;
diff --git a/ios/chrome/browser/overlays/test/BUILD.gn b/ios/chrome/browser/overlays/test/BUILD.gn index 00d4182..d1c349c3 100644 --- a/ios/chrome/browser/overlays/test/BUILD.gn +++ b/ios/chrome/browser/overlays/test/BUILD.gn
@@ -7,6 +7,8 @@ sources = [ "fake_overlay_presentation_context.cc", "fake_overlay_presentation_context.h", + "fake_overlay_request_callback_installer.cc", + "fake_overlay_request_callback_installer.h", "fake_overlay_user_data.cc", "fake_overlay_user_data.h", "overlay_test_macros.h",
diff --git a/ios/chrome/browser/overlays/test/fake_overlay_request_callback_installer.cc b/ios/chrome/browser/overlays/test/fake_overlay_request_callback_installer.cc new file mode 100644 index 0000000..743f55d --- /dev/null +++ b/ios/chrome/browser/overlays/test/fake_overlay_request_callback_installer.cc
@@ -0,0 +1,59 @@ +// Copyright 2020 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/overlays/test/fake_overlay_request_callback_installer.h" + +#include "base/bind.h" +#include "base/callback.h" +#include "base/logging.h" +#include "ios/chrome/browser/overlays/public/overlay_callback_manager.h" +#include "ios/chrome/browser/overlays/public/overlay_dispatch_callback.h" +#include "ios/chrome/browser/overlays/public/overlay_request_support.h" +#include "ios/chrome/browser/overlays/public/overlay_response_support.h" + +FakeOverlayRequestCallbackInstaller::FakeOverlayRequestCallbackInstaller( + FakeOverlayRequestCallbackReceiver* receiver) + : receiver_(receiver), request_support_(OverlayRequestSupport::All()) { + DCHECK(receiver_); +} + +FakeOverlayRequestCallbackInstaller::~FakeOverlayRequestCallbackInstaller() = + default; + +#pragma mark - Public + +void FakeOverlayRequestCallbackInstaller::SetRequestSupport( + const OverlayRequestSupport* request_support) { + DCHECK(request_support); + request_support_ = request_support; +} + +void FakeOverlayRequestCallbackInstaller:: + StartInstallingDispatchCallbacksWithSupport( + const OverlayResponseSupport* response_support) { + DCHECK(response_support); + dispatch_response_supports_.insert(response_support); +} + +#pragma mark - OverlayRequestCallbackInstaller + +const OverlayRequestSupport* +FakeOverlayRequestCallbackInstaller::GetRequestSupport() const { + return request_support_; +} + +void FakeOverlayRequestCallbackInstaller::InstallCallbacksInternal( + OverlayRequest* request) { + OverlayCallbackManager* manager = request->GetCallbackManager(); + manager->AddCompletionCallback( + base::BindOnce(&FakeOverlayRequestCallbackReceiver::CompletionCallback, + base::Unretained(receiver_), request)); + for (const OverlayResponseSupport* support : dispatch_response_supports_) { + manager->AddDispatchCallback(OverlayDispatchCallback( + base::BindRepeating( + &FakeOverlayRequestCallbackReceiver::DispatchCallback, + base::Unretained(receiver_), request, support), + support)); + } +}
diff --git a/ios/chrome/browser/overlays/test/fake_overlay_request_callback_installer.h b/ios/chrome/browser/overlays/test/fake_overlay_request_callback_installer.h new file mode 100644 index 0000000..2a646ec --- /dev/null +++ b/ios/chrome/browser/overlays/test/fake_overlay_request_callback_installer.h
@@ -0,0 +1,62 @@ +// Copyright 2019 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_OVERLAYS_TEST_FAKE_OVERLAY_REQUEST_CALLBACK_INSTALLER_H_ +#define IOS_CHROME_BROWSER_OVERLAYS_TEST_FAKE_OVERLAY_REQUEST_CALLBACK_INSTALLER_H_ + +#include <set> + +#include "ios/chrome/browser/overlays/public/overlay_request_callback_installer.h" + +class OverlayResponseSupport; + +// Interface for a test object whose interface is called by callbacks added +// by FakeOverlayRequestCallbackInstaller. +class FakeOverlayRequestCallbackReceiver { + public: + // Function used as the completion callback for |request|. |response| is + // |request|'s completion response. + virtual void CompletionCallback(OverlayRequest* request, + OverlayResponse* response) = 0; + // Function used as the callback when |response| is dispatched through + // |request|. Only executed if |response| is supported by |response_support|. + virtual void DispatchCallback(OverlayRequest* request, + const OverlayResponseSupport* response_support, + OverlayResponse* response) = 0; +}; + +// OverlayRequestCallbackInstaller subclass used for testing. Sets up callbacks +// that execute on a mocked receiver that is exposed for testing. +class FakeOverlayRequestCallbackInstaller + : public OverlayRequestCallbackInstaller { + public: + // Constructor for a fake callback installer that creates callbacks that are + // forwarded to |receiver|. |receiver| must be non-null, and must outlive any + // requests passed to InstallCallback(). + explicit FakeOverlayRequestCallbackInstaller( + FakeOverlayRequestCallbackReceiver* receiver); + ~FakeOverlayRequestCallbackInstaller() override; + + // Sets the request support for the callback installer. |request_support| + // must not be null. All requests are supported by default. + void SetRequestSupport(const OverlayRequestSupport* request_support); + + // Begins installing dispatch callbacks for OverlayRequests that are executed + // for dispatched responses supported by |response_support|. Installed + // dispatch callbacks will execute MockCallbackReveiver::DispatchCallback() + // with |response_support|. + void StartInstallingDispatchCallbacksWithSupport( + const OverlayResponseSupport* response_support); + + private: + // OverlayRequestCallbackInstaller: + const OverlayRequestSupport* GetRequestSupport() const override; + void InstallCallbacksInternal(OverlayRequest* request) override; + + FakeOverlayRequestCallbackReceiver* receiver_ = nullptr; + const OverlayRequestSupport* request_support_ = nullptr; + std::set<const OverlayResponseSupport*> dispatch_response_supports_; +}; + +#endif // IOS_CHROME_BROWSER_OVERLAYS_TEST_FAKE_OVERLAY_REQUEST_CALLBACK_INSTALLER_H_
diff --git a/ios/chrome/browser/overlays/test/overlay_test_macros.h b/ios/chrome/browser/overlays/test/overlay_test_macros.h index 121c757..c5d8a0d 100644 --- a/ios/chrome/browser/overlays/test/overlay_test_macros.h +++ b/ios/chrome/browser/overlays/test/overlay_test_macros.h
@@ -6,6 +6,7 @@ #define IOS_CHROME_BROWSER_OVERLAYS_TEST_OVERLAY_TEST_MACROS_H_ #include "ios/chrome/browser/overlays/public/overlay_request_config.h" +#include "ios/chrome/browser/overlays/public/overlay_response_info.h" // Macro used to define an OverlayRequestConfig that holds no data. Can be used // in tests for functionality specific to config types. @@ -18,11 +19,11 @@ // Macro used to define a response info that holds no data. Can be used // in tests for functionality specific to info types. -#define DEFINE_TEST_OVERLAY_RESPONSE_INFO(InfoType) \ - class InfoType : public OverlayUserData<InfoType> { \ - private: \ - OVERLAY_USER_DATA_SETUP(InfoType); \ - }; \ +#define DEFINE_TEST_OVERLAY_RESPONSE_INFO(InfoType) \ + class InfoType : public OverlayResponseInfo<InfoType> { \ + private: \ + OVERLAY_USER_DATA_SETUP(InfoType); \ + }; \ OVERLAY_USER_DATA_SETUP_IMPL(InfoType) #endif // IOS_CHROME_BROWSER_OVERLAYS_TEST_OVERLAY_TEST_MACROS_H_
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/card_view_controller_egtest.mm b/ios/chrome/browser/ui/autofill/manual_fill/card_view_controller_egtest.mm index 6df2663d..9fdfda0e 100644 --- a/ios/chrome/browser/ui/autofill/manual_fill/card_view_controller_egtest.mm +++ b/ios/chrome/browser/ui/autofill/manual_fill/card_view_controller_egtest.mm
@@ -261,6 +261,11 @@ // Tests that the "Add Credit Cards..." action works. - (void)testAddCreditCardsActionOpensAddCreditCardSettings { + if (![ChromeEarlGrey isSettingsAddPaymentMethodEnabled]) { + EARL_GREY_TEST_SKIPPED( + @"This test has no meaning when AddPaymentMethod is disabled"); + } + [AutofillAppInterface saveLocalCreditCard]; // Bring up the keyboard. @@ -287,6 +292,11 @@ // Tests that the "Add Credit Cards..." action works on OTR. - (void)testOTRAddCreditCardsActionOpensAddCreditCardSettings { + if (![ChromeEarlGrey isSettingsAddPaymentMethodEnabled]) { + EARL_GREY_TEST_SKIPPED( + @"This test has no meaning when AddPaymentMethod is disabled"); + } + [AutofillAppInterface saveLocalCreditCard]; // Open a tab in incognito. @@ -320,6 +330,11 @@ // Tests that the manual fallback view icon is not highlighted after presenting // the add credit card view. - (void)testCreditCardsButtonStateAfterPresentingAddCreditCard { + if (![ChromeEarlGrey isSettingsAddPaymentMethodEnabled]) { + EARL_GREY_TEST_SKIPPED( + @"This test has no meaning when AddPaymentMethod is disabled"); + } + [AutofillAppInterface saveLocalCreditCard]; // Bring up the keyboard.
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_utils.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_utils.mm index 9bd3ae44..7edddd7 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_utils.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_utils.mm
@@ -122,7 +122,6 @@ [searchHintLabel setTextAlignment:NSTextAlignmentRight]; } searchHintLabel.textColor = [UIColor colorNamed:kTextfieldPlaceholderColor]; - searchHintLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody]; searchHintLabel.adjustsFontForContentSizeCategory = YES; searchHintLabel.textAlignment = NSTextAlignmentCenter; }
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view.mm index 4fbfc1bf..232b87a 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view.mm
@@ -19,6 +19,7 @@ #import "ios/chrome/browser/ui/toolbar/buttons/toolbar_configuration.h" #import "ios/chrome/browser/ui/toolbar/public/toolbar_constants.h" #import "ios/chrome/browser/ui/toolbar/public/toolbar_utils.h" +#import "ios/chrome/browser/ui/util/dynamic_type_util.h" #import "ios/chrome/browser/ui/util/named_guide.h" #import "ios/chrome/browser/ui/util/named_guide_util.h" #import "ios/chrome/browser/ui/util/uikit_ui_util.h" @@ -178,6 +179,7 @@ self.searchHintLabel = [[UILabel alloc] init]; content_suggestions::configureSearchHintLabel(self.searchHintLabel, searchField); + self.searchHintLabel.font = [self hintLabelFont]; self.hintLabelLeadingConstraint = [self.searchHintLabel.leadingAnchor constraintGreaterThanOrEqualToAnchor:[searchField leadingAnchor] constant:ntp_header::kHintLabelSidePadding]; @@ -409,6 +411,10 @@ previousTraitCollection.horizontalSizeClass)) { self.identityDiscTopConstraint.constant = IdentityDiscToolbarOffset(self); } + if (previousTraitCollection.preferredContentSizeCategory != + self.traitCollection.preferredContentSizeCategory) { + self.searchHintLabel.font = [self hintLabelFont]; + } } #pragma mark - Property accessors @@ -435,6 +441,12 @@ #pragma mark - Private +// Returns the font size for the hint label. +- (UIFont*)hintLabelFont { + return LocationBarSteadyViewFont( + self.traitCollection.preferredContentSizeCategory); +} + // Scale the the hint label down to at most content_suggestions::kHintTextScale. - (void)scaleHintLabelForPercent:(CGFloat)percent { CGFloat scaleValue =
diff --git a/ios/chrome/browser/ui/location_bar/location_bar_steady_view.mm b/ios/chrome/browser/ui/location_bar/location_bar_steady_view.mm index 0d8009b..1324db5 100644 --- a/ios/chrome/browser/ui/location_bar/location_bar_steady_view.mm +++ b/ios/chrome/browser/ui/location_bar/location_bar_steady_view.mm
@@ -457,9 +457,8 @@ // Returns the font size for the location label. - (UIFont*)locationLabelFont { - return PreferredFontForTextStyleWithMaxCategory( - UIFontTextStyleBody, self.traitCollection.preferredContentSizeCategory, - UIContentSizeCategoryAccessibilityExtraLarge); + return LocationBarSteadyViewFont( + self.traitCollection.preferredContentSizeCategory); } @end
diff --git a/ios/chrome/browser/ui/settings/autofill/autofill_credit_card_settings_egtest.mm b/ios/chrome/browser/ui/settings/autofill/autofill_credit_card_settings_egtest.mm index 3f34981..78fda48 100644 --- a/ios/chrome/browser/ui/settings/autofill/autofill_credit_card_settings_egtest.mm +++ b/ios/chrome/browser/ui/settings/autofill/autofill_credit_card_settings_egtest.mm
@@ -268,6 +268,7 @@ EARL_GREY_TEST_SKIPPED( @"This test makes sense only when there is no Add Payment button."); } + NSString* lastDigits = [AutofillAppInterface saveLocalCreditCard]; [self openCreditCardListInEditMode]; @@ -326,6 +327,11 @@ ensureAppLaunchedWithFeaturesEnabled:{kSettingsAddPaymentMethod} disabled:{} relaunchPolicy:NoForceRelaunchAndResetState]; + if (![ChromeEarlGrey isSettingsAddPaymentMethodEnabled]) { + EARL_GREY_TEST_SKIPPED( + @"This test has no meaning when AddPaymentMethod is disabled"); + } + NSString* lastDigits = [AutofillAppInterface saveLocalCreditCard]; [self openCreditCardListInEditMode]; @@ -350,6 +356,10 @@ ensureAppLaunchedWithFeaturesEnabled:{kSettingsAddPaymentMethod} disabled:{} relaunchPolicy:NoForceRelaunchAndResetState]; + if (![ChromeEarlGrey isSettingsAddPaymentMethodEnabled]) { + EARL_GREY_TEST_SKIPPED( + @"This test has no meaning when AddPaymentMethod is disabled"); + } [AutofillAppInterface saveLocalCreditCard]; [self openCreditCardListInEditMode]; @@ -371,7 +381,10 @@ ensureAppLaunchedWithFeaturesEnabled:{kSettingsAddPaymentMethod} disabled:{} relaunchPolicy:NoForceRelaunchAndResetState]; - + if (![ChromeEarlGrey isSettingsAddPaymentMethodEnabled]) { + EARL_GREY_TEST_SKIPPED( + @"This test has no meaning when AddPaymentMethod is disabled"); + } NSString* lastDigits = [AutofillAppInterface saveLocalCreditCard]; [[EarlGrey selectElementWithMatcher:chrome_test_util:: SettingsBottomToolbarDeleteButton()]
diff --git a/ios/chrome/browser/ui/util/dynamic_type_util.h b/ios/chrome/browser/ui/util/dynamic_type_util.h index 333bf41..3ebc581b1 100644 --- a/ios/chrome/browser/ui/util/dynamic_type_util.h +++ b/ios/chrome/browser/ui/util/dynamic_type_util.h
@@ -29,4 +29,10 @@ UIContentSizeCategory currentCategory, UIContentSizeCategory maxCategory); +// ******************** +// Specific cases utils +// ******************** + +UIFont* LocationBarSteadyViewFont(UIContentSizeCategory currentCategory); + #endif // IOS_CHROME_BROWSER_UI_UTIL_DYNAMIC_TYPE_UTIL_H_
diff --git a/ios/chrome/browser/ui/util/dynamic_type_util.mm b/ios/chrome/browser/ui/util/dynamic_type_util.mm index 0cda4e79..f3a3ebc6 100644 --- a/ios/chrome/browser/ui/util/dynamic_type_util.mm +++ b/ios/chrome/browser/ui/util/dynamic_type_util.mm
@@ -71,3 +71,9 @@ [UITraitCollection traitCollectionWithPreferredContentSizeCategory:category]]; } + +UIFont* LocationBarSteadyViewFont(UIContentSizeCategory currentCategory) { + return PreferredFontForTextStyleWithMaxCategory( + UIFontTextStyleBody, currentCategory, + UIContentSizeCategoryAccessibilityExtraLarge); +}
diff --git a/ios/third_party/material_components_ios/BUILD.gn b/ios/third_party/material_components_ios/BUILD.gn index 73e04a3..a26131c5 100644 --- a/ios/third_party/material_components_ios/BUILD.gn +++ b/ios/third_party/material_components_ios/BUILD.gn
@@ -83,8 +83,6 @@ "src/components/BottomSheet/src/private/MDCDraggableView.h", "src/components/BottomSheet/src/private/MDCSheetBehavior.h", "src/components/BottomSheet/src/private/MDCSheetContainerView.h", - "src/components/ButtonBar/src/ColorThemer/MDCButtonBarColorThemer.h", - "src/components/ButtonBar/src/ColorThemer/MaterialButtonBar+ColorThemer.h", "src/components/ButtonBar/src/MDCButtonBar.h", "src/components/ButtonBar/src/MDCButtonBarButton.h", "src/components/ButtonBar/src/MaterialButtonBar.h", @@ -189,8 +187,6 @@ "src/components/FeatureHighlight/src/MaterialFeatureHighlight.h", "src/components/FeatureHighlight/src/MaterialFeatureHighlightStrings.h", "src/components/FeatureHighlight/src/MaterialFeatureHighlightStrings_table.h", - "src/components/FeatureHighlight/src/TypographyThemer/MDCFeatureHighlightTypographyThemer.h", - "src/components/FeatureHighlight/src/TypographyThemer/MaterialFeatureHighlight+TypographyThemer.h", "src/components/FeatureHighlight/src/private/MDCFeatureHighlightAnimationController.h", "src/components/FeatureHighlight/src/private/MDCFeatureHighlightDismissGestureRecognizer.h", "src/components/FeatureHighlight/src/private/MDCFeatureHighlightLayer.h", @@ -221,16 +217,12 @@ "src/components/Ink/src/private/MDCLegacyInkLayer.h", "src/components/LibraryInfo/src/MDCLibraryInfo.h", "src/components/LibraryInfo/src/MaterialLibraryInfo.h", - "src/components/List/src/ColorThemer/MDCListColorThemer.h", - "src/components/List/src/ColorThemer/MaterialList+ColorThemer.h", "src/components/List/src/MDCBaseCell.h", "src/components/List/src/MDCSelfSizingStereoCell.h", "src/components/List/src/MaterialList.h", "src/components/List/src/Theming/MDCBaseCell+MaterialTheming.h", "src/components/List/src/Theming/MDCSelfSizingStereoCell+MaterialTheming.h", "src/components/List/src/Theming/MaterialList+Theming.h", - "src/components/List/src/TypographyThemer/MDCListTypographyThemer.h", - "src/components/List/src/TypographyThemer/MaterialList+TypographyThemer.h", "src/components/List/src/private/MDCSelfSizingStereoCellLayout.h", "src/components/NavigationBar/src/ColorThemer/MDCNavigationBarColorThemer.h", "src/components/NavigationBar/src/ColorThemer/MaterialNavigationBar+ColorThemer.h", @@ -313,8 +305,6 @@ "src/components/Snackbar/src/private/MDCSnackbarOverlayView.h", "src/components/Snackbar/src/private/MaterialSnackbarStrings.h", "src/components/Snackbar/src/private/MaterialSnackbarStrings_table.h", - "src/components/Tabs/src/ColorThemer/MDCTabBarColorThemer.h", - "src/components/Tabs/src/ColorThemer/MaterialTabs+ColorThemer.h", "src/components/Tabs/src/MDCTabBar.h", "src/components/Tabs/src/MDCTabBarAlignment.h", "src/components/Tabs/src/MDCTabBarDisplayDelegate.h", @@ -381,7 +371,6 @@ "src/components/TextControls/src/private/MDCTextControlVerticalPositioningReferenceOutlined.h", "src/components/TextControls/src/private/UIBezierPath+MDCTextControlStyle.h", "src/components/TextFields/src/ColorThemer/MDCFilledTextFieldColorThemer.h", - "src/components/TextFields/src/ColorThemer/MDCOutlinedTextFieldColorThemer.h", "src/components/TextFields/src/ColorThemer/MaterialTextFields+ColorThemer.h", "src/components/TextFields/src/MDCIntrinsicHeightTextView.h", "src/components/TextFields/src/MDCMultilineTextField.h", @@ -823,9 +812,6 @@ "src/components/BottomSheet/src/private/MDCSheetBehavior.m", "src/components/BottomSheet/src/private/MDCSheetContainerView.h", "src/components/BottomSheet/src/private/MDCSheetContainerView.m", - "src/components/ButtonBar/src/ColorThemer/MDCButtonBarColorThemer.h", - "src/components/ButtonBar/src/ColorThemer/MDCButtonBarColorThemer.m", - "src/components/ButtonBar/src/ColorThemer/MaterialButtonBar+ColorThemer.h", "src/components/ButtonBar/src/MDCButtonBar.h", "src/components/ButtonBar/src/MDCButtonBar.m", "src/components/ButtonBar/src/MDCButtonBarButton.h", @@ -993,9 +979,6 @@ "src/components/FeatureHighlight/src/MaterialFeatureHighlight.h", "src/components/FeatureHighlight/src/MaterialFeatureHighlightStrings.h", "src/components/FeatureHighlight/src/MaterialFeatureHighlightStrings_table.h", - "src/components/FeatureHighlight/src/TypographyThemer/MDCFeatureHighlightTypographyThemer.h", - "src/components/FeatureHighlight/src/TypographyThemer/MDCFeatureHighlightTypographyThemer.m", - "src/components/FeatureHighlight/src/TypographyThemer/MaterialFeatureHighlight+TypographyThemer.h", "src/components/FeatureHighlight/src/private/MDCFeatureHighlightAnimationController.h", "src/components/FeatureHighlight/src/private/MDCFeatureHighlightAnimationController.m", "src/components/FeatureHighlight/src/private/MDCFeatureHighlightDismissGestureRecognizer.h", @@ -1045,9 +1028,6 @@ "src/components/LibraryInfo/src/MDCLibraryInfo.h", "src/components/LibraryInfo/src/MDCLibraryInfo.m", "src/components/LibraryInfo/src/MaterialLibraryInfo.h", - "src/components/List/src/ColorThemer/MDCListColorThemer.h", - "src/components/List/src/ColorThemer/MDCListColorThemer.m", - "src/components/List/src/ColorThemer/MaterialList+ColorThemer.h", "src/components/List/src/MDCBaseCell.h", "src/components/List/src/MDCBaseCell.m", "src/components/List/src/MDCSelfSizingStereoCell.h", @@ -1058,9 +1038,6 @@ "src/components/List/src/Theming/MDCSelfSizingStereoCell+MaterialTheming.h", "src/components/List/src/Theming/MDCSelfSizingStereoCell+MaterialTheming.m", "src/components/List/src/Theming/MaterialList+Theming.h", - "src/components/List/src/TypographyThemer/MDCListTypographyThemer.h", - "src/components/List/src/TypographyThemer/MDCListTypographyThemer.m", - "src/components/List/src/TypographyThemer/MaterialList+TypographyThemer.h", "src/components/List/src/private/MDCSelfSizingStereoCellLayout.h", "src/components/List/src/private/MDCSelfSizingStereoCellLayout.m", "src/components/NavigationBar/src/ColorThemer/MDCNavigationBarColorThemer.h", @@ -1191,9 +1168,6 @@ "src/components/Snackbar/src/private/MDCSnackbarOverlayView.m", "src/components/Snackbar/src/private/MaterialSnackbarStrings.h", "src/components/Snackbar/src/private/MaterialSnackbarStrings_table.h", - "src/components/Tabs/src/ColorThemer/MDCTabBarColorThemer.h", - "src/components/Tabs/src/ColorThemer/MDCTabBarColorThemer.m", - "src/components/Tabs/src/ColorThemer/MaterialTabs+ColorThemer.h", "src/components/Tabs/src/MDCTabBar.h", "src/components/Tabs/src/MDCTabBar.m", "src/components/Tabs/src/MDCTabBarAlignment.h", @@ -1297,8 +1271,6 @@ "src/components/TextControls/src/private/UIBezierPath+MDCTextControlStyle.m", "src/components/TextFields/src/ColorThemer/MDCFilledTextFieldColorThemer.h", "src/components/TextFields/src/ColorThemer/MDCFilledTextFieldColorThemer.m", - "src/components/TextFields/src/ColorThemer/MDCOutlinedTextFieldColorThemer.h", - "src/components/TextFields/src/ColorThemer/MDCOutlinedTextFieldColorThemer.m", "src/components/TextFields/src/ColorThemer/MaterialTextFields+ColorThemer.h", "src/components/TextFields/src/MDCIntrinsicHeightTextView.h", "src/components/TextFields/src/MDCIntrinsicHeightTextView.m",
diff --git a/ios/web/common/BUILD.gn b/ios/web/common/BUILD.gn index 633fee2a..7ecbf12 100644 --- a/ios/web/common/BUILD.gn +++ b/ios/web/common/BUILD.gn
@@ -23,6 +23,7 @@ "//base", "//ios/web/public/navigation", "//net", + "//services/network/public/cpp", "//url", ]
diff --git a/ios/web/common/origin_util.mm b/ios/web/common/origin_util.mm index 52a0c46..57d3c33ee 100644 --- a/ios/web/common/origin_util.mm +++ b/ios/web/common/origin_util.mm
@@ -6,6 +6,7 @@ #include "base/stl_util.h" #include "net/base/url_util.h" +#include "services/network/public/cpp/is_potentially_trustworthy.h" #include "url/gurl.h" #include "url/url_util.h" @@ -16,25 +17,7 @@ namespace web { bool IsOriginSecure(const GURL& url) { - if (url.SchemeIsCryptographic() || url.SchemeIsFile()) - return true; - - // TODO(crbug.com/939077): Also consider inner origins of blob: URLs - // (ideally, by deleting this function altogether and instead reusing - // //services/network/public/cpp/is_potentially_trustworthy.h (possibly after - // moving it to a location that can be consumed by //ios). - if (url.SchemeIsFileSystem() && url.inner_url() && - IsOriginSecure(*url.inner_url())) { - return true; - } - - if (base::Contains(url::GetSecureSchemes(), url.scheme())) - return true; - - if (net::IsLocalhost(url)) - return true; - - return false; + return network::IsUrlPotentiallyTrustworthy(url); } } // namespace web
diff --git a/ios/web/js_messaging/BUILD.gn b/ios/web/js_messaging/BUILD.gn index 7038bba..011d8244 100644 --- a/ios/web/js_messaging/BUILD.gn +++ b/ios/web/js_messaging/BUILD.gn
@@ -9,6 +9,7 @@ deps = [ "//base", "//crypto", + "//ios/web/common:features", "//ios/web/navigation:wk_navigation_util", "//ios/web/public", "//ios/web/public/deprecated",
diff --git a/ios/web/js_messaging/crw_wk_script_message_router.mm b/ios/web/js_messaging/crw_wk_script_message_router.mm index 99dc4a5..9ab9296 100644 --- a/ios/web/js_messaging/crw_wk_script_message_router.mm +++ b/ios/web/js_messaging/crw_wk_script_message_router.mm
@@ -5,6 +5,7 @@ #import "ios/web/js_messaging/crw_wk_script_message_router.h" #include "base/logging.h" +#include "ios/web/common/features.h" #include "ios/web/navigation/wk_navigation_util.h" #import "net/base/mac/url_conversions.h" @@ -88,7 +89,8 @@ didReceiveScriptMessage:(WKScriptMessage*)message { // Ignore frame registration messages from internal placeholder pages. GURL url = net::GURLWithNSURL(message.frameInfo.request.URL); - if (web::wk_navigation_util::IsPlaceholderUrl(url)) { + if (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) && + web::wk_navigation_util::IsPlaceholderUrl(url)) { return; }
diff --git a/ios/web/navigation/crw_web_view_navigation_observer.mm b/ios/web/navigation/crw_web_view_navigation_observer.mm index c23c693..c8e7d7e 100644 --- a/ios/web/navigation/crw_web_view_navigation_observer.mm +++ b/ios/web/navigation/crw_web_view_navigation_observer.mm
@@ -29,6 +29,7 @@ using web::NavigationManagerImpl; using web::wk_navigation_util::IsRestoreSessionUrl; +// TODO(crbug.com/1038303): This legacy won't be needed anymore. using web::wk_navigation_util::IsPlaceholderUrl; @interface CRWWebViewNavigationObserver () @@ -154,7 +155,8 @@ // from restore_session.html to the restored URL. bool previousURLHasAboutScheme = self.documentURL.SchemeIs(url::kAboutScheme) || - IsPlaceholderUrl(self.documentURL) || + (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) && + IsPlaceholderUrl(self.documentURL)) || web::GetWebClient()->IsAppSpecificURL(self.documentURL); bool needs_back_forward_navigation_reload = existingContext &&
diff --git a/ios/web/navigation/crw_wk_navigation_handler.mm b/ios/web/navigation/crw_wk_navigation_handler.mm index 97a057e..81b5c32 100644 --- a/ios/web/navigation/crw_wk_navigation_handler.mm +++ b/ios/web/navigation/crw_wk_navigation_handler.mm
@@ -43,6 +43,7 @@ #error "This file requires ARC support." #endif +// TODO(crbug.com/1038303): Remove references to "Placeholder". using web::wk_navigation_util::IsPlaceholderUrl; using web::wk_navigation_util::CreatePlaceholderUrlForUrl; using web::wk_navigation_util::ExtractUrlFromPlaceholderUrl; @@ -199,7 +200,8 @@ } // If this is a placeholder navigation, pass through. - if (IsPlaceholderUrl(requestURL)) { + if (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) && + IsPlaceholderUrl(requestURL)) { if (action.sourceFrame.mainFrame) { // Disallow renderer initiated navigations to placeholder URLs. decisionHandler(WKNavigationActionPolicyCancel); @@ -231,7 +233,8 @@ (!context->IsRendererInitiated() || (context->GetPageTransition() & ui::PAGE_TRANSITION_FORWARD_BACK))) { transition = context->GetPageTransition(); - if (context->IsLoadingErrorPage()) { + if (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) && + context->IsLoadingErrorPage()) { // loadHTMLString: navigation which loads error page into WKWebView. decisionHandler(WKNavigationActionPolicyAllow); return; @@ -446,7 +449,8 @@ // If this is a placeholder navigation, pass through. GURL responseURL = net::GURLWithNSURL(WKResponse.response.URL); - if (IsPlaceholderUrl(responseURL)) { + if (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) && + IsPlaceholderUrl(responseURL)) { handler(WKNavigationResponsePolicyAllow); return; } @@ -516,13 +520,16 @@ if (context) { // This is already seen and registered navigation. - if (context->IsLoadingErrorPage()) { + if (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) && + context->IsLoadingErrorPage()) { // This is loadHTMLString: navigation to display error page in web view. self.navigationState = web::WKNavigationState::REQUESTED; return; } - if (!context->IsPlaceholderNavigation() && !IsWKInternalUrl(webViewURL)) { + if ((base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) || + !context->IsPlaceholderNavigation()) && + !IsWKInternalUrl(webViewURL)) { web::NavigationItem* item = web::GetItemWithUniqueID(self.navigationManagerImpl, context); if (item) { @@ -578,14 +585,15 @@ // app-specific load and should not be restarted. // 2) back/forward navigation to an app-specific URL should be allowed. bool exemptedAppSpecificLoad = false; - bool currentItemIsPlaceholder = - CreatePlaceholderUrlForUrl(webViewURL) == - net::GURLWithNSURL(webView.backForwardList.currentItem.URL); - bool isBackForward = self.pendingNavigationInfo.navigationType == - WKNavigationTypeBackForward; - bool isRestoringSession = IsRestoreSessionUrl(self.documentURL); - exemptedAppSpecificLoad = - currentItemIsPlaceholder || isBackForward || isRestoringSession; + bool currentItemIsPlaceholder = + !base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) && + CreatePlaceholderUrlForUrl(webViewURL) == + net::GURLWithNSURL(webView.backForwardList.currentItem.URL); + bool isBackForward = + self.pendingNavigationInfo.navigationType == WKNavigationTypeBackForward; + bool isRestoringSession = IsRestoreSessionUrl(self.documentURL); + exemptedAppSpecificLoad = + currentItemIsPlaceholder || isBackForward || isRestoringSession; if (!web::GetWebClient()->IsAppSpecificURL(webViewURL) || !exemptedAppSpecificLoad) { @@ -619,13 +627,17 @@ // crbug.com/861836. self.webStateImpl->ClearTransientContent(); + BOOL isPlaceholderURL = + base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) + ? NO + : IsPlaceholderUrl(webViewURL); std::unique_ptr<web::NavigationContextImpl> navigationContext = [self.delegate navigationHandler:self registerLoadRequestForURL:webViewURL sameDocumentNavigation:NO hasUserGesture:self.pendingNavigationInfo.hasUserGesture rendererInitiated:YES - placeholderNavigation:IsPlaceholderUrl(webViewURL)]; + placeholderNavigation:isPlaceholderURL]; web::NavigationContextImpl* navigationContextPtr = navigationContext.get(); // GetPendingItem which may be called inside OnNavigationStarted relies on // association between NavigationContextImpl and WKNavigation. @@ -642,7 +654,8 @@ GURL webViewURL = net::GURLWithNSURL(webView.URL); // This callback should never be triggered for placeholder navigations. - DCHECK(!IsPlaceholderUrl(webViewURL)); + DCHECK(base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) || + !IsPlaceholderUrl(webViewURL)); [self.navigationStates setState:web::WKNavigationState::REDIRECTED forNavigation:navigation]; @@ -751,7 +764,9 @@ // webView.backForwardList.currentItem.URL will return the right committed // URL (crbug.com/784480). webViewURL = currentWKItemURL; - } else if (context && !context->IsPlaceholderNavigation() && + } else if (context && + (base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) || + !context->IsPlaceholderNavigation()) && context->GetUrl() == currentWKItemURL) { // If webView.backForwardList.currentItem.URL matches |context|, then this // is a known edge case where |webView.URL| is wrong. @@ -766,7 +781,8 @@ // Don't show webview for placeholder navigation to avoid covering existing // content. - if (!IsPlaceholderUrl(webViewURL)) + if (base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) || + !IsPlaceholderUrl(webViewURL)) [self.delegate navigationHandlerDisplayWebView:self]; if (@available(iOS 11.3, *)) { @@ -775,7 +791,10 @@ // because redirect callback was not called. if (@available(iOS 12, *)) { // rdar://37547029 was fixed on iOS 12. - } else if (context && !context->IsPlaceholderNavigation() && + } else if (context && + (base::FeatureList::IsEnabled( + web::features::kUseJSForErrorPage) || + !context->IsPlaceholderNavigation()) && context->GetUrl() != webViewURL) { [self didReceiveRedirectForNavigation:context withURL:webViewURL]; } @@ -822,7 +841,8 @@ // Do not inject window ID if this is a placeholder URL. For WebUI, let the // window ID be injected when the |loadHTMLString:baseURL| navigation is // committed. - if (!IsPlaceholderUrl(webViewURL)) { + if (base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) || + !IsPlaceholderUrl(webViewURL)) { [self.JSInjector resetInjectedScriptSet]; const std::string& mime_type = self.webStateImpl->GetContentsMimeType(); @@ -867,19 +887,25 @@ setDocumentURL:webViewURL context:context]; - if (!committedNavigation && context && !context->IsLoadingErrorPage()) { + if (!committedNavigation && context && + (base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) || + !context->IsLoadingErrorPage())) { self.webStateImpl->OnNavigationFinished(context); } // Do not update the states of the last committed item for placeholder page // because the actual navigation item will not be committed until the native // content or WebUI is shown. - if (context && !context->IsPlaceholderNavigation() && - !context->IsLoadingErrorPage() && + if (context && + (base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) || + (!context->IsPlaceholderNavigation() && + !context->IsLoadingErrorPage())) && !context->GetUrl().SchemeIs(url::kAboutScheme) && !IsRestoreSessionUrl(context->GetUrl())) { [self.delegate webViewHandlerUpdateSSLStatusForCurrentNavigationItem:self]; - if (!context->IsLoadingErrorPage() && !IsRestoreSessionUrl(webViewURL)) { + if ((base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) || + !context->IsLoadingErrorPage()) && + !IsRestoreSessionUrl(webViewURL)) { [self setLastCommittedNavigationItemTitle:webView.title]; } } @@ -933,7 +959,8 @@ // Invariant: every |navigation| should have a |context| and a |item|. // TODO(crbug.com/899383) Fix invariant violation when a new pending item is // created before a placeholder load finishes. - if (IsPlaceholderUrl(webViewURL)) { + if (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) && + IsPlaceholderUrl(webViewURL)) { GURL originalURL = ExtractUrlFromPlaceholderUrl(webViewURL); if (self.currentNavItem != item && self.currentNavItem->GetVirtualURL() != originalURL) { @@ -947,9 +974,11 @@ UMA_HISTOGRAM_BOOLEAN("IOS.FinishedNavigationHasItem", item); if (context && item) { - GURL navigationURL = context->IsPlaceholderNavigation() - ? CreatePlaceholderUrlForUrl(context->GetUrl()) - : context->GetUrl(); + GURL navigationURL = + !base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) && + context->IsPlaceholderNavigation() + ? CreatePlaceholderUrlForUrl(context->GetUrl()) + : context->GetUrl(); if (navigationURL == currentWKItemURL) { // If webView.backForwardList.currentItem.URL matches |context|, then this // is a known edge case where |webView.URL| is wrong. @@ -970,40 +999,42 @@ context->SetUrl(currentWKItemURL); } - if (IsPlaceholderUrl(webViewURL)) { - if (item->GetURL() == webViewURL) { - // Current navigation item is restored from a placeholder URL as part - // of session restoration. It is now safe to update the navigation - // item URL to the original app-specific URL. - item->SetURL(ExtractUrlFromPlaceholderUrl(webViewURL)); + if (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)) { + if (IsPlaceholderUrl(webViewURL)) { + if (item->GetURL() == webViewURL) { + // Current navigation item is restored from a placeholder URL as part + // of session restoration. It is now safe to update the navigation + // item URL to the original app-specific URL. + item->SetURL(ExtractUrlFromPlaceholderUrl(webViewURL)); + } + + if (item->error_retry_state_machine().state() == + web::ErrorRetryState::kNoNavigationError) { + // Offline pages can leave the WKBackForwardList current item as a + // placeholder with no saved content. In this case, trigger a retry + // on that navigation with an update |item| url and |context| error. + item->SetURL( + ExtractUrlFromPlaceholderUrl(net::GURLWithNSURL(webView.URL))); + item->SetVirtualURL(item->GetURL()); + context->SetError([NSError + errorWithDomain:NSURLErrorDomain + code:NSURLErrorNetworkConnectionLost + userInfo:@{ + NSURLErrorFailingURLStringErrorKey : + base::SysUTF8ToNSString(item->GetURL().spec()) + }]); + item->error_retry_state_machine().SetRetryPlaceholderNavigation(); + } } - if (item->error_retry_state_machine().state() == - web::ErrorRetryState::kNoNavigationError) { - // Offline pages can leave the WKBackForwardList current item as a - // placeholder with no saved content. In this case, trigger a retry - // on that navigation with an update |item| url and |context| error. - item->SetURL( - ExtractUrlFromPlaceholderUrl(net::GURLWithNSURL(webView.URL))); - item->SetVirtualURL(item->GetURL()); - context->SetError([NSError - errorWithDomain:NSURLErrorDomain - code:NSURLErrorNetworkConnectionLost - userInfo:@{ - NSURLErrorFailingURLStringErrorKey : - base::SysUTF8ToNSString(item->GetURL().spec()) - }]); - item->error_retry_state_machine().SetRetryPlaceholderNavigation(); - } + web::ErrorRetryCommand command = + item->error_retry_state_machine().DidFinishNavigation(webViewURL); + [self handleErrorRetryCommand:command + navigationItem:item + navigationContext:context + originalNavigation:navigation + webView:webView]; } - - web::ErrorRetryCommand command = - item->error_retry_state_machine().DidFinishNavigation(webViewURL); - [self handleErrorRetryCommand:command - navigationItem:item - navigationContext:context - originalNavigation:navigation - webView:webView]; } [self.navigationStates setState:web::WKNavigationState::FINISHED @@ -1542,8 +1573,10 @@ self.navigationManagerImpl->SetPendingItem(context->ReleaseItem()); web::NavigationItemImpl* item = web::GetItemWithUniqueID(self.navigationManagerImpl, context); - if (item && item->error_retry_state_machine().state() == - web::ErrorRetryState::kRetryFailedNavigationItem) { + if (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) && + item && + item->error_retry_state_machine().state() == + web::ErrorRetryState::kRetryFailedNavigationItem) { item->error_retry_state_machine().SetDisplayingWebError(); } } @@ -1713,21 +1746,26 @@ web::GetItemWithUniqueID(self.navigationManagerImpl, navigationContext); if (item) { - GURL errorURL = - net::GURLWithNSURL(error.userInfo[NSURLErrorFailingURLErrorKey]); - web::ErrorRetryCommand command = web::ErrorRetryCommand::kDoNothing; - if (provisionalLoad) { - command = item->error_retry_state_machine().DidFailProvisionalNavigation( - net::GURLWithNSURL(webView.URL), errorURL); + if (base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)) { + // TODO(crbug.com/991608): Instantiate error page. } else { - command = item->error_retry_state_machine().DidFailNavigation( - net::GURLWithNSURL(webView.URL)); + GURL errorURL = + net::GURLWithNSURL(error.userInfo[NSURLErrorFailingURLErrorKey]); + web::ErrorRetryCommand command = web::ErrorRetryCommand::kDoNothing; + if (provisionalLoad) { + command = + item->error_retry_state_machine().DidFailProvisionalNavigation( + net::GURLWithNSURL(webView.URL), errorURL); + } else { + command = item->error_retry_state_machine().DidFailNavigation( + net::GURLWithNSURL(webView.URL)); + } + [self handleErrorRetryCommand:command + navigationItem:item + navigationContext:navigationContext + originalNavigation:navigation + webView:webView]; } - [self handleErrorRetryCommand:command - navigationItem:item - navigationContext:navigationContext - originalNavigation:navigation - webView:webView]; } // Don't commit the pending item or call OnNavigationFinished until the @@ -1763,7 +1801,8 @@ self.webStateImpl->OnNavigationFinished(navigationContext.get()); } } - } else if (!provisionalLoad) { + } else if (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) && + !provisionalLoad) { web::NavigationContextImpl* navigationContext = [self.navigationStates contextForNavigation:navigation]; web::NavigationItemImpl* item = @@ -1786,6 +1825,7 @@ navigationContext:(web::NavigationContextImpl*)context originalNavigation:(WKNavigation*)originalNavigation webView:(WKWebView*)webView { + DCHECK(!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)); if (command == web::ErrorRetryCommand::kDoNothing) return; @@ -1939,7 +1979,10 @@ self.webStateImpl, failingURL, /*has_user_gesture=*/false, ui::PAGE_TRANSITION_FIRST, /*is_renderer_initiated=*/false); - loadHTMLContext->SetLoadingErrorPage(true); + + if (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)) + loadHTMLContext->SetLoadingErrorPage(true); + loadHTMLContext->SetNavigationItemUniqueID(itemID); [self.navigationStates setContext:std::move(loadHTMLContext) @@ -1969,9 +2012,12 @@ // |OnNavigationFinished| callback. This is also needed if |context| is // not yet committed, which can happen on a reload/back/forward load // that failed in provisional navigation. - if (context->IsPlaceholderNavigation() || !context->HasCommitted()) { + if ((!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) && + context->IsPlaceholderNavigation()) || + !context->HasCommitted()) { context->SetUrl(itemURL); - context->SetPlaceholderNavigation(false); + if (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)) + context->SetPlaceholderNavigation(false); context->SetHasCommitted(true); self.webStateImpl->OnNavigationFinished(context); } @@ -2189,6 +2235,7 @@ rendererInitiated:(BOOL)rendererInitiated forContext:(std::unique_ptr<web::NavigationContextImpl>) originalContext { + DCHECK(!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)); GURL placeholderURL = CreatePlaceholderUrlForUrl(originalURL); // TODO(crbug.com/956511): Remove this code when NativeContent support is // removed. @@ -2254,7 +2301,8 @@ [self.delegate navigationHandlerDidStartLoading:self]; // Do not commit pending item in the middle of loading a placeholder URL. The // item will be committed when webUI is displayed. - if (!context->IsPlaceholderNavigation()) { + if (base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) || + !context->IsPlaceholderNavigation()) { self.navigationManagerImpl->CommitPendingItem(context->ReleaseItem()); if (context->IsLoadingHtmlString()) { self.navigationManagerImpl->GetLastCommittedItem()->SetURL(
diff --git a/ios/web/navigation/navigation_context_impl.mm b/ios/web/navigation/navigation_context_impl.mm index 5bf9e66..a25391f 100644 --- a/ios/web/navigation/navigation_context_impl.mm +++ b/ios/web/navigation/navigation_context_impl.mm
@@ -7,6 +7,7 @@ #import <Foundation/Foundation.h> #include "base/memory/ptr_util.h" +#include "ios/web/common/features.h" #import "ios/web/navigation/navigation_item_impl.h" #include "net/http/http_response_headers.h" @@ -148,10 +149,12 @@ } bool NavigationContextImpl::IsLoadingErrorPage() const { + DCHECK(!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)); return is_loading_error_page_; } void NavigationContextImpl::SetLoadingErrorPage(bool is_loading_error_page) { + DCHECK(!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)); is_loading_error_page_ = is_loading_error_page; } @@ -164,10 +167,12 @@ } bool NavigationContextImpl::IsPlaceholderNavigation() const { + DCHECK(!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)); return is_placeholder_navigation_; } void NavigationContextImpl::SetPlaceholderNavigation(bool flag) { + DCHECK(!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)); is_placeholder_navigation_ = flag; }
diff --git a/ios/web/navigation/navigation_item_impl.mm b/ios/web/navigation/navigation_item_impl.mm index 53f1002..70cef74 100644 --- a/ios/web/navigation/navigation_item_impl.mm +++ b/ios/web/navigation/navigation_item_impl.mm
@@ -339,6 +339,7 @@ } ErrorRetryStateMachine& NavigationItemImpl::error_retry_state_machine() { + DCHECK(!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)); return error_retry_state_machine_; }
diff --git a/ios/web/navigation/navigation_manager_impl.mm b/ios/web/navigation/navigation_manager_impl.mm index 4995a8a..d16eb3a3 100644 --- a/ios/web/navigation/navigation_manager_impl.mm +++ b/ios/web/navigation/navigation_manager_impl.mm
@@ -7,6 +7,7 @@ #include <algorithm> #include "base/metrics/histogram_macros.h" +#include "ios/web/common/features.h" #import "ios/web/navigation/navigation_manager_delegate.h" #import "ios/web/navigation/wk_navigation_util.h" #import "ios/web/public/web_client.h" @@ -462,7 +463,8 @@ // Do not rewrite placeholder URL. Navigation code relies on this special URL // to implement native view and WebUI, and rewriter code should not be exposed // to this special type of about:blank URL. - if (!IsPlaceholderUrl(url)) { + if (base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) || + !IsPlaceholderUrl(url)) { bool url_was_rewritten = false; if (additional_rewriters && !additional_rewriters->empty()) { url_was_rewritten = web::BrowserURLRewriter::RewriteURLWithWriters( @@ -519,6 +521,7 @@ } bool NavigationManagerImpl::IsPlaceholderUrl(const GURL& url) const { + DCHECK(!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)); return false; // Default implementation doesn't use placeholder URLs }
diff --git a/ios/web/navigation/wk_based_navigation_manager_impl.mm b/ios/web/navigation/wk_based_navigation_manager_impl.mm index e1b18eb..d1e6360 100644 --- a/ios/web/navigation/wk_based_navigation_manager_impl.mm +++ b/ios/web/navigation/wk_based_navigation_manager_impl.mm
@@ -53,6 +53,7 @@ // Returns true if |url1| is the same as |url2| or is a placeholder of |url2|. bool IsSameOrPlaceholderOf(const GURL& url1, const GURL& url2) { + DCHECK(!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)); return url1 == url2 || url1 == web::wk_navigation_util::CreatePlaceholderUrlForUrl(url2); } @@ -210,9 +211,18 @@ current_item_url = target_url; } - if (proxy.backForwardList.currentItem && - IsSameOrPlaceholderOf(current_item_url, pending_item_->GetURL()) && - IsSameOrPlaceholderOf(current_item_url, net::GURLWithNSURL(proxy.URL))) { + BOOL isCurrentURLSameAsPending = NO; + if (base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)) { + isCurrentURLSameAsPending = + current_item_url == pending_item_->GetURL() && + current_item_url == net::GURLWithNSURL(proxy.URL); + } else { + isCurrentURLSameAsPending = + IsSameOrPlaceholderOf(current_item_url, pending_item_->GetURL()) && + IsSameOrPlaceholderOf(current_item_url, net::GURLWithNSURL(proxy.URL)); + } + + if (proxy.backForwardList.currentItem && isCurrentURLSameAsPending) { pending_item_index_ = web_view_cache_.GetCurrentItemIndex(); // If |currentItem| is not already associated with a NavigationItemImpl, @@ -837,7 +847,8 @@ GURL virtual_url; if (wk_navigation_util::IsRestoreSessionUrl(document_url) && wk_navigation_util::ExtractTargetURL(document_url, &virtual_url)) { - if (wk_navigation_util::IsPlaceholderUrl(virtual_url)) { + if (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) && + wk_navigation_util::IsPlaceholderUrl(virtual_url)) { last_committed_web_view_item_->SetVirtualURL( wk_navigation_util::ExtractUrlFromPlaceholderUrl(virtual_url)); } else { @@ -950,6 +961,7 @@ } bool WKBasedNavigationManagerImpl::IsPlaceholderUrl(const GURL& url) const { + DCHECK(!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)); return wk_navigation_util::IsPlaceholderUrl(url); } @@ -1087,7 +1099,8 @@ if (wk_navigation_util::IsRestoreSessionUrl(url)) { GURL virtual_url; if (wk_navigation_util::ExtractTargetURL(url, &virtual_url)) { - if (wk_navigation_util::IsPlaceholderUrl(virtual_url)) { + if (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) && + wk_navigation_util::IsPlaceholderUrl(virtual_url)) { new_item->SetVirtualURL( wk_navigation_util::ExtractUrlFromPlaceholderUrl(virtual_url)); } else { @@ -1101,7 +1114,8 @@ // navigation. Rather than expose the internal placeholder to the UI and to // URL-sensing components outside of //ios/web layer, set virtual URL to the // placeholder original URL here. - if (wk_navigation_util::IsPlaceholderUrl(url)) { + if (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) && + wk_navigation_util::IsPlaceholderUrl(url)) { new_item->SetVirtualURL( wk_navigation_util::ExtractUrlFromPlaceholderUrl(url)); }
diff --git a/ios/web/navigation/wk_based_navigation_manager_impl_unittest.mm b/ios/web/navigation/wk_based_navigation_manager_impl_unittest.mm index 704147e5..6ce746d 100644 --- a/ios/web/navigation/wk_based_navigation_manager_impl_unittest.mm +++ b/ios/web/navigation/wk_based_navigation_manager_impl_unittest.mm
@@ -757,6 +757,9 @@ // Tests that the virtual URL of a placeholder item is updated to the original // URL. TEST_F(WKBasedNavigationManagerTest, HideInternalPlaceholderUrl) { + if (base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)) + return; + GURL original_url = GURL("http://www.1.com?query=special%26chars"); GURL url = wk_navigation_util::CreatePlaceholderUrlForUrl(original_url); NSString* url_spec = base::SysUTF8ToNSString(url.spec());
diff --git a/ios/web/navigation/wk_navigation_util.mm b/ios/web/navigation/wk_navigation_util.mm index c226b79..1d194e9 100644 --- a/ios/web/navigation/wk_navigation_util.mm +++ b/ios/web/navigation/wk_navigation_util.mm
@@ -79,18 +79,23 @@ } bool IsWKInternalUrl(const GURL& url) { - return IsPlaceholderUrl(url) || IsRestoreSessionUrl(url); + return (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) && + IsPlaceholderUrl(url)) || + IsRestoreSessionUrl(url); } bool IsWKInternalUrl(NSURL* url) { - return IsPlaceholderUrl(url) || IsRestoreSessionUrl(url); + return (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) && + IsPlaceholderUrl(url)) || + IsRestoreSessionUrl(url); } bool URLNeedsUserAgentType(const GURL& url) { if (web::GetWebClient()->IsAppSpecificURL(url)) return false; - if (url.SchemeIs(url::kAboutScheme) && IsPlaceholderUrl(url)) { + if (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) && + url.SchemeIs(url::kAboutScheme) && IsPlaceholderUrl(url)) { return !web::GetWebClient()->IsAppSpecificURL( ExtractUrlFromPlaceholderUrl(url)); } @@ -197,11 +202,13 @@ } bool IsPlaceholderUrl(const GURL& url) { + DCHECK(!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)); return url.IsAboutBlank() && base::StartsWith(url.query(), kOriginalUrlKey, base::CompareCase::SENSITIVE); } bool IsPlaceholderUrl(NSURL* url) { + DCHECK(!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)); // about:blank NSURLs don't have nil host and query, so use absolute string // matching. return [url.scheme isEqual:@"about"] && @@ -210,6 +217,7 @@ } GURL CreatePlaceholderUrlForUrl(const GURL& original_url) { + DCHECK(!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)); if (!original_url.is_valid()) return GURL::EmptyGURL(); @@ -220,6 +228,7 @@ } GURL ExtractUrlFromPlaceholderUrl(const GURL& url) { + DCHECK(!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)); std::string value; if (IsPlaceholderUrl(url) && net::GetValueForKeyInQuery(url, kOriginalUrlKey, &value)) {
diff --git a/ios/web/navigation/wk_navigation_util_unittest.mm b/ios/web/navigation/wk_navigation_util_unittest.mm index aa5a52a..3c89e6bf 100644 --- a/ios/web/navigation/wk_navigation_util_unittest.mm +++ b/ios/web/navigation/wk_navigation_util_unittest.mm
@@ -313,6 +313,9 @@ } TEST_F(WKNavigationUtilTest, IsPlaceholderUrl) { + if (base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)) + return; + // Valid placeholder URLs. EXPECT_TRUE(IsPlaceholderUrl(GURL("about:blank?for="))); EXPECT_TRUE(IsPlaceholderUrl(GURL("about:blank?for=chrome%3A%2F%2Fnewtab"))); @@ -334,11 +337,17 @@ } TEST_F(WKNavigationUtilTest, EncodReturnsEmptyOnInvalidUrls) { + if (base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)) + return; + EXPECT_EQ(GURL::EmptyGURL(), CreatePlaceholderUrlForUrl(GURL::EmptyGURL())); EXPECT_EQ(GURL::EmptyGURL(), CreatePlaceholderUrlForUrl(GURL("notaurl"))); } TEST_F(WKNavigationUtilTest, EncodeDecodeValidUrls) { + if (base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)) + return; + { GURL original("chrome://chrome-urls"); GURL encoded("about:blank?for=chrome%3A%2F%2Fchrome-urls"); @@ -355,6 +364,9 @@ // Tests that invalid URLs will be rejected in decoding. TEST_F(WKNavigationUtilTest, DecodeRejectInvalidUrls) { + if (base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)) + return; + GURL encoded("about:blank?for=thisisnotanurl"); EXPECT_EQ(GURL::EmptyGURL(), ExtractUrlFromPlaceholderUrl(encoded)); } @@ -383,7 +395,9 @@ GURL app_specific( url::SchemeHostPort(kTestAppSpecificScheme, "foo", 0).Serialize()); EXPECT_FALSE(URLNeedsUserAgentType(app_specific)); - EXPECT_FALSE(URLNeedsUserAgentType(CreatePlaceholderUrlForUrl(app_specific))); + if (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)) + EXPECT_FALSE( + URLNeedsUserAgentType(CreatePlaceholderUrlForUrl(app_specific))); } } // namespace wk_navigation_util
diff --git a/ios/web/public/test/BUILD.gn b/ios/web/public/test/BUILD.gn index b2fcc67..4670b58 100644 --- a/ios/web/public/test/BUILD.gn +++ b/ios/web/public/test/BUILD.gn
@@ -15,6 +15,7 @@ "//base", "//base/test:test_support", "//ios/web:web", + "//ios/web/common:features", "//ios/web/js_messaging", "//ios/web/navigation", "//ios/web/navigation:wk_navigation_util",
diff --git a/ios/web/public/test/web_test_with_web_state.mm b/ios/web/public/test/web_test_with_web_state.mm index 7df45d1..5a79c8c 100644 --- a/ios/web/public/test/web_test_with_web_state.mm +++ b/ios/web/public/test/web_test_with_web_state.mm
@@ -10,6 +10,7 @@ #include "base/scoped_observer.h" #include "base/strings/sys_string_conversions.h" #import "base/test/ios/wait_util.h" +#include "ios/web/common/features.h" #import "ios/web/js_messaging/crw_js_injector.h" #import "ios/web/navigation/crw_wk_navigation_states.h" #import "ios/web/navigation/navigation_manager_impl.h" @@ -20,6 +21,7 @@ #import "ios/web/web_state/ui/crw_web_controller.h" #import "ios/web/web_state/ui/wk_web_view_configuration_provider.h" #import "ios/web/web_state/web_state_impl.h" +#include "url/url_constants.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." @@ -138,18 +140,23 @@ // TODO(crbug.com/777884): consider changing |-loadHTML| to match WKWebView's // |-loadHTMLString:baseURL| that doesn't create a navigation entry. if (!web_state()->GetNavigationManager()->GetItemCount()) { - GURL placeholder_url = wk_navigation_util::CreatePlaceholderUrlForUrl(url); + GURL placeholder_url(url::kAboutBlankURL); + if (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)) + placeholder_url = wk_navigation_util::CreatePlaceholderUrlForUrl(url); + NavigationManager::WebLoadParams params(placeholder_url); web_state()->GetNavigationManager()->LoadURLWithParams(params); - // Set NoNavigationError so the placeHolder doesn't trigger a - // kNavigatingToFailedNavigationItem. - web::WebStateImpl* web_state_impl = - static_cast<web::WebStateImpl*>(web_state()); - web_state_impl->GetNavigationManagerImpl() - .GetCurrentItemImpl() - ->error_retry_state_machine() - .SetIgnorePlaceholderNavigation(); + if (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)) { + // Set NoNavigationError so the placeHolder doesn't trigger a + // kNavigatingToFailedNavigationItem. + web::WebStateImpl* web_state_impl = + static_cast<web::WebStateImpl*>(web_state()); + web_state_impl->GetNavigationManagerImpl() + .GetCurrentItemImpl() + ->error_retry_state_machine() + .SetIgnorePlaceholderNavigation(); + } ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForPageLoadTimeout, ^{ return web_controller.navigationState == web::WKNavigationState::FINISHED;
diff --git a/ios/web/web_state/ui/crw_web_controller.mm b/ios/web/web_state/ui/crw_web_controller.mm index 398fdded..e396a108 100644 --- a/ios/web/web_state/ui/crw_web_controller.mm +++ b/ios/web/web_state/ui/crw_web_controller.mm
@@ -781,7 +781,8 @@ WKNavigation* navigation = [self.webView goToBackForwardListItem:wk_item]; GURL URL = net::GURLWithNSURL(wk_item.URL); - if (IsPlaceholderUrl(URL)) { + if (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) && + IsPlaceholderUrl(URL)) { // No need to create navigation context for placeholder back forward // navigations. Future callbacks do not expect that context will exist. return; @@ -889,8 +890,10 @@ _userInteractionState.SetUserInteractionRegisteredSinceLastUrlChange(false); } if (context && !context->IsLoadingHtmlString() && - !context->IsLoadingErrorPage() && !IsWKInternalUrl(newURL) && - !newURL.SchemeIs(url::kAboutScheme) && self.webView) { + (base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) || + !context->IsLoadingErrorPage()) && + !IsWKInternalUrl(newURL) && !newURL.SchemeIs(url::kAboutScheme) && + self.webView) { // On iOS13, WebKit started changing the URL visible webView.URL when // opening a new tab and then writing to it, e.g. // window.open('javascript:document.write(1)'). This URL is never commited, @@ -924,7 +927,8 @@ *trustLevel = web::URLVerificationTrustLevel::kAbsolute; // Placeholder URL is an implementation detail. Don't expose it to users of // web layer. - if (IsPlaceholderUrl(_documentURL)) + if (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) && + IsPlaceholderUrl(_documentURL)) return ExtractUrlFromPlaceholderUrl(_documentURL); return _documentURL; } @@ -1588,7 +1592,8 @@ lastNavigationState == web::WKNavigationState::REDIRECTED; if (!hasPendingNavigation && - !IsPlaceholderUrl(net::GURLWithNSURL(self.webView.URL))) { + (base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) || + !IsPlaceholderUrl(net::GURLWithNSURL(self.webView.URL)))) { // Do not update the title if there is a navigation in progress because // there is no way to tell if KVO change fired for new or previous page. [self.navigationHandler @@ -1652,12 +1657,16 @@ - (void)navigationObserver:(CRWWebViewNavigationObserver*)navigationObserver didLoadNewURL:(const GURL&)webViewURL forSameDocumentNavigation:(BOOL)isSameDocumentNavigation { - std::unique_ptr<web::NavigationContextImpl> newContext = [_requestController - registerLoadRequestForURL:webViewURL - sameDocumentNavigation:isSameDocumentNavigation - hasUserGesture:NO - rendererInitiated:YES - placeholderNavigation:IsPlaceholderUrl(webViewURL)]; + BOOL isPlaceholderURL = + base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) + ? NO + : IsPlaceholderUrl(webViewURL); + std::unique_ptr<web::NavigationContextImpl> newContext = + [_requestController registerLoadRequestForURL:webViewURL + sameDocumentNavigation:isSameDocumentNavigation + hasUserGesture:NO + rendererInitiated:YES + placeholderNavigation:isPlaceholderURL]; [self.navigationHandler webPageChangedWithContext:newContext.get() webView:self.webView]; newContext->SetHasCommitted(!isSameDocumentNavigation);
diff --git a/ios/web/web_state/ui/crw_web_controller_unittest.mm b/ios/web/web_state/ui/crw_web_controller_unittest.mm index 2776d557c..91f7386 100644 --- a/ios/web/web_state/ui/crw_web_controller_unittest.mm +++ b/ios/web/web_state/ui/crw_web_controller_unittest.mm
@@ -286,11 +286,13 @@ [navigation_delegate_ webView:mock_web_view_ didFailNavigation:navigation withError:error]; - NavigationManagerImpl& navigation_manager = - web_controller().webStateImpl->GetNavigationManagerImpl(); - NavigationItemImpl* item = navigation_manager.GetLastCommittedItemImpl(); - EXPECT_EQ(ErrorRetryState::kNoNavigationError, - item->error_retry_state_machine().state()); + if (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)) { + NavigationManagerImpl& navigation_manager = + web_controller().webStateImpl->GetNavigationManagerImpl(); + NavigationItemImpl* item = navigation_manager.GetLastCommittedItemImpl(); + EXPECT_EQ(ErrorRetryState::kNoNavigationError, + item->error_retry_state_machine().state()); + } } // Tests returning pending item stored in navigation context.
diff --git a/ios/web/web_state/ui/crw_web_request_controller.h b/ios/web/web_state/ui/crw_web_request_controller.h index e2981985..f4d808d 100644 --- a/ios/web/web_state/ui/crw_web_request_controller.h +++ b/ios/web/web_state/ui/crw_web_request_controller.h
@@ -84,6 +84,7 @@ // Calls |registerLoadRequestForURL| with empty referrer and link or client // redirect transition based on user interaction state. Returns navigation // context for this request. +// TODO(crbug.com/1038303): Remove |placeholderNavigation|. - (std::unique_ptr<web::NavigationContextImpl>) registerLoadRequestForURL:(const GURL&)URL sameDocumentNavigation:(BOOL)sameDocumentNavigation @@ -93,6 +94,7 @@ // Creates a page change request and registers it with the navigation handler. // Returns navigation context for this request. +// TODO(crbug.com/1038303): Remove |placeholderNavigation|. - (std::unique_ptr<web::NavigationContextImpl>) registerLoadRequestForURL:(const GURL&)requestURL referrer:(const web::Referrer&)referrer
diff --git a/ios/web/web_state/ui/crw_web_request_controller.mm b/ios/web/web_state/ui/crw_web_request_controller.mm index cc1ef45..7b56109 100644 --- a/ios/web/web_state/ui/crw_web_request_controller.mm +++ b/ios/web/web_state/ui/crw_web_request_controller.mm
@@ -129,10 +129,13 @@ item->SetNavigationInitiationType( web::NavigationInitiationType::BROWSER_INITIATED); - // The error_retry_state_machine may still be in the - // |kDisplayingWebErrorForFailedNavigation| from the navigation that is being - // replaced. As the navigation is now successful, the error can be cleared. - item->error_retry_state_machine().SetNoNavigationError(); + if (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)) { + // The error_retry_state_machine may still be in the + // |kDisplayingWebErrorForFailedNavigation| from the navigation that is + // being replaced. As the navigation is now successful, the error can be + // cleared. + item->error_retry_state_machine().SetNoNavigationError(); + } // The load data call will replace the current navigation and the webView URL // of the navigation will be replaced by |URL|. Set the URL of the // navigationItem to keep them synced. @@ -321,7 +324,8 @@ // redirects can not change the origin. It is possible to have more than one // pending navigations, so the redirect does not necesserily belong to the // pending navigation item. - if (!placeholderNavigation && + if ((base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) || + !placeholderNavigation) && item->GetURL().GetOrigin() == requestURL.GetOrigin()) { self.navigationManagerImpl->UpdatePendingItemUrl(requestURL); } @@ -350,7 +354,8 @@ web::NavigationContextImpl::CreateNavigationContext( self.webState, requestURL, hasUserGesture, transition, rendererInitiated); - context->SetPlaceholderNavigation(placeholderNavigation); + if (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)) + context->SetPlaceholderNavigation(placeholderNavigation); context->SetNavigationItemUniqueID(item->GetUniqueID()); context->SetIsPost([self.navigationHandler isCurrentNavigationItemPOST]); context->SetIsSameDocument(sameDocumentNavigation); @@ -358,7 +363,9 @@ // If WKWebView.loading is used for WebState::IsLoading, do not set it for // renderer-initated navigation otherwise WebState::IsLoading will remain true // after hash change in the web page. - if (!IsWKInternalUrl(requestURL) && !placeholderNavigation && + if (!IsWKInternalUrl(requestURL) && + (base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) || + !placeholderNavigation) && (!web::features::UseWKWebViewLoading() || !rendererInitiated)) { self.webState->SetIsLoading(true); } @@ -388,7 +395,8 @@ // placeholder URLs because this may be the only opportunity to update // |isLoading| for native view reload. - if (context && context->IsPlaceholderNavigation()) + if (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) && + context && context->IsPlaceholderNavigation()) return; if (context && IsRestoreSessionUrl(context->GetUrl())) @@ -397,7 +405,8 @@ if (IsRestoreSessionUrl(net::GURLWithNSURL(self.webView.URL))) return; - if (context && context->IsLoadingErrorPage()) + if (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) && + context && context->IsLoadingErrorPage()) return; if (!loadSuccess) { @@ -622,9 +631,15 @@ // Set |item| to nullptr here to avoid any use-after-free issues, as it can // be cleared by the call to -registerLoadRequestForURL below. item = nullptr; - GURL contextURL = IsPlaceholderUrl(navigationURL) - ? ExtractUrlFromPlaceholderUrl(navigationURL) - : navigationURL; + GURL contextURL = + (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) && + IsPlaceholderUrl(navigationURL)) + ? ExtractUrlFromPlaceholderUrl(navigationURL) + : navigationURL; + BOOL isPlaceholderURL = + base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) + ? NO + : IsPlaceholderUrl(navigationURL); std::unique_ptr<web::NavigationContextImpl> navigationContext = [self registerLoadRequestForURL:contextURL referrer:self.currentNavItemReferrer @@ -632,7 +647,7 @@ sameDocumentNavigation:sameDocumentNavigation hasUserGesture:YES rendererInitiated:NO - placeholderNavigation:IsPlaceholderUrl(navigationURL)]; + placeholderNavigation:isPlaceholderURL]; if (self.navigationManagerImpl->IsRestoreSessionInProgress()) { if (self.navigationManagerImpl->ShouldBlockUrlDuringRestore(
diff --git a/ios/web/web_state/web_state_impl.mm b/ios/web/web_state/web_state_impl.mm index 8d9b7c4..70ef89df 100644 --- a/ios/web/web_state/web_state_impl.mm +++ b/ios/web/web_state/web_state_impl.mm
@@ -14,6 +14,7 @@ #include "base/strings/sys_string_conversions.h" #include "base/threading/sequenced_task_runner_handle.h" #import "ios/web/common/crw_content_view.h" +#include "ios/web/common/features.h" #include "ios/web/common/url_util.h" #import "ios/web/js_messaging/crw_js_injector.h" #import "ios/web/navigation/navigation_context_impl.h" @@ -661,9 +662,10 @@ navigation_manager_->GetLastCommittedItemImpl(); GURL lastCommittedURL; if (item) { - if (wk_navigation_util::IsPlaceholderUrl(item->GetURL()) || - item->error_retry_state_machine().state() == - ErrorRetryState::kReadyToDisplayError) { + if (!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) && + (wk_navigation_util::IsPlaceholderUrl(item->GetURL()) || + item->error_retry_state_machine().state() == + ErrorRetryState::kReadyToDisplayError)) { // When webView.URL is a placeholder URL, |currentURLWithTrustLevel:| // returns virtual URL if one is available. lastCommittedURL = item->GetVirtualURL(); @@ -736,7 +738,8 @@ void WebStateImpl::OnNavigationStarted(web::NavigationContextImpl* context) { // Navigation manager loads internal URLs to restore session history and // create back-forward entries for WebUI. Do not trigger external callbacks. - if (context->IsPlaceholderNavigation() || + if ((!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) && + context->IsPlaceholderNavigation()) || wk_navigation_util::IsRestoreSessionUrl(context->GetUrl())) { return; } @@ -748,7 +751,8 @@ void WebStateImpl::OnNavigationFinished(web::NavigationContextImpl* context) { // Navigation manager loads internal URLs to restore session history and // create back-forward entries for WebUI. Do not trigger external callbacks. - if (context->IsPlaceholderNavigation() || + if ((!base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage) && + context->IsPlaceholderNavigation()) || wk_navigation_util::IsRestoreSessionUrl(context->GetUrl())) { return; }
diff --git a/ios/web/web_state/web_state_impl_unittest.mm b/ios/web/web_state/web_state_impl_unittest.mm index 2fc4109..70fcb362 100644 --- a/ios/web/web_state/web_state_impl_unittest.mm +++ b/ios/web/web_state/web_state_impl_unittest.mm
@@ -16,6 +16,7 @@ #include "base/mac/foundation_util.h" #import "base/strings/sys_string_conversions.h" #import "base/test/ios/wait_util.h" +#include "ios/web/common/features.h" #import "ios/web/navigation/navigation_context_impl.h" #import "ios/web/navigation/navigation_item_impl.h" #import "ios/web/navigation/serializable_user_data_manager_impl.h" @@ -352,6 +353,9 @@ // Tests that placeholder navigations are not visible to WebStateObservers. TEST_F(WebStateImplTest, PlaceholderNavigationNotExposedToObservers) { + if (base::FeatureList::IsEnabled(web::features::kUseJSForErrorPage)) + return; + TestWebStateObserver observer(web_state_.get()); GURL placeholder_url = wk_navigation_util::CreatePlaceholderUrlForUrl(GURL("chrome://newtab"));
diff --git a/testing/scripts/run_performance_tests.py b/testing/scripts/run_performance_tests.py index 11c6fa2..e00907b 100755 --- a/testing/scripts/run_performance_tests.py +++ b/testing/scripts/run_performance_tests.py
@@ -181,7 +181,7 @@ self._generate_also_run_disabled_tests_args() + self._generate_output_args(output_dir) + self._generate_shard_args() + - self._get_passthrough_args() + self._get_additional_flags() ) @property @@ -196,8 +196,8 @@ else: return './%s' % executable - def _get_passthrough_args(self): - return self._options.passthrough_args + self._additional_flags + def _get_additional_flags(self): + return self._additional_flags def _generate_shard_args(self): """Teach the gtest to ignore the environment variables. @@ -231,10 +231,10 @@ if self._options.use_gtest_benchmark_script: output_args.append('--output-dir=' + output_dir) # These flags are to make sure that test output perf metrics in the log. - if not '--verbose' in self._get_passthrough_args(): + if not '--verbose' in self._get_additional_flags(): output_args.append('--verbose') if (not '--test-launcher-print-test-stdio=always' - in self._get_passthrough_args()): + in self._get_additional_flags()): output_args.append('--test-launcher-print-test-stdio=always') return output_args @@ -534,7 +534,8 @@ 'lines is the name of the subfolder to find results in.\n') if options.non_telemetry: - command_generator = GtestCommandGenerator(options) + command_generator = GtestCommandGenerator( + options, additional_flags=options.passthrough_args) benchmark_name = options.gtest_benchmark_name # Fallback to use the name of the executable if flag isn't set. # TODO(crbug.com/870899): remove fallback logic and raise parser error if
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 994dd8d..bc28fc3 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -2616,25 +2616,6 @@ ] } ], - "FastBorderRadius": [ - { - "platforms": [ - "android", - "chromeos", - "linux", - "mac", - "windows" - ], - "experiments": [ - { - "name": "Enabled", - "enable_features": [ - "FastBorderRadius" - ] - } - ] - } - ], "FilterAdsOnAbusiveSites": [ { "platforms": [ @@ -4516,24 +4497,6 @@ ] } ], - "PasswordManagerStickyBubble": [ - { - "platforms": [ - "chromeos", - "linux", - "mac", - "windows" - ], - "experiments": [ - { - "name": "Enabled", - "enable_features": [ - "PasswordManagerStickyBubble" - ] - } - ] - } - ], "PasswordProtectionForEnterprise": [ { "platforms": [
diff --git a/third_party/.gitignore b/third_party/.gitignore index ceb684e..a7211e59 100644 --- a/third_party/.gitignore +++ b/third_party/.gitignore
@@ -93,6 +93,7 @@ /gnu_binutils/ /google_android_play_core/core-*.aar /google_appengine_cloudstorage +/google_benchmark/src /google_toolbox_for_mac/src /googlemac /grpc/src
diff --git a/third_party/blink/common/features.cc b/third_party/blink/common/features.cc index 961e8ab..a0f4940 100644 --- a/third_party/blink/common/features.cc +++ b/third_party/blink/common/features.cc
@@ -58,11 +58,6 @@ const base::Feature kDisplayLocking{"DisplayLocking", base::FEATURE_DISABLED_BY_DEFAULT}; -// Enable applying rounded corner masks via a GL shader rather than -// a mask layer. -const base::Feature kFastBorderRadius{"FastBorderRadius", - base::FEATURE_ENABLED_BY_DEFAULT}; - const base::Feature kJSONModules{"JSONModules", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/third_party/blink/public/common/features.h b/third_party/blink/public/common/features.h index 2f4d338..5b552305 100644 --- a/third_party/blink/public/common/features.h +++ b/third_party/blink/public/common/features.h
@@ -30,7 +30,6 @@ BLINK_COMMON_EXPORT extern const base::Feature kDisplayLocking; BLINK_COMMON_EXPORT extern const base::Feature kAssumeOverlapAfterFixedOrStickyPosition; -BLINK_COMMON_EXPORT extern const base::Feature kFastBorderRadius; BLINK_COMMON_EXPORT extern const base::Feature kJSONModules; BLINK_COMMON_EXPORT extern const base::Feature kLayoutNG; BLINK_COMMON_EXPORT extern const base::Feature kMixedContentAutoupgrade;
diff --git a/third_party/blink/renderer/bindings/scripts/bind_gen/codegen_context.py b/third_party/blink/renderer/bindings/scripts/bind_gen/codegen_context.py index d0d1d20..cce4de6 100644 --- a/third_party/blink/renderer/bindings/scripts/bind_gen/codegen_context.py +++ b/third_party/blink/renderer/bindings/scripts/bind_gen/codegen_context.py
@@ -51,6 +51,7 @@ "constructor": None, "constructor_group": None, "dict_member": None, + "exposed_construct": None, "operation": None, "operation_group": None, @@ -224,7 +225,8 @@ @property def property_(self): return (self.attribute or self.constant or self.constructor_group - or self.dict_member or self.operation_group) + or self.dict_member or self.exposed_construct + or self.operation_group) @property def return_type(self):
diff --git a/third_party/blink/renderer/bindings/scripts/bind_gen/codegen_expr.py b/third_party/blink/renderer/bindings/scripts/bind_gen/codegen_expr.py index 6e84e8a6..d8c3295 100644 --- a/third_party/blink/renderer/bindings/scripts/bind_gen/codegen_expr.py +++ b/third_party/blink/renderer/bindings/scripts/bind_gen/codegen_expr.py
@@ -147,9 +147,9 @@ def expr_from_exposure(exposure, global_names=None): """ Args: - exposure: web_idl.Exposure - in_global: A global name of [Exposed] that the ExecutionContext is - supposed to be / represent. + exposure: web_idl.Exposure of the target construct. + global_names: When specified, it's taken into account that the global + object implements |global_names|. """ assert isinstance(exposure, web_idl.Exposure) assert (global_names is None @@ -157,7 +157,9 @@ and all(isinstance(name, str) for name in global_names))) def ref_enabled(feature): - return _Expr("RuntimeEnabledFeatures::{}Enabled()".format(feature)) + arg = "${execution_context}" if feature.is_context_dependent else "" + return _Expr("RuntimeEnabledFeatures::{}Enabled({})".format( + feature, arg)) top_terms = [_Expr(True)] @@ -175,15 +177,25 @@ "Worklet": "IsWorkletGlobalScope", } exposed_terms = [] - for entry in exposure.global_names_and_features: - terms = [] - if entry.global_name not in (global_names or []): + if global_names is None: + for entry in exposure.global_names_and_features: + terms = [] pred = GLOBAL_NAME_TO_EXECUTION_CONTEXT_TEST[entry.global_name] terms.append(_Expr("${{execution_context}}->{}()".format(pred))) - if entry.feature: - terms.append(ref_enabled(entry.feature)) - if terms: - exposed_terms.append(expr_and(terms)) + if entry.feature: + terms.append(ref_enabled(entry.feature)) + if terms: + exposed_terms.append(expr_and(terms)) + else: + matched_global_count = 0 + for entry in exposure.global_names_and_features: + if entry.global_name not in global_names: + continue + matched_global_count += 1 + if entry.feature: + exposed_terms.append(ref_enabled(entry.feature)) + assert (not exposure.global_names_and_features + or matched_global_count > 0) if exposed_terms: top_terms.append(expr_or(exposed_terms))
diff --git a/third_party/blink/renderer/bindings/scripts/bind_gen/interface.py b/third_party/blink/renderer/bindings/scripts/bind_gen/interface.py index 94748d8b..74f9ada 100644 --- a/third_party/blink/renderer/bindings/scripts/bind_gen/interface.py +++ b/third_party/blink/renderer/bindings/scripts/bind_gen/interface.py
@@ -78,14 +78,16 @@ if cg_context.attribute_get: kind = "AttributeGet" - if cg_context.attribute_set: + elif cg_context.attribute_set: kind = "AttributeSet" - if cg_context.constant: + elif cg_context.constant: kind = "Constant" - if cg_context.constructor_group: + elif cg_context.constructor_group: property_name = "" kind = "Constructor" - if cg_context.operation_group: + elif cg_context.exposed_construct: + kind = "ExposedConstruct" + elif cg_context.operation_group: kind = "Operation" if overload_index is None: @@ -95,9 +97,9 @@ if cg_context.for_world == CodeGenContext.MAIN_WORLD: world_suffix = "ForMainWorld" - if cg_context.for_world == CodeGenContext.NON_MAIN_WORLDS: + elif cg_context.for_world == CodeGenContext.NON_MAIN_WORLDS: world_suffix = "ForNonMainWorlds" - if cg_context.for_world == CodeGenContext.ALL_WORLDS: + elif cg_context.for_world == CodeGenContext.ALL_WORLDS: world_suffix = "" return name_style.func(property_name, kind, callback_suffix, world_suffix) @@ -107,7 +109,7 @@ assert isinstance(cg_context, CodeGenContext) assert cg_context.constant - property_name = cg_context.property_.identifier + property_name = cg_context.property_.identifier.lower() kind = "Constant" @@ -643,7 +645,8 @@ def make_log_activity(cg_context): assert isinstance(cg_context, CodeGenContext) - ext_attrs = cg_context.member_like.extended_attributes + target = cg_context.member_like or cg_context.property_ + ext_attrs = target.extended_attributes if "LogActivity" not in ext_attrs: return None target = ext_attrs.value_of("LogActivity") @@ -669,10 +672,10 @@ if cg_context.attribute_get: _1 = "LogGetter" _4 = "" - if cg_context.attribute_set: + elif cg_context.attribute_set: _1 = "LogSetter" _4 = ", ${info}[0]" - if cg_context.operation_group: + elif cg_context.operation_group: _1 = "LogMethod" _4 = ", ${info}" body = _format(pattern, _1=_1, _2=_2, _3=_3, _4=_4) @@ -936,7 +939,8 @@ def make_report_deprecate_as(cg_context): assert isinstance(cg_context, CodeGenContext) - name = cg_context.member_like.extended_attributes.value_of("DeprecateAs") + target = cg_context.member_like or cg_context.property_ + name = target.extended_attributes.value_of("DeprecateAs") if not name: return None @@ -954,7 +958,8 @@ def make_report_measure_as(cg_context): assert isinstance(cg_context, CodeGenContext) - ext_attrs = cg_context.member_like.extended_attributes + target = cg_context.member_like or cg_context.property_ + ext_attrs = target.extended_attributes if not ("Measure" in ext_attrs or "MeasureAs" in ext_attrs): assert "HighEntropy" not in ext_attrs, "{}: {}".format( cg_context.idl_location_and_name, @@ -969,9 +974,11 @@ suffix = "_AttributeSetter" elif cg_context.constructor: suffix = "_Constructor" + elif cg_context.exposed_construct: + suffix = "_ConstructorGetter" elif cg_context.operation: suffix = "_Method" - name = cg_context.member_like.extended_attributes.value_of("MeasureAs") + name = target.extended_attributes.value_of("MeasureAs") if name: name = "k{}".format(name) elif cg_context.constructor: @@ -979,8 +986,7 @@ else: name = "kV8{}_{}{}".format( cg_context.class_like.identifier, - name_style.raw.upper_camel_case(cg_context.member_like.identifier), - suffix) + name_style.raw.upper_camel_case(target.identifier), suffix) node = SequenceNode() @@ -1062,22 +1068,30 @@ def make_runtime_call_timer_scope(cg_context): assert isinstance(cg_context, CodeGenContext) - pattern = "RUNTIME_CALL_TIMER_SCOPE{_1}(${isolate}, {_2});" - _1 = "_DISABLED_BY_DEFAULT" + target = cg_context.member_like or cg_context.property_ + suffix = "" if cg_context.attribute_get: suffix = "_Getter" elif cg_context.attribute_set: suffix = "_Setter" - counter = cg_context.member_like.extended_attributes.value_of( - "RuntimeCallStatsCounter") + elif cg_context.exposed_construct: + suffix = "_ConstructorGetterCallback" + + counter = target.extended_attributes.value_of("RuntimeCallStatsCounter") if counter: - _2 = "k{}{}".format(counter, suffix) + macro_name = "RUNTIME_CALL_TIMER_SCOPE" + counter_name = "k{}{}".format(counter, suffix) else: - _2 = "\"Blink_{}_{}{}\"".format( - blink_class_name(cg_context.class_like), - cg_context.member_like.identifier, suffix) - node = TextNode(_format(pattern, _1=_1, _2=_2)) + macro_name = "RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT" + counter_name = "\"Blink_{}_{}{}\"".format( + blink_class_name(cg_context.class_like), target.identifier, suffix) + + node = TextNode( + _format( + "{macro_name}(${isolate}, {counter_name})", + macro_name=macro_name, + counter_name=counter_name)) node.accumulate( CodeGenAccumulator.require_include_headers([ "third_party/blink/renderer/platform/bindings/runtime_call_stats.h", @@ -1394,6 +1408,34 @@ return node +def make_exposed_construct_callback_def(cg_context, function_name): + assert isinstance(cg_context, CodeGenContext) + assert isinstance(function_name, str) + + func_def = _make_empty_callback_def( + cg_context, + function_name, + arg_decls=[ + "v8::Local<v8::Name> property", + "const v8::PropertyCallbackInfo<v8::Value>& info", + ]) + body = func_def.body + + v8_set_return_value = _format( + "V8SetReturnValueInterfaceObject(${info}, {}::GetWrapperTypeInfo());", + v8_bridge_class_name(cg_context.exposed_construct)) + body.extend([ + make_runtime_call_timer_scope(cg_context), + make_report_deprecate_as(cg_context), + make_report_measure_as(cg_context), + make_log_activity(cg_context), + TextNode(""), + TextNode(v8_set_return_value), + ]) + + return func_def + + def make_operation_function_def(cg_context, function_name): assert isinstance(cg_context, CodeGenContext) assert isinstance(function_name, str) @@ -1690,6 +1732,44 @@ ]) +def _make_exposed_construct_registration_table(table_name, + exposed_construct_entries): + assert isinstance(table_name, str) + assert isinstance(exposed_construct_entries, (list, tuple)) + assert all( + isinstance(entry, _PropEntryExposedConstruct) + for entry in exposed_construct_entries) + + T = TextNode + + entry_nodes = [] + for entry in exposed_construct_entries: + pattern = ("{{" + "\"{property_name}\", " + "{exposed_construct_callback}, " + "nullptr, " + "static_cast<v8::PropertyAttribute>(v8::DontEnum), " + "V8DOMConfiguration::kOnInstance, " + "V8DOMConfiguration::kDoNotCheckHolder, " + "V8DOMConfiguration::kHasNoSideEffect, " + "V8DOMConfiguration::kAlwaysCallGetter, " + "{world}" + "}}, ") + text = _format( + pattern, + property_name=entry.member.identifier, + exposed_construct_callback=entry.prop_callback_name, + world=_make_property_entry_world(entry.world)) + entry_nodes.append(T(text)) + + return ListNode([ + T("static constexpr V8DOMConfiguration::AttributeConfiguration " + + table_name + "[] = {"), + ListNode(entry_nodes), + T("};"), + ]) + + def _make_operation_registration_table(table_name, operation_entries): assert isinstance(table_name, str) assert isinstance(operation_entries, (list, tuple)) @@ -1785,6 +1865,17 @@ self.ctor_func_length = ctor_func_length +class _PropEntryExposedConstruct(_PropEntryMember): + def __init__(self, is_context_dependent, exposure_conditional, world, + exposed_construct, prop_callback_name): + assert isinstance(prop_callback_name, str) + + _PropEntryMember.__init__(self, is_context_dependent, + exposure_conditional, world, + exposed_construct) + self.prop_callback_name = prop_callback_name + + class _PropEntryOperationGroup(_PropEntryMember): def __init__(self, is_context_dependent, exposure_conditional, world, operation_group, op_callback_name, op_func_length): @@ -1800,7 +1891,7 @@ def _make_property_entries_and_callback_defs( cg_context, attribute_entries, constant_entries, constructor_entries, - operation_entries): + exposed_construct_entries, operation_entries): """ Creates intermediate objects to help property installation and also makes code nodes of callback functions. @@ -1808,6 +1899,7 @@ Args: attribute_entries: constructor_entries: + exposed_construct_entries: operation_entries: Output parameters to store the intermediate objects. """ @@ -1815,6 +1907,7 @@ assert isinstance(attribute_entries, list) assert isinstance(constant_entries, list) assert isinstance(constructor_entries, list) + assert isinstance(exposed_construct_entries, list) assert isinstance(operation_entries, list) interface = cg_context.interface @@ -1824,7 +1917,8 @@ def iterate(members, callback): for member in members: - is_context_dependent = member.exposure.is_context_dependent + is_context_dependent = member.exposure.is_context_dependent( + global_names) exposure_conditional = expr_from_exposure(member.exposure, global_names) @@ -1916,6 +2010,27 @@ ctor_func_length=( constructor_group.min_num_of_required_arguments))) + def process_exposed_construct(exposed_construct, is_context_dependent, + exposure_conditional, world): + cgc = cg_context.make_copy( + exposed_construct=exposed_construct, for_world=world) + prop_callback_name = callback_function_name(cgc) + prop_callback_node = make_exposed_construct_callback_def( + cgc, prop_callback_name) + + callback_def_nodes.extend([ + prop_callback_node, + TextNode(""), + ]) + + exposed_construct_entries.append( + _PropEntryExposedConstruct( + is_context_dependent=is_context_dependent, + exposure_conditional=exposure_conditional, + world=world, + exposed_construct=exposed_construct, + prop_callback_name=prop_callback_name)) + def process_operation_group(operation_group, is_context_dependent, exposure_conditional, world): cgc = cg_context.make_copy( @@ -1940,6 +2055,7 @@ iterate(interface.attributes, process_attribute) iterate(interface.constants, process_constant) iterate(interface.constructor_groups, process_constructor_group) + iterate(interface.exposed_constructs, process_exposed_construct) iterate(interface.operation_groups, process_operation_group) return callback_def_nodes @@ -2068,7 +2184,7 @@ def make_install_properties(cg_context, function_name, class_name, trampoline_var_name, is_context_dependent, attribute_entries, constant_entries, - operation_entries): + exposed_construct_entries, operation_entries): """ Returns: A triplet of CodeNode of: @@ -2088,12 +2204,17 @@ assert isinstance(constant_entries, (list, tuple)) assert all( isinstance(entry, _PropEntryConstant) for entry in constant_entries) + assert isinstance(exposed_construct_entries, (list, tuple)) + assert all( + isinstance(entry, _PropEntryExposedConstruct) + for entry in exposed_construct_entries) assert isinstance(operation_entries, (list, tuple)) assert all( isinstance(entry, _PropEntryOperationGroup) for entry in operation_entries) - if not (attribute_entries or constant_entries or operation_entries): + if not (attribute_entries or constant_entries or exposed_construct_entries + or operation_entries): return None, None, None if is_context_dependent: @@ -2258,6 +2379,21 @@ _make_constant_value_registration_table, installer_call_text) + table_name = "kExposedConstructTable" + if is_context_dependent: + installer_call_text = ( + "V8DOMConfiguration::InstallAttributes(${isolate}, ${world}, " + "${instance_object}, ${prototype_object}, " + "kExposedConstructTable, base::size(kExposedConstructTable));") + else: + installer_call_text = ( + "V8DOMConfiguration::InstallAttributes(${isolate}, ${world}, " + "${instance_template}, ${prototype_template}, " + "kExposedConstructTable, base::size(kExposedConstructTable));") + install_properties(table_name, exposed_construct_entries, + _make_exposed_construct_registration_table, + installer_call_text) + table_name = "kOperationTable" if is_context_dependent: installer_call_text = ( @@ -2340,7 +2476,7 @@ is_cross_components = path_manager.is_cross_components # Class names - api_class_name = name_style.class_("v8", interface.identifier) + api_class_name = v8_bridge_class_name(interface) if is_cross_components: impl_class_name = name_style.class_(api_class_name, "impl") else: @@ -2437,12 +2573,14 @@ attribute_entries = [] constant_entries = [] constructor_entries = [] + exposed_construct_entries = [] operation_entries = [] callback_defs = _make_property_entries_and_callback_defs( cg_context, attribute_entries=attribute_entries, constant_entries=constant_entries, constructor_entries=constructor_entries, + exposed_construct_entries=exposed_construct_entries, operation_entries=operation_entries) # Installer functions @@ -2459,6 +2597,8 @@ is_context_dependent=False, attribute_entries=filter(is_unconditional, attribute_entries), constant_entries=filter(is_unconditional, constant_entries), + exposed_construct_entries=filter(is_unconditional, + exposed_construct_entries), operation_entries=filter(is_unconditional, operation_entries)) (install_context_independent_props_decl, install_context_independent_props_def, @@ -2470,6 +2610,8 @@ is_context_dependent=False, attribute_entries=filter(is_context_independent, attribute_entries), constant_entries=filter(is_context_independent, constant_entries), + exposed_construct_entries=filter(is_context_independent, + exposed_construct_entries), operation_entries=filter(is_context_independent, operation_entries)) (install_context_dependent_props_decl, install_context_dependent_props_def, install_context_dependent_props_trampoline) = make_install_properties( @@ -2480,6 +2622,8 @@ is_context_dependent=True, attribute_entries=filter(is_context_dependent, attribute_entries), constant_entries=filter(is_context_dependent, constant_entries), + exposed_construct_entries=filter(is_context_dependent, + exposed_construct_entries), operation_entries=filter(is_context_dependent, operation_entries)) (install_interface_template_decl, install_interface_template_def, install_interface_template_trampoline) = make_install_interface_template( @@ -2620,5 +2764,5 @@ def generate_interfaces(web_idl_database): - interface = web_idl_database.find("Node") + interface = web_idl_database.find("Window") generate_interface(interface)
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/exposure.py b/third_party/blink/renderer/bindings/scripts/web_idl/exposure.py index 5c4bcbc..46e2e45 100644 --- a/third_party/blink/renderer/bindings/scripts/web_idl/exposure.py +++ b/third_party/blink/renderer/bindings/scripts/web_idl/exposure.py
@@ -5,13 +5,29 @@ from .runtime_enabled_features import RuntimeEnabledFeatures +class _Feature(str): + """Represents a runtime-enabled feature.""" + + def __init__(self, value): + str.__init__(self, value) + self._is_context_dependent = ( + RuntimeEnabledFeatures.is_context_dependent(self)) + + @property + def is_context_dependent(self): + return self._is_context_dependent + + class _GlobalNameAndFeature(object): def __init__(self, global_name, feature=None): assert isinstance(global_name, str) assert feature is None or isinstance(feature, str) self._global_name = global_name - self._feature = feature + if feature is None: + self._feature = None + else: + self._feature = _Feature(feature) @property def global_name(self): @@ -23,6 +39,8 @@ class Exposure(object): + """Represents a set of conditions under which the construct is exposed.""" + def __init__(self, other=None): assert other is None or isinstance(other, Exposure) @@ -94,15 +112,33 @@ return False return self._only_in_secure_contexts - @property - def is_context_dependent(self): + def is_context_dependent(self, global_names=None): """ Returns True if the exposure of this construct depends on a context. + + Args: + global_names: When specified, it's taken into account that the + global object implements |global_names|. """ - return bool(self.global_names_and_features - or self.context_dependent_runtime_enabled_features - or self.context_enabled_features - or self.only_in_secure_contexts) + assert (global_names is None + or (isinstance(global_names, (list, tuple)) + and all(isinstance(name, str) for name in global_names))) + + if (self.context_dependent_runtime_enabled_features + or self.context_enabled_features + or self.only_in_secure_contexts): + return True + + if not global_names: + return bool(self.global_names_and_features) + + is_context_dependent = False + for entry in self.global_names_and_features: + if entry.global_name not in global_names: + continue + if entry.feature and entry.feature.is_context_dependent: + is_context_dependent = True + return is_context_dependent class ExposureMutable(Exposure): @@ -128,11 +164,12 @@ def add_runtime_enabled_feature(self, name): assert isinstance(name, str) - if RuntimeEnabledFeatures.is_context_dependent(name): - self._context_dependent_runtime_enabled_features.append(name) + feature = _Feature(name) + if feature.is_context_dependent: + self._context_dependent_runtime_enabled_features.append(feature) else: - self._context_independent_runtime_enabled_features.append(name) - self._runtime_enabled_features.append(name) + self._context_independent_runtime_enabled_features.append(feature) + self._runtime_enabled_features.append(feature) def add_context_enabled_feature(self, name): assert isinstance(name, str) @@ -146,6 +183,6 @@ if isinstance(value, bool): self._only_in_secure_contexts = value elif isinstance(value, str): - self._only_in_secure_contexts = (value, ) + self._only_in_secure_contexts = (_Feature(value), ) else: - self._only_in_secure_contexts = tuple(value) + self._only_in_secure_contexts = tuple(map(_Feature, value))
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/extended_attribute.py b/third_party/blink/renderer/bindings/scripts/web_idl/extended_attribute.py index 0c73cae..52c04173 100644 --- a/third_party/blink/renderer/bindings/scripts/web_idl/extended_attribute.py +++ b/third_party/blink/renderer/bindings/scripts/web_idl/extended_attribute.py
@@ -280,5 +280,11 @@ class ExtendedAttributesMutable(ExtendedAttributes): + def __getstate__(self): + assert False, "ExtendedAttributesMutable must not be pickled." + + def __setstate__(self, state): + assert False, "ExtendedAttributesMutable must not be pickled." + def append(self, ext_attr): self._append(ext_attr)
diff --git a/third_party/blink/renderer/core/animation/basic_shape_interpolation_functions.cc b/third_party/blink/renderer/core/animation/basic_shape_interpolation_functions.cc index 8fd75310..9cecc2c 100644 --- a/third_party/blink/renderer/core/animation/basic_shape_interpolation_functions.cc +++ b/third_party/blink/renderer/core/animation/basic_shape_interpolation_functions.cc
@@ -216,7 +216,7 @@ const InterpolableValue& interpolable_value, const CSSToLengthConversionData& conversion_data) { scoped_refptr<BasicShapeCircle> circle = BasicShapeCircle::Create(); - const InterpolableList& list = ToInterpolableList(interpolable_value); + const auto& list = To<InterpolableList>(interpolable_value); circle->SetCenterX( CreateCoordinate(*list.Get(kCircleCenterXIndex), conversion_data)); circle->SetCenterY( @@ -289,7 +289,7 @@ const InterpolableValue& interpolable_value, const CSSToLengthConversionData& conversion_data) { scoped_refptr<BasicShapeEllipse> ellipse = BasicShapeEllipse::Create(); - const InterpolableList& list = ToInterpolableList(interpolable_value); + const auto& list = To<InterpolableList>(interpolable_value); ellipse->SetCenterX( CreateCoordinate(*list.Get(kEllipseCenterXIndex), conversion_data)); ellipse->SetCenterY( @@ -408,7 +408,7 @@ const InterpolableValue& interpolable_value, const CSSToLengthConversionData& conversion_data) { scoped_refptr<BasicShapeInset> inset = BasicShapeInset::Create(); - const InterpolableList& list = ToInterpolableList(interpolable_value); + const auto& list = To<InterpolableList>(interpolable_value); inset->SetTop(To<InterpolableLength>(*list.Get(kInsetTopIndex)) .CreateLength(conversion_data, kValueRangeAll)); inset->SetRight(To<InterpolableLength>(*list.Get(kInsetRightIndex)) @@ -473,7 +473,7 @@ const CSSToLengthConversionData& conversion_data) { scoped_refptr<BasicShapePolygon> polygon = BasicShapePolygon::Create(); polygon->SetWindRule(non_interpolable_value.GetWindRule()); - const InterpolableList& list = ToInterpolableList(interpolable_value); + const auto& list = To<InterpolableList>(interpolable_value); wtf_size_t size = non_interpolable_value.size(); DCHECK_EQ(list.length(), size); DCHECK_EQ(size % 2, 0U);
diff --git a/third_party/blink/renderer/core/animation/css/css_animations.cc b/third_party/blink/renderer/core/animation/css/css_animations.cc index 6b59621..cea1599 100644 --- a/third_party/blink/renderer/core/animation/css/css_animations.cc +++ b/third_party/blink/renderer/core/animation/css/css_animations.cc
@@ -213,7 +213,7 @@ DCHECK_LE(sample.size(), 1u); if (sample.IsEmpty()) return nullptr; - return ToTransitionInterpolation(*sample.at(0)).GetInterpolatedValue(); + return To<TransitionInterpolation>(*sample.at(0)).GetInterpolatedValue(); } // Returns the start time of an animation given the start delay. A negative
diff --git a/third_party/blink/renderer/core/animation/css_angle_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_angle_interpolation_type.cc index 832abb8..df1685a 100644 --- a/third_party/blink/renderer/core/animation/css_angle_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_angle_interpolation_type.cc
@@ -30,7 +30,7 @@ const InterpolableValue& value, const NonInterpolableValue*, const StyleResolverState&) const { - return CSSNumericLiteralValue::Create(ToInterpolableNumber(value).Value(), + return CSSNumericLiteralValue::Create(To<InterpolableNumber>(value).Value(), CSSPrimitiveValue::UnitType::kDegrees); }
diff --git a/third_party/blink/renderer/core/animation/css_border_image_length_box_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_border_image_length_box_interpolation_type.cc index fb5cbf7..8da39b29f 100644 --- a/third_party/blink/renderer/core/animation/css_border_image_length_box_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_border_image_length_box_interpolation_type.cc
@@ -375,14 +375,14 @@ const InterpolableValue& interpolable_value, const NonInterpolableValue* non_interpolable_value, StyleResolverState& state) const { - const InterpolableList& list = ToInterpolableList(interpolable_value); + const auto& list = To<InterpolableList>(interpolable_value); const NonInterpolableList& non_interpolable_list = ToNonInterpolableList(*non_interpolable_value); const auto& convert_side = [&list, &non_interpolable_list, &state](wtf_size_t index) -> BorderImageLength { switch (GetSideType(non_interpolable_list.Get(index))) { case SideType::kNumber: - return clampTo<double>(ToInterpolableNumber(list.Get(index))->Value(), + return clampTo<double>(To<InterpolableNumber>(list.Get(index))->Value(), 0); case SideType::kAuto: return Length::Auto();
diff --git a/third_party/blink/renderer/core/animation/css_clip_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_clip_interpolation_type.cc index f73e0c3..28bd63a 100644 --- a/third_party/blink/renderer/core/animation/css_clip_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_clip_interpolation_type.cc
@@ -275,7 +275,7 @@ StyleResolverState& state) const { const ClipAutos& autos = ToCSSClipNonInterpolableValue(non_interpolable_value)->GetClipAutos(); - const InterpolableList& list = ToInterpolableList(interpolable_value); + const auto& list = To<InterpolableList>(interpolable_value); const auto& convert_index = [&list, &state](bool is_auto, wtf_size_t index) { if (is_auto) return Length::Auto();
diff --git a/third_party/blink/renderer/core/animation/css_color_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_color_interpolation_type.cc index 1b38fa5a..469d4c0 100644 --- a/third_party/blink/renderer/core/animation/css_color_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_color_interpolation_type.cc
@@ -114,16 +114,16 @@ const StyleResolverState& state, bool is_visited, bool is_text_decoration) { - const InterpolableList& list = ToInterpolableList(interpolable_color); + const auto& list = To<InterpolableList>(interpolable_color); DCHECK_EQ(list.length(), kInterpolableColorIndexCount); - double red = ToInterpolableNumber(list.Get(kRed))->Value(); - double green = ToInterpolableNumber(list.Get(kGreen))->Value(); - double blue = ToInterpolableNumber(list.Get(kBlue))->Value(); - double alpha = ToInterpolableNumber(list.Get(kAlpha))->Value(); + double red = To<InterpolableNumber>(list.Get(kRed))->Value(); + double green = To<InterpolableNumber>(list.Get(kGreen))->Value(); + double blue = To<InterpolableNumber>(list.Get(kBlue))->Value(); + double alpha = To<InterpolableNumber>(list.Get(kAlpha))->Value(); if (double currentcolor_fraction = - ToInterpolableNumber(list.Get(kCurrentcolor))->Value()) { + To<InterpolableNumber>(list.Get(kCurrentcolor))->Value()) { auto current_color_getter = is_visited ? ColorPropertyFunctions::GetVisitedColor : ColorPropertyFunctions::GetUnvisitedColor; @@ -146,16 +146,16 @@ } const TextLinkColors& colors = state.GetDocument().GetTextLinkColors(); if (double webkit_activelink_fraction = - ToInterpolableNumber(list.Get(kWebkitActivelink))->Value()) + To<InterpolableNumber>(list.Get(kWebkitActivelink))->Value()) AddPremultipliedColor(red, green, blue, alpha, webkit_activelink_fraction, colors.ActiveLinkColor()); if (double webkit_link_fraction = - ToInterpolableNumber(list.Get(kWebkitLink))->Value()) + To<InterpolableNumber>(list.Get(kWebkitLink))->Value()) AddPremultipliedColor( red, green, blue, alpha, webkit_link_fraction, is_visited ? colors.VisitedLinkColor() : colors.LinkColor()); if (double quirk_inherit_fraction = - ToInterpolableNumber(list.Get(kQuirkInherit))->Value()) + To<InterpolableNumber>(list.Get(kQuirkInherit))->Value()) AddPremultipliedColor(red, green, blue, alpha, quirk_inherit_fraction, colors.TextColor()); @@ -274,7 +274,7 @@ const InterpolableValue& interpolable_value, const NonInterpolableValue*, StyleResolverState& state) const { - const InterpolableList& color_pair = ToInterpolableList(interpolable_value); + const auto& color_pair = To<InterpolableList>(interpolable_value); DCHECK_EQ(color_pair.length(), kInterpolableColorPairIndexCount); ColorPropertyFunctions::SetUnvisitedColor( CssProperty(), *state.Style(), @@ -292,7 +292,7 @@ const InterpolableValue& interpolable_value, const NonInterpolableValue*, const StyleResolverState& state) const { - const InterpolableList& color_pair = ToInterpolableList(interpolable_value); + const auto& color_pair = To<InterpolableList>(interpolable_value); Color color = ResolveInterpolableColor(*color_pair.Get(kUnvisited), state); return cssvalue::CSSColorValue::Create(color.Rgb()); } @@ -304,26 +304,23 @@ double interpolation_fraction) const { DCHECK(!underlying_value_owner.Value().non_interpolable_value); DCHECK(!value.non_interpolable_value); - InterpolableList& underlying_list = ToInterpolableList( + auto& underlying_list = To<InterpolableList>( *underlying_value_owner.MutableValue().interpolable_value); - const InterpolableList& other_list = - ToInterpolableList(*value.interpolable_value); + const auto& other_list = To<InterpolableList>(*value.interpolable_value); // Both lists should have kUnvisited and kVisited. DCHECK(underlying_list.length() == kInterpolableColorPairIndexCount); DCHECK(other_list.length() == kInterpolableColorPairIndexCount); for (wtf_size_t i = 0; i < underlying_list.length(); i++) { - InterpolableList& underlying = - ToInterpolableList(*underlying_list.GetMutable(i)); - const InterpolableList& other = ToInterpolableList(*other_list.Get(i)); + auto& underlying = To<InterpolableList>(*underlying_list.GetMutable(i)); + const auto& other = To<InterpolableList>(*other_list.Get(i)); DCHECK(underlying.length() == kInterpolableColorIndexCount); DCHECK(other.length() == kInterpolableColorIndexCount); for (wtf_size_t j = 0; j < underlying.length(); j++) { DCHECK(underlying.Get(j)->IsNumber()); DCHECK(other.Get(j)->IsNumber()); - InterpolableNumber& underlying_number = - ToInterpolableNumber(*underlying.GetMutable(j)); - const InterpolableNumber& other_number = - ToInterpolableNumber(*other.Get(j)); + auto& underlying_number = + To<InterpolableNumber>(*underlying.GetMutable(j)); + const auto& other_number = To<InterpolableNumber>(*other.Get(j)); if (j != kAlpha || underlying_number.Value() != other_number.Value()) underlying_number.ScaleAndAdd(underlying_fraction, other_number); }
diff --git a/third_party/blink/renderer/core/animation/css_custom_list_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_custom_list_interpolation_type.cc index 1a787a8..61ded28d 100644 --- a/third_party/blink/renderer/core/animation/css_custom_list_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_custom_list_interpolation_type.cc
@@ -56,8 +56,7 @@ const InterpolableValue& interpolable_value, const NonInterpolableValue* non_interpolable_value, const StyleResolverState& state) const { - const InterpolableList& interpolable_list = - ToInterpolableList(interpolable_value); + const auto& interpolable_list = To<InterpolableList>(interpolable_value); const NonInterpolableList* non_interpolable_list = non_interpolable_value ? &ToNonInterpolableList(*non_interpolable_value) : nullptr;
diff --git a/third_party/blink/renderer/core/animation/css_filter_list_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_filter_list_interpolation_type.cc index 1c8e68f..06caf9e 100644 --- a/third_party/blink/renderer/core/animation/css_filter_list_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_filter_list_interpolation_type.cc
@@ -63,8 +63,8 @@ bool IsValid(const StyleResolverState&, const InterpolationValue& underlying) const final { - const InterpolableList& underlying_list = - ToInterpolableList(*underlying.interpolable_value); + const auto& underlying_list = + To<InterpolableList>(*underlying.interpolable_value); if (underlying_list.length() != types_.size()) return false; for (wtf_size_t i = 0; i < types_.size(); i++) { @@ -129,8 +129,8 @@ InterpolationValue CSSFilterListInterpolationType::MaybeConvertNeutral( const InterpolationValue& underlying, ConversionCheckers& conversion_checkers) const { - const InterpolableList* interpolable_list = - ToInterpolableList(underlying.interpolable_value.get()); + const auto* interpolable_list = + To<InterpolableList>(underlying.interpolable_value.get()); conversion_checkers.push_back( std::make_unique<UnderlyingFilterListChecker>(interpolable_list)); // The neutral value for composition for a filter list is the empty list, as @@ -191,10 +191,9 @@ PairwiseInterpolationValue CSSFilterListInterpolationType::MaybeMergeSingles( InterpolationValue&& start, InterpolationValue&& end) const { - InterpolableList& start_interpolable_list = - ToInterpolableList(*start.interpolable_value); - InterpolableList& end_interpolable_list = - ToInterpolableList(*end.interpolable_value); + auto& start_interpolable_list = + To<InterpolableList>(*start.interpolable_value); + auto& end_interpolable_list = To<InterpolableList>(*end.interpolable_value); wtf_size_t start_length = start_interpolable_list.length(); wtf_size_t end_length = end_interpolable_list.length(); @@ -252,8 +251,7 @@ const InterpolableValue& interpolable_value, const NonInterpolableValue* non_interpolable_value, StyleResolverState& state) const { - const InterpolableList& interpolable_list = - ToInterpolableList(interpolable_value); + const auto& interpolable_list = To<InterpolableList>(interpolable_value); wtf_size_t length = interpolable_list.length(); FilterOperations filter_operations; @@ -290,9 +288,9 @@ return nullptr; auto interpolable_list = std::unique_ptr<InterpolableList>( - ToInterpolableList(value.interpolable_value.release())); - const InterpolableList& underlying_list = - ToInterpolableList(*underlying.interpolable_value); + To<InterpolableList>(value.interpolable_value.release())); + const auto& underlying_list = + To<InterpolableList>(*underlying.interpolable_value); if (composite == EffectModel::CompositeOperation::kCompositeAdd) { return PerformAdditiveComposition(std::move(interpolable_list),
diff --git a/third_party/blink/renderer/core/animation/css_font_variation_settings_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_font_variation_settings_interpolation_type.cc index 6262ba2..5d5cef7 100644 --- a/third_party/blink/renderer/core/animation/css_font_variation_settings_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_font_variation_settings_interpolation_type.cc
@@ -194,7 +194,7 @@ const InterpolableValue& interpolable_value, const NonInterpolableValue* non_interpolable_value, StyleResolverState& state) const { - const InterpolableList& numbers = ToInterpolableList(interpolable_value); + const auto& numbers = To<InterpolableList>(interpolable_value); const Vector<AtomicString>& tags = GetTags(*non_interpolable_value); DCHECK_EQ(numbers.length(), tags.size()); @@ -205,7 +205,7 @@ for (wtf_size_t i = 0; i < length; ++i) { settings->Append(FontVariationAxis( tags[i], - clampTo<float>(ToInterpolableNumber(numbers.Get(i))->Value()))); + clampTo<float>(To<InterpolableNumber>(numbers.Get(i))->Value()))); } state.GetFontBuilder().SetVariationSettings(settings); }
diff --git a/third_party/blink/renderer/core/animation/css_font_weight_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_font_weight_interpolation_type.cc index b3c5a38..9870c5ec5 100644 --- a/third_party/blink/renderer/core/animation/css_font_weight_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_font_weight_interpolation_type.cc
@@ -109,7 +109,7 @@ const NonInterpolableValue*, StyleResolverState& state) const { state.GetFontBuilder().SetWeight(FontSelectionValue( - clampTo(ToInterpolableNumber(interpolable_value).Value(), + clampTo(To<InterpolableNumber>(interpolable_value).Value(), MinWeightValue(), MaxWeightValue()))); }
diff --git a/third_party/blink/renderer/core/animation/css_image_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_image_interpolation_type.cc index 4d48e5a..6033e9d 100644 --- a/third_party/blink/renderer/core/animation/css_image_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_image_interpolation_type.cc
@@ -138,7 +138,7 @@ const InterpolableValue& interpolable_value, const NonInterpolableValue* non_interpolable_value) { return ToCSSImageNonInterpolableValue(non_interpolable_value) - ->Crossfade(ToInterpolableNumber(interpolable_value).Value()); + ->Crossfade(To<InterpolableNumber>(interpolable_value).Value()); } StyleImage* CSSImageInterpolationType::ResolveStyleImage(
diff --git a/third_party/blink/renderer/core/animation/css_image_list_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_image_list_interpolation_type.cc index 9acb1cf..03212b9 100644 --- a/third_party/blink/renderer/core/animation/css_image_list_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_image_list_interpolation_type.cc
@@ -167,8 +167,7 @@ const InterpolableValue& interpolable_value, const NonInterpolableValue* non_interpolable_value, StyleResolverState& state) const { - const InterpolableList& interpolable_list = - ToInterpolableList(interpolable_value); + const auto& interpolable_list = To<InterpolableList>(interpolable_value); const wtf_size_t length = interpolable_list.length(); DCHECK_GT(length, 0U); const NonInterpolableList& non_interpolable_list =
diff --git a/third_party/blink/renderer/core/animation/css_image_slice_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_image_slice_interpolation_type.cc index 2686262f..afbe0dc 100644 --- a/third_party/blink/renderer/core/animation/css_image_slice_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_image_slice_interpolation_type.cc
@@ -265,12 +265,12 @@ const NonInterpolableValue* non_interpolable_value, StyleResolverState& state) const { ComputedStyle& style = *state.Style(); - const InterpolableList& list = ToInterpolableList(interpolable_value); + const auto& list = To<InterpolableList>(interpolable_value); const SliceTypes& types = ToCSSImageSliceNonInterpolableValue(non_interpolable_value)->Types(); const auto& convert_side = [&types, &list, &style](wtf_size_t index) { float value = - clampTo<float>(ToInterpolableNumber(list.Get(index))->Value(), 0); + clampTo<float>(To<InterpolableNumber>(list.Get(index))->Value(), 0); return types.is_number[index] ? Length::Fixed(value * style.EffectiveZoom()) : Length::Percent(value); };
diff --git a/third_party/blink/renderer/core/animation/css_length_list_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_length_list_interpolation_type.cc index 07864c91..a8b494a9 100644 --- a/third_party/blink/renderer/core/animation/css_length_list_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_length_list_interpolation_type.cc
@@ -164,8 +164,7 @@ const InterpolableValue& interpolable_value, const NonInterpolableValue* non_interpolable_value, StyleResolverState& state) const { - const InterpolableList& interpolable_list = - ToInterpolableList(interpolable_value); + const auto& interpolable_list = To<InterpolableList>(interpolable_value); const wtf_size_t length = interpolable_list.length(); DCHECK_GT(length, 0U); const NonInterpolableList& non_interpolable_list =
diff --git a/third_party/blink/renderer/core/animation/css_number_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_number_interpolation_type.cc index 54893a3..e24be066 100644 --- a/third_party/blink/renderer/core/animation/css_number_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_number_interpolation_type.cc
@@ -38,7 +38,7 @@ const InterpolableValue& value, const NonInterpolableValue*, const StyleResolverState&) const { - double number = ToInterpolableNumber(value).Value(); + double number = To<InterpolableNumber>(value).Value(); return CSSNumericLiteralValue::Create( round_to_integer_ ? round(number) : number, CSSPrimitiveValue::UnitType::kNumber); @@ -105,7 +105,7 @@ const NonInterpolableValue*, StyleResolverState& state) const { double clamped_number = NumberPropertyFunctions::ClampNumber( - CssProperty(), ToInterpolableNumber(interpolable_value).Value()); + CssProperty(), To<InterpolableNumber>(interpolable_value).Value()); if (!NumberPropertyFunctions::SetNumber(CssProperty(), *state.Style(), clamped_number)) { StyleBuilder::ApplyProperty(
diff --git a/third_party/blink/renderer/core/animation/css_offset_rotate_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_offset_rotate_interpolation_type.cc index eb886c3..b593944 100644 --- a/third_party/blink/renderer/core/animation/css_offset_rotate_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_offset_rotate_interpolation_type.cc
@@ -164,7 +164,7 @@ const NonInterpolableValue* non_interpolable_value, StyleResolverState& state) const { state.Style()->SetOffsetRotate(StyleOffsetRotation( - clampTo<float>(ToInterpolableNumber(interpolable_value).Value()), + clampTo<float>(To<InterpolableNumber>(interpolable_value).Value()), ToCSSOffsetRotationNonInterpolableValue(*non_interpolable_value) .RotationType())); }
diff --git a/third_party/blink/renderer/core/animation/css_percentage_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_percentage_interpolation_type.cc index 46408b17..0164fad 100644 --- a/third_party/blink/renderer/core/animation/css_percentage_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_percentage_interpolation_type.cc
@@ -30,7 +30,7 @@ const NonInterpolableValue*, const StyleResolverState&) const { return CSSNumericLiteralValue::Create( - ToInterpolableNumber(value).Value(), + To<InterpolableNumber>(value).Value(), CSSPrimitiveValue::UnitType::kPercentage); }
diff --git a/third_party/blink/renderer/core/animation/css_ray_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_ray_interpolation_type.cc index 76f6140..3eb8265 100644 --- a/third_party/blink/renderer/core/animation/css_ray_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_ray_interpolation_type.cc
@@ -116,7 +116,7 @@ const CSSRayNonInterpolableValue& ray_non_interpolable_value = ToCSSRayNonInterpolableValue(*non_interpolable_value); state.Style()->SetOffsetPath( - StyleRay::Create(ToInterpolableNumber(interpolable_value).Value(), + StyleRay::Create(To<InterpolableNumber>(interpolable_value).Value(), ray_non_interpolable_value.Mode().Size(), ray_non_interpolable_value.Mode().Contain())); }
diff --git a/third_party/blink/renderer/core/animation/css_resolution_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_resolution_interpolation_type.cc index 14756aa..726f7879 100644 --- a/third_party/blink/renderer/core/animation/css_resolution_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_resolution_interpolation_type.cc
@@ -31,7 +31,7 @@ const NonInterpolableValue*, const StyleResolverState&) const { return CSSNumericLiteralValue::Create( - ToInterpolableNumber(value).Value(), + To<InterpolableNumber>(value).Value(), CSSPrimitiveValue::UnitType::kDotsPerPixel); }
diff --git a/third_party/blink/renderer/core/animation/css_rotate_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_rotate_interpolation_type.cc index cf28f05..c3e09166 100644 --- a/third_party/blink/renderer/core/animation/css_rotate_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_rotate_interpolation_type.cc
@@ -250,7 +250,7 @@ *underlying_value_owner.Value().non_interpolable_value); const CSSRotateNonInterpolableValue& non_interpolable_value = ToCSSRotateNonInterpolableValue(*value.non_interpolable_value); - double progress = ToInterpolableNumber(*value.interpolable_value).Value(); + double progress = To<InterpolableNumber>(*value.interpolable_value).Value(); underlying_value_owner.MutableValue().non_interpolable_value = underlying_non_interpolable_value.Composite(non_interpolable_value, progress); @@ -260,7 +260,7 @@ const InterpolableValue& interpolable_value, const NonInterpolableValue* untyped_non_interpolable_value, StyleResolverState& state) const { - double progress = ToInterpolableNumber(interpolable_value).Value(); + double progress = To<InterpolableNumber>(interpolable_value).Value(); const CSSRotateNonInterpolableValue& non_interpolable_value = ToCSSRotateNonInterpolableValue(*untyped_non_interpolable_value); OptionalRotation rotation = non_interpolable_value.SlerpedRotation(progress);
diff --git a/third_party/blink/renderer/core/animation/css_scale_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_scale_interpolation_type.cc index 3efeb2b..40cc315 100644 --- a/third_party/blink/renderer/core/animation/css_scale_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_scale_interpolation_type.cc
@@ -27,14 +27,14 @@ Init(1, 1, 1, true); } explicit Scale(const InterpolableValue& value) { - const InterpolableList& list = ToInterpolableList(value); + const auto& list = To<InterpolableList>(value); if (list.length() == 0) { Init(1, 1, 1, true); return; } - Init(ToInterpolableNumber(*list.Get(0)).Value(), - ToInterpolableNumber(*list.Get(1)).Value(), - ToInterpolableNumber(*list.Get(2)).Value(), false); + Init(To<InterpolableNumber>(*list.Get(0)).Value(), + To<InterpolableNumber>(*list.Get(1)).Value(), + To<InterpolableNumber>(*list.Get(2)).Value(), false); } void Init(double x, double y, double z, bool is_value_none) { @@ -207,9 +207,9 @@ InterpolationValue&& start, InterpolationValue&& end) const { wtf_size_t start_list_length = - ToInterpolableList(*start.interpolable_value).length(); + To<InterpolableList>(*start.interpolable_value).length(); wtf_size_t end_list_length = - ToInterpolableList(*end.interpolable_value).length(); + To<InterpolableList>(*end.interpolable_value).length(); if (start_list_length < end_list_length) start.interpolable_value = CreateScaleIdentity(); else if (end_list_length < start_list_length) @@ -233,7 +233,7 @@ double underlying_fraction, const InterpolationValue& value, double interpolation_fraction) const { - if (ToInterpolableList( + if (To<InterpolableList>( *underlying_value_owner.MutableValue().interpolable_value) .length() == 0) { underlying_value_owner.MutableValue().interpolable_value = @@ -244,11 +244,10 @@ ToCSSScaleNonInterpolableValue(*value.non_interpolable_value); DCHECK(metadata.IsStartAdditive() || metadata.IsEndAdditive()); - InterpolableList& underlying_list = ToInterpolableList( + auto& underlying_list = To<InterpolableList>( *underlying_value_owner.MutableValue().interpolable_value); for (wtf_size_t i = 0; i < 3; i++) { - InterpolableNumber& underlying = - ToInterpolableNumber(*underlying_list.GetMutable(i)); + auto& underlying = To<InterpolableNumber>(*underlying_list.GetMutable(i)); double start = metadata.Start().array[i] * (metadata.IsStartAdditive() ? underlying.Value() : 1);
diff --git a/third_party/blink/renderer/core/animation/css_shadow_list_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_shadow_list_interpolation_type.cc index 32e5a11..2f55ee0 100644 --- a/third_party/blink/renderer/core/animation/css_shadow_list_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_shadow_list_interpolation_type.cc
@@ -160,8 +160,7 @@ const InterpolableValue& interpolable_value, const NonInterpolableValue* non_interpolable_value, const StyleResolverState& state) { - const InterpolableList& interpolable_list = - ToInterpolableList(interpolable_value); + const auto& interpolable_list = To<InterpolableList>(interpolable_value); wtf_size_t length = interpolable_list.length(); if (length == 0) return nullptr;
diff --git a/third_party/blink/renderer/core/animation/css_size_list_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_size_list_interpolation_type.cc index 7ae4e510..85d5f6c 100644 --- a/third_party/blink/renderer/core/animation/css_size_list_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_size_list_interpolation_type.cc
@@ -175,7 +175,7 @@ const InterpolableValue& interpolable_value, const NonInterpolableValue* non_interpolable_value, StyleResolverState& state) const { - const auto& interpolable_list = ToInterpolableList(interpolable_value); + const auto& interpolable_list = To<InterpolableList>(interpolable_value); const auto& non_interpolable_list = ToNonInterpolableList(*non_interpolable_value); wtf_size_t length = interpolable_list.length();
diff --git a/third_party/blink/renderer/core/animation/css_time_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_time_interpolation_type.cc index 6f41dba..7e9a7d2 100644 --- a/third_party/blink/renderer/core/animation/css_time_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_time_interpolation_type.cc
@@ -30,7 +30,7 @@ const InterpolableValue& value, const NonInterpolableValue*, const StyleResolverState&) const { - return CSSNumericLiteralValue::Create(ToInterpolableNumber(value).Value(), + return CSSNumericLiteralValue::Create(To<InterpolableNumber>(value).Value(), CSSPrimitiveValue::UnitType::kSeconds); }
diff --git a/third_party/blink/renderer/core/animation/css_translate_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_translate_interpolation_type.cc index e4675fd..55bce0b 100644 --- a/third_party/blink/renderer/core/animation/css_translate_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_translate_interpolation_type.cc
@@ -23,7 +23,7 @@ } bool IsNoneValue(const InterpolationValue& value) { - return ToInterpolableList(*value.interpolable_value).length() == 0; + return To<InterpolableList>(*value.interpolable_value).length() == 0; } class InheritedTranslateChecker @@ -141,8 +141,9 @@ InterpolationValue&& start, InterpolationValue&& end) const { size_t start_list_length = - ToInterpolableList(*start.interpolable_value).length(); - size_t end_list_length = ToInterpolableList(*end.interpolable_value).length(); + To<InterpolableList>(*start.interpolable_value).length(); + size_t end_list_length = + To<InterpolableList>(*end.interpolable_value).length(); if (start_list_length < end_list_length) start.interpolable_value = CreateTranslateIdentity(); else if (end_list_length < start_list_length) @@ -181,7 +182,7 @@ const InterpolableValue& interpolable_value, const NonInterpolableValue*, StyleResolverState& state) const { - const InterpolableList& list = ToInterpolableList(interpolable_value); + const auto& list = To<InterpolableList>(interpolable_value); if (list.length() == 0) { state.Style()->SetTranslate(nullptr); return;
diff --git a/third_party/blink/renderer/core/animation/css_visibility_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_visibility_interpolation_type.cc index d0153dd..8e30240c 100644 --- a/third_party/blink/renderer/core/animation/css_visibility_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_visibility_interpolation_type.cc
@@ -64,7 +64,7 @@ bool IsValid(const StyleResolverState&, const InterpolationValue& underlying) const final { double underlying_fraction = - ToInterpolableNumber(*underlying.interpolable_value).Value(); + To<InterpolableNumber>(*underlying.interpolable_value).Value(); EVisibility underlying_visibility = ToCSSVisibilityNonInterpolableValue(*underlying.non_interpolable_value) .Visibility(underlying_fraction); @@ -100,7 +100,7 @@ const InterpolationValue& underlying, ConversionCheckers& conversion_checkers) const { double underlying_fraction = - ToInterpolableNumber(*underlying.interpolable_value).Value(); + To<InterpolableNumber>(*underlying.interpolable_value).Value(); EVisibility underlying_visibility = ToCSSVisibilityNonInterpolableValue(*underlying.non_interpolable_value) .Visibility(underlying_fraction); @@ -188,7 +188,7 @@ StyleResolverState& state) const { // Visibility interpolation has been deferred to application time here due to // its non-linear behaviour. - double fraction = ToInterpolableNumber(interpolable_value).Value(); + double fraction = To<InterpolableNumber>(interpolable_value).Value(); EVisibility visibility = ToCSSVisibilityNonInterpolableValue(non_interpolable_value) ->Visibility(fraction);
diff --git a/third_party/blink/renderer/core/animation/effect_stack.cc b/third_party/blink/renderer/core/animation/effect_stack.cc index 27f9f233..8f5d0aa 100644 --- a/third_party/blink/renderer/core/animation/effect_stack.cc +++ b/third_party/blink/renderer/core/animation/effect_stack.cc
@@ -63,7 +63,8 @@ !property.IsCSSProperty() || property.IsPresentationAttribute(); const bool effect_depends_on_underlying_value = interpolation->IsInvalidatableInterpolation() && - ToInvalidatableInterpolation(*interpolation).DependsOnUnderlyingValue(); + To<InvalidatableInterpolation>(*interpolation.Get()) + .DependsOnUnderlyingValue(); if (!allow_stacked_effects || !effect_depends_on_underlying_value) active_interpolations.clear(); active_interpolations.push_back(interpolation);
diff --git a/third_party/blink/renderer/core/animation/effect_stack_test.cc b/third_party/blink/renderer/core/animation/effect_stack_test.cc index ef4d234..4f4a13b 100644 --- a/third_party/blink/renderer/core/animation/effect_stack_test.cc +++ b/third_party/blink/renderer/core/animation/effect_stack_test.cc
@@ -82,8 +82,8 @@ active_interpolations.at(PropertyHandle(GetCSSPropertyFontSize())); EnsureInterpolatedValueCached(interpolations, GetDocument(), element); - const TypedInterpolationValue* typed_value = - ToInvalidatableInterpolation(*interpolations.at(0)) + const auto* typed_value = + To<InvalidatableInterpolation>(*interpolations.at(0)) .GetCachedValueForTesting(); // font-size is stored as an |InterpolableLength|; here we assume pixels. EXPECT_TRUE(typed_value->GetInterpolableValue().IsLength()); @@ -97,12 +97,13 @@ active_interpolations.at(PropertyHandle(GetCSSPropertyZIndex())); EnsureInterpolatedValueCached(interpolations, GetDocument(), element); - const TypedInterpolationValue* typed_value = - ToInvalidatableInterpolation(*interpolations.at(0)) + const auto* typed_value = + To<InvalidatableInterpolation>(*interpolations.at(0)) .GetCachedValueForTesting(); // z-index is stored as a straight number value. EXPECT_TRUE(typed_value->GetInterpolableValue().IsNumber()); - return ToInterpolableNumber(&typed_value->GetInterpolableValue())->Value(); + return To<InterpolableNumber>(&typed_value->GetInterpolableValue()) + ->Value(); } Persistent<DocumentTimeline> timeline;
diff --git a/third_party/blink/renderer/core/animation/interpolable_filter.cc b/third_party/blink/renderer/core/animation/interpolable_filter.cc index 9e9df37..91a602f 100644 --- a/third_party/blink/renderer/core/animation/interpolable_filter.cc +++ b/third_party/blink/renderer/core/animation/interpolable_filter.cc
@@ -173,7 +173,7 @@ case FilterOperation::SATURATE: case FilterOperation::SEPIA: { double value = - ClampParameter(ToInterpolableNumber(*value_).Value(), type_); + ClampParameter(To<InterpolableNumber>(*value_).Value(), type_); return MakeGarbageCollected<BasicColorMatrixFilterOperation>(value, type_); } @@ -183,7 +183,7 @@ case FilterOperation::INVERT: case FilterOperation::OPACITY: { double value = - ClampParameter(ToInterpolableNumber(*value_).Value(), type_); + ClampParameter(To<InterpolableNumber>(*value_).Value(), type_); return MakeGarbageCollected<BasicComponentTransferFilterOperation>(value, type_); }
diff --git a/third_party/blink/renderer/core/animation/interpolable_value.cc b/third_party/blink/renderer/core/animation/interpolable_value.cc index 272c70d..cd96b85 100644 --- a/third_party/blink/renderer/core/animation/interpolable_value.cc +++ b/third_party/blink/renderer/core/animation/interpolable_value.cc
@@ -9,11 +9,11 @@ namespace blink { bool InterpolableNumber::Equals(const InterpolableValue& other) const { - return value_ == ToInterpolableNumber(other).value_; + return value_ == To<InterpolableNumber>(other).value_; } bool InterpolableList::Equals(const InterpolableValue& other) const { - const InterpolableList& other_list = ToInterpolableList(other); + const auto& other_list = To<InterpolableList>(other); if (length() != other_list.length()) return false; for (wtf_size_t i = 0; i < length(); i++) { @@ -31,8 +31,8 @@ void InterpolableNumber::Interpolate(const InterpolableValue& to, const double progress, InterpolableValue& result) const { - const InterpolableNumber& to_number = ToInterpolableNumber(to); - InterpolableNumber& result_number = ToInterpolableNumber(result); + const auto& to_number = To<InterpolableNumber>(to); + auto& result_number = To<InterpolableNumber>(result); if (progress == 0 || value_ == to_number.value_) result_number.value_ = value_; @@ -46,14 +46,14 @@ void InterpolableList::AssertCanInterpolateWith( const InterpolableValue& other) const { DCHECK(other.IsList()); - DCHECK_EQ(ToInterpolableList(other).length(), length()); + DCHECK_EQ(To<InterpolableList>(other).length(), length()); } void InterpolableList::Interpolate(const InterpolableValue& to, const double progress, InterpolableValue& result) const { - const InterpolableList& to_list = ToInterpolableList(to); - InterpolableList& result_list = ToInterpolableList(result); + const auto& to_list = To<InterpolableList>(to); + auto& result_list = To<InterpolableList>(result); for (wtf_size_t i = 0; i < length(); i++) { DCHECK(values_[i]); @@ -80,11 +80,11 @@ } void InterpolableNumber::Add(const InterpolableValue& other) { - value_ += ToInterpolableNumber(other).value_; + value_ += To<InterpolableNumber>(other).value_; } void InterpolableList::Add(const InterpolableValue& other) { - const InterpolableList& other_list = ToInterpolableList(other); + const auto& other_list = To<InterpolableList>(other); DCHECK_EQ(other_list.length(), length()); for (wtf_size_t i = 0; i < length(); i++) values_[i]->Add(*other_list.values_[i]); @@ -92,7 +92,7 @@ void InterpolableList::ScaleAndAdd(double scale, const InterpolableValue& other) { - const InterpolableList& other_list = ToInterpolableList(other); + const auto& other_list = To<InterpolableList>(other); DCHECK_EQ(other_list.length(), length()); for (wtf_size_t i = 0; i < length(); i++) values_[i]->ScaleAndAdd(scale, *other_list.values_[i]);
diff --git a/third_party/blink/renderer/core/animation/interpolable_value.h b/third_party/blink/renderer/core/animation/interpolable_value.h index 2301fd01..0a846d2f 100644 --- a/third_party/blink/renderer/core/animation/interpolable_value.h +++ b/third_party/blink/renderer/core/animation/interpolable_value.h
@@ -11,6 +11,7 @@ #include "base/memory/ptr_util.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/wtf/casting.h" #include "third_party/blink/renderer/platform/wtf/vector.h" namespace blink { @@ -151,16 +152,18 @@ Vector<std::unique_ptr<InterpolableValue>> values_; }; -DEFINE_TYPE_CASTS(InterpolableNumber, - InterpolableValue, - value, - value->IsNumber(), - value.IsNumber()); -DEFINE_TYPE_CASTS(InterpolableList, - InterpolableValue, - value, - value->IsList(), - value.IsList()); +template <> +struct DowncastTraits<InterpolableNumber> { + static bool AllowFrom(const InterpolableValue& value) { + return value.IsNumber(); + } +}; +template <> +struct DowncastTraits<InterpolableList> { + static bool AllowFrom(const InterpolableValue& value) { + return value.IsList(); + } +}; } // namespace blink
diff --git a/third_party/blink/renderer/core/animation/interpolable_value_test.cc b/third_party/blink/renderer/core/animation/interpolable_value_test.cc index 0bdb331..3ac40d4 100644 --- a/third_party/blink/renderer/core/animation/interpolable_value_test.cc +++ b/third_party/blink/renderer/core/animation/interpolable_value_test.cc
@@ -32,7 +32,7 @@ std::unique_ptr<TypedInterpolationValue> interpolated_value = i->GetInterpolatedValue(); EXPECT_TRUE(interpolated_value); - return ToInterpolableNumber(interpolated_value->GetInterpolableValue()) + return To<InterpolableNumber>(interpolated_value->GetInterpolableValue()) .Value(); } @@ -74,11 +74,11 @@ std::unique_ptr<InterpolableValue> interpolated_value = InterpolateLists(std::move(list_a), std::move(list_b), 0.3); - const InterpolableList& out_list = ToInterpolableList(*interpolated_value); + const auto& out_list = To<InterpolableList>(*interpolated_value); - EXPECT_FLOAT_EQ(30, ToInterpolableNumber(out_list.Get(0))->Value()); - EXPECT_FLOAT_EQ(-30.6f, ToInterpolableNumber(out_list.Get(1))->Value()); - EXPECT_FLOAT_EQ(104.35f, ToInterpolableNumber(out_list.Get(2))->Value()); + EXPECT_FLOAT_EQ(30, To<InterpolableNumber>(out_list.Get(0))->Value()); + EXPECT_FLOAT_EQ(-30.6f, To<InterpolableNumber>(out_list.Get(1))->Value()); + EXPECT_FLOAT_EQ(104.35f, To<InterpolableNumber>(out_list.Get(2))->Value()); } TEST_F(AnimationInterpolableValueTest, NestedList) { @@ -98,13 +98,13 @@ std::unique_ptr<InterpolableValue> interpolated_value = InterpolateLists(std::move(list_a), std::move(list_b), 0.5); - const InterpolableList& out_list = ToInterpolableList(*interpolated_value); + const auto& out_list = To<InterpolableList>(*interpolated_value); - EXPECT_FLOAT_EQ(50, ToInterpolableNumber(out_list.Get(0))->Value()); + EXPECT_FLOAT_EQ(50, To<InterpolableNumber>(out_list.Get(0))->Value()); EXPECT_FLOAT_EQ( - 75, ToInterpolableNumber(ToInterpolableList(out_list.Get(1))->Get(0)) + 75, To<InterpolableNumber>(To<InterpolableList>(out_list.Get(1))->Get(0)) ->Value()); - EXPECT_FLOAT_EQ(0.5, ToInterpolableNumber(out_list.Get(2))->Value()); + EXPECT_FLOAT_EQ(0.5, To<InterpolableNumber>(out_list.Get(2))->Value()); } TEST_F(AnimationInterpolableValueTest, ScaleAndAddNumbers) { @@ -132,9 +132,9 @@ add_list->Set(1, std::make_unique<InterpolableNumber>(2)); add_list->Set(2, std::make_unique<InterpolableNumber>(3)); ScaleAndAdd(*base_list, 2, *add_list); - EXPECT_FLOAT_EQ(11, ToInterpolableNumber(base_list->Get(0))->Value()); - EXPECT_FLOAT_EQ(22, ToInterpolableNumber(base_list->Get(1))->Value()); - EXPECT_FLOAT_EQ(33, ToInterpolableNumber(base_list->Get(2))->Value()); + EXPECT_FLOAT_EQ(11, To<InterpolableNumber>(base_list->Get(0))->Value()); + EXPECT_FLOAT_EQ(22, To<InterpolableNumber>(base_list->Get(1))->Value()); + EXPECT_FLOAT_EQ(33, To<InterpolableNumber>(base_list->Get(2))->Value()); } } // namespace blink
diff --git a/third_party/blink/renderer/core/animation/interpolation_effect_test.cc b/third_party/blink/renderer/core/animation/interpolation_effect_test.cc index a38dbb2..0bdf8fe 100644 --- a/third_party/blink/renderer/core/animation/interpolation_effect_test.cc +++ b/third_party/blink/renderer/core/animation/interpolation_effect_test.cc
@@ -14,10 +14,10 @@ namespace { double GetInterpolableNumber(Interpolation* value) { - TransitionInterpolation* interpolation = ToTransitionInterpolation(value); + auto* interpolation = To<TransitionInterpolation>(value); std::unique_ptr<TypedInterpolationValue> interpolated_value = interpolation->GetInterpolatedValue(); - return ToInterpolableNumber(interpolated_value->GetInterpolableValue()) + return To<InterpolableNumber>(interpolated_value->GetInterpolableValue()) .Value(); }
diff --git a/third_party/blink/renderer/core/animation/invalidatable_interpolation.cc b/third_party/blink/renderer/core/animation/invalidatable_interpolation.cc index 15e991a..ec3f423 100644 --- a/third_party/blink/renderer/core/animation/invalidatable_interpolation.cc +++ b/third_party/blink/renderer/core/animation/invalidatable_interpolation.cc
@@ -231,8 +231,8 @@ // Compute the underlying value to composite onto. UnderlyingValueOwner underlying_value_owner; - const InvalidatableInterpolation& first_interpolation = - ToInvalidatableInterpolation(*interpolations.at(starting_index)); + const auto& first_interpolation = + To<InvalidatableInterpolation>(*interpolations.at(starting_index)); first_interpolation.EnsureValidInterpolationTypes(environment); if (first_interpolation.DependsOnUnderlyingValue()) { underlying_value_owner.Set( @@ -258,8 +258,8 @@ // Composite interpolations onto the underlying value. bool should_apply = false; for (wtf_size_t i = starting_index; i < interpolations.size(); i++) { - const InvalidatableInterpolation& current_interpolation = - ToInvalidatableInterpolation(*interpolations.at(i)); + const auto& current_interpolation = + To<InvalidatableInterpolation>(*interpolations.at(i)); DCHECK(current_interpolation.DependsOnUnderlyingValue()); current_interpolation.EnsureValidInterpolationTypes(environment); const TypedInterpolationValue* current_value =
diff --git a/third_party/blink/renderer/core/animation/invalidatable_interpolation.h b/third_party/blink/renderer/core/animation/invalidatable_interpolation.h index d644929..83e3f18f 100644 --- a/third_party/blink/renderer/core/animation/invalidatable_interpolation.h +++ b/third_party/blink/renderer/core/animation/invalidatable_interpolation.h
@@ -98,11 +98,12 @@ mutable std::unique_ptr<TypedInterpolationValue> cached_value_; }; -DEFINE_TYPE_CASTS(InvalidatableInterpolation, - Interpolation, - value, - value->IsInvalidatableInterpolation(), - value.IsInvalidatableInterpolation()); +template <> +struct DowncastTraits<InvalidatableInterpolation> { + static bool AllowFrom(const Interpolation& value) { + return value.IsInvalidatableInterpolation(); + } +}; } // namespace blink
diff --git a/third_party/blink/renderer/core/animation/keyframe_effect_model_test.cc b/third_party/blink/renderer/core/animation/keyframe_effect_model_test.cc index 9cb0caa..daaaf1f 100644 --- a/third_party/blink/renderer/core/animation/keyframe_effect_model_test.cc +++ b/third_party/blink/renderer/core/animation/keyframe_effect_model_test.cc
@@ -68,8 +68,8 @@ interpolations.push_back(interpolation_value); EnsureInterpolatedValueCached(interpolations, GetDocument(), element); - const TypedInterpolationValue* typed_value = - ToInvalidatableInterpolation(interpolation_value) + const auto* typed_value = + To<InvalidatableInterpolation>(interpolation_value) ->GetCachedValueForTesting(); // Length values are stored as an |InterpolableLength|; here we assume // pixels. @@ -89,8 +89,8 @@ interpolations.push_back(interpolation_value); EnsureInterpolatedValueCached(interpolations, GetDocument(), element); - const TypedInterpolationValue* typed_value = - ToInvalidatableInterpolation(interpolation_value) + const auto* typed_value = + To<InvalidatableInterpolation>(interpolation_value) ->GetCachedValueForTesting(); const NonInterpolableValue* non_interpolable_value = typed_value->GetNonInterpolableValue(); @@ -167,8 +167,7 @@ void ExpectProperty(CSSPropertyID property, Interpolation* interpolation_value) { - InvalidatableInterpolation* interpolation = - ToInvalidatableInterpolation(interpolation_value); + auto* interpolation = To<InvalidatableInterpolation>(interpolation_value); const PropertyHandle& property_handle = interpolation->GetProperty(); ASSERT_TRUE(property_handle.IsCSSProperty()); ASSERT_EQ(property, property_handle.GetCSSProperty().PropertyID()); @@ -177,8 +176,8 @@ Interpolation* FindValue(HeapVector<Member<Interpolation>>& values, CSSPropertyID id) { for (auto& value : values) { - const PropertyHandle& property = - ToInvalidatableInterpolation(value)->GetProperty(); + const auto& property = + To<InvalidatableInterpolation>(value.Get())->GetProperty(); if (property.IsCSSProperty() && property.GetCSSProperty().PropertyID() == id) return value;
diff --git a/third_party/blink/renderer/core/animation/list_interpolation_functions.cc b/third_party/blink/renderer/core/animation/list_interpolation_functions.cc index 146f840..afbb332 100644 --- a/third_party/blink/renderer/core/animation/list_interpolation_functions.cc +++ b/third_party/blink/renderer/core/animation/list_interpolation_functions.cc
@@ -32,12 +32,12 @@ : underlying_list_(underlying_list), builder_(builder), index_(index) {} InterpolableValue& MutableInterpolableValue() final { - return *ToInterpolableList(underlying_list_.MutableInterpolableValue()) + return *To<InterpolableList>(underlying_list_.MutableInterpolableValue()) .GetMutable(index_); } void SetInterpolableValue( std::unique_ptr<InterpolableValue> interpolable_value) final { - ToInterpolableList(underlying_list_.MutableInterpolableValue()) + To<InterpolableList>(underlying_list_.MutableInterpolableValue()) .Set(index_, std::move(interpolable_value)); } const NonInterpolableValue* GetNonInterpolableValue() const final { @@ -65,10 +65,8 @@ if (!a || !b) return false; - const InterpolableList& interpolable_list_a = - ToInterpolableList(*a.interpolable_value); - const InterpolableList& interpolable_list_b = - ToInterpolableList(*b.interpolable_value); + const auto& interpolable_list_a = To<InterpolableList>(*a.interpolable_value); + const auto& interpolable_list_b = To<InterpolableList>(*b.interpolable_value); if (interpolable_list_a.length() != interpolable_list_b.length()) return false; @@ -123,9 +121,9 @@ LengthMatchingStrategy length_matching_strategy, MergeSingleItemConversionsCallback merge_single_item_conversions) { const wtf_size_t start_length = - ToInterpolableList(*start.interpolable_value).length(); + To<InterpolableList>(*start.interpolable_value).length(); const wtf_size_t end_length = - ToInterpolableList(*end.interpolable_value).length(); + To<InterpolableList>(*end.interpolable_value).length(); if (length_matching_strategy == ListInterpolationFunctions::LengthMatchingStrategy::kEqual && @@ -164,10 +162,9 @@ Vector<scoped_refptr<const NonInterpolableValue>> result_non_interpolable_values(final_length); - InterpolableList& start_interpolable_list = - ToInterpolableList(*start.interpolable_value); - InterpolableList& end_interpolable_list = - ToInterpolableList(*end.interpolable_value); + auto& start_interpolable_list = + To<InterpolableList>(*start.interpolable_value); + auto& end_interpolable_list = To<InterpolableList>(*end.interpolable_value); const NonInterpolableList& start_non_interpolable_list = ToNonInterpolableList(*start.non_interpolable_value); const NonInterpolableList& end_non_interpolable_list = @@ -220,8 +217,7 @@ } static void RepeatToLength(InterpolationValue& value, wtf_size_t length) { - InterpolableList& interpolable_list = - ToInterpolableList(*value.interpolable_value); + auto& interpolable_list = To<InterpolableList>(*value.interpolable_value); const NonInterpolableList& non_interpolable_list = ToNonInterpolableList(*value.non_interpolable_value); wtf_size_t current_length = interpolable_list.length(); @@ -249,13 +245,12 @@ // CloneAndZero-ing the additional items from length_value into value. static void PadToSameLength(InterpolationValue& value, const InterpolationValue& length_value) { - InterpolableList& interpolable_list = - ToInterpolableList(*value.interpolable_value); + auto& interpolable_list = To<InterpolableList>(*value.interpolable_value); const NonInterpolableList& non_interpolable_list = ToNonInterpolableList(*value.non_interpolable_value); const wtf_size_t current_length = interpolable_list.length(); - InterpolableList& target_interpolable_list = - ToInterpolableList(*length_value.interpolable_value); + auto& target_interpolable_list = + To<InterpolableList>(*length_value.interpolable_value); const NonInterpolableList& target_non_interpolable_list = ToNonInterpolableList(*length_value.non_interpolable_value); const wtf_size_t target_length = target_interpolable_list.length(); @@ -341,11 +336,11 @@ non_interpolable_values_are_compatible, CompositeItemCallback composite_item) { const wtf_size_t underlying_length = - ToInterpolableList(*underlying_value_owner.Value().interpolable_value) + To<InterpolableList>(*underlying_value_owner.Value().interpolable_value) .length(); - const InterpolableList& interpolable_list = - ToInterpolableList(*value.interpolable_value); + const auto& interpolable_list = + To<InterpolableList>(*value.interpolable_value); const wtf_size_t value_length = interpolable_list.length(); if (length_matching_strategy == @@ -372,7 +367,7 @@ MatchLengths(underlying_length, value_length, length_matching_strategy); if (!InterpolableListsAreCompatible( - ToInterpolableList( + To<InterpolableList>( *underlying_value_owner.Value().interpolable_value), interpolable_list, final_length, length_matching_strategy, interpolable_values_are_compatible)) { @@ -414,8 +409,8 @@ DCHECK_EQ(value_length, final_length); PadToSameLength(underlying_value, value); } - InterpolableList& underlying_interpolable_list = - ToInterpolableList(*underlying_value.interpolable_value); + auto& underlying_interpolable_list = + To<InterpolableList>(*underlying_value.interpolable_value); NonInterpolableList::AutoBuilder builder(underlying_value_owner);
diff --git a/third_party/blink/renderer/core/animation/list_interpolation_functions_test.cc b/third_party/blink/renderer/core/animation/list_interpolation_functions_test.cc index 23ac9fa3..4d63279 100644 --- a/third_party/blink/renderer/core/animation/list_interpolation_functions_test.cc +++ b/third_party/blink/renderer/core/animation/list_interpolation_functions_test.cc
@@ -219,12 +219,12 @@ WTF::BindRepeating(NonInterpolableValuesAreCompatible), WTF::BindRepeating(Composite)); - const auto& result = ToInterpolableList(*owner.Value().interpolable_value); + const auto& result = To<InterpolableList>(*owner.Value().interpolable_value); ASSERT_EQ(result.length(), 3u); - EXPECT_EQ(ToInterpolableNumber(result.Get(0))->Value(), 2.0); - EXPECT_EQ(ToInterpolableNumber(result.Get(1))->Value(), 4.0); - EXPECT_EQ(ToInterpolableNumber(result.Get(2))->Value(), 6.0); + EXPECT_EQ(To<InterpolableNumber>(result.Get(0))->Value(), 2.0); + EXPECT_EQ(To<InterpolableNumber>(result.Get(1))->Value(), 4.0); + EXPECT_EQ(To<InterpolableNumber>(result.Get(2))->Value(), 6.0); } // Two lists of different lengths are not interpolable, so we expect the @@ -246,11 +246,11 @@ WTF::BindRepeating(NonInterpolableValuesAreCompatible), WTF::BindRepeating(Composite)); - const auto& result = ToInterpolableList(*owner.Value().interpolable_value); + const auto& result = To<InterpolableList>(*owner.Value().interpolable_value); ASSERT_EQ(result.length(), 2u); - EXPECT_EQ(ToInterpolableNumber(result.Get(0))->Value(), 4.0); - EXPECT_EQ(ToInterpolableNumber(result.Get(1))->Value(), 5.0); + EXPECT_EQ(To<InterpolableNumber>(result.Get(0))->Value(), 4.0); + EXPECT_EQ(To<InterpolableNumber>(result.Get(1))->Value(), 5.0); } // If one (or more) of the element pairs are incompatible, the list as a whole @@ -276,12 +276,12 @@ WTF::BindRepeating(NonInterpolableValuesAreCompatible), WTF::BindRepeating(Composite)); - const auto& result = ToInterpolableList(*owner.Value().interpolable_value); + const auto& result = To<InterpolableList>(*owner.Value().interpolable_value); ASSERT_EQ(result.length(), 3u); - EXPECT_EQ(ToInterpolableNumber(result.Get(0))->Value(), 4.0); - EXPECT_EQ(ToInterpolableNumber(result.Get(1))->Value(), 5.0); - EXPECT_EQ(ToInterpolableNumber(result.Get(2))->Value(), 6.0); + EXPECT_EQ(To<InterpolableNumber>(result.Get(0))->Value(), 4.0); + EXPECT_EQ(To<InterpolableNumber>(result.Get(1))->Value(), 5.0); + EXPECT_EQ(To<InterpolableNumber>(result.Get(2))->Value(), 6.0); } // If one (or more) of the element pairs are incompatible, the list as a whole @@ -304,12 +304,12 @@ WTF::BindRepeating(NonInterpolableValuesAreCompatible), WTF::BindRepeating(Composite)); - const auto& result = ToInterpolableList(*owner.Value().interpolable_value); + const auto& result = To<InterpolableList>(*owner.Value().interpolable_value); ASSERT_EQ(result.length(), 3u); - EXPECT_EQ(ToInterpolableNumber(result.Get(0))->Value(), 4.0); - EXPECT_EQ(ToInterpolableNumber(result.Get(1))->Value(), 5.0); - EXPECT_EQ(ToInterpolableNumber(result.Get(2))->Value(), 6.0); + EXPECT_EQ(To<InterpolableNumber>(result.Get(0))->Value(), 4.0); + EXPECT_EQ(To<InterpolableNumber>(result.Get(1))->Value(), 5.0); + EXPECT_EQ(To<InterpolableNumber>(result.Get(2))->Value(), 6.0); } TEST(ListInterpolationFunctionsTest, BuilderNoModify) {
diff --git a/third_party/blink/renderer/core/animation/path_interpolation_functions.cc b/third_party/blink/renderer/core/animation/path_interpolation_functions.cc index 3260e29..531c436 100644 --- a/third_party/blink/renderer/core/animation/path_interpolation_functions.cc +++ b/third_party/blink/renderer/core/animation/path_interpolation_functions.cc
@@ -128,9 +128,10 @@ conversion_checkers.push_back( UnderlyingPathSegTypesChecker::Create(underlying)); auto result = std::make_unique<InterpolableList>(kPathComponentIndexCount); - result->Set(kPathArgsIndex, ToInterpolableList(*underlying.interpolable_value) - .Get(kPathArgsIndex) - ->CloneAndZero()); + result->Set(kPathArgsIndex, + To<InterpolableList>(*underlying.interpolable_value) + .Get(kPathArgsIndex) + ->CloneAndZero()); result->Set(kPathNeutralIndex, std::make_unique<InterpolableNumber>(1)); return InterpolationValue(std::move(result), underlying.non_interpolable_value.get()); @@ -170,9 +171,9 @@ double underlying_fraction, const InterpolationType& type, const InterpolationValue& value) { - const InterpolableList& list = ToInterpolableList(*value.interpolable_value); + const auto& list = To<InterpolableList>(*value.interpolable_value); double neutral_component = - ToInterpolableNumber(list.Get(kPathNeutralIndex))->Value(); + To<InterpolableNumber>(list.Get(kPathNeutralIndex))->Value(); if (neutral_component == 0) { underlying_value_owner.Set(type, value); @@ -197,8 +198,8 @@ std::unique_ptr<SVGPathByteStream> path_byte_stream = std::make_unique<SVGPathByteStream>(); InterpolatedSVGPathSource source( - ToInterpolableList( - *ToInterpolableList(interpolable_value).Get(kPathArgsIndex)), + To<InterpolableList>( + *To<InterpolableList>(interpolable_value).Get(kPathArgsIndex)), ToSVGPathNonInterpolableValue(non_interpolable_value)->PathSegTypes()); SVGPathByteStreamBuilder builder(*path_byte_stream); svg_path_parser::ParsePath(source, builder);
diff --git a/third_party/blink/renderer/core/animation/svg_angle_interpolation_type.cc b/third_party/blink/renderer/core/animation/svg_angle_interpolation_type.cc index 053572b..1330538 100644 --- a/third_party/blink/renderer/core/animation/svg_angle_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/svg_angle_interpolation_type.cc
@@ -28,7 +28,7 @@ SVGPropertyBase* SVGAngleInterpolationType::AppliedSVGValue( const InterpolableValue& interpolable_value, const NonInterpolableValue*) const { - double double_value = ToInterpolableNumber(interpolable_value).Value(); + double double_value = To<InterpolableNumber>(interpolable_value).Value(); auto* result = MakeGarbageCollected<SVGAngle>(); result->NewValueSpecifiedUnits(SVGAngle::kSvgAngletypeDeg, double_value); return result;
diff --git a/third_party/blink/renderer/core/animation/svg_integer_interpolation_type.cc b/third_party/blink/renderer/core/animation/svg_integer_interpolation_type.cc index a7ca4bc..cbf79e3 100644 --- a/third_party/blink/renderer/core/animation/svg_integer_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/svg_integer_interpolation_type.cc
@@ -27,7 +27,7 @@ SVGPropertyBase* SVGIntegerInterpolationType::AppliedSVGValue( const InterpolableValue& interpolable_value, const NonInterpolableValue*) const { - double value = ToInterpolableNumber(interpolable_value).Value(); + double value = To<InterpolableNumber>(interpolable_value).Value(); return MakeGarbageCollected<SVGInteger>(round(value)); }
diff --git a/third_party/blink/renderer/core/animation/svg_integer_optional_integer_interpolation_type.cc b/third_party/blink/renderer/core/animation/svg_integer_optional_integer_interpolation_type.cc index 896f7df..a18c385 100644 --- a/third_party/blink/renderer/core/animation/svg_integer_optional_integer_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/svg_integer_optional_integer_interpolation_type.cc
@@ -41,13 +41,13 @@ static SVGInteger* ToPositiveInteger(const InterpolableValue* number) { return MakeGarbageCollected<SVGInteger>( - clampTo<int>(round(ToInterpolableNumber(number)->Value()), 1)); + clampTo<int>(round(To<InterpolableNumber>(number)->Value()), 1)); } SVGPropertyBase* SVGIntegerOptionalIntegerInterpolationType::AppliedSVGValue( const InterpolableValue& interpolable_value, const NonInterpolableValue*) const { - const InterpolableList& list = ToInterpolableList(interpolable_value); + const auto& list = To<InterpolableList>(interpolable_value); return MakeGarbageCollected<SVGIntegerOptionalInteger>( ToPositiveInteger(list.Get(0)), ToPositiveInteger(list.Get(1))); }
diff --git a/third_party/blink/renderer/core/animation/svg_interpolation_environment.h b/third_party/blink/renderer/core/animation/svg_interpolation_environment.h index 62787f9..b1865c3b 100644 --- a/third_party/blink/renderer/core/animation/svg_interpolation_environment.h +++ b/third_party/blink/renderer/core/animation/svg_interpolation_environment.h
@@ -43,11 +43,12 @@ Member<const SVGPropertyBase> svg_base_value_ = nullptr; }; -DEFINE_TYPE_CASTS(SVGInterpolationEnvironment, - InterpolationEnvironment, - value, - value->IsSVG(), - value.IsSVG()); +template <> +struct DowncastTraits<SVGInterpolationEnvironment> { + static bool AllowFrom(const InterpolationEnvironment& value) { + return value.IsSVG(); + } +}; } // namespace blink
diff --git a/third_party/blink/renderer/core/animation/svg_interpolation_type.cc b/third_party/blink/renderer/core/animation/svg_interpolation_type.cc index 8ba2e56..885cae5 100644 --- a/third_party/blink/renderer/core/animation/svg_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/svg_interpolation_type.cc
@@ -19,8 +19,8 @@ if (keyframe.IsNeutral()) return MaybeConvertNeutral(underlying, conversion_checkers); - SVGPropertyBase* svg_value = - ToSVGInterpolationEnvironment(environment) + auto* svg_value = + To<SVGInterpolationEnvironment>(environment) .SvgBaseValue() .CloneForAnimation(To<SVGPropertySpecificKeyframe>(keyframe).Value()); return MaybeConvertSVGValue(*svg_value); @@ -29,14 +29,14 @@ InterpolationValue SVGInterpolationType::MaybeConvertUnderlyingValue( const InterpolationEnvironment& environment) const { return MaybeConvertSVGValue( - ToSVGInterpolationEnvironment(environment).SvgBaseValue()); + To<SVGInterpolationEnvironment>(environment).SvgBaseValue()); } void SVGInterpolationType::Apply( const InterpolableValue& interpolable_value, const NonInterpolableValue* non_interpolable_value, InterpolationEnvironment& environment) const { - ToSVGInterpolationEnvironment(environment) + To<SVGInterpolationEnvironment>(environment) .SvgElement() .SetWebAnimatedAttribute( Attribute(),
diff --git a/third_party/blink/renderer/core/animation/svg_length_interpolation_type.cc b/third_party/blink/renderer/core/animation/svg_length_interpolation_type.cc index 5a3a95a7..523eec8c 100644 --- a/third_party/blink/renderer/core/animation/svg_length_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/svg_length_interpolation_type.cc
@@ -85,7 +85,7 @@ const InterpolableValue& interpolable_value, const NonInterpolableValue* non_interpolable_value, InterpolationEnvironment& environment) const { - SVGElement& element = ToSVGInterpolationEnvironment(environment).SvgElement(); + auto& element = To<SVGInterpolationEnvironment>(environment).SvgElement(); SVGLengthContext length_context(&element); element.SetWebAnimatedAttribute( Attribute(),
diff --git a/third_party/blink/renderer/core/animation/svg_length_list_interpolation_type.cc b/third_party/blink/renderer/core/animation/svg_length_list_interpolation_type.cc index 60c9841..58378b1 100644 --- a/third_party/blink/renderer/core/animation/svg_length_list_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/svg_length_list_interpolation_type.cc
@@ -54,8 +54,9 @@ InterpolationValue&& start, InterpolationValue&& end) const { wtf_size_t start_length = - ToInterpolableList(*start.interpolable_value).length(); - wtf_size_t end_length = ToInterpolableList(*end.interpolable_value).length(); + To<InterpolableList>(*start.interpolable_value).length(); + wtf_size_t end_length = + To<InterpolableList>(*end.interpolable_value).length(); if (start_length != end_length) return nullptr; return InterpolationType::MaybeMergeSingles(std::move(start), std::move(end)); @@ -67,10 +68,10 @@ const InterpolationValue& value, double interpolation_fraction) const { wtf_size_t start_length = - ToInterpolableList(*underlying_value_owner.Value().interpolable_value) + To<InterpolableList>(*underlying_value_owner.Value().interpolable_value) .length(); wtf_size_t end_length = - ToInterpolableList(*value.interpolable_value).length(); + To<InterpolableList>(*value.interpolable_value).length(); if (start_length == end_length) InterpolationType::Composite(underlying_value_owner, underlying_fraction, @@ -91,11 +92,11 @@ const InterpolableValue& interpolable_value, const NonInterpolableValue* non_interpolable_value, InterpolationEnvironment& environment) const { - SVGElement& element = ToSVGInterpolationEnvironment(environment).SvgElement(); + auto& element = To<SVGInterpolationEnvironment>(environment).SvgElement(); SVGLengthContext length_context(&element); auto* result = MakeGarbageCollected<SVGLengthList>(unit_mode_); - const InterpolableList& list = ToInterpolableList(interpolable_value); + const auto& list = To<InterpolableList>(interpolable_value); for (wtf_size_t i = 0; i < list.length(); i++) { result->Append(SVGLengthInterpolationType::ResolveInterpolableSVGLength( *list.Get(i), length_context, unit_mode_, negative_values_forbidden_));
diff --git a/third_party/blink/renderer/core/animation/svg_number_interpolation_type.cc b/third_party/blink/renderer/core/animation/svg_number_interpolation_type.cc index bf2cf3a6..c09ed725 100644 --- a/third_party/blink/renderer/core/animation/svg_number_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/svg_number_interpolation_type.cc
@@ -39,7 +39,7 @@ const InterpolableValue& interpolable_value, const NonInterpolableValue*) const { float value = - clampTo<float>(ToInterpolableNumber(interpolable_value).Value()); + clampTo<float>(To<InterpolableNumber>(interpolable_value).Value()); return MakeGarbageCollected<SVGNumber>(is_non_negative_ && value < 0 ? 0 : value); }
diff --git a/third_party/blink/renderer/core/animation/svg_number_list_interpolation_type.cc b/third_party/blink/renderer/core/animation/svg_number_list_interpolation_type.cc index a20d97e7..229dd4b 100644 --- a/third_party/blink/renderer/core/animation/svg_number_list_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/svg_number_list_interpolation_type.cc
@@ -48,8 +48,9 @@ PairwiseInterpolationValue SVGNumberListInterpolationType::MaybeMergeSingles( InterpolationValue&& start, InterpolationValue&& end) const { - size_t start_length = ToInterpolableList(*start.interpolable_value).length(); - size_t end_length = ToInterpolableList(*end.interpolable_value).length(); + size_t start_length = + To<InterpolableList>(*start.interpolable_value).length(); + size_t end_length = To<InterpolableList>(*end.interpolable_value).length(); if (start_length != end_length) return nullptr; return InterpolationType::MaybeMergeSingles(std::move(start), std::move(end)); @@ -57,7 +58,7 @@ static void PadWithZeroes(std::unique_ptr<InterpolableValue>& list_pointer, wtf_size_t padded_length) { - InterpolableList& list = ToInterpolableList(*list_pointer); + auto& list = To<InterpolableList>(*list_pointer); if (list.length() >= padded_length) return; @@ -76,14 +77,14 @@ double underlying_fraction, const InterpolationValue& value, double interpolation_fraction) const { - const InterpolableList& list = ToInterpolableList(*value.interpolable_value); + const auto& list = To<InterpolableList>(*value.interpolable_value); - if (ToInterpolableList(*underlying_value_owner.Value().interpolable_value) + if (To<InterpolableList>(*underlying_value_owner.Value().interpolable_value) .length() <= list.length()) PadWithZeroes(underlying_value_owner.MutableValue().interpolable_value, list.length()); - InterpolableList& underlying_list = ToInterpolableList( + auto& underlying_list = To<InterpolableList>( *underlying_value_owner.MutableValue().interpolable_value); DCHECK_GE(underlying_list.length(), list.length()); @@ -99,10 +100,10 @@ const InterpolableValue& interpolable_value, const NonInterpolableValue*) const { auto* result = MakeGarbageCollected<SVGNumberList>(); - const InterpolableList& list = ToInterpolableList(interpolable_value); + const auto& list = To<InterpolableList>(interpolable_value); for (wtf_size_t i = 0; i < list.length(); i++) { result->Append(MakeGarbageCollected<SVGNumber>( - ToInterpolableNumber(list.Get(i))->Value())); + To<InterpolableNumber>(list.Get(i))->Value())); } return result; }
diff --git a/third_party/blink/renderer/core/animation/svg_number_optional_number_interpolation_type.cc b/third_party/blink/renderer/core/animation/svg_number_optional_number_interpolation_type.cc index ca685ba..c29dd29 100644 --- a/third_party/blink/renderer/core/animation/svg_number_optional_number_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/svg_number_optional_number_interpolation_type.cc
@@ -42,12 +42,12 @@ SVGPropertyBase* SVGNumberOptionalNumberInterpolationType::AppliedSVGValue( const InterpolableValue& interpolable_value, const NonInterpolableValue*) const { - const InterpolableList& list = ToInterpolableList(interpolable_value); + const auto& list = To<InterpolableList>(interpolable_value); return MakeGarbageCollected<SVGNumberOptionalNumber>( MakeGarbageCollected<SVGNumber>( - ToInterpolableNumber(list.Get(0))->Value()), + To<InterpolableNumber>(list.Get(0))->Value()), MakeGarbageCollected<SVGNumber>( - ToInterpolableNumber(list.Get(1))->Value())); + To<InterpolableNumber>(list.Get(1))->Value())); } } // namespace blink
diff --git a/third_party/blink/renderer/core/animation/svg_path_seg_interpolation_functions.cc b/third_party/blink/renderer/core/animation/svg_path_seg_interpolation_functions.cc index bb14de36..582006e 100644 --- a/third_party/blink/renderer/core/animation/svg_path_seg_interpolation_functions.cc +++ b/third_party/blink/renderer/core/animation/svg_path_seg_interpolation_functions.cc
@@ -20,7 +20,7 @@ float ConsumeInterpolableControlAxis(const InterpolableValue* number, bool is_absolute, double current_value) { - double value = ToInterpolableNumber(number)->Value(); + double value = To<InterpolableNumber>(number)->Value(); return clampTo<float>(is_absolute ? value : value - current_value); } @@ -37,7 +37,7 @@ bool is_absolute, double& current_value) { double previous_value = current_value; - current_value = ToInterpolableNumber(number)->Value(); + current_value = To<InterpolableNumber>(number)->Value(); return clampTo<float>(is_absolute ? current_value : current_value - previous_value); } @@ -85,7 +85,7 @@ const InterpolableValue& value, SVGPathSegType seg_type, PathCoordinates& coordinates) { - const InterpolableList& list = ToInterpolableList(value); + const auto& list = To<InterpolableList>(value); bool is_absolute = IsAbsolutePathSegType(seg_type); PathSegmentData segment; segment.command = seg_type; @@ -127,7 +127,7 @@ PathSegmentData ConsumeInterpolableCurvetoCubic(const InterpolableValue& value, SVGPathSegType seg_type, PathCoordinates& coordinates) { - const InterpolableList& list = ToInterpolableList(value); + const auto& list = To<InterpolableList>(value); bool is_absolute = IsAbsolutePathSegType(seg_type); PathSegmentData segment; segment.command = seg_type; @@ -166,7 +166,7 @@ const InterpolableValue& value, SVGPathSegType seg_type, PathCoordinates& coordinates) { - const InterpolableList& list = ToInterpolableList(value); + const auto& list = To<InterpolableList>(value); bool is_absolute = IsAbsolutePathSegType(seg_type); PathSegmentData segment; segment.command = seg_type; @@ -201,7 +201,7 @@ PathSegmentData ConsumeInterpolableArc(const InterpolableValue& value, SVGPathSegType seg_type, PathCoordinates& coordinates) { - const InterpolableList& list = ToInterpolableList(value); + const auto& list = To<InterpolableList>(value); bool is_absolute = IsAbsolutePathSegType(seg_type); PathSegmentData segment; segment.command = seg_type; @@ -209,11 +209,11 @@ list.Get(0), is_absolute, coordinates.current_x)); segment.target_point.SetY(ConsumeInterpolableCoordinateAxis( list.Get(1), is_absolute, coordinates.current_y)); - segment.ArcRadii().SetX(ToInterpolableNumber(list.Get(2))->Value()); - segment.ArcRadii().SetY(ToInterpolableNumber(list.Get(3))->Value()); - segment.SetArcAngle(ToInterpolableNumber(list.Get(4))->Value()); - segment.arc_large = ToInterpolableNumber(list.Get(5))->Value() >= 0.5; - segment.arc_sweep = ToInterpolableNumber(list.Get(6))->Value() >= 0.5; + segment.ArcRadii().SetX(To<InterpolableNumber>(list.Get(2))->Value()); + segment.ArcRadii().SetY(To<InterpolableNumber>(list.Get(3))->Value()); + segment.SetArcAngle(To<InterpolableNumber>(list.Get(4))->Value()); + segment.arc_large = To<InterpolableNumber>(list.Get(5))->Value() >= 0.5; + segment.arc_sweep = To<InterpolableNumber>(list.Get(6))->Value() >= 0.5; return segment; } @@ -275,7 +275,7 @@ const InterpolableValue& value, SVGPathSegType seg_type, PathCoordinates& coordinates) { - const InterpolableList& list = ToInterpolableList(value); + const auto& list = To<InterpolableList>(value); bool is_absolute = IsAbsolutePathSegType(seg_type); PathSegmentData segment; segment.command = seg_type;
diff --git a/third_party/blink/renderer/core/animation/svg_point_list_interpolation_type.cc b/third_party/blink/renderer/core/animation/svg_point_list_interpolation_type.cc index 86b32f0..eed39ad 100644 --- a/third_party/blink/renderer/core/animation/svg_point_list_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/svg_point_list_interpolation_type.cc
@@ -52,8 +52,9 @@ InterpolationValue&& start, InterpolationValue&& end) const { wtf_size_t start_length = - ToInterpolableList(*start.interpolable_value).length(); - wtf_size_t end_length = ToInterpolableList(*end.interpolable_value).length(); + To<InterpolableList>(*start.interpolable_value).length(); + wtf_size_t end_length = + To<InterpolableList>(*end.interpolable_value).length(); if (start_length != end_length) return nullptr; @@ -66,10 +67,10 @@ const InterpolationValue& value, double interpolation_fraction) const { wtf_size_t start_length = - ToInterpolableList(*underlying_value_owner.Value().interpolable_value) + To<InterpolableList>(*underlying_value_owner.Value().interpolable_value) .length(); wtf_size_t end_length = - ToInterpolableList(*value.interpolable_value).length(); + To<InterpolableList>(*value.interpolable_value).length(); if (start_length == end_length) InterpolationType::Composite(underlying_value_owner, underlying_fraction, value, interpolation_fraction); @@ -82,12 +83,12 @@ const NonInterpolableValue*) const { auto* result = MakeGarbageCollected<SVGPointList>(); - const InterpolableList& list = ToInterpolableList(interpolable_value); + const auto& list = To<InterpolableList>(interpolable_value); DCHECK_EQ(list.length() % 2, 0U); for (wtf_size_t i = 0; i < list.length(); i += 2) { FloatPoint point = - FloatPoint(ToInterpolableNumber(list.Get(i))->Value(), - ToInterpolableNumber(list.Get(i + 1))->Value()); + FloatPoint(To<InterpolableNumber>(list.Get(i))->Value(), + To<InterpolableNumber>(list.Get(i + 1))->Value()); result->Append(MakeGarbageCollected<SVGPoint>(point)); }
diff --git a/third_party/blink/renderer/core/animation/svg_rect_interpolation_type.cc b/third_party/blink/renderer/core/animation/svg_rect_interpolation_type.cc index 39ad352..c2675e6 100644 --- a/third_party/blink/renderer/core/animation/svg_rect_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/svg_rect_interpolation_type.cc
@@ -48,12 +48,12 @@ SVGPropertyBase* SVGRectInterpolationType::AppliedSVGValue( const InterpolableValue& interpolable_value, const NonInterpolableValue*) const { - const InterpolableList& list = ToInterpolableList(interpolable_value); + const auto& list = To<InterpolableList>(interpolable_value); auto* result = MakeGarbageCollected<SVGRect>(); - result->SetX(ToInterpolableNumber(list.Get(kRectX))->Value()); - result->SetY(ToInterpolableNumber(list.Get(kRectY))->Value()); - result->SetWidth(ToInterpolableNumber(list.Get(kRectWidth))->Value()); - result->SetHeight(ToInterpolableNumber(list.Get(kRectHeight))->Value()); + result->SetX(To<InterpolableNumber>(list.Get(kRectX))->Value()); + result->SetY(To<InterpolableNumber>(list.Get(kRectY))->Value()); + result->SetWidth(To<InterpolableNumber>(list.Get(kRectWidth))->Value()); + result->SetHeight(To<InterpolableNumber>(list.Get(kRectHeight))->Value()); return result; }
diff --git a/third_party/blink/renderer/core/animation/svg_transform_list_interpolation_type.cc b/third_party/blink/renderer/core/animation/svg_transform_list_interpolation_type.cc index d01134994..8e84b83 100644 --- a/third_party/blink/renderer/core/animation/svg_transform_list_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/svg_transform_list_interpolation_type.cc
@@ -57,12 +57,12 @@ } SVGTransform* TranslateFromInterpolableValue(const InterpolableValue& value) { - const InterpolableList& list = ToInterpolableList(value); + const auto& list = To<InterpolableList>(value); auto* transform = MakeGarbageCollected<SVGTransform>(SVGTransformType::kTranslate); - transform->SetTranslate(ToInterpolableNumber(list.Get(0))->Value(), - ToInterpolableNumber(list.Get(1))->Value()); + transform->SetTranslate(To<InterpolableNumber>(list.Get(0))->Value(), + To<InterpolableNumber>(list.Get(1))->Value()); return transform; } @@ -76,12 +76,12 @@ } SVGTransform* ScaleFromInterpolableValue(const InterpolableValue& value) { - const InterpolableList& list = ToInterpolableList(value); + const auto& list = To<InterpolableList>(value); auto* transform = MakeGarbageCollected<SVGTransform>(SVGTransformType::kScale); - transform->SetScale(ToInterpolableNumber(list.Get(0))->Value(), - ToInterpolableNumber(list.Get(1))->Value()); + transform->SetScale(To<InterpolableNumber>(list.Get(0))->Value(), + To<InterpolableNumber>(list.Get(1))->Value()); return transform; } @@ -96,13 +96,13 @@ } SVGTransform* RotateFromInterpolableValue(const InterpolableValue& value) { - const InterpolableList& list = ToInterpolableList(value); + const auto& list = To<InterpolableList>(value); auto* transform = MakeGarbageCollected<SVGTransform>(SVGTransformType::kRotate); - transform->SetRotate(ToInterpolableNumber(list.Get(0))->Value(), - ToInterpolableNumber(list.Get(1))->Value(), - ToInterpolableNumber(list.Get(2))->Value()); + transform->SetRotate(To<InterpolableNumber>(list.Get(0))->Value(), + To<InterpolableNumber>(list.Get(1))->Value(), + To<InterpolableNumber>(list.Get(2))->Value()); return transform; } @@ -114,7 +114,7 @@ SVGTransform* SkewXFromInterpolableValue(const InterpolableValue& value) { auto* transform = MakeGarbageCollected<SVGTransform>(SVGTransformType::kSkewx); - transform->SetSkewX(ToInterpolableNumber(value).Value()); + transform->SetSkewX(To<InterpolableNumber>(value).Value()); return transform; } @@ -126,7 +126,7 @@ SVGTransform* SkewYFromInterpolableValue(const InterpolableValue& value) { auto* transform = MakeGarbageCollected<SVGTransform>(SVGTransformType::kSkewy); - transform->SetSkewY(ToInterpolableNumber(value).Value()); + transform->SetSkewY(To<InterpolableNumber>(value).Value()); return transform; } @@ -256,8 +256,8 @@ } if (!keyframe.IsNeutral()) { - SVGPropertyBase* svg_value = - ToSVGInterpolationEnvironment(environment) + auto* svg_value = + To<SVGInterpolationEnvironment>(environment) .SvgBaseValue() .CloneForAnimation( To<SVGPropertySpecificKeyframe>(keyframe).Value()); @@ -271,7 +271,7 @@ auto interpolable_list = std::make_unique<InterpolableList>(types.size()); wtf_size_t interpolable_list_index = 0; for (auto& part : interpolable_parts) { - InterpolableList& list = ToInterpolableList(*part); + auto& list = To<InterpolableList>(*part); for (wtf_size_t i = 0; i < list.length(); ++i) { interpolable_list->Set(interpolable_list_index, std::move(list.GetMutable(i))); @@ -287,7 +287,7 @@ const InterpolableValue& interpolable_value, const NonInterpolableValue* non_interpolable_value) const { auto* result = MakeGarbageCollected<SVGTransformList>(); - const InterpolableList& list = ToInterpolableList(interpolable_value); + const auto& list = To<InterpolableList>(interpolable_value); const Vector<SVGTransformType>& transform_types = ToSVGTransformNonInterpolableValue(non_interpolable_value) ->TransformTypes();
diff --git a/third_party/blink/renderer/core/animation/transition_interpolation.h b/third_party/blink/renderer/core/animation/transition_interpolation.h index 62e7b92..e87dd4b 100644 --- a/third_party/blink/renderer/core/animation/transition_interpolation.h +++ b/third_party/blink/renderer/core/animation/transition_interpolation.h
@@ -98,11 +98,12 @@ mutable std::unique_ptr<InterpolableValue> cached_interpolable_value_; }; -DEFINE_TYPE_CASTS(TransitionInterpolation, - Interpolation, - value, - value->IsTransitionInterpolation(), - value.IsTransitionInterpolation()); +template <> +struct DowncastTraits<TransitionInterpolation> { + static bool AllowFrom(const Interpolation& value) { + return value.IsTransitionInterpolation(); + } +}; } // namespace blink
diff --git a/third_party/blink/renderer/core/animation/underlying_length_checker.h b/third_party/blink/renderer/core/animation/underlying_length_checker.h index ba7d0b61..badae96 100644 --- a/third_party/blink/renderer/core/animation/underlying_length_checker.h +++ b/third_party/blink/renderer/core/animation/underlying_length_checker.h
@@ -21,7 +21,7 @@ static wtf_size_t GetUnderlyingLength(const InterpolationValue& underlying) { if (!underlying) return 0; - return ToInterpolableList(*underlying.interpolable_value).length(); + return To<InterpolableList>(*underlying.interpolable_value).length(); } bool IsValid(const InterpolationEnvironment&,
diff --git a/third_party/blink/renderer/core/css/resolver/css_variable_animator.cc b/third_party/blink/renderer/core/css/resolver/css_variable_animator.cc index 1edd47f..f137cab 100644 --- a/third_party/blink/renderer/core/css/resolver/css_variable_animator.cc +++ b/third_party/blink/renderer/core/css/resolver/css_variable_animator.cc
@@ -70,13 +70,13 @@ const ActiveInterpolations& interpolations = ActiveInterpolationsForCustomProperty(update_, property); const Interpolation& interpolation = *interpolations.front(); - if (interpolation.IsInvalidatableInterpolation()) { + if (IsA<InvalidatableInterpolation>(interpolation)) { CSSInterpolationTypesMap map(state_.GetDocument().GetPropertyRegistry(), state_.GetDocument()); CSSInterpolationEnvironment environment(map, state_, this); InvalidatableInterpolation::ApplyStack(interpolations, environment); } else { - ToTransitionInterpolation(interpolation).Apply(state_); + To<TransitionInterpolation>(interpolation).Apply(state_); } pending_properties_.erase(property); }
diff --git a/third_party/blink/renderer/core/css/resolver/style_animator.cc b/third_party/blink/renderer/core/css/resolver/style_animator.cc index c9ebb4d..4bac6dd7 100644 --- a/third_party/blink/renderer/core/css/resolver/style_animator.cc +++ b/third_party/blink/renderer/core/css/resolver/style_animator.cc
@@ -65,13 +65,13 @@ const ActiveInterpolations& interpolations = GetActiveInterpolations(state_.AnimationUpdate(), property_handle); const Interpolation& interpolation = *interpolations.front(); - if (interpolation.IsInvalidatableInterpolation()) { + if (IsA<InvalidatableInterpolation>(interpolation)) { CSSInterpolationTypesMap map(state_.GetDocument().GetPropertyRegistry(), state_.GetDocument()); CSSInterpolationEnvironment environment(map, state_, &cascade_, &resolver); InvalidatableInterpolation::ApplyStack(interpolations, environment); } else { - ToTransitionInterpolation(interpolation).Apply(state_); + To<TransitionInterpolation>(interpolation).Apply(state_); } }
diff --git a/third_party/blink/renderer/core/css/resolver/style_resolver.cc b/third_party/blink/renderer/core/css/resolver/style_resolver.cc index 4b30898e1..880c118c 100644 --- a/third_party/blink/renderer/core/css/resolver/style_resolver.cc +++ b/third_party/blink/renderer/core/css/resolver/style_resolver.cc
@@ -1344,13 +1344,13 @@ state.Style()->ForcedColorAdjust() != EForcedColorAdjust::kNone) continue; const Interpolation& interpolation = *entry.value.front(); - if (interpolation.IsInvalidatableInterpolation()) { + if (IsA<InvalidatableInterpolation>(interpolation)) { CSSInterpolationTypesMap map(state.GetDocument().GetPropertyRegistry(), state.GetDocument()); CSSInterpolationEnvironment environment(map, state, nullptr); InvalidatableInterpolation::ApplyStack(entry.value, environment); } else { - ToTransitionInterpolation(interpolation).Apply(state); + To<TransitionInterpolation>(interpolation).Apply(state); } } }
diff --git a/third_party/blink/renderer/core/fileapi/file_test.cc b/third_party/blink/renderer/core/fileapi/file_test.cc index 3959c353..7ab9d122 100644 --- a/third_party/blink/renderer/core/fileapi/file_test.cc +++ b/third_party/blink/renderer/core/fileapi/file_test.cc
@@ -26,7 +26,7 @@ static void Create(File* file, base::Time modified_time) { mojo::PendingRemote<mojom::blink::Blob> remote; PostCrossThreadTask( - *base::CreateSequencedTaskRunner({base::ThreadPool()}), FROM_HERE, + *base::CreateSingleThreadTaskRunner({base::ThreadPool()}), FROM_HERE, CrossThreadBindOnce( [](const String& uuid, mojo::PendingReceiver<mojom::blink::Blob> receiver,
diff --git a/third_party/blink/renderer/core/layout/ng/layout_ng_flexible_box.cc b/third_party/blink/renderer/core/layout/ng/layout_ng_flexible_box.cc index 152b8baf..d4a96aa 100644 --- a/third_party/blink/renderer/core/layout/ng/layout_ng_flexible_box.cc +++ b/third_party/blink/renderer/core/layout/ng/layout_ng_flexible_box.cc
@@ -52,4 +52,31 @@ descendant.node.UseLegacyOutOfFlowPositioning(); } +namespace { + +void MergeAnonymousFlexItems(LayoutObject* remove_child) { + // When we remove a flex item, and the previous and next siblings of the item + // are text nodes wrapped in anonymous flex items, the adjacent text nodes + // need to be merged into the same flex item. + LayoutObject* prev = remove_child->PreviousSibling(); + if (!prev || !prev->IsAnonymousBlock()) + return; + LayoutObject* next = remove_child->NextSibling(); + if (!next || !next->IsAnonymousBlock()) + return; + ToLayoutBoxModelObject(next)->MoveAllChildrenTo(ToLayoutBoxModelObject(prev)); + To<LayoutBlockFlow>(next)->DeleteLineBoxTree(); + next->Destroy(); +} + +} // namespace + +void LayoutNGFlexibleBox::RemoveChild(LayoutObject* child) { + if (!DocumentBeingDestroyed() && + !StyleRef().IsDeprecatedFlexboxUsingFlexLayout()) + MergeAnonymousFlexItems(child); + + LayoutBlock::RemoveChild(child); +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/layout/ng/layout_ng_flexible_box.h b/third_party/blink/renderer/core/layout/ng/layout_ng_flexible_box.h index 332506c6..f1a361e 100644 --- a/third_party/blink/renderer/core/layout/ng/layout_ng_flexible_box.h +++ b/third_party/blink/renderer/core/layout/ng/layout_ng_flexible_box.h
@@ -25,6 +25,8 @@ const char* GetName() const override { return "LayoutNGFlexibleBox"; } protected: + void RemoveChild(LayoutObject*) override; + bool IsOfType(LayoutObjectType type) const override { return type == kLayoutObjectNGFlexibleBox || LayoutNGMixin<LayoutBlock>::IsOfType(type);
diff --git a/third_party/blink/renderer/core/layout/ng/ng_flex_layout_algorithm.cc b/third_party/blink/renderer/core/layout/ng/ng_flex_layout_algorithm.cc index 92bb41a6..771f81758 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_flex_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_flex_layout_algorithm.cc
@@ -49,11 +49,12 @@ } LayoutUnit NGFlexLayoutAlgorithm::MainAxisContentExtent( - LayoutUnit sum_hypothetical_main_size) { + LayoutUnit sum_hypothetical_main_size) const { if (Style().ResolvedIsColumnFlexDirection()) { return ComputeBlockSizeForFragment( ConstraintSpace(), Style(), border_padding_, - sum_hypothetical_main_size + (border_padding_).BlockSum()) - + sum_hypothetical_main_size + + border_scrollbar_padding_.BlockSum()) - border_scrollbar_padding_.BlockSum(); } return content_box_size_.inline_size;
diff --git a/third_party/blink/renderer/core/layout/ng/ng_flex_layout_algorithm.h b/third_party/blink/renderer/core/layout/ng/ng_flex_layout_algorithm.h index fa0e0eb5f..3739c67 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_flex_layout_algorithm.h +++ b/third_party/blink/renderer/core/layout/ng/ng_flex_layout_algorithm.h
@@ -57,7 +57,7 @@ // This is same method as FlexItem but we need that logic before FlexItem is // constructed. bool MainAxisIsInlineAxis(const NGBlockNode& child) const; - LayoutUnit MainAxisContentExtent(LayoutUnit sum_hypothetical_main_size); + LayoutUnit MainAxisContentExtent(LayoutUnit sum_hypothetical_main_size) const; void HandleOutOfFlowPositioned(NGBlockNode child); // TODO(dgrogan): This is redundant with FlexLayoutAlgorithm.IsMultiline() but
diff --git a/third_party/blink/renderer/modules/nfc/ndef_message.cc b/third_party/blink/renderer/modules/nfc/ndef_message.cc index 7d2fa8e2..5f6413e 100644 --- a/third_party/blink/renderer/modules/nfc/ndef_message.cc +++ b/third_party/blink/renderer/modules/nfc/ndef_message.cc
@@ -17,8 +17,17 @@ NDEFMessage* NDEFMessage::Create(const ExecutionContext* execution_context, const NDEFMessageInit* init, ExceptionState& exception_state) { + // https://w3c.github.io/web-nfc/#creating-ndef-message + + // NDEFMessageInit#records is a required field. + DCHECK(init->hasRecords()); + if (init->records().IsEmpty()) { + exception_state.ThrowTypeError( + "NDEFMessageInit#records being empty makes no sense."); + return nullptr; + } + NDEFMessage* message = MakeGarbageCollected<NDEFMessage>(); - if (init->hasRecords()) { for (const NDEFRecordInit* record_init : init->records()) { NDEFRecord* record = NDEFRecord::Create(execution_context, record_init, exception_state); @@ -27,7 +36,6 @@ DCHECK(record); message->records_.push_back(record); } - } return message; } @@ -35,6 +43,7 @@ NDEFMessage* NDEFMessage::Create(const ExecutionContext* execution_context, const NDEFMessageSource& source, ExceptionState& exception_state) { + // https://w3c.github.io/web-nfc/#creating-ndef-message if (source.IsString()) { NDEFMessage* message = MakeGarbageCollected<NDEFMessage>(); message->records_.push_back(MakeGarbageCollected<NDEFRecord>(
diff --git a/third_party/blink/renderer/modules/nfc/ndef_message_init.idl b/third_party/blink/renderer/modules/nfc/ndef_message_init.idl index 1a516c8..d078ff87 100644 --- a/third_party/blink/renderer/modules/nfc/ndef_message_init.idl +++ b/third_party/blink/renderer/modules/nfc/ndef_message_init.idl
@@ -5,5 +5,5 @@ // https://w3c.github.io/web-nfc/#dom-ndefmessageinit dictionary NDEFMessageInit { - sequence<NDEFRecordInit> records; + required sequence<NDEFRecordInit> records; };
diff --git a/third_party/blink/renderer/modules/nfc/ndef_record.cc b/third_party/blink/renderer/modules/nfc/ndef_record.cc index 10c9fee..f8e145e7 100644 --- a/third_party/blink/renderer/modules/nfc/ndef_record.cc +++ b/third_party/blink/renderer/modules/nfc/ndef_record.cc
@@ -251,21 +251,11 @@ NDEFRecord* NDEFRecord::Create(const ExecutionContext* execution_context, const NDEFRecordInit* init, ExceptionState& exception_state) { - // https://w3c.github.io/web-nfc/#creating-web-nfc-message - String record_type; - if (!init->hasRecordType()) { - if (!init->hasData()) { - exception_state.ThrowTypeError("The record has neither type nor data."); - return nullptr; - } - if (init->data().IsString()) { - record_type = "text"; - } else { - record_type = "mime"; - } - } else { - record_type = init->recordType(); - } + // https://w3c.github.io/web-nfc/#creating-ndef-record + + // NDEFRecordInit#recordType is a required field. + DCHECK(init->hasRecordType()); + const String& record_type = init->recordType(); // https://w3c.github.io/web-nfc/#dom-ndefrecordinit-mediatype if (init->hasMediaType() && record_type != "mime") {
diff --git a/third_party/blink/renderer/modules/nfc/ndef_record_init.idl b/third_party/blink/renderer/modules/nfc/ndef_record_init.idl index 110ae70..74f203fb 100644 --- a/third_party/blink/renderer/modules/nfc/ndef_record_init.idl +++ b/third_party/blink/renderer/modules/nfc/ndef_record_init.idl
@@ -13,7 +13,7 @@ // https://w3c.github.io/web-nfc/#dom-ndefrecordinit dictionary NDEFRecordInit { - USVString recordType; + required USVString recordType; USVString mediaType; USVString id;
diff --git a/third_party/blink/renderer/modules/nfc/ndef_writer.cc b/third_party/blink/renderer/modules/nfc/ndef_writer.cc index 506407d..0405afe 100644 --- a/third_party/blink/renderer/modules/nfc/ndef_writer.cc +++ b/third_party/blink/renderer/modules/nfc/ndef_writer.cc
@@ -66,7 +66,7 @@ return ScriptPromise(); } - // Step 10.10.1: Run "create NDEF message", if this throws an exception, + // Step 11.2: Run "create NDEF message", if this throws an exception, // reject p with that exception and abort these steps. NDEFMessage* ndef_message = NDEFMessage::Create(execution_context, push_message, exception_state); @@ -74,12 +74,6 @@ return ScriptPromise(); } - // If NDEFMessage.records is empty, reject promise with TypeError - if (ndef_message->records().size() == 0) { - exception_state.ThrowTypeError("Empty NDEFMessage was provided."); - return ScriptPromise(); - } - auto message = device::mojom::blink::NDEFMessage::From(ndef_message); DCHECK(message);
diff --git a/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor_test.cc b/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor_test.cc index 2a300033..859ae04 100644 --- a/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor_test.cc +++ b/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor_test.cc
@@ -2659,7 +2659,7 @@ } TEST_P(PaintArtifactCompositorTest, SynthesizedClipSimple) { - // This tests the simplist case that a single layer needs to be clipped + // This tests the simplest case that a single layer needs to be clipped // by a single composited rounded clip. FloatSize corner(5, 5); FloatRoundedRect rrect(FloatRect(50, 50, 300, 200), corner, corner, corner, @@ -2671,49 +2671,17 @@ .RectDrawing(IntRect(0, 0, 100, 100), Color::kBlack); Update(artifact.Build()); - if (RuntimeEnabledFeatures::FastBorderRadiusEnabled()) { - // Expectation in effect stack diagram: - // l0 - // [ mask_isolation_0 ] - // [ e0 ] - // One content layer. - ASSERT_EQ(1u, LayerCount()); - // There is still a "synthesized layer" but it's null. - ASSERT_EQ(1u, SynthesizedClipLayerCount()); - EXPECT_FALSE(SynthesizedClipLayerAt(0)); - - const cc::Layer* content0 = LayerAt(0); - - constexpr int c0_id = 1; - constexpr int e0_id = 1; - - int c1_id = content0->clip_tree_index(); - const cc::ClipNode& cc_c1 = *GetPropertyTrees().clip_tree.Node(c1_id); - EXPECT_EQ(gfx::RectF(50, 50, 300, 200), cc_c1.clip); - ASSERT_EQ(c0_id, cc_c1.parent_id); - int mask_isolation_0_id = content0->effect_tree_index(); - const cc::EffectNode& mask_isolation_0 = - *GetPropertyTrees().effect_tree.Node(mask_isolation_0_id); - ASSERT_EQ(e0_id, mask_isolation_0.parent_id); - EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_0.blend_mode); - EXPECT_TRUE(mask_isolation_0.is_fast_rounded_corner); - EXPECT_EQ(gfx::RRectF(50, 50, 300, 200, 5), - mask_isolation_0.rounded_corner_bounds); - EXPECT_FALSE(mask_isolation_0.HasRenderSurface()); - return; - } - // Expectation in effect stack diagram: - // l1 - // l0 [ mask_effect_0 ] + // l0 // [ mask_isolation_0 ] // [ e0 ] // One content layer. - ASSERT_EQ(2u, LayerCount()); + ASSERT_EQ(1u, LayerCount()); + // There is still a "synthesized layer" but it's null. ASSERT_EQ(1u, SynthesizedClipLayerCount()); + EXPECT_FALSE(SynthesizedClipLayerAt(0)); const cc::Layer* content0 = LayerAt(0); - const cc::Layer* clip_mask0 = LayerAt(1); constexpr int c0_id = 1; constexpr int e0_id = 1; @@ -2727,20 +2695,10 @@ *GetPropertyTrees().effect_tree.Node(mask_isolation_0_id); ASSERT_EQ(e0_id, mask_isolation_0.parent_id); EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_0.blend_mode); - EXPECT_TRUE(mask_isolation_0.HasRenderSurface()); - - EXPECT_EQ(SynthesizedClipLayerAt(0), clip_mask0); - EXPECT_EQ(gfx::Size(300, 200), clip_mask0->bounds()); - EXPECT_EQ(c1_id, clip_mask0->clip_tree_index()); - int mask_effect_0_id = clip_mask0->effect_tree_index(); - const cc::EffectNode& mask_effect_0 = - *GetPropertyTrees().effect_tree.Node(mask_effect_0_id); - ASSERT_EQ(mask_isolation_0_id, mask_effect_0.parent_id); - EXPECT_EQ(SkBlendMode::kDstIn, mask_effect_0.blend_mode); - - // The masks DrawsContent because it has content that it masks which also - // DrawsContent. - EXPECT_TRUE(clip_mask0->DrawsContent()); + EXPECT_TRUE(mask_isolation_0.is_fast_rounded_corner); + EXPECT_EQ(gfx::RRectF(50, 50, 300, 200, 5), + mask_isolation_0.rounded_corner_bounds); + EXPECT_FALSE(mask_isolation_0.HasRenderSurface()); } TEST_P(PaintArtifactCompositorTest, SynthesizedClipRotatedNotSupported) { @@ -2813,49 +2771,17 @@ .RectDrawing(IntRect(0, 0, 100, 100), Color::kBlack); Update(artifact.Build()); - if (RuntimeEnabledFeatures::FastBorderRadiusEnabled()) { - // Expectation in effect stack diagram: - // l0 - // [ mask_isolation_0 ] - // [ e0 ] - // One content layer. - ASSERT_EQ(1u, LayerCount()); - // There is still a "synthesized layer" but it's null. - ASSERT_EQ(1u, SynthesizedClipLayerCount()); - EXPECT_FALSE(SynthesizedClipLayerAt(0)); - - const cc::Layer* content0 = LayerAt(0); - - constexpr int c0_id = 1; - constexpr int e0_id = 1; - - int c1_id = content0->clip_tree_index(); - const cc::ClipNode& cc_c1 = *GetPropertyTrees().clip_tree.Node(c1_id); - EXPECT_EQ(gfx::RectF(50, 50, 300, 200), cc_c1.clip); - ASSERT_EQ(c0_id, cc_c1.parent_id); - int mask_isolation_0_id = content0->effect_tree_index(); - const cc::EffectNode& mask_isolation_0 = - *GetPropertyTrees().effect_tree.Node(mask_isolation_0_id); - ASSERT_EQ(e0_id, mask_isolation_0.parent_id); - EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_0.blend_mode); - EXPECT_TRUE(mask_isolation_0.is_fast_rounded_corner); - EXPECT_EQ(gfx::RRectF(50, 50, 300, 200, 5), - mask_isolation_0.rounded_corner_bounds); - EXPECT_FALSE(mask_isolation_0.HasRenderSurface()); - return; - } - // Expectation in effect stack diagram: - // l1 - // l0 [ mask_effect_0 ] + // l0 // [ mask_isolation_0 ] // [ e0 ] // One content layer. - ASSERT_EQ(2u, LayerCount()); + ASSERT_EQ(1u, LayerCount()); + // There is still a "synthesized layer" but it's null. ASSERT_EQ(1u, SynthesizedClipLayerCount()); + EXPECT_FALSE(SynthesizedClipLayerAt(0)); const cc::Layer* content0 = LayerAt(0); - const cc::Layer* clip_mask0 = LayerAt(1); constexpr int c0_id = 1; constexpr int e0_id = 1; @@ -2869,21 +2795,15 @@ *GetPropertyTrees().effect_tree.Node(mask_isolation_0_id); ASSERT_EQ(e0_id, mask_isolation_0.parent_id); EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_0.blend_mode); - EXPECT_TRUE(mask_isolation_0.HasRenderSurface()); - - EXPECT_EQ(SynthesizedClipLayerAt(0), clip_mask0); - EXPECT_EQ(gfx::Size(300, 200), clip_mask0->bounds()); - EXPECT_EQ(c1_id, clip_mask0->clip_tree_index()); - int mask_effect_0_id = clip_mask0->effect_tree_index(); - const cc::EffectNode& mask_effect_0 = - *GetPropertyTrees().effect_tree.Node(mask_effect_0_id); - ASSERT_EQ(mask_isolation_0_id, mask_effect_0.parent_id); - EXPECT_EQ(SkBlendMode::kDstIn, mask_effect_0.blend_mode); + EXPECT_TRUE(mask_isolation_0.is_fast_rounded_corner); + EXPECT_EQ(gfx::RRectF(50, 50, 300, 200, 5), + mask_isolation_0.rounded_corner_bounds); + EXPECT_FALSE(mask_isolation_0.HasRenderSurface()); } TEST_P(PaintArtifactCompositorTest, - SynthesizedClipSimpleFastBorderNotSupported2) { - // This tests the simplist case that a single layer needs to be clipped + SynthesizedClipShaderBasedBorderRadiusNotSupported2) { + // This tests the simplest case that a single layer needs to be clipped // by a single composited rounded clip. Because the radius is unsymmetric, // it falls back to a mask layer. FloatSize corner(30, 40); @@ -2936,8 +2856,9 @@ EXPECT_TRUE(clip_mask0->DrawsContent()); } -TEST_P(PaintArtifactCompositorTest, - SynthesizedClipSimpleFastBorderNotSupportedMacNonEqualCorners) { +TEST_P( + PaintArtifactCompositorTest, + SynthesizedClipSimpleShaderBasedBorderRadiusNotSupportedMacNonEqualCorners) { // Tests that on Mac, we fall back to a mask layer if the corners are not all // the same radii. FloatSize corner(30, 30); @@ -2953,19 +2874,13 @@ #if defined(OS_MACOSX) ASSERT_EQ(2u, LayerCount()); #else - if (RuntimeEnabledFeatures::FastBorderRadiusEnabled()) - ASSERT_EQ(1u, LayerCount()); - else - ASSERT_EQ(2u, LayerCount()); + ASSERT_EQ(1u, LayerCount()); #endif } TEST_P(PaintArtifactCompositorTest, SynthesizedClipNested) { - // This tests the simplist case that a single layer needs to be clipped + // This tests the simplest case that a single layer needs to be clipped // by a single composited rounded clip. - if (!RuntimeEnabledFeatures::FastBorderRadiusEnabled()) - return; - FloatSize corner(5, 5); FloatRoundedRect rrect(FloatRect(50, 50, 300, 200), corner, corner, corner, corner); @@ -3218,62 +3133,19 @@ .RectDrawing(IntRect(0, 0, 100, 100), Color::kBlack); Update(artifact.Build()); - if (RuntimeEnabledFeatures::FastBorderRadiusEnabled()) { - // Expectation in effect stack diagram: - // l2 - // l0 l1 - // [ mask_isolation_0 ] - // [ e0 ] - // Two content layers, one clip mask. - ASSERT_EQ(2u, LayerCount()); - // There is still a "synthesized layer" but it's null. - ASSERT_EQ(1u, SynthesizedClipLayerCount()); - EXPECT_FALSE(SynthesizedClipLayerAt(0)); - - const cc::Layer* content0 = LayerAt(0); - const cc::Layer* content1 = LayerAt(1); - - constexpr int t0_id = 1; - constexpr int c0_id = 1; - constexpr int e0_id = 1; - - EXPECT_EQ(t0_id, content0->transform_tree_index()); - int c1_id = content0->clip_tree_index(); - const cc::ClipNode& cc_c1 = *GetPropertyTrees().clip_tree.Node(c1_id); - EXPECT_EQ(gfx::RectF(50, 50, 300, 200), cc_c1.clip); - ASSERT_EQ(c0_id, cc_c1.parent_id); - int mask_isolation_0_id = content0->effect_tree_index(); - const cc::EffectNode& mask_isolation_0 = - *GetPropertyTrees().effect_tree.Node(mask_isolation_0_id); - ASSERT_EQ(e0_id, mask_isolation_0.parent_id); - EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_0.blend_mode); - - int t1_id = content1->transform_tree_index(); - const cc::TransformNode& cc_t1 = - *GetPropertyTrees().transform_tree.Node(t1_id); - ASSERT_EQ(t0_id, cc_t1.parent_id); - EXPECT_EQ(c1_id, content1->clip_tree_index()); - EXPECT_EQ(mask_isolation_0_id, content1->effect_tree_index()); - - EXPECT_TRUE(mask_isolation_0.is_fast_rounded_corner); - EXPECT_EQ(gfx::RRectF(50, 50, 300, 200, 5), - mask_isolation_0.rounded_corner_bounds); - EXPECT_FALSE(mask_isolation_0.HasRenderSurface()); - return; - } - // Expectation in effect stack diagram: // l2 - // l0 l1 [ mask_effect_0 ] + // l0 l1 // [ mask_isolation_0 ] // [ e0 ] // Two content layers, one clip mask. - ASSERT_EQ(3u, LayerCount()); + ASSERT_EQ(2u, LayerCount()); + // There is still a "synthesized layer" but it's null. ASSERT_EQ(1u, SynthesizedClipLayerCount()); + EXPECT_FALSE(SynthesizedClipLayerAt(0)); const cc::Layer* content0 = LayerAt(0); const cc::Layer* content1 = LayerAt(1); - const cc::Layer* clip_mask0 = LayerAt(2); constexpr int t0_id = 1; constexpr int c0_id = 1; @@ -3297,15 +3169,10 @@ EXPECT_EQ(c1_id, content1->clip_tree_index()); EXPECT_EQ(mask_isolation_0_id, content1->effect_tree_index()); - EXPECT_EQ(SynthesizedClipLayerAt(0), clip_mask0); - EXPECT_EQ(gfx::Size(300, 200), clip_mask0->bounds()); - EXPECT_EQ(t0_id, clip_mask0->transform_tree_index()); - EXPECT_EQ(c1_id, clip_mask0->clip_tree_index()); - int mask_effect_0_id = clip_mask0->effect_tree_index(); - const cc::EffectNode& mask_effect_0 = - *GetPropertyTrees().effect_tree.Node(mask_effect_0_id); - ASSERT_EQ(mask_isolation_0_id, mask_effect_0.parent_id); - EXPECT_EQ(SkBlendMode::kDstIn, mask_effect_0.blend_mode); + EXPECT_TRUE(mask_isolation_0.is_fast_rounded_corner); + EXPECT_EQ(gfx::RRectF(50, 50, 300, 200, 5), + mask_isolation_0.rounded_corner_bounds); + EXPECT_FALSE(mask_isolation_0.HasRenderSurface()); } TEST_P(PaintArtifactCompositorTest, SynthesizedClipDiscontiguous) { @@ -3329,78 +3196,21 @@ .RectDrawing(IntRect(0, 0, 100, 100), Color::kBlack); Update(artifact.Build()); - if (RuntimeEnabledFeatures::FastBorderRadiusEnabled()) { - // Expectation in effect stack diagram: - // l1 l4 - // l0 l3 - // [ mask_isolation_0 ] l2 [ mask_isolation_1 ] - // [ e0 ] - // Three content layers. - ASSERT_EQ(3u, LayerCount()); - // There are still "synthesized layers" but they're null. - ASSERT_EQ(2u, SynthesizedClipLayerCount()); - EXPECT_FALSE(SynthesizedClipLayerAt(0)); - EXPECT_FALSE(SynthesizedClipLayerAt(1)); - - const cc::Layer* content0 = LayerAt(0); - const cc::Layer* content1 = LayerAt(1); - const cc::Layer* content2 = LayerAt(2); - - constexpr int t0_id = 1; - constexpr int c0_id = 1; - constexpr int e0_id = 1; - - EXPECT_EQ(t0_id, content0->transform_tree_index()); - int c1_id = content0->clip_tree_index(); - const cc::ClipNode& cc_c1 = *GetPropertyTrees().clip_tree.Node(c1_id); - EXPECT_EQ(gfx::RectF(50, 50, 300, 200), cc_c1.clip); - ASSERT_EQ(c0_id, cc_c1.parent_id); - int mask_isolation_0_id = content0->effect_tree_index(); - const cc::EffectNode& mask_isolation_0 = - *GetPropertyTrees().effect_tree.Node(mask_isolation_0_id); - ASSERT_EQ(e0_id, mask_isolation_0.parent_id); - EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_0.blend_mode); - EXPECT_TRUE(mask_isolation_0.is_fast_rounded_corner); - EXPECT_EQ(gfx::RRectF(50, 50, 300, 200, 5), - mask_isolation_0.rounded_corner_bounds); - EXPECT_FALSE(mask_isolation_0.HasRenderSurface()); - - int t1_id = content1->transform_tree_index(); - const cc::TransformNode& cc_t1 = - *GetPropertyTrees().transform_tree.Node(t1_id); - ASSERT_EQ(t0_id, cc_t1.parent_id); - EXPECT_EQ(c0_id, content1->clip_tree_index()); - EXPECT_EQ(e0_id, content1->effect_tree_index()); - - EXPECT_EQ(t0_id, content2->transform_tree_index()); - EXPECT_EQ(c1_id, content2->clip_tree_index()); - int mask_isolation_1_id = content2->effect_tree_index(); - const cc::EffectNode& mask_isolation_1 = - *GetPropertyTrees().effect_tree.Node(mask_isolation_1_id); - EXPECT_NE(mask_isolation_0_id, mask_isolation_1_id); - ASSERT_EQ(e0_id, mask_isolation_1.parent_id); - EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_1.blend_mode); - EXPECT_TRUE(mask_isolation_1.is_fast_rounded_corner); - EXPECT_EQ(gfx::RRectF(50, 50, 300, 200, 5), - mask_isolation_1.rounded_corner_bounds); - EXPECT_FALSE(mask_isolation_1.HasRenderSurface()); - return; - } - // Expectation in effect stack diagram: // l1 l4 - // l0 [ mask_effect_0 ] l3 [ mask_effect_1 ] + // l0 l3 // [ mask_isolation_0 ] l2 [ mask_isolation_1 ] // [ e0 ] - // Three content layers, two clip mask. - ASSERT_EQ(5u, LayerCount()); + // Three content layers. + ASSERT_EQ(3u, LayerCount()); + // There are still "synthesized layers" but they're null. ASSERT_EQ(2u, SynthesizedClipLayerCount()); + EXPECT_FALSE(SynthesizedClipLayerAt(0)); + EXPECT_FALSE(SynthesizedClipLayerAt(1)); const cc::Layer* content0 = LayerAt(0); - const cc::Layer* clip_mask0 = LayerAt(1); - const cc::Layer* content1 = LayerAt(2); - const cc::Layer* content2 = LayerAt(3); - const cc::Layer* clip_mask1 = LayerAt(4); + const cc::Layer* content1 = LayerAt(1); + const cc::Layer* content2 = LayerAt(2); constexpr int t0_id = 1; constexpr int c0_id = 1; @@ -3416,17 +3226,10 @@ *GetPropertyTrees().effect_tree.Node(mask_isolation_0_id); ASSERT_EQ(e0_id, mask_isolation_0.parent_id); EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_0.blend_mode); - EXPECT_TRUE(mask_isolation_0.HasRenderSurface()); - - EXPECT_EQ(SynthesizedClipLayerAt(0), clip_mask0); - EXPECT_EQ(gfx::Size(300, 200), clip_mask0->bounds()); - EXPECT_EQ(t0_id, clip_mask0->transform_tree_index()); - EXPECT_EQ(c1_id, clip_mask0->clip_tree_index()); - int mask_effect_0_id = clip_mask0->effect_tree_index(); - const cc::EffectNode& mask_effect_0 = - *GetPropertyTrees().effect_tree.Node(mask_effect_0_id); - ASSERT_EQ(mask_isolation_0_id, mask_effect_0.parent_id); - EXPECT_EQ(SkBlendMode::kDstIn, mask_effect_0.blend_mode); + EXPECT_TRUE(mask_isolation_0.is_fast_rounded_corner); + EXPECT_EQ(gfx::RRectF(50, 50, 300, 200, 5), + mask_isolation_0.rounded_corner_bounds); + EXPECT_FALSE(mask_isolation_0.HasRenderSurface()); int t1_id = content1->transform_tree_index(); const cc::TransformNode& cc_t1 = @@ -3443,17 +3246,10 @@ EXPECT_NE(mask_isolation_0_id, mask_isolation_1_id); ASSERT_EQ(e0_id, mask_isolation_1.parent_id); EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_1.blend_mode); - EXPECT_TRUE(mask_isolation_1.HasRenderSurface()); - - EXPECT_EQ(SynthesizedClipLayerAt(1), clip_mask1); - EXPECT_EQ(gfx::Size(300, 200), clip_mask1->bounds()); - EXPECT_EQ(t0_id, clip_mask1->transform_tree_index()); - EXPECT_EQ(c1_id, clip_mask1->clip_tree_index()); - int mask_effect_1_id = clip_mask1->effect_tree_index(); - const cc::EffectNode& mask_effect_1 = - *GetPropertyTrees().effect_tree.Node(mask_effect_1_id); - ASSERT_EQ(mask_isolation_1_id, mask_effect_1.parent_id); - EXPECT_EQ(SkBlendMode::kDstIn, mask_effect_1.blend_mode); + EXPECT_TRUE(mask_isolation_1.is_fast_rounded_corner); + EXPECT_EQ(gfx::RRectF(50, 50, 300, 200, 5), + mask_isolation_1.rounded_corner_bounds); + EXPECT_FALSE(mask_isolation_1.HasRenderSurface()); } TEST_P(PaintArtifactCompositorTest, SynthesizedClipAcrossChildEffect) { @@ -3475,65 +3271,20 @@ .RectDrawing(IntRect(0, 0, 100, 100), Color::kBlack); Update(artifact.Build()); - if (RuntimeEnabledFeatures::FastBorderRadiusEnabled()) { - // Expectation in effect stack diagram: - // l1 l3 - // l0 [ e1 ] l2 - // [ mask_isolation_0 ] - // [ e0 ] - // Three content layers. - ASSERT_EQ(3u, LayerCount()); - // There is still a "synthesized layer" but it's null. - ASSERT_EQ(1u, SynthesizedClipLayerCount()); - EXPECT_FALSE(SynthesizedClipLayerAt(0)); - - const cc::Layer* content0 = LayerAt(0); - const cc::Layer* content1 = LayerAt(1); - const cc::Layer* content2 = LayerAt(2); - - constexpr int c0_id = 1; - constexpr int e0_id = 1; - - int c1_id = content0->clip_tree_index(); - const cc::ClipNode& cc_c1 = *GetPropertyTrees().clip_tree.Node(c1_id); - EXPECT_EQ(gfx::RectF(50, 50, 300, 200), cc_c1.clip); - ASSERT_EQ(c0_id, cc_c1.parent_id); - int mask_isolation_0_id = content0->effect_tree_index(); - const cc::EffectNode& mask_isolation_0 = - *GetPropertyTrees().effect_tree.Node(mask_isolation_0_id); - ASSERT_EQ(e0_id, mask_isolation_0.parent_id); - EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_0.blend_mode); - EXPECT_FALSE(mask_isolation_0.HasRenderSurface()); - - EXPECT_EQ(c1_id, content1->clip_tree_index()); - int e1_id = content1->effect_tree_index(); - const cc::EffectNode& cc_e1 = *GetPropertyTrees().effect_tree.Node(e1_id); - ASSERT_EQ(mask_isolation_0_id, cc_e1.parent_id); - - EXPECT_EQ(c1_id, content2->clip_tree_index()); - EXPECT_EQ(mask_isolation_0_id, content2->effect_tree_index()); - - int e2_id = content2->effect_tree_index(); - const cc::EffectNode& cc_e2 = *GetPropertyTrees().effect_tree.Node(e2_id); - EXPECT_TRUE(cc_e2.is_fast_rounded_corner); - EXPECT_EQ(gfx::RRectF(50, 50, 300, 200, 5), - mask_isolation_0.rounded_corner_bounds); - return; - } - // Expectation in effect stack diagram: // l1 l3 - // l0 [ e1 ] l2 [ mask_effect_0 ] + // l0 [ e1 ] l2 // [ mask_isolation_0 ] // [ e0 ] - // Three content layers, one clip mask. - ASSERT_EQ(4u, LayerCount()); + // Three content layers. + ASSERT_EQ(3u, LayerCount()); + // There is still a "synthesized layer" but it's null. ASSERT_EQ(1u, SynthesizedClipLayerCount()); + EXPECT_FALSE(SynthesizedClipLayerAt(0)); const cc::Layer* content0 = LayerAt(0); const cc::Layer* content1 = LayerAt(1); const cc::Layer* content2 = LayerAt(2); - const cc::Layer* clip_mask0 = LayerAt(3); constexpr int c0_id = 1; constexpr int e0_id = 1; @@ -3547,7 +3298,7 @@ *GetPropertyTrees().effect_tree.Node(mask_isolation_0_id); ASSERT_EQ(e0_id, mask_isolation_0.parent_id); EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_0.blend_mode); - EXPECT_TRUE(mask_isolation_0.HasRenderSurface()); + EXPECT_FALSE(mask_isolation_0.HasRenderSurface()); EXPECT_EQ(c1_id, content1->clip_tree_index()); int e1_id = content1->effect_tree_index(); @@ -3557,14 +3308,11 @@ EXPECT_EQ(c1_id, content2->clip_tree_index()); EXPECT_EQ(mask_isolation_0_id, content2->effect_tree_index()); - EXPECT_EQ(SynthesizedClipLayerAt(0), clip_mask0); - EXPECT_EQ(gfx::Size(300, 200), clip_mask0->bounds()); - EXPECT_EQ(c1_id, clip_mask0->clip_tree_index()); - int mask_effect_0_id = clip_mask0->effect_tree_index(); - const cc::EffectNode& mask_effect_0 = - *GetPropertyTrees().effect_tree.Node(mask_effect_0_id); - ASSERT_EQ(mask_isolation_0_id, mask_effect_0.parent_id); - EXPECT_EQ(SkBlendMode::kDstIn, mask_effect_0.blend_mode); + int e2_id = content2->effect_tree_index(); + const cc::EffectNode& cc_e2 = *GetPropertyTrees().effect_tree.Node(e2_id); + EXPECT_TRUE(cc_e2.is_fast_rounded_corner); + EXPECT_EQ(gfx::RRectF(50, 50, 300, 200, 5), + mask_isolation_0.rounded_corner_bounds); } TEST_P(PaintArtifactCompositorTest, SynthesizedClipRespectOutputClip) { @@ -3590,87 +3338,23 @@ .RectDrawing(IntRect(0, 0, 100, 100), Color::kBlack); Update(artifact.Build()); - if (RuntimeEnabledFeatures::FastBorderRadiusEnabled()) { - // Expectation in effect stack diagram: - // l3 - // l1 l2 l5 - // l0 [ mask_isolation_1 ] l4 - // [ mask_isolation_0 ][ e1 ][ mask_isolation_2 ] - // [ e0 ] - // Three content layers. - ASSERT_EQ(3u, LayerCount()); - // There are still "synthesized layers" but they're null. - ASSERT_EQ(3u, SynthesizedClipLayerCount()); - EXPECT_FALSE(SynthesizedClipLayerAt(0)); - EXPECT_FALSE(SynthesizedClipLayerAt(1)); - EXPECT_FALSE(SynthesizedClipLayerAt(2)); - - const cc::Layer* content0 = LayerAt(0); - const cc::Layer* content1 = LayerAt(1); - const cc::Layer* content2 = LayerAt(2); - - constexpr int c0_id = 1; - constexpr int e0_id = 1; - - int c1_id = content0->clip_tree_index(); - const cc::ClipNode& cc_c1 = *GetPropertyTrees().clip_tree.Node(c1_id); - EXPECT_EQ(gfx::RectF(50, 50, 300, 200), cc_c1.clip); - ASSERT_EQ(c0_id, cc_c1.parent_id); - int mask_isolation_0_id = content0->effect_tree_index(); - const cc::EffectNode& mask_isolation_0 = - *GetPropertyTrees().effect_tree.Node(mask_isolation_0_id); - ASSERT_EQ(e0_id, mask_isolation_0.parent_id); - EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_0.blend_mode); - EXPECT_TRUE(mask_isolation_0.is_fast_rounded_corner); - EXPECT_EQ(gfx::RRectF(50, 50, 300, 200, 5), - mask_isolation_0.rounded_corner_bounds); - EXPECT_FALSE(mask_isolation_0.HasRenderSurface()); - - EXPECT_EQ(c1_id, content1->clip_tree_index()); - int mask_isolation_1_id = content1->effect_tree_index(); - const cc::EffectNode& mask_isolation_1 = - *GetPropertyTrees().effect_tree.Node(mask_isolation_1_id); - EXPECT_NE(mask_isolation_0_id, mask_isolation_1_id); - EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_1.blend_mode); - int e1_id = mask_isolation_1.parent_id; - const cc::EffectNode& cc_e1 = *GetPropertyTrees().effect_tree.Node(e1_id); - ASSERT_EQ(e0_id, cc_e1.parent_id); - EXPECT_TRUE(mask_isolation_1.is_fast_rounded_corner); - EXPECT_EQ(gfx::RRectF(50, 50, 300, 200, 5), - mask_isolation_1.rounded_corner_bounds); - EXPECT_FALSE(mask_isolation_1.HasRenderSurface()); - - EXPECT_EQ(c1_id, content2->clip_tree_index()); - int mask_isolation_2_id = content2->effect_tree_index(); - const cc::EffectNode& mask_isolation_2 = - *GetPropertyTrees().effect_tree.Node(mask_isolation_2_id); - EXPECT_NE(mask_isolation_0_id, mask_isolation_2_id); - EXPECT_NE(mask_isolation_1_id, mask_isolation_2_id); - ASSERT_EQ(e0_id, mask_isolation_2.parent_id); - EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_2.blend_mode); - EXPECT_TRUE(mask_isolation_2.is_fast_rounded_corner); - EXPECT_EQ(gfx::RRectF(50, 50, 300, 200, 5), - mask_isolation_2.rounded_corner_bounds); - EXPECT_FALSE(mask_isolation_2.HasRenderSurface()); - return; - } - // Expectation in effect stack diagram: // l3 - // l1 l2 [ mask_effect_1 ] l5 - // l0 [ mask_effect_0 ][ mask_isolation_1 ] l4 [ mask_effect_2 ] + // l1 l2 l5 + // l0 [ mask_isolation_1 ] l4 // [ mask_isolation_0 ][ e1 ][ mask_isolation_2 ] // [ e0 ] - // Three content layers, three clip mask. - ASSERT_EQ(6u, LayerCount()); + // Three content layers. + ASSERT_EQ(3u, LayerCount()); + // There are still "synthesized layers" but they're null. ASSERT_EQ(3u, SynthesizedClipLayerCount()); + EXPECT_FALSE(SynthesizedClipLayerAt(0)); + EXPECT_FALSE(SynthesizedClipLayerAt(1)); + EXPECT_FALSE(SynthesizedClipLayerAt(2)); const cc::Layer* content0 = LayerAt(0); - const cc::Layer* clip_mask0 = LayerAt(1); - const cc::Layer* content1 = LayerAt(2); - const cc::Layer* clip_mask1 = LayerAt(3); - const cc::Layer* content2 = LayerAt(4); - const cc::Layer* clip_mask2 = LayerAt(5); + const cc::Layer* content1 = LayerAt(1); + const cc::Layer* content2 = LayerAt(2); constexpr int c0_id = 1; constexpr int e0_id = 1; @@ -3684,15 +3368,10 @@ *GetPropertyTrees().effect_tree.Node(mask_isolation_0_id); ASSERT_EQ(e0_id, mask_isolation_0.parent_id); EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_0.blend_mode); - - EXPECT_EQ(SynthesizedClipLayerAt(0), clip_mask0); - EXPECT_EQ(gfx::Size(300, 200), clip_mask0->bounds()); - EXPECT_EQ(c1_id, clip_mask0->clip_tree_index()); - int mask_effect_0_id = clip_mask0->effect_tree_index(); - const cc::EffectNode& mask_effect_0 = - *GetPropertyTrees().effect_tree.Node(mask_effect_0_id); - ASSERT_EQ(mask_isolation_0_id, mask_effect_0.parent_id); - EXPECT_EQ(SkBlendMode::kDstIn, mask_effect_0.blend_mode); + EXPECT_TRUE(mask_isolation_0.is_fast_rounded_corner); + EXPECT_EQ(gfx::RRectF(50, 50, 300, 200, 5), + mask_isolation_0.rounded_corner_bounds); + EXPECT_FALSE(mask_isolation_0.HasRenderSurface()); EXPECT_EQ(c1_id, content1->clip_tree_index()); int mask_isolation_1_id = content1->effect_tree_index(); @@ -3703,15 +3382,10 @@ int e1_id = mask_isolation_1.parent_id; const cc::EffectNode& cc_e1 = *GetPropertyTrees().effect_tree.Node(e1_id); ASSERT_EQ(e0_id, cc_e1.parent_id); - - EXPECT_EQ(SynthesizedClipLayerAt(1), clip_mask1); - EXPECT_EQ(gfx::Size(300, 200), clip_mask1->bounds()); - EXPECT_EQ(c1_id, clip_mask1->clip_tree_index()); - int mask_effect_1_id = clip_mask1->effect_tree_index(); - const cc::EffectNode& mask_effect_1 = - *GetPropertyTrees().effect_tree.Node(mask_effect_1_id); - ASSERT_EQ(mask_isolation_1_id, mask_effect_1.parent_id); - EXPECT_EQ(SkBlendMode::kDstIn, mask_effect_1.blend_mode); + EXPECT_TRUE(mask_isolation_1.is_fast_rounded_corner); + EXPECT_EQ(gfx::RRectF(50, 50, 300, 200, 5), + mask_isolation_1.rounded_corner_bounds); + EXPECT_FALSE(mask_isolation_1.HasRenderSurface()); EXPECT_EQ(c1_id, content2->clip_tree_index()); int mask_isolation_2_id = content2->effect_tree_index(); @@ -3721,15 +3395,10 @@ EXPECT_NE(mask_isolation_1_id, mask_isolation_2_id); ASSERT_EQ(e0_id, mask_isolation_2.parent_id); EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_2.blend_mode); - - EXPECT_EQ(SynthesizedClipLayerAt(2), clip_mask2); - EXPECT_EQ(gfx::Size(300, 200), clip_mask2->bounds()); - EXPECT_EQ(c1_id, clip_mask2->clip_tree_index()); - int mask_effect_2_id = clip_mask2->effect_tree_index(); - const cc::EffectNode& mask_effect_2 = - *GetPropertyTrees().effect_tree.Node(mask_effect_2_id); - ASSERT_EQ(mask_isolation_2_id, mask_effect_2.parent_id); - EXPECT_EQ(SkBlendMode::kDstIn, mask_effect_2.blend_mode); + EXPECT_TRUE(mask_isolation_2.is_fast_rounded_corner); + EXPECT_EQ(gfx::RRectF(50, 50, 300, 200, 5), + mask_isolation_2.rounded_corner_bounds); + EXPECT_FALSE(mask_isolation_2.HasRenderSurface()); } TEST_P(PaintArtifactCompositorTest, SynthesizedClipDelegateBlending) { @@ -3757,84 +3426,22 @@ .RectDrawing(IntRect(0, 0, 100, 100), Color::kBlack); Update(artifact.Build()); - if (RuntimeEnabledFeatures::FastBorderRadiusEnabled()) { - // Expectation in effect stack diagram: - // l1 l2 l3 l5 - // l0 [ e1 ] l4 - // [ mask_isolation_0 ][ mask_isolation_1 ][ mask_isolation_2 ] - // [ e0 ] - // Three content layers. - ASSERT_EQ(3u, LayerCount()); - // There are still "synthesized layers" but they're null. - ASSERT_EQ(3u, SynthesizedClipLayerCount()); - EXPECT_FALSE(SynthesizedClipLayerAt(0)); - EXPECT_FALSE(SynthesizedClipLayerAt(1)); - EXPECT_FALSE(SynthesizedClipLayerAt(2)); - - const cc::Layer* content0 = LayerAt(0); - const cc::Layer* content1 = LayerAt(1); - const cc::Layer* content2 = LayerAt(2); - - constexpr int c0_id = 1; - constexpr int e0_id = 1; - - int c1_id = content0->clip_tree_index(); - const cc::ClipNode& cc_c1 = *GetPropertyTrees().clip_tree.Node(c1_id); - EXPECT_EQ(gfx::RectF(50, 50, 300, 200), cc_c1.clip); - ASSERT_EQ(c0_id, cc_c1.parent_id); - int mask_isolation_0_id = content0->effect_tree_index(); - const cc::EffectNode& mask_isolation_0 = - *GetPropertyTrees().effect_tree.Node(mask_isolation_0_id); - ASSERT_EQ(e0_id, mask_isolation_0.parent_id); - EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_0.blend_mode); - EXPECT_TRUE(mask_isolation_0.is_fast_rounded_corner); - EXPECT_EQ(gfx::RRectF(50, 50, 300, 200, 5), - mask_isolation_0.rounded_corner_bounds); - - EXPECT_EQ(c1_id, content1->clip_tree_index()); - int e1_id = content1->effect_tree_index(); - const cc::EffectNode& cc_e1 = *GetPropertyTrees().effect_tree.Node(e1_id); - EXPECT_EQ(SkBlendMode::kSrcOver, cc_e1.blend_mode); - int mask_isolation_1_id = cc_e1.parent_id; - const cc::EffectNode& mask_isolation_1 = - *GetPropertyTrees().effect_tree.Node(mask_isolation_1_id); - EXPECT_NE(mask_isolation_0_id, mask_isolation_1_id); - ASSERT_EQ(e0_id, mask_isolation_1.parent_id); - EXPECT_EQ(SkBlendMode::kMultiply, mask_isolation_1.blend_mode); - EXPECT_TRUE(mask_isolation_1.is_fast_rounded_corner); - EXPECT_EQ(gfx::RRectF(50, 50, 300, 200, 5), - mask_isolation_1.rounded_corner_bounds); - - EXPECT_EQ(c1_id, content2->clip_tree_index()); - int mask_isolation_2_id = content2->effect_tree_index(); - const cc::EffectNode& mask_isolation_2 = - *GetPropertyTrees().effect_tree.Node(mask_isolation_2_id); - EXPECT_NE(mask_isolation_0_id, mask_isolation_2_id); - EXPECT_NE(mask_isolation_1_id, mask_isolation_2_id); - ASSERT_EQ(e0_id, mask_isolation_2.parent_id); - EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_0.blend_mode); - EXPECT_TRUE(mask_isolation_2.is_fast_rounded_corner); - EXPECT_EQ(gfx::RRectF(50, 50, 300, 200, 5), - mask_isolation_2.rounded_corner_bounds); - - return; - } - // Expectation in effect stack diagram: // l1 l2 l3 l5 - // l0 [ mask_effect_0 ][ e1 ][ mask_effect_1 ] l4 [ mask_effect_2 ] + // l0 [ e1 ] l4 // [ mask_isolation_0 ][ mask_isolation_1 ][ mask_isolation_2 ] // [ e0 ] - // Three content layers, three clip mask. - ASSERT_EQ(6u, LayerCount()); + // Three content layers. + ASSERT_EQ(3u, LayerCount()); + // There are still "synthesized layers" but they're null. ASSERT_EQ(3u, SynthesizedClipLayerCount()); + EXPECT_FALSE(SynthesizedClipLayerAt(0)); + EXPECT_FALSE(SynthesizedClipLayerAt(1)); + EXPECT_FALSE(SynthesizedClipLayerAt(2)); const cc::Layer* content0 = LayerAt(0); - const cc::Layer* clip_mask0 = LayerAt(1); - const cc::Layer* content1 = LayerAt(2); - const cc::Layer* clip_mask1 = LayerAt(3); - const cc::Layer* content2 = LayerAt(4); - const cc::Layer* clip_mask2 = LayerAt(5); + const cc::Layer* content1 = LayerAt(1); + const cc::Layer* content2 = LayerAt(2); constexpr int c0_id = 1; constexpr int e0_id = 1; @@ -3848,15 +3455,9 @@ *GetPropertyTrees().effect_tree.Node(mask_isolation_0_id); ASSERT_EQ(e0_id, mask_isolation_0.parent_id); EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_0.blend_mode); - - EXPECT_EQ(SynthesizedClipLayerAt(0), clip_mask0); - EXPECT_EQ(gfx::Size(300, 200), clip_mask0->bounds()); - EXPECT_EQ(c1_id, clip_mask0->clip_tree_index()); - int mask_effect_0_id = clip_mask0->effect_tree_index(); - const cc::EffectNode& mask_effect_0 = - *GetPropertyTrees().effect_tree.Node(mask_effect_0_id); - ASSERT_EQ(mask_isolation_0_id, mask_effect_0.parent_id); - EXPECT_EQ(SkBlendMode::kDstIn, mask_effect_0.blend_mode); + EXPECT_TRUE(mask_isolation_0.is_fast_rounded_corner); + EXPECT_EQ(gfx::RRectF(50, 50, 300, 200, 5), + mask_isolation_0.rounded_corner_bounds); EXPECT_EQ(c1_id, content1->clip_tree_index()); int e1_id = content1->effect_tree_index(); @@ -3868,15 +3469,9 @@ EXPECT_NE(mask_isolation_0_id, mask_isolation_1_id); ASSERT_EQ(e0_id, mask_isolation_1.parent_id); EXPECT_EQ(SkBlendMode::kMultiply, mask_isolation_1.blend_mode); - - EXPECT_EQ(SynthesizedClipLayerAt(1), clip_mask1); - EXPECT_EQ(gfx::Size(300, 200), clip_mask1->bounds()); - EXPECT_EQ(c1_id, clip_mask1->clip_tree_index()); - int mask_effect_1_id = clip_mask1->effect_tree_index(); - const cc::EffectNode& mask_effect_1 = - *GetPropertyTrees().effect_tree.Node(mask_effect_1_id); - ASSERT_EQ(mask_isolation_1_id, mask_effect_1.parent_id); - EXPECT_EQ(SkBlendMode::kDstIn, mask_effect_1.blend_mode); + EXPECT_TRUE(mask_isolation_1.is_fast_rounded_corner); + EXPECT_EQ(gfx::RRectF(50, 50, 300, 200, 5), + mask_isolation_1.rounded_corner_bounds); EXPECT_EQ(c1_id, content2->clip_tree_index()); int mask_isolation_2_id = content2->effect_tree_index(); @@ -3886,15 +3481,9 @@ EXPECT_NE(mask_isolation_1_id, mask_isolation_2_id); ASSERT_EQ(e0_id, mask_isolation_2.parent_id); EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_0.blend_mode); - - EXPECT_EQ(SynthesizedClipLayerAt(2), clip_mask2); - EXPECT_EQ(gfx::Size(300, 200), clip_mask2->bounds()); - EXPECT_EQ(c1_id, clip_mask2->clip_tree_index()); - int mask_effect_2_id = clip_mask2->effect_tree_index(); - const cc::EffectNode& mask_effect_2 = - *GetPropertyTrees().effect_tree.Node(mask_effect_2_id); - ASSERT_EQ(mask_isolation_2_id, mask_effect_2.parent_id); - EXPECT_EQ(SkBlendMode::kDstIn, mask_effect_2.blend_mode); + EXPECT_TRUE(mask_isolation_2.is_fast_rounded_corner); + EXPECT_EQ(gfx::RRectF(50, 50, 300, 200, 5), + mask_isolation_2.rounded_corner_bounds); } TEST_P(PaintArtifactCompositorTest, WillBeRemovedFromFrame) {
diff --git a/third_party/blink/renderer/platform/graphics/compositing/property_tree_manager.cc b/third_party/blink/renderer/platform/graphics/compositing/property_tree_manager.cc index 757e737f..55e1c77de 100644 --- a/third_party/blink/renderer/platform/graphics/compositing/property_tree_manager.cc +++ b/third_party/blink/renderer/platform/graphics/compositing/property_tree_manager.cc
@@ -794,9 +794,6 @@ bool PropertyTreeManager::SupportsShaderBasedRoundedCorner( const ClipPaintPropertyNode& clip, PropertyTreeManager::CcEffectType type) { - if (!RuntimeEnabledFeatures::FastBorderRadiusEnabled()) - return false; - if (type & CcEffectType::kSyntheticFor2dAxisAlignment) return false; @@ -815,11 +812,10 @@ return false; } - // Rounded corners that differ are not supported by the - // CALayerOverlay system on Mac. Instead of letting it fall back - // to the (worse for memory and battery) non-CALayerOverlay system - // for such cases, fall back to a non-fast border-radius mask for - // the effect node. + // Rounded corners that differ are not supported by the CALayerOverlay system + // on Mac. Instead of letting it fall back to the (worse for memory and + // battery) non-CALayerOverlay system for such cases, fall back to a + // non-shader border-radius mask for the effect node. #if defined(OS_MACOSX) if (radii.TopLeft() != radii.TopRight() || radii.TopLeft() != radii.BottomRight() ||
diff --git a/third_party/blink/renderer/platform/heap/thread_state.cc b/third_party/blink/renderer/platform/heap/thread_state.cc index 4d1078c9..18d1115 100644 --- a/third_party/blink/renderer/platform/heap/thread_state.cc +++ b/third_party/blink/renderer/platform/heap/thread_state.cc
@@ -167,16 +167,15 @@ void Dispatch() { switch (thread_state_->GetGCState()) { - case ThreadState::kIncrementalGCScheduled: - thread_state_->IncrementalMarkingStart(reason_); - ScheduleTask(); - break; case ThreadState::kIncrementalMarkingStepScheduled: thread_state_->IncrementalMarkingStep( BlinkGC::kNoHeapPointersOnStack, next_incremental_marking_step_duration_); UpdateIncrementalMarkingStepDuration(); - ScheduleTask(); + if (thread_state_->GetGCState() != + ThreadState::kIncrementalMarkingStepPaused) { + ScheduleTask(); + } break; case ThreadState::kIncrementalMarkingFinalizeScheduled: thread_state_->IncrementalMarkingFinalize();
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index 896e6ac..748d9e9 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -701,10 +701,6 @@ name: "FallbackCursorMode", }, { - name: "FastBorderRadius", - status: "experimental", - }, - { name: "FeaturePolicyForClientHints", status: "experimental", },
diff --git a/third_party/blink/renderer/platform/testing/paint_test_configurations.h b/third_party/blink/renderer/platform/testing/paint_test_configurations.h index 09780dc..0e3631b 100644 --- a/third_party/blink/renderer/platform/testing/paint_test_configurations.h +++ b/third_party/blink/renderer/platform/testing/paint_test_configurations.h
@@ -11,23 +11,17 @@ namespace blink { -enum { - kCompositeAfterPaint = 1 << 0, - kUnderInvalidationChecking = 1 << 1, - kFastBorderRadius = 1 << 2 -}; +enum { kCompositeAfterPaint = 1 << 0, kUnderInvalidationChecking = 1 << 1 }; class PaintTestConfigurations : public testing::WithParamInterface<unsigned>, private ScopedCompositeAfterPaintForTest, - private ScopedPaintUnderInvalidationCheckingForTest, - private ScopedFastBorderRadiusForTest { + private ScopedPaintUnderInvalidationCheckingForTest { public: PaintTestConfigurations() : ScopedCompositeAfterPaintForTest(GetParam() & kCompositeAfterPaint), - ScopedPaintUnderInvalidationCheckingForTest(GetParam() & - kUnderInvalidationChecking), - ScopedFastBorderRadiusForTest(GetParam() & kFastBorderRadius) {} + ScopedPaintUnderInvalidationCheckingForTest( + GetParam() & kUnderInvalidationChecking) {} ~PaintTestConfigurations() { // Must destruct all objects before toggling back feature flags. WebHeap::CollectAllGarbageForTesting(); @@ -42,10 +36,10 @@ INSTANTIATE_TEST_SUITE_P(All, test_class, \ ::testing::Values(kCompositeAfterPaint)) +// TODO(pdr): Remove this in favor of INSTANTIATE_PAINT_TEST_SUITE_P. #define INSTANTIATE_LAYER_LIST_TEST_SUITE_P(test_class) \ - INSTANTIATE_TEST_SUITE_P( \ - All, test_class, \ - ::testing::Values(0, kCompositeAfterPaint, kFastBorderRadius)) + INSTANTIATE_TEST_SUITE_P(All, test_class, \ + ::testing::Values(0, kCompositeAfterPaint)) #define INSTANTIATE_SCROLL_HIT_TEST_SUITE_P(test_class) \ INSTANTIATE_TEST_SUITE_P(All, test_class, \
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 4801c4cc..a32eae3 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -1303,7 +1303,6 @@ crbug.com/591099 external/wpt/css/css-flexbox/flexbox_align-items-stretch-3.html [ Failure ] ### virtual/layout_ng_flex_box/css3/flexbox/ -crbug.com/591099 virtual/layout_ng_flex_box/css3/flexbox/auto-height-column-with-border-and-padding.html [ Failure ] crbug.com/591099 virtual/layout_ng_flex_box/css3/flexbox/flex-align-vertical-writing-mode.html [ Failure ] crbug.com/591099 virtual/layout_ng_flex_box/css3/flexbox/flex-align.html [ Failure ] crbug.com/591099 virtual/layout_ng_flex_box/css3/flexbox/flexbox-baseline-margins.html [ Failure ] @@ -1318,8 +1317,6 @@ ### virtual/layout_ng_flex_box/external/wpt/css/css-flexbox/ crbug.com/591099 virtual/layout_ng_flex_box/external/wpt/css/css-flexbox/align-items-004.htm [ Failure ] crbug.com/591099 virtual/layout_ng_flex_box/external/wpt/css/css-flexbox/align-items-baseline-overflow-non-visible.html [ Failure ] -crbug.com/591099 virtual/layout_ng_flex_box/external/wpt/css/css-flexbox/anonymous-flex-item-001.html [ Failure ] -crbug.com/591099 virtual/layout_ng_flex_box/external/wpt/css/css-flexbox/anonymous-flex-item-003.html [ Failure ] crbug.com/807497 virtual/layout_ng_flex_box/external/wpt/css/css-flexbox/anonymous-flex-item-005.html [ Failure ] crbug.com/591099 virtual/layout_ng_flex_box/external/wpt/css/css-flexbox/flex-basis-010.html [ Failure ] crbug.com/249112 virtual/layout_ng_flex_box/external/wpt/css/css-flexbox/flex-minimum-height-flex-items-005.xht [ Failure ] @@ -1335,7 +1332,6 @@ crbug.com/336604 virtual/layout_ng_flex_box/external/wpt/css/css-flexbox/flexbox_visibility-collapse-line-wrapping.html [ Failure ] crbug.com/336604 virtual/layout_ng_flex_box/external/wpt/css/css-flexbox/flexbox_visibility-collapse.html [ Failure ] crbug.com/467127 virtual/layout_ng_flex_box/external/wpt/css/css-flexbox/negative-margins-001.html [ Failure ] -crbug.com/591099 virtual/layout_ng_flex_box/external/wpt/css/css-flexbox/overflow-top-left.html [ Failure ] crbug.com/591099 virtual/layout_ng_flex_box/external/wpt/css/css-flexbox/percentage-heights-007.html [ Failure ] crbug.com/591099 virtual/layout_ng_flex_box/external/wpt/css/css-flexbox/percentage-heights-quirks-node.html [ Failure ] crbug.com/591099 virtual/layout_ng_flex_box/external/wpt/css/css-flexbox/quirks-auto-block-size-with-percentage-item.html [ Pass Failure ] @@ -4386,9 +4382,16 @@ crbug.com/678493 http/tests/permissions/chromium/test-request-window.html [ Timeout Pass ] crbug.com/678499 http/tests/security/contentSecurityPolicy/require-sri-for/require-sri-for-script-preload-allowed.php [ Failure Pass ] -crbug.com/747751 [ Win ] http/tests/devtools/application-panel/resources-panel-resource-preview.js [ Failure Pass ] crbug.com/747751 http/tests/devtools/application-panel/storage-view-reports-quota.js [ Pass Timeout ] +crbug.com/1038678 http/tests/devtools/application-panel/resources-panel-iframe-idb.js [ Skip ] +crbug.com/1038678 http/tests/devtools/application-panel/resources-panel-on-navigation.js [ Skip ] +crbug.com/1038678 http/tests/devtools/application-panel/resources-panel-resource-preview.js [ Skip ] +crbug.com/1038678 http/tests/devtools/application-panel/resources-panel-selection-on-reload.js [ Skip ] +crbug.com/1038678 http/tests/devtools/application-panel/resources-panel-websql.js [ Skip ] +crbug.com/1038678 http/tests/devtools/service-workers/service-workers-redundant.js [ Skip ] +crbug.com/1038678 http/tests/devtools/service-workers/service-workers-view.js [ Skip ] + crbug.com/689781 external/wpt/media-source/mediasource-duration.html [ Failure Pass ] crbug.com/689781 [ Win ] http/tests/media/media-source/mediasource-duration.html [ Failure Pass ] crbug.com/689781 [ Mac ] http/tests/media/media-source/mediasource-duration.html [ Failure Pass ]
diff --git a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json index 7f03997..e5d23db 100644 --- a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json +++ b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json
@@ -64199,6 +64199,18 @@ {} ] ], + "css/css-pseudo/marker-content-017.html": [ + [ + "css/css-pseudo/marker-content-017.html", + [ + [ + "/css/css-pseudo/marker-content-017-ref.html", + "==" + ] + ], + {} + ] + ], "css/css-pseudo/marker-display-dynamic-001.html": [ [ "css/css-pseudo/marker-display-dynamic-001.html", @@ -114241,6 +114253,18 @@ {} ] ], + "dom/nodes/remove-from-shadow-host-and-adopt-into-iframe.html": [ + [ + "dom/nodes/remove-from-shadow-host-and-adopt-into-iframe.html", + [ + [ + "/dom/nodes/remove-from-shadow-host-and-adopt-into-iframe-ref.html", + "==" + ] + ], + {} + ] + ], "encoding/eof-shift_jis.html": [ [ "encoding/eof-shift_jis.html", @@ -144708,6 +144732,9 @@ "css/css-pseudo/marker-content-016-ref.html": [ [] ], + "css/css-pseudo/marker-content-017-ref.html": [ + [] + ], "css/css-pseudo/marker-font-properties-ref.html": [ [] ], @@ -155487,6 +155514,9 @@ "dom/nodes/query-target-in-load-event.part.html": [ [] ], + "dom/nodes/remove-from-shadow-host-and-adopt-into-iframe-ref.html": [ + [] + ], "dom/nodes/selectors.js": [ [] ], @@ -159681,6 +159711,9 @@ "html/browsers/origin/cross-origin-objects/frame.html": [ [] ], + "html/browsers/origin/cross-origin-objects/resources/cross-origin-due-to-document-domain-only-helper.html": [ + [] + ], "html/browsers/origin/cross-origin-objects/win-documentdomain.sub.html": [ [] ], @@ -170655,6 +170688,9 @@ "portals/resources/postmessage-referrer.sub.html": [ [] ], + "portals/resources/predecessor-fires-unload-watch-unload.html": [ + [] + ], "portals/resources/simple-portal-adopts-and-activates-predecessor.html": [ [] ], @@ -249572,6 +249608,12 @@ {} ] ], + "html/browsers/origin/cross-origin-objects/cross-origin-due-to-document-domain-only.html": [ + [ + "html/browsers/origin/cross-origin-objects/cross-origin-due-to-document-domain-only.html", + {} + ] + ], "html/browsers/origin/cross-origin-objects/cross-origin-objects-on-new-window.html": [ [ "html/browsers/origin/cross-origin-objects/cross-origin-objects-on-new-window.html", @@ -282627,6 +282669,12 @@ {} ] ], + "portals/predecessor-fires-unload.html": [ + [ + "portals/predecessor-fires-unload.html", + {} + ] + ], "preload/avoid-delaying-onload-link-preload.html": [ [ "preload/avoid-delaying-onload-link-preload.html", @@ -401227,6 +401275,14 @@ "9a0585db72206768e2a7ed77f9245f67103d587b", "reftest" ], + "css/css-pseudo/marker-content-017-ref.html": [ + "9628123611d0bfb9dd90ac621ba39177982e8075", + "support" + ], + "css/css-pseudo/marker-content-017.html": [ + "267e519feee6541596f11310e2075419e13cffc2", + "reftest" + ], "css/css-pseudo/marker-default-styles.html": [ "05da6f89a9e2f858eadfdfb63e5194feda5ce3fc", "testharness" @@ -444171,6 +444227,14 @@ "d37015ec9f923bfc74319631723defa0b222654d", "testharness" ], + "dom/nodes/remove-from-shadow-host-and-adopt-into-iframe-ref.html": [ + "98de2b688369099806c525034a6bfc9e63d20a72", + "support" + ], + "dom/nodes/remove-from-shadow-host-and-adopt-into-iframe.html": [ + "612aed637df48d19f3050844ed418f3e35d8fa91", + "reftest" + ], "dom/nodes/remove-unscopable.html": [ "0238b0fa97a40dd9e5058d4153d1483553552033", "testharness" @@ -454911,6 +454975,10 @@ "a5d8e59406e870c7be80dfe57ef404ddc7b288a4", "manual" ], + "html/browsers/origin/cross-origin-objects/cross-origin-due-to-document-domain-only.html": [ + "919a05ed2a2a5c40f56ce46e1597e8bd763b0921", + "testharness" + ], "html/browsers/origin/cross-origin-objects/cross-origin-objects-expected.txt": [ "571eb0149d60b8c75ce2c35a33a93ba1e27ed9ed", "support" @@ -454931,6 +454999,10 @@ "ca2dd8ebf829d6f677fdf57b4a6db029a4aa457d", "support" ], + "html/browsers/origin/cross-origin-objects/resources/cross-origin-due-to-document-domain-only-helper.html": [ + "10ac8ece0e174b9a180c904c5bcdf6cc514c3a92", + "support" + ], "html/browsers/origin/cross-origin-objects/win-documentdomain.sub.html": [ "a315e21208728ed38155fa0e13c5f4d58dbea496", "support" @@ -466984,7 +467056,7 @@ "testharness" ], "html/semantics/forms/constraints/form-validation-validity-valid-expected.txt": [ - "1a4036169b2a818980486bd8a035fbe23dc90912", + "e1bb6e4b43073cbd175e81e16bdeb7455c7c29fb", "support" ], "html/semantics/forms/constraints/form-validation-validity-valid.html": [ @@ -466992,7 +467064,7 @@ "testharness" ], "html/semantics/forms/constraints/form-validation-validity-valueMissing-expected.txt": [ - "7426a0f7f2873bc5cff70c7fa56e219cf97fda2e", + "611137c81134a0411e73438d2c158ba7f1eb5346", "support" ], "html/semantics/forms/constraints/form-validation-validity-valueMissing.html": [ @@ -467012,7 +467084,7 @@ "testharness" ], "html/semantics/forms/constraints/support/validator.js": [ - "9b28b32309e349a87a5ee6b5b8cced2c501dd6a1", + "48c3a5b40e6bbe06b18dde7f473188a827b7de6a", "support" ], "html/semantics/forms/constraints/tooShort-input-email-add-manual.html": [ @@ -491975,6 +492047,10 @@ "70a16436a67f254372be5f861d83d9e9b66f895f", "testharness" ], + "portals/predecessor-fires-unload.html": [ + "6512195eaf613ad556a148d9136425aa20915648", + "testharness" + ], "portals/references/portals-rendering.html": [ "4a8414ab5656593811772c3728e4ee83eb034457", "support" @@ -492099,6 +492175,10 @@ "92aef00380ae4a6180039ad0b10169c81a190441", "support" ], + "portals/resources/predecessor-fires-unload-watch-unload.html": [ + "ada5a64967e9b169209b5cfede256c60ac3f8acc", + "support" + ], "portals/resources/simple-portal-adopts-and-activates-predecessor.html": [ "56bfd10f647fb63597dbc5ec902a8c2b90257b18", "support" @@ -525860,7 +525940,7 @@ "support" ], "web-nfc/NDEFMessage_constructor.https.html": [ - "1c842f5c7b61c35d09e2cd41014e1b8e04839624", + "4e53828c310976b5b37657f84a89f03c48e7bc59", "testharness" ], "web-nfc/NDEFReader-document-hidden-manual.https-expected.txt": [ @@ -525888,11 +525968,11 @@ "testharness" ], "web-nfc/NDEFReadingEvent_constructor.https.html": [ - "cc56f8a18bdc6f7a0cde3f9f7246330f8e867dd6", + "5427b75ae2b6d0fa6c45b24af51b02a8737ffd0b", "testharness" ], "web-nfc/NDEFRecord_constructor.https.html": [ - "c62ea7b0d620b6f38f589c751329b40be096e557", + "2da7ca91078aa5ec8232f5347fb276618dad3c3c", "testharness" ], "web-nfc/NDEFWriter-document-hidden-manual.https-expected.txt": [ @@ -525904,11 +525984,11 @@ "manual" ], "web-nfc/NDEFWriter_push.https-expected.txt": [ - "3ee37e970e148a4afb2412774453d3e1d0d869b3", + "08edb6f2ee36fc39e80f52b88afeb14a185b0fd7", "support" ], "web-nfc/NDEFWriter_push.https.html": [ - "1bdbf0bb50b38b2e385a5938a79c7bf679805b2b", + "4ff0af8fb0b3947595bdf48015ebabce165003ba", "testharness" ], "web-nfc/OWNERS": [ @@ -529108,7 +529188,7 @@ "testharness" ], "webrtc/RTCDataChannel-close.html": [ - "13215d70e8bb5bc3afcc9a66aa73fd81c4281f78", + "9f43dc93c5ba7917c327d642fa6883ff19d74cac", "testharness" ], "webrtc/RTCDataChannel-id.html": [ @@ -529144,7 +529224,7 @@ "testharness" ], "webrtc/RTCError.html": [ - "4d0726093c19c2828e59e7f61d2f65954c8075fc", + "9c7227521edeb8e9db1c744ce3f6a145bc66314b", "testharness" ], "webrtc/RTCIceCandidate-constructor.html": [ @@ -529216,7 +529296,7 @@ "testharness" ], "webrtc/RTCPeerConnection-connectionState.https.html": [ - "9ed5808727a6a293eedc705f40abdc7dc62f8eb4", + "a054a1e8cccbd02cc7b55f96ff483219846cf997", "testharness" ], "webrtc/RTCPeerConnection-constructor-expected.txt": [
diff --git a/third_party/blink/web_tests/external/wpt/html/browsers/origin/cross-origin-objects/cross-origin-due-to-document-domain-only.html b/third_party/blink/web_tests/external/wpt/html/browsers/origin/cross-origin-objects/cross-origin-due-to-document-domain-only.html new file mode 100644 index 0000000..919a05e --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/browsers/origin/cross-origin-objects/cross-origin-due-to-document-domain-only.html
@@ -0,0 +1,33 @@ +<!doctype html> +<title>Cross-origin due to document.domain</title> +<meta charset=utf-8> +<script src=/resources/testharness.js></script> +<script src=/resources/testharnessreport.js></script> +<div id=log></div> +<iframe src=resources/cross-origin-due-to-document-domain-only-helper.html></iframe> +<script> +async_test(t => { + onload = t.step_func_done(() => { + const frame = document.querySelector("iframe"); + const innerSelf = self[0]; + const innerLocation = innerSelf.location; + const innerDocument = innerSelf.document; + assert_equals(innerLocation.host, location.host); + assert_true(innerSelf.expandosForever); + assert_true(innerLocation.expandosForever); + assert_equals(frame.contentWindow, innerSelf); + assert_equals(frame.contentDocument, innerDocument); + innerSelf.setDocumentDomain(); + assert_throws("SecurityError", () => innerSelf.expandosForever); + assert_throws("SecurityError", () => innerLocation.expandosForever); + assert_throws("SecurityError", () => innerLocation.host); + assert_equals(innerSelf.parent, self); + assert_throws("SecurityError", () => innerSelf.frameElement); + assert_throws("SecurityError", () => innerLocation.reload()); + assert_equals(frame.contentWindow, innerSelf); + assert_equals(frame.contentDocument, null); + // Cross-origin Document object obtained before it became cross-origin has no protections + assert_equals(innerDocument.URL, frame.src); + }); +}); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/browsers/origin/cross-origin-objects/resources/cross-origin-due-to-document-domain-only-helper.html b/third_party/blink/web_tests/external/wpt/html/browsers/origin/cross-origin-objects/resources/cross-origin-due-to-document-domain-only-helper.html new file mode 100644 index 0000000..10ac8ece --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/browsers/origin/cross-origin-objects/resources/cross-origin-due-to-document-domain-only-helper.html
@@ -0,0 +1,9 @@ +<!doctype html> +<meta charset=utf-8> +<script> +self.expandosForever = true +self.location.expandosForever = true +function setDocumentDomain() { + document.domain = document.domain +} +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/forms/constraints/form-validation-validity-valid-expected.txt b/third_party/blink/web_tests/external/wpt/html/semantics/forms/constraints/form-validation-validity-valid-expected.txt index 1a403616..e1bb6e4 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/forms/constraints/form-validation-validity-valid-expected.txt +++ b/third_party/blink/web_tests/external/wpt/html/semantics/forms/constraints/form-validation-validity-valid-expected.txt
@@ -38,7 +38,7 @@ PASS [INPUT in NUMBER status] validity.valid must be false if validity.stepMismatch is true PASS [INPUT in NUMBER status] validity.valid must be false if validity.valueMissing is true PASS [INPUT in CHECKBOX status] validity.valid must be false if validity.valueMissing is true -FAIL [INPUT in RADIO status] validity.valid must be false if validity.valueMissing is true assert_false: The validity.valid should be false, when control is disabled. expected false got true +FAIL [INPUT in RADIO status] validity.valid must be false if validity.valueMissing is true assert_false: The validity.valid should be false. expected false got true PASS [INPUT in FILE status] validity.valid must be false if validity.valueMissing is true PASS [select] validity.valid must be false if validity.valueMissing is true PASS [textarea] validity.valid must be false if validity.valueMissing is true
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/forms/constraints/form-validation-validity-valueMissing-expected.txt b/third_party/blink/web_tests/external/wpt/html/semantics/forms/constraints/form-validation-validity-valueMissing-expected.txt index 7426a0f7..611137c81 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/forms/constraints/form-validation-validity-valueMissing-expected.txt +++ b/third_party/blink/web_tests/external/wpt/html/semantics/forms/constraints/form-validation-validity-valueMissing-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 94 tests; 90 PASS, 4 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 94 tests; 91 PASS, 3 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS [INPUT in TEXT status] The required attribute is not set PASS [INPUT in TEXT status] The value is not empty and required is true PASS [INPUT in TEXT status] The value is empty and required is true @@ -85,11 +85,11 @@ PASS [INPUT in CHECKBOX status] The checked attribute is false PASS [INPUT in RADIO status] The required attribute is not set PASS [INPUT in RADIO status] The checked attribute is true -FAIL [INPUT in RADIO status] The checked attribute is false assert_true: The validity.valueMissing should be true, when control is disabled. expected true got false +FAIL [INPUT in RADIO status] The checked attribute is false assert_true: The validity.valueMissing should be true. expected true got false PASS [INPUT in FILE status] The required attribute is not set PASS [INPUT in FILE status] The Files attribute is null PASS [select] The required attribute is not set -FAIL [select] Selected the option with value equals to 1 assert_false: The validity.valueMissing should be false, when control is disabled. expected false got true +PASS [select] Selected the option with value equals to 1 PASS [select] Selected the option with value equals to empty PASS [textarea] The required attribute is not set PASS [textarea] The value is not empty
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/forms/constraints/support/validator.js b/third_party/blink/web_tests/external/wpt/html/semantics/forms/constraints/support/validator.js index 9b28b32..48c3a5b 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/forms/constraints/support/validator.js +++ b/third_party/blink/web_tests/external/wpt/html/semantics/forms/constraints/support/validator.js
@@ -4,11 +4,8 @@ var self = this; test(function() { self.pre_check(ctl, 'tooLong'); - self.set_conditions(ctl, data.conditions); self.iterate_over(ctl, data).forEach(function(val) { const {ctl, data, condStr} = val; - if (data.dirty) - self.set_dirty(ctl); if (data.expected) assert_true( ctl.validity.tooLong, @@ -25,11 +22,8 @@ var self = this; test(function () { self.pre_check(ctl, "tooShort"); - self.set_conditions(ctl, data.conditions); self.iterate_over(ctl, data).forEach(function(val) { const {ctl, data, condStr} = val; - if (data.dirty) - self.set_dirty(ctl); if (data.expected) assert_true( ctl.validity.tooShort, @@ -46,7 +40,6 @@ var self = this; test(function () { self.pre_check(ctl, "patternMismatch"); - self.set_conditions(ctl, data.conditions); self.iterate_over(ctl, data).forEach(function(val) { const {ctl, data, condStr} = val; if (data.expected) @@ -65,7 +58,6 @@ var self = this; test(function () { self.pre_check(ctl, "valueMissing"); - self.set_conditions(ctl, data.conditions); self.iterate_over(ctl, data).forEach(function(val) { const {ctl, data, condStr} = val; if (data.expected) @@ -84,7 +76,6 @@ var self = this; test(function () { self.pre_check(ctl, "typeMismatch"); - self.set_conditions(ctl, data.conditions); self.iterate_over(ctl, data).forEach(function(val) { const {ctl, data, condStr} = val; if (data.expected) @@ -103,7 +94,6 @@ var self = this; test(function () { self.pre_check(ctl, "rangeOverflow"); - self.set_conditions(ctl, data.conditions); self.iterate_over(ctl, data).forEach(function(val) { const {ctl, data, condStr} = val; if (data.expected) @@ -122,7 +112,6 @@ var self = this; test(function () { self.pre_check(ctl, "rangeUnderflow"); - self.set_conditions(ctl, data.conditions); self.iterate_over(ctl, data).forEach(function(val) { const {ctl, data, condStr} = val; if (data.expected) @@ -141,7 +130,6 @@ var self = this; test(function () { self.pre_check(ctl, "stepMismatch"); - self.set_conditions(ctl, data.conditions); self.iterate_over(ctl, data).forEach(function(val) { const {ctl, data, condStr} = val; if (data.expected) @@ -160,7 +148,6 @@ var self = this; test(function () { self.pre_check(ctl, "badInput"); - self.set_conditions(ctl, data.conditions); self.iterate_over(ctl, data).forEach(function(val) { const {ctl, data, condStr} = val; if (data.expected) @@ -179,17 +166,24 @@ var self = this; test(function () { self.pre_check(ctl, "customError"); - ctl.setCustomValidity(data.conditions.message); self.iterate_over(ctl, data).forEach(function(val) { const {ctl, data, condStr} = val; if (data.expected) { assert_true( ctl.validity.customError, 'The validity.customError attribute should be true' + condStr); - assert_equals( - ctl.validationMessage, data.conditions.message, - 'The validationMessage attribute should be \'' + - data.conditions.message + '\'' + condStr); + // validationMessage returns the empty string if ctl is barred from + // constraint validation, which happens if ctl is disabled. + if (ctl.disabled) { + assert_equals( + ctl.validationMessage, '', + 'The validationMessage attribute must be empty' + condStr); + } else { + assert_equals( + ctl.validationMessage, data.conditions.message, + 'The validationMessage attribute should be \'' + + data.conditions.message + '\'' + condStr); + } } else { assert_false( ctl.validity.customError, @@ -205,11 +199,8 @@ test_isValid: function(ctl, data) { var self = this; test(function () { - self.set_conditions(ctl, data.conditions); self.iterate_over(ctl, data).forEach(function(val) { const {ctl, data, condStr} = val; - if (data.dirty) - self.set_dirty(ctl); if (data.expected) assert_true( ctl.validity.valid, @@ -352,7 +343,9 @@ ctl.removeAttribute(item); }); for (var attr in obj) { - if (attr === "checked" || obj[attr] || obj[attr] === "") + if (attr === "message") + ctl.setCustomValidity(obj[attr]); + else if (attr === "checked" || obj[attr] || obj[attr] === "") ctl[attr] = obj[attr]; } }, @@ -398,12 +391,27 @@ iterate_over: function(ctl, data) { // Iterate over normal, disabled, readonly, and both. var ctlDisabled = ctl.cloneNode(true); + this.set_conditions(ctlDisabled, data.conditions); + if (data.dirty) + this.set_dirty(ctlDisabled); ctlDisabled.disabled = true; + var ctlReadonly = ctl.cloneNode(true); + this.set_conditions(ctlReadonly, data.conditions); + if (data.dirty) + this.set_dirty(ctlReadonly); ctlReadonly.readonly = true; + var ctlBoth = ctl.cloneNode(true); + this.set_conditions(ctlBoth, data.conditions); + if (data.dirty) + this.set_dirty(ctlBoth); ctlBoth.disabled = true; ctlBoth.readonly = true; + + ctl = ctl.cloneNode(true); + this.set_conditions(ctl, data.conditions); + return [ {ctl: ctl, data: data, condStr: '.'}, {ctl: ctlDisabled, data: data, condStr: ', when control is disabled.'},
diff --git a/third_party/blink/web_tests/external/wpt/web-nfc/NDEFMessage_constructor.https.html b/third_party/blink/web_tests/external/wpt/web-nfc/NDEFMessage_constructor.https.html index 1c842f5..4e53828c 100644 --- a/third_party/blink/web_tests/external/wpt/web-nfc/NDEFMessage_constructor.https.html +++ b/third_party/blink/web_tests/external/wpt/web-nfc/NDEFMessage_constructor.https.html
@@ -12,11 +12,21 @@ }, 'NDEFMessage constructor without init dict'); test(() => { - const message = new NDEFMessage(null); - assert_equals(message.records.length, 0, 'empty records'); + assert_throws(new TypeError, () => new NDEFMessage(null), + 'NDEFMessageInit#records is a required field.'); }, 'NDEFMessage constructor with null init dict'); test(() => { + assert_throws(new TypeError, () => new NDEFMessage({dummy_key: 'dummy_value'}), + 'NDEFMessageInit#records is a required field.'); + }, 'NDEFMessage constructor without NDEFMessageInit#records field'); + + test(() => { + assert_throws(new TypeError, () => new NDEFMessage({records: []}), + 'NDEFMessageInit#records should not be empty.'); + }, 'NDEFMessage constructor with NDEFMessageInit#records being empty'); + + test(() => { const message = new NDEFMessage( createMessage([createTextRecord(test_text_data)])); assert_equals(message.records.length, 1, 'one text record');
diff --git a/third_party/blink/web_tests/external/wpt/web-nfc/NDEFReadingEvent_constructor.https.html b/third_party/blink/web_tests/external/wpt/web-nfc/NDEFReadingEvent_constructor.https.html index cc56f8a1..5427b75 100644 --- a/third_party/blink/web_tests/external/wpt/web-nfc/NDEFReadingEvent_constructor.https.html +++ b/third_party/blink/web_tests/external/wpt/web-nfc/NDEFReadingEvent_constructor.https.html
@@ -12,6 +12,12 @@ }, 'NDEFReadingEvent constructor without init dict'); test(() => { + assert_throws(new TypeError, () => new NDEFReadingEvent('type', + {serialNumber: '', message: null}), + 'NDEFMessageInit#records is a required field.'); + }, 'NDEFReadingEvent constructor failed to construct its NDEFMessage'); + + test(() => { const message = createMessage([createMimeRecordFromJson(test_buffer_data)]); const event = new NDEFReadingEvent('type', {serialNumber: null, message: message}); assert_equals(event.serialNumber, '', 'serialNumber'); @@ -24,11 +30,6 @@ }, 'NDEFReadingEvent constructor with serialNumber not present'); test(() => { - const event = new NDEFReadingEvent('type', {serialNumber: '', message: null}); - assert_equals(0, event.message.records.length, 'no records'); - }, 'NDEFReadingEvent constructor with null message'); - - test(() => { const message = createMessage([createMimeRecord(test_buffer_data)]); const event = new NDEFReadingEvent('type', {serialNumber: '', message: message}); assert_equals(event.type, 'type', 'type');
diff --git a/third_party/blink/web_tests/external/wpt/web-nfc/NDEFRecord_constructor.https.html b/third_party/blink/web_tests/external/wpt/web-nfc/NDEFRecord_constructor.https.html index c62ea7b..2da7ca9 100644 --- a/third_party/blink/web_tests/external/wpt/web-nfc/NDEFRecord_constructor.https.html +++ b/third_party/blink/web_tests/external/wpt/web-nfc/NDEFRecord_constructor.https.html
@@ -13,10 +13,15 @@ test(() => { assert_throws(new TypeError, () => new NDEFRecord(null), - 'The record has neither type nor data.'); + 'NDEFRecordInit#recordType is a required field.'); }, 'NDEFRecord constructor with null init dict'); test(() => { + assert_throws(new TypeError, () => new NDEFRecord({id: test_record_id, data: test_text_data}), + 'NDEFRecordInit#recordType is a required field.'); + }, 'NDEFRecord constructor without NDEFRecordInit#recordType field'); + + test(() => { assert_throws(new TypeError, () => new NDEFRecord( createRecord('empty', test_text_data, test_record_id)), 'id does not apply for empty record type.');
diff --git a/third_party/blink/web_tests/external/wpt/web-nfc/NDEFWriter_push.https-expected.txt b/third_party/blink/web_tests/external/wpt/web-nfc/NDEFWriter_push.https-expected.txt index 3ee37e97..08edb6f 100644 --- a/third_party/blink/web_tests/external/wpt/web-nfc/NDEFWriter_push.https-expected.txt +++ b/third_party/blink/web_tests/external/wpt/web-nfc/NDEFWriter_push.https-expected.txt
@@ -23,8 +23,6 @@ PASS NDEFWriter.push should read data when ignoreRead is false. PASS NDEFWriter.push should ignore reading data when ignoreRead is true. PASS NDEFWriter.push should replace all previously configured push operations. -PASS Test that recordType should be set to 'text' if NDEFRecordInit.record's recordType is undefined and NDEFRecordInit.record's data is DOMString. -PASS Test that recordType should be set to 'mime' if NDEFRecordInit.record's recordType is undefined and NDEFRecordInit.record's data is not DOMString. PASS Test that mediaType should be set to 'application/octet-stream' if NDEFRecordInit.record's recordType is 'mime' and NDEFRecordInit.record's mediaType is undefined. PASS NDEFWriter.push should fail when the NFC device coming up does not expose NDEF technology. PASS NDEFWriter.push should succeed to push data to an unformatted NFC device when the NDEFPushOptions.overwrite is false.
diff --git a/third_party/blink/web_tests/external/wpt/web-nfc/NDEFWriter_push.https.html b/third_party/blink/web_tests/external/wpt/web-nfc/NDEFWriter_push.https.html index 1bdbf0bb..4ff0af8f 100644 --- a/third_party/blink/web_tests/external/wpt/web-nfc/NDEFWriter_push.https.html +++ b/third_party/blink/web_tests/external/wpt/web-nfc/NDEFWriter_push.https.html
@@ -388,20 +388,6 @@ nfc_test(async (t, mockNFC) => { const writer = new NDEFWriter(); - await writer.push({ records: [{ data: test_text_data}] }); - assertNDEFMessagesEqual(test_text_data, mockNFC.pushedMessage()); -}, "Test that recordType should be set to 'text' if NDEFRecordInit.record's \ -recordType is undefined and NDEFRecordInit.record's data is DOMString."); - -nfc_test(async (t, mockNFC) => { - const writer = new NDEFWriter(); - await writer.push({ records: [{ data: test_buffer_data}] }); - assertNDEFMessagesEqual(test_buffer_data, mockNFC.pushedMessage()); -}, "Test that recordType should be set to 'mime' if NDEFRecordInit.record's \ -recordType is undefined and NDEFRecordInit.record's data is not DOMString."); - -nfc_test(async (t, mockNFC) => { - const writer = new NDEFWriter(); await writer.push({ records: [{ recordType: "mime", data: test_buffer_data }] }); assertNDEFMessagesEqual(test_buffer_data, mockNFC.pushedMessage()); }, "Test that mediaType should be set to 'application/octet-stream' if \
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/main-flamechart-a11y-test-expected.txt b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/main-flamechart-a11y-test-expected.txt new file mode 100644 index 0000000..3a61750 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/main-flamechart-a11y-test-expected.txt
@@ -0,0 +1,5 @@ +Testing a11y in performance panel - main flamechart. +Page reloaded. +aXe violations: [] + +
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/main-flamechart-a11y-test.js b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/main-flamechart-a11y-test.js new file mode 100644 index 0000000..2b46552f --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/main-flamechart-a11y-test.js
@@ -0,0 +1,17 @@ +// Copyright 2019 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. + +(async function() { + TestRunner.addResult('Testing a11y in performance panel - main flamechart.'); + + await TestRunner.loadModule('axe_core_test_runner'); + await TestRunner.loadModule('performance_test_runner'); + await TestRunner.showPanel('timeline'); + + await PerformanceTestRunner.runPerfTraceWithReload(); + const mainFlameChartElement = await PerformanceTestRunner.getMainFlameChartElement(); + await AxeCoreTestRunner.runValidation(mainFlameChartElement); + + TestRunner.completeTest(); +})();
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/network-flamechart-a11y-test-expected.txt b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/network-flamechart-a11y-test-expected.txt new file mode 100644 index 0000000..f4fdd75 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/network-flamechart-a11y-test-expected.txt
@@ -0,0 +1,5 @@ +Testing a11y in performance panel - network flamechart. +Page reloaded. +aXe violations: [] + +
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/network-flamechart-a11y-test.js b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/network-flamechart-a11y-test.js new file mode 100644 index 0000000..4a8d243e --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/network-flamechart-a11y-test.js
@@ -0,0 +1,17 @@ +// Copyright 2019 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. + +(async function() { + TestRunner.addResult('Testing a11y in performance panel - network flamechart.'); + + await TestRunner.loadModule('axe_core_test_runner'); + await TestRunner.loadModule('performance_test_runner'); + await TestRunner.showPanel('timeline'); + + await PerformanceTestRunner.runPerfTraceWithReload(); + const networkFlameChartElement = await PerformanceTestRunner.getNetworkFlameChartElement(); + await AxeCoreTestRunner.runValidation(networkFlameChartElement); + + TestRunner.completeTest(); +})();
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/panel-right-toolbar-a11y-test-expected.txt b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/panel-right-toolbar-a11y-test-expected.txt new file mode 100644 index 0000000..8e89414 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/panel-right-toolbar-a11y-test-expected.txt
@@ -0,0 +1,5 @@ +Testing a11y in performance panel - panel right toolbar. +Page reloaded. +aXe violations: [] + +
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/panel-right-toolbar-a11y-test.js b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/panel-right-toolbar-a11y-test.js new file mode 100644 index 0000000..40dcddf --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/panel-right-toolbar-a11y-test.js
@@ -0,0 +1,17 @@ +// Copyright 2019 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. + +(async function() { + TestRunner.addResult('Testing a11y in performance panel - panel right toolbar.'); + + await TestRunner.loadModule('axe_core_test_runner'); + await TestRunner.loadModule('performance_test_runner'); + await TestRunner.showPanel('timeline'); + + await PerformanceTestRunner.runPerfTraceWithReload(); + const widget = await PerformanceTestRunner.getTimelineWidget(); + await AxeCoreTestRunner.runValidation(widget._panelRightToolbar.element); + + TestRunner.completeTest(); +})();
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/panel-toolbar-a11y-test-expected.txt b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/panel-toolbar-a11y-test-expected.txt new file mode 100644 index 0000000..f1006a0 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/panel-toolbar-a11y-test-expected.txt
@@ -0,0 +1,5 @@ +Testing a11y in performance panel - panel toolbar. +Page reloaded. +aXe violations: [] + +
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/panel-toolbar-a11y-test.js b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/panel-toolbar-a11y-test.js new file mode 100644 index 0000000..f5cb815 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/panel-toolbar-a11y-test.js
@@ -0,0 +1,17 @@ +// Copyright 2019 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. + +(async function() { + TestRunner.addResult('Testing a11y in performance panel - panel toolbar.'); + + await TestRunner.loadModule('axe_core_test_runner'); + await TestRunner.loadModule('performance_test_runner'); + await TestRunner.showPanel('timeline'); + + await PerformanceTestRunner.runPerfTraceWithReload(); + const widget = await PerformanceTestRunner.getTimelineWidget(); + await AxeCoreTestRunner.runValidation(widget._panelToolbar.element); + + TestRunner.completeTest(); +})();
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/settings-pane-a11y-test-expected.txt b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/settings-pane-a11y-test-expected.txt new file mode 100644 index 0000000..f699f3e --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/settings-pane-a11y-test-expected.txt
@@ -0,0 +1,5 @@ +Testing a11y in performance panel - settings pane. +Page reloaded. +aXe violations: [] + +
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/settings-pane-a11y-test.js b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/settings-pane-a11y-test.js new file mode 100644 index 0000000..70d42ef --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/settings-pane-a11y-test.js
@@ -0,0 +1,19 @@ +// Copyright 2019 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. + +(async function() { + TestRunner.addResult('Testing a11y in performance panel - settings pane.'); + + await TestRunner.loadModule('axe_core_test_runner'); + await TestRunner.loadModule('performance_test_runner'); + await TestRunner.showPanel('timeline'); + + await PerformanceTestRunner.runPerfTraceWithReload(); + const widget = await PerformanceTestRunner.getTimelineWidget(); + const settingsButton = widget._showSettingsPaneButton.element; + settingsButton.click(); + await AxeCoreTestRunner.runValidation(widget._settingsPane.contentElement); + + TestRunner.completeTest(); +})();
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/timeline-overview-container-a11y-test-expected.txt b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/timeline-overview-container-a11y-test-expected.txt new file mode 100644 index 0000000..d2bdf27 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/timeline-overview-container-a11y-test-expected.txt
@@ -0,0 +1,5 @@ +Testing a11y in performance panel - timeline overview container. +Page reloaded. +aXe violations: [] + +
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/timeline-overview-container-a11y-test.js b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/timeline-overview-container-a11y-test.js new file mode 100644 index 0000000..7f3698b --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/performance/timeline-overview-container-a11y-test.js
@@ -0,0 +1,18 @@ +// Copyright 2019 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. + +(async function() { + TestRunner.addResult('Testing a11y in performance panel - timeline overview container.'); + + await TestRunner.loadModule('axe_core_test_runner'); + await TestRunner.loadModule('performance_test_runner'); + await TestRunner.showPanel('timeline'); + + await PerformanceTestRunner.runPerfTraceWithReload(); + const widget = await PerformanceTestRunner.getTimelineWidget(); + const timeLineViewElement = widget._overviewPane.element; + await AxeCoreTestRunner.runValidation(timeLineViewElement); + + TestRunner.completeTest(); +})();
diff --git a/third_party/blink/web_tests/inspector-protocol/animation/animation-release.js b/third_party/blink/web_tests/inspector-protocol/animation/animation-release.js index 74d9004..0703574 100644 --- a/third_party/blink/web_tests/inspector-protocol/animation/animation-release.js +++ b/third_party/blink/web_tests/inspector-protocol/animation/animation-release.js
@@ -3,21 +3,23 @@ <div id='node' style='background-color: red; width: 100px'></div> `, 'Tests that the animation is correctly paused.'); - dp.Animation.enable(); - session.evaluate(` + await dp.Animation.enable(); + + const animationStartedPromise = dp.Animation.onceAnimationStarted(); + await session.evaluate(` window.animation = node.animate([{ width: '100px' }, { width: '2000px' }], { duration: 0, fill: 'forwards' }); `); - var id = (await dp.Animation.onceAnimationStarted()).params.animation.id; + var id = (await animationStartedPromise).params.animation.id; testRunner.log('Animation started'); var width = await session.evaluate('node.offsetWidth'); testRunner.log('Box is animating: ' + (width != 100).toString()); - dp.Animation.setPaused({ animations: [ id ], paused: true }); - session.evaluate('animation.cancel()'); + await dp.Animation.setPaused({ animations: [ id ], paused: true }); + await session.evaluate('animation.cancel()'); width = await session.evaluate('node.offsetWidth'); testRunner.log('Animation paused'); testRunner.log('Box is animating: ' + (width != 100).toString()); - dp.Animation.releaseAnimations({ animations: [ id ] }); + await dp.Animation.releaseAnimations({ animations: [ id ] }); width = await session.evaluate('node.offsetWidth'); testRunner.log('Animation released'); testRunner.log('Box is animating: ' + (width != 100).toString());
diff --git a/third_party/crc32c/BUILD.gn b/third_party/crc32c/BUILD.gn index 5f1cba3..e8312a9 100644 --- a/third_party/crc32c/BUILD.gn +++ b/third_party/crc32c/BUILD.gn
@@ -4,6 +4,7 @@ import("//build/config/features.gni") import("//testing/test.gni") +import("//third_party/google_benchmark/buildconfig.gni") # Only applied to CRC32C source and tests. (not exported) config("crc32c_config") { @@ -166,3 +167,19 @@ "//third_party/googletest:gtest", ] } + +if (enable_google_benchmarks) { + test("crc32c_benchmark") { + sources = [ + "src/src/crc32c_benchmark.cc", + ] + configs += [ ":crc32c_config" ] + deps = [ + ":crc32c", + ":crc32c_arm64", + ":crc32c_internal_headers", + ":crc32c_sse42", + "//third_party/google_benchmark", + ] + } +}
diff --git a/third_party/google_benchmark/BUILD.gn b/third_party/google_benchmark/BUILD.gn new file mode 100644 index 0000000..ffbedff --- /dev/null +++ b/third_party/google_benchmark/BUILD.gn
@@ -0,0 +1,82 @@ +# Copyright 2019 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("buildconfig.gni") + +if (enable_google_benchmarks) { + config("benchmark_config") { + include_dirs = [ "src/include" ] + } + + source_set("google_benchmark") { + testonly = true + + public = [ + "src/include/benchmark/benchmark.h", + ] + + sources = [ + "src/src/arraysize.h", + "src/src/benchmark.cc", + "src/src/benchmark_api_internal.cc", + "src/src/benchmark_api_internal.h", + "src/src/benchmark_name.cc", + "src/src/benchmark_register.cc", + "src/src/benchmark_register.h", + "src/src/benchmark_runner.cc", + "src/src/benchmark_runner.h", + "src/src/check.h", + "src/src/colorprint.cc", + "src/src/colorprint.h", + "src/src/commandlineflags.cc", + "src/src/commandlineflags.h", + "src/src/complexity.cc", + "src/src/complexity.h", + "src/src/console_reporter.cc", + "src/src/counter.cc", + "src/src/counter.h", + "src/src/csv_reporter.cc", + "src/src/cycle_clock.h", + "src/src/internal_macros.h", + "src/src/json_reporter.cc", + "src/src/log.h", + "src/src/mutex.h", + "src/src/re.h", + "src/src/reporter.cc", + "src/src/sleep.cc", + "src/src/sleep.h", + "src/src/statistics.cc", + "src/src/statistics.h", + "src/src/string_util.cc", + "src/src/string_util.h", + "src/src/sysinfo.cc", + "src/src/thread_manager.h", + "src/src/thread_timer.h", + "src/src/timers.cc", + "src/src/timers.h", + ] + + all_dependent_configs = [ ":benchmark_config" ] + + configs -= [ "//build/config/compiler:chromium_code" ] + configs += [ "//build/config/compiler:no_chromium_code" ] + + defines = [ + # Tell gtest to always use standard regular expressions. + "HAVE_GNU_POSIX_REGEX=0", + "HAVE_POSIX_REGEX=0", + "HAVE_STD_REGEX=1", + ] + } + + source_set("benchmark_main") { + testonly = true + sources = [ + "src/src/benchmark_main.cc", + ] + deps = [ + ":google_benchmark", + ] + } +}
diff --git a/third_party/google_benchmark/OWNERS b/third_party/google_benchmark/OWNERS new file mode 100644 index 0000000..eedcf40 --- /dev/null +++ b/third_party/google_benchmark/OWNERS
@@ -0,0 +1,8 @@ +# Primary for bugs, reviews: +pwnall@chromium.org + +# Secondary: +jsbell@chromium.org + +# TEAM: storage-dev@chromium.org +# COMPONENT: Internals>Storage
diff --git a/third_party/google_benchmark/README.chromium b/third_party/google_benchmark/README.chromium new file mode 100644 index 0000000..fdf4f54 --- /dev/null +++ b/third_party/google_benchmark/README.chromium
@@ -0,0 +1,25 @@ +Name: Google Benchmark +Short Name: benchmark +URL: https://github.com/google/benchmark +Version: unknown +License: Apache 2.0 +License File: NOT_SHIPPED +Security Critical: no + +Description: +A microbenchmark support library. + +Google Benchmark is NOT supported for writing benchmarks in Chromium. It is +included to run benchmarks in third-party code that have already been written +against Google Benchmarks. + +To include this library in the Chromium checkout, add the following clause to +your .gclient configuration. + + "custom_vars": { + "checkout_google_benchmark": True, + } + + +Local Additions: +* gn file for building in chromium
diff --git a/third_party/google_benchmark/buildconfig.gni b/third_party/google_benchmark/buildconfig.gni new file mode 100644 index 0000000..6913888d --- /dev/null +++ b/third_party/google_benchmark/buildconfig.gni
@@ -0,0 +1,11 @@ +# Copyright 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//build/config/gclient_args.gni") + +declare_args() { + # Google Benchmark is not checked out by default, because it is only used by + # a few specialized benchmarks that most developers do not interact with. + enable_google_benchmarks = checkout_google_benchmark +}
diff --git a/tools/chrome_proxy/webdriver/lite_page.py b/tools/chrome_proxy/webdriver/lite_page.py index d0f8aa5..4fb3c123 100644 --- a/tools/chrome_proxy/webdriver/lite_page.py +++ b/tools/chrome_proxy/webdriver/lite_page.py
@@ -282,33 +282,5 @@ response.response_headers) continue - # Checks that the server provides a working interactive CASPR. - @ChromeVersionEqualOrAfterM(65) - def testInteractiveCASPR(self): - with TestDriver() as test_driver: - test_driver.AddChromeArg('--enable-spdy-proxy-auth') - test_driver.EnableChromeFeature('Previews') - test_driver.EnableChromeFeature('DataReductionProxyDecidesTransform') - # Need to force 2G speed to get a preview. - test_driver.AddChromeArg('--force-effective-connection-type=2G') - # Set exp=client_test_icaspr to force iCASPR response. - test_driver.SetExperiment('ihdp_integration') - - test_driver.LoadURL('http://check.googlezip.net/previews/ihdp.html') - - # The original page does not have any script resources (scripts are - # inlined in the HTML). The snapshotted page should contain exactly one - # script: the snapshot. - num_scripts = 0 - for response in test_driver.GetHTTPResponses(): - if response.request_type == 'Script': - num_scripts += 1 - - self.assertEqual(1, num_scripts) - - # Make sure the snapshot is restored correctly. - window_x = test_driver.ExecuteJavascriptStatement('window.x') - self.assertEqual(10, window_x) - if __name__ == '__main__': IntegrationTest.RunAllTests()
diff --git a/tools/grit/grit/tool/update_resource_ids/__init__.py b/tools/grit/grit/tool/update_resource_ids/__init__.py index 45a0c08..24029c91 100644 --- a/tools/grit/grit/tool/update_resource_ids/__init__.py +++ b/tools/grit/grit/tool/update_resource_ids/__init__.py
@@ -106,8 +106,7 @@ return ''.join(res) -def _CreateAndOutputResult(data, repl, output): - new_data = _MultiReplace(data, repl) +def _WriteFile(output, new_data): if output: with open(output, 'wt') as fh: fh.write(new_data) @@ -118,18 +117,24 @@ class _Args: """Encapsulated arguments for this module.""" def __init__(self): - self.input = None - self.output = None + self.add_header = False + self.analyze_inputs = False self.count = False + self.depfile = None self.fake = False + self.input = None self.naive = False + self.output = None self.parse = False self.tokenize = False @staticmethod def Parse(raw_args): own_opts, raw_args = getopt.getopt(raw_args, 'o:cpt', [ + 'add-header', + 'analyze-inputs', 'count', + 'depfile=', 'fake', 'naive', 'parse', @@ -144,8 +149,14 @@ for (key, val) in own_opts: if key == '-o': args.output = val + elif key == '--add-header': + args.add_header = True + elif key == '--analyze-inputs': + args.analyze_inputs = True elif key in ('--count', '-c'): args.count = True + elif key == '--depfile': + args.depfile = val elif key == '--fake': args.fake = True elif key == '--naive': @@ -164,7 +175,8 @@ Usage: grit update_resource_ids [--parse|-p] [--read-grd|-r] [--tokenize|-t] [--naive] [--fake] [-o OUTPUT_FILE] - RESOURCE_IDS_FILE + [--analyze-inputs] [--depfile DEPFILE] + [--add-header] RESOURCE_IDS_FILE RESOURCE_IDS_FILE is the path of the input resource_ids file. @@ -188,6 +200,9 @@ --tokenize|-t Tokenizes RESOURCE_IDS_FILE and reprints it as syntax- highlighted output. + --depfile=DEPFILE Write out a depfile for ninja to know about dependencies. + --analyze-inputs Writes dependencies to stdout. + --add-header Adds a "THIS FILE IS GENERATED" header to the output. """ def __init(self): @@ -242,13 +257,32 @@ item_list = common.BuildItemList(root_obj) src_dir = os.path.abspath(os.sep.join([file_dir, root_obj['SRCDIR'].val])) - usage_gen = reader.GenerateResourceUsages(item_list, src_dir, args.fake) + seen_files = set() + usage_gen = reader.GenerateResourceUsages(item_list, src_dir, args.fake, + seen_files) if args.count: return self._DumpResourceCounts(usage_gen) for item, tag_name_to_usage in usage_gen: item.SetUsages(tag_name_to_usage) + if args.analyze_inputs: + print('\n'.join(sorted(seen_files))) + return 0 + new_ids_gen = assigner.GenerateNewIds(item_list, args.naive) # Create replacement specs usable by _MultiReplace(). repl = [(tag.lo, tag.hi, str(new_id)) for tag, new_id in new_ids_gen] - _CreateAndOutputResult(data, repl, args.output) + # Update "SRCDIR" entry. + new_srcdir = os.path.relpath(src_dir, os.path.dirname(args.output)) + repl.append( + (root_obj['SRCDIR'].lo, root_obj['SRCDIR'].hi, repr(new_srcdir))) + new_data = _MultiReplace(data, repl) + if args.add_header: + new_data = ('# GENERATED FILE.\n' + + '# Edit {} instead.\n'.format(args.input) + + '#################\n') + new_data + _WriteFile(args.output, new_data) + + if args.depfile: + deps_data = '{}: {}'.format(args.output, ' '.join(sorted(seen_files))) + _WriteFile(args.depfile, deps_data)
diff --git a/tools/grit/grit/tool/update_resource_ids/reader.py b/tools/grit/grit/tool/update_resource_ids/reader.py index a5666cc..2661d54 100644 --- a/tools/grit/grit/tool/update_resource_ids/reader.py +++ b/tools/grit/grit/tool/update_resource_ids/reader.py
@@ -15,29 +15,34 @@ import os from grit import grd_reader +from grit import util from grit.tool.update_resource_ids import common TAGS_OF_INTEREST = set(['include', 'message', 'structure']) - -def _CountResourceUsage(grd): +def _CountResourceUsage(grd, seen_files): tag_name_to_count = {tag: set() for tag in TAGS_OF_INTEREST} # Pass '_chromium', but '_google_chrome' would produce the same result. root = grd_reader.Parse(grd, defines={'_chromium': True}) + seen_files.add(grd) # Count all descendant tags, regardless of whether they're active. for node in root.Preorder(): if node.name in TAGS_OF_INTEREST: tag_name_to_count[node.name].add(node.attrs['name']) + elif node.name == 'part': + part_path = os.path.join(os.path.dirname(grd), node.GetInputPath()) + seen_files.add(util.normpath(part_path)) return {k: len(v) for k, v in tag_name_to_count.iteritems() if v} -def GenerateResourceUsages(item_list, src_dir, fake): +def GenerateResourceUsages(item_list, src_dir, fake, seen_files): """Visits a list of ItemInfo to generate maps from tag name to usage. Args: root_obj: Root dict of a resource_ids file. src_dir: Absolute directory of Chrome's src/ directory. fake: For testing: Sets 10 as usages for all tags, to avoid reading GRD. + seen_files: A set to collect paths of files read. Yields: Tuple (item, tag_name_to_usage), where |item| is from |item_list| and |tag_name_to_usage| is a dict() mapping tag name to (int) usage. @@ -64,9 +69,12 @@ raise ValueError('%s: Generated GRD must use META with "sizes" field ' 'to specify size bounds.' % item.grd) grd_file = os.sep.join([src_dir, item.grd]) - if not os.path.isfile(grd_file): - raise ValueError('Nonexistent GRD provided: %s' % item.grd) - tag_name_to_usage = _CountResourceUsage(grd_file) + if not os.path.exists(grd_file): + # Silently skip missing files so that src-internal files do not break + # public checkouts. + yield item, {} + continue + tag_name_to_usage = _CountResourceUsage(grd_file, seen_files) tag_names = set(tag_name_to_usage.keys()) if not tag_names.issubset(supported_tag_names): missing = [t + 's' for t in tag_names - supported_tag_names]
diff --git a/tools/grit/grit_rule.gni b/tools/grit/grit_rule.gni index ff83793..d1f7596 100644 --- a/tools/grit/grit_rule.gni +++ b/tools/grit/grit_rule.gni
@@ -223,7 +223,10 @@ _js_minifier = "//tools/grit/minify_with_uglify.py" _css_minifier = "//tools/grit/minimize_css.py" -grit_resource_id_file = "//tools/gritsettings/resource_ids" +grit_resource_id_target = "//tools/gritsettings:default_resource_ids" +grit_resource_id_file = + get_label_info(grit_resource_id_target, "target_gen_dir") + + "/default_resource_ids" grit_info_script = "//tools/grit/grit_info.py" # TODO(asvitkine): Add predetermined ids files for other platforms. @@ -238,171 +241,167 @@ } template("grit") { - assert(defined(invoker.source), - "\"source\" must be defined for the grit template $target_name") - - if (defined(invoker.resource_ids)) { - resource_ids = invoker.resource_ids + if (defined(invoker.output_dir)) { + _output_dir = invoker.output_dir } else { - resource_ids = grit_resource_id_file + _output_dir = target_gen_dir } - if (defined(invoker.output_dir)) { - output_dir = invoker.output_dir - } else { - output_dir = target_gen_dir + _grit_outputs = + get_path_info(rebase_path(invoker.outputs, ".", _output_dir), "abspath") + + # Add .info output for all pak files + _pak_info_outputs = [] + foreach(output, _grit_outputs) { + if (get_path_info(output, "extension") == "pak") { + _pak_info_outputs += [ output + ".info" ] + } } if (defined(invoker.output_name)) { - grit_output_name = invoker.output_name + _grit_output_name = invoker.output_name } else { - grit_output_name = target_name + _grit_output_name = target_name } - # These are all passed as arguments to the script so have to be relative to - # the build directory. - rebased_output_dir = rebase_path(output_dir, root_build_dir) - source_path = rebase_path(invoker.source, root_build_dir) - - # Compute flags. - grit_flags = [] - if (defined(invoker.grit_flags)) { - grit_flags += invoker.grit_flags - } - if (resource_ids != "") { - grit_flags += [ - "-f", - rebase_path(resource_ids, root_build_dir), - ] - } - if (grit_predetermined_resource_ids_file != "") { - grit_flags += [ - "-p", - rebase_path(grit_predetermined_resource_ids_file, root_build_dir), - ] - } - - if (defined(invoker.source_is_generated)) { - source_is_generated = invoker.source_is_generated - } else { - source_is_generated = false - } - - assert_files_flags = [] - - # We want to make sure the declared outputs actually match what Grit is - # writing. We write the list to a file (some of the output lists are long - # enough to not fit on a Windows command line) and ask Grit to verify those - # are the actual outputs at runtime. - asserted_list_file = - "$target_out_dir/${grit_output_name}_expected_outputs.txt" - write_file(asserted_list_file, - rebase_path(invoker.outputs, root_build_dir, output_dir)) - assert_files_flags += [ "--assert-file-list=" + - rebase_path(asserted_list_file, root_build_dir) ] - grit_outputs = - get_path_info(rebase_path(invoker.outputs, ".", output_dir), "abspath") - - # Add .info output for all pak files - pak_info_outputs = [] - foreach(output, grit_outputs) { - if (get_path_info(output, "extension") == "pak") { - pak_info_outputs += [ output + ".info" ] - } - } - - grit_custom_target = target_name + "_grit" - action(grit_custom_target) { + _grit_custom_target = target_name + "_grit" + action(_grit_custom_target) { testonly = defined(invoker.testonly) && invoker.testonly script = "//tools/grit/grit.py" + depfile = "$target_gen_dir/$target_name.d" inputs = [ invoker.source, - asserted_list_file, ] - if (resource_ids != "") { - # The script depends on the ID file. Only add this dependency if the ID - # file is specified. - inputs += [ resource_ids ] - } - if (grit_predetermined_resource_ids_file != "") { - # If the predetermined ID file is present, the script outputs depend on - # it too. - inputs += [ grit_predetermined_resource_ids_file ] - } + deps = [ + "//tools/grit:grit_sources", + ] + outputs = [ "${depfile}.stamp" ] + _grit_outputs + _pak_info_outputs - depfile = "$target_gen_dir/$target_name.d" - outputs = [ "${depfile}.stamp" ] + grit_outputs + pak_info_outputs - - args = [ - "-i", - source_path, - "build", - "-o", - rebased_output_dir, - "--depdir", - ".", - "--depfile", - rebase_path(depfile, root_build_dir), - "--write-only-new=1", - "--depend-on-stamp", - ] + grit_defines - - # Add brotli executable if using brotli. - if (defined(invoker.use_brotli) && invoker.use_brotli) { - brotli_target = "//third_party/brotli:brotli($host_toolchain)" - brotli_executable = get_label_info(brotli_target, "root_out_dir") + "/" + - get_label_info(brotli_target, "name") - if (host_os == "win") { - brotli_executable += ".exe" - } - - inputs += [ brotli_executable ] - args += [ - "--brotli", - rebase_path(brotli_executable, root_build_dir), - ] - } + _grit_flags = grit_defines # Add extra defines with -D flags. - define_args = [] if (defined(invoker.defines)) { foreach(i, invoker.defines) { - define_args += [ + _grit_flags += [ "-D", i, ] } } - args += define_args + grit_flags + assert_files_flags + if (defined(invoker.grit_flags)) { + _grit_flags += invoker.grit_flags + } + + _rebased_source_path = rebase_path(invoker.source, root_build_dir) + _source_is_generated = + defined(invoker.source_is_generated) && invoker.source_is_generated + if (!_source_is_generated && compute_inputs_for_analyze) { + # Only call exec_script when the user has explicitly opted into greater + # precision at the expense of performance. + _rel_inputs = exec_script("//tools/grit/grit_info.py", + [ + "--inputs", + _rebased_source_path, + ] + _grit_flags, + "list lines") + inputs += rebase_path(_rel_inputs, ".", root_build_dir) + } + + args = [ + "-i", + _rebased_source_path, + "build", + "-o", + rebase_path(_output_dir, root_build_dir), + "--depdir", + ".", + "--depfile", + rebase_path(depfile, root_build_dir), + "--write-only-new=1", + "--depend-on-stamp", + ] + _grit_flags + + # Add brotli executable if using brotli. + if (defined(invoker.use_brotli) && invoker.use_brotli) { + _brotli_target = "//third_party/brotli:brotli($host_toolchain)" + _brotli_executable = get_label_info(_brotli_target, "root_out_dir") + + "/" + get_label_info(_brotli_target, "name") + if (host_os == "win") { + _brotli_executable += ".exe" + } + + inputs += [ _brotli_executable ] + args += [ + "--brotli", + rebase_path(_brotli_executable, root_build_dir), + ] + } + + _resource_ids = grit_resource_id_file + if (defined(invoker.resource_ids)) { + _resource_ids = invoker.resource_ids + } + + if (_resource_ids != "") { + inputs += [ _resource_ids ] + args += [ + "-f", + rebase_path(_resource_ids, root_build_dir), + ] + if (_resource_ids == grit_resource_id_file) { + deps += [ grit_resource_id_target ] + } + } + if (grit_predetermined_resource_ids_file != "") { + inputs += [ grit_predetermined_resource_ids_file ] + args += [ + "-p", + rebase_path(grit_predetermined_resource_ids_file, root_build_dir), + ] + } + + # We want to make sure the declared outputs actually match what Grit is + # writing. We write the list to a file (some of the output lists are long + # enough to not fit on a Windows command line) and ask Grit to verify those + # are the actual outputs at runtime. + _asserted_list_file = + "$target_out_dir/${_grit_output_name}_expected_outputs.txt" + write_file(_asserted_list_file, + rebase_path(invoker.outputs, root_build_dir, _output_dir)) + inputs += [ _asserted_list_file ] + args += [ + "--assert-file-list", + rebase_path(_asserted_list_file, root_build_dir), + ] if (enable_resource_whitelist_generation) { - rc_grit_outputs = [] - foreach(output, grit_outputs) { + _rc_grit_outputs = [] + foreach(output, _grit_outputs) { if (get_path_info(output, "extension") == "rc") { - rc_grit_outputs += [ output ] + _rc_grit_outputs += [ output ] } } - if (rc_grit_outputs != []) { + if (_rc_grit_outputs != []) { # Resource whitelisting cannot be used with .rc files. # Make sure that there aren't any .pak outputs which would require # whitelist annotations. - assert(pak_info_outputs == [], "can't combine .pak and .rc outputs") + assert(_pak_info_outputs == [], "can't combine .pak and .rc outputs") } else { args += [ "--whitelist-support" ] } } if (_strip_resource_files) { - js_minifier_command = rebase_path(_js_minifier, root_build_dir) - css_minifier_command = rebase_path(_css_minifier, root_build_dir) + _js_minifier_command = rebase_path(_js_minifier, root_build_dir) + _css_minifier_command = rebase_path(_css_minifier, root_build_dir) args += [ "--js-minifier", - js_minifier_command, + _js_minifier_command, "--css-minifier", - css_minifier_command, + _css_minifier_command, ] inputs += [ _js_minifier, @@ -410,27 +409,6 @@ ] } - # Must be after the args are computed since they are re-used. - # See the comments for the two variables used in this condition for - # why this works this way. - if (compute_inputs_for_analyze && !source_is_generated) { - grit_info_script = "//tools/grit/grit_info.py" - grit_info_args = [ - "--inputs", - source_path, - ] + grit_flags + grit_defines + define_args - - # Only call exec_script when the user has explicitly opted into greater - # precision at the expense of performance. - rel_inputs = exec_script(grit_info_script, - grit_info_args, - "list lines", - [ grit_info_script ]) - inputs += rebase_path(rel_inputs, ".", root_build_dir) - } else { - assert(source_is_generated || !source_is_generated) # Prevent error. - } - if (defined(invoker.visibility)) { # This needs to include both what the invoker specified (since they # probably include generated headers from this target), as well as the @@ -442,9 +420,6 @@ visibility = [ ":${invoker.target_name}" ] + invoker.visibility } - deps = [ - "//tools/grit:grit_sources", - ] if (defined(invoker.use_brotli) && invoker.use_brotli) { if (is_mac && is_asan) { deps += [ "//tools/grit:brotli_mac_asan_workaround" ] @@ -468,11 +443,11 @@ # Since we generate a file, we need to be run before the targets that # depend on us. sources = [] - foreach(output, grit_outputs) { - extension = get_path_info(output, "extension") - if (extension != "json" && extension != "gz" && extension != "pak" && - extension != "xml") { - sources += [ output ] + foreach(_output, _grit_outputs) { + _extension = get_path_info(_output, "extension") + if (_extension != "json" && _extension != "gz" && _extension != "pak" && + _extension != "xml") { + sources += [ _output ] } } @@ -481,7 +456,7 @@ # action publicly so other scripts can take the outputs from the grit # script as inputs. public_deps = [ - ":$grit_custom_target", + ":$_grit_custom_target", ] deps = [ @@ -499,6 +474,6 @@ if (defined(invoker.visibility)) { visibility = invoker.visibility } - output_name = grit_output_name + output_name = _grit_output_name } }
diff --git a/tools/gritsettings/BUILD.gn b/tools/gritsettings/BUILD.gn new file mode 100644 index 0000000..5d38372 --- /dev/null +++ b/tools/gritsettings/BUILD.gn
@@ -0,0 +1,41 @@ +# Copyright 2020 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//build/config/compute_inputs_for_analyze.gni") +import("//tools/grit/grit_rule.gni") + +action("default_resource_ids") { + script = "//tools/grit/grit.py" + inputs = [ + "resource_ids.spec", + ] + outputs = [ + grit_resource_id_file, + ] + deps = [ + "//tools/grit:grit_sources", + ] + depfile = "$target_gen_dir/$target_name.d" + _rebased_input = rebase_path(inputs[0], root_build_dir) + args = [ + "update_resource_ids", + "-o", + rebase_path(grit_resource_id_file, root_build_dir), + "--add-header", + "--depfile", + rebase_path(depfile, root_build_dir), + _rebased_input, + ] + + if (compute_inputs_for_analyze) { + _depfile_inputs = exec_script(script, + [ + "update_resource_ids", + "--analyze-inputs", + _rebased_input, + ], + "list lines") + inputs += rebase_path(_depfile_inputs, ".", root_build_dir) + } +}
diff --git a/tools/gritsettings/resource_ids b/tools/gritsettings/resource_ids.spec similarity index 79% rename from tools/gritsettings/resource_ids rename to tools/gritsettings/resource_ids.spec index 58498955c..08e1323 100644 --- a/tools/gritsettings/resource_ids +++ b/tools/gritsettings/resource_ids.spec
@@ -30,10 +30,6 @@ # "META": {"join": <duplicate count>}, # for the item following duplicates. Be sure to look for duplicates that # may appear earlier than those that immediately precede the item. -# * To update IDs, run the following (from src/): -# -# python tools/grit/grit.py update_resource_ids \ -# -o tools/gritsettings/resource_ids tools/gritsettings/resource_ids { # The first entry in the file, SRCDIR, is special: It is a relative path from # this file to the base of your checkout. @@ -60,13 +56,13 @@ "chrome/app/generated_resources.grd": { # Big alignment since strings (previous item) are frequently added. "META": {"join": 2, "align": 200}, - "messages": [800], + "messages": [600], }, "chrome/app/resources/locale_settings.grd": { # Big alignment since strings (previous item) are frequently added. "META": {"align": 1000}, - "messages": [9000], + "messages": [1000], }, # These each start with the same resource id because we only use one @@ -74,29 +70,29 @@ "chrome/app/resources/locale_settings_chromiumos.grd": { # Big alignment since strings (previous item) are frequently added. "META": {"align": 100}, - "messages": [9100], + "messages": [1100], }, "chrome/app/resources/locale_settings_google_chromeos.grd": { - "messages": [9100], + "messages": [1100], }, "chrome/app/resources/locale_settings_linux.grd": { - "messages": [9100], + "messages": [1100], }, "chrome/app/resources/locale_settings_mac.grd": { - "messages": [9100], + "messages": [1100], }, "chrome/app/resources/locale_settings_win.grd": { - "messages": [9100], + "messages": [1100], }, "chrome/app/theme/chrome_unscaled_resources.grd": { "META": {"join": 5}, - "includes": [9150], + "includes": [1120], }, # Leave space for theme_resources since it has many structures. "chrome/app/theme/theme_resources.grd": { - "structures": [9230], + "structures": [1140], }, # END chrome/app section. @@ -104,92 +100,92 @@ "chrome/browser/dev_ui_browser_resources.grd": { # Big alignment at start of section. "META": {"align": 100}, - "includes": [9500], + "includes": [1200], }, "chrome/browser/browser_resources.grd": { - "includes": [9570], - "structures": [9910], + "includes": [1220], + "structures": [1240], }, "chrome/browser/resources/bookmarks/bookmarks_resources.grd": { - "includes": [9940], - "structures": [9960], + "includes": [1260], + "structures": [1280], }, "chrome/browser/resources/bookmarks/bookmarks_resources_vulcanized.grd": { - "includes": [9980], + "includes": [1300], }, "chrome/browser/resources/chromeos/camera/camera_resources.grd": { - "includes": [9990], - "structures": [10050], + "includes": [1320], + "structures": [1340], }, "chrome/browser/resources/chromeos/camera/src/strings/camera_strings.grd": { - "messages": [10110], + "messages": [1360], }, "chrome/browser/resources/chromeos/cellular_setup/cellular_setup_resources.grd": { - "structures": [10200], + "structures": [1380], }, "chrome/browser/resources/chromeos/multidevice_setup/multidevice_setup_resources.grd": { - "structures": [10210], + "structures": [1400], }, "chrome/browser/resources/component_extension_resources.grd": { - "includes": [10220], - "structures": [10360], + "includes": [1420], + "structures": [1440], }, "chrome/browser/resources/downloads/downloads_resources_vulcanized.grd": { - "includes": [10370], + "includes": [1460], }, "chrome/browser/resources/downloads/downloads_resources.grd": { - "includes": [10380], - "structures": [10390], + "includes": [1480], + "structures": [1500], }, "chrome/browser/resources/extensions/extensions_resources_vulcanized.grd": { - "includes": [10400], + "includes": [1520], }, "chrome/browser/resources/extensions/extensions_resources.grd": { - "includes": [10410], - "structures": [10450], + "includes": [1540], + "structures": [1560], }, "chrome/browser/resources/history/history_resources_vulcanized.grd": { - "includes": [10470], + "includes": [1580], }, "chrome/browser/resources/history/history_resources.grd": { - "includes": [10480], + "includes": [1600], }, "chrome/browser/resources/local_ntp/local_ntp_resources.grd": { - "includes": [10510], + "includes": [1620], }, "chrome/browser/resources/new_tab_page/new_tab_page_resources.grd": { - "includes": [10550], - "structures": [10560], + "includes": [1640], + "structures": [1660], }, "chrome/browser/resources/print_preview/print_preview_resources_vulcanized.grd": { - "includes": [10570], + "includes": [1680], }, "chrome/browser/resources/print_preview/print_preview_resources.grd": { - "includes": [10580], - "structures": [10630], + "includes": [1700], + "structures": [1720], }, "chrome/browser/resources/settings/os_settings_resources_vulcanized.grd": { - "includes": [10670], + "includes": [1740], }, "chrome/browser/resources/settings/os_settings_resources.grd": { - "structures": [10680], + "structures": [1760], }, "chrome/browser/resources/settings/settings_resources_vulcanized.grd": { - "includes": [11160], + "includes": [1780], }, "chrome/browser/resources/settings/settings_resources.grd": { - "structures": [11170], + "structures": [1800], }, "chrome/browser/resources/tab_strip/tab_strip_resources.grd": { - "structures": [11620], - "includes": [11640], + "structures": [1820], + "includes": [1840], }, "chrome/browser/resources/welcome/welcome_resources.grd": { - "includes": [11660], - "structures": [11690], + "includes": [1860], + "structures": [1880], }, "chrome/browser/vr/testapp/vr_testapp_resources.grd": { - "includes": [11710], + "includes": [1900], }, # END chrome/browser section. @@ -197,43 +193,43 @@ "chrome/browser/media/kaleidoscope/internal/kaleidoscope_resources.grd": { # Big alignment at start of section. "META": {"align": 100}, - "includes": [11800], + "includes": [2000], }, "chrome/browser/resources/bluetooth_internals/resources.grd": { - "includes": [11810], + "includes": [2020], }, "chrome/browser/resources/invalidations/invalidations_resources.grd": { - "includes": [11850], + "includes": [2040], }, "chrome/browser/resources/media/webrtc_logs_resources.grd": { - "includes": [11860], + "includes": [2060], }, "chrome/browser/resources/net_internals/net_internals_resources.grd": { - "includes": [11870], + "includes": [2080], }, "chrome/browser/resources/omnibox/resources.grd": { - "includes": [11880], + "includes": [2100], }, "chrome/browser/resources/quota_internals/quota_internals_resources.grd": { - "includes": [11900], + "includes": [2120], }, "chrome/browser/resources/sync_file_system_internals/sync_file_system_internals_resources.grd": { - "includes": [11910], + "includes": [2140], }, "chrome/browser/resources/usb_internals/resources.grd": { - "includes": [11920], + "includes": [2160], }, "chrome/browser/resources/webapks/webapks_ui_resources.grd": { - "includes": [11930], + "includes": [2180], }, "components/sync/driver/resources.grd": { - "includes": [11940], + "includes": [2200], }, "content/browser/resources/media/media_internals_resources.grd": { - "includes": [11960], + "includes": [2220], }, "content/browser/webrtc/resources/resources.grd": { - "includes": [11970], + "includes": [2240], }, # END chrome/ WebUI resources section @@ -241,21 +237,21 @@ "chrome/android/features/test_dummy/internal/resources/resources.grd": { # Big alignment at start of section. "META": {"align": 100}, - "includes": [12000], + "includes": [2300], }, "chrome/common/common_resources.grd": { - "includes": [12010], + "includes": [2320], }, "chrome/credential_provider/gaiacp/gaia_resources.grd": { - "includes": [12020], - "messages": [12030], + "includes": [2340], + "messages": [2360], }, "chrome/renderer/resources/renderer_resources.grd": { - "includes": [12070], - "structures": [12150], + "includes": [2380], + "structures": [2400], }, "chrome/test/data/webui_test_resources.grd": { - "includes": [12160], + "includes": [2420], }, # END chrome/ miscellaneous section. @@ -263,10 +259,10 @@ "chromeos/chromeos_strings.grd": { # Big alignment at start of section. "META": {"align": 100}, - "messages": [12200], + "messages": [2500], }, "chromeos/components/help_app_ui/resources/help_app_resources.grd": { - "includes": [12250], + "includes": [2520], }, # Both help_app_bundle_resources.grd and help_app_bundle_mock_resources.grd # start with the same id because only one of them is built depending on if @@ -274,14 +270,14 @@ # of languages (74). "chromeos/components/help_app_ui/resources/app/help_app_bundle_resources.grd": { "META": {"sizes": {"includes": [100],}}, # Relies on src-internal. - "includes": [12260], + "includes": [2540], }, "chromeos/components/help_app_ui/resources/mock/help_app_bundle_mock_resources.grd": { - "includes": [12260], + "includes": [2540], }, "chromeos/components/media_app_ui/resources/media_app_resources.grd": { "META": {"join": 2}, - "includes": [12380], + "includes": [2560], }, # Both media_app_bundle_resources.grd and media_app_bundle_mock_resources.grd # start with the same id because only one of them is built depending on if @@ -289,17 +285,17 @@ # of languages (74). "chromeos/components/media_app_ui/resources/app/app/media_app_bundle_resources.grd": { "META": {"sizes": {"includes": [120],}}, # Relies on src-internal. - "includes": [12390], + "includes": [2580], }, "chromeos/components/media_app_ui/resources/mock/media_app_bundle_mock_resources.grd": { - "includes": [12390], + "includes": [2580], }, "chromeos/components/sample_system_web_app_ui/resources/sample_system_web_app_resources.grd": { "META": {"join": 2}, - "includes": [12530], + "includes": [2600], }, "chromeos/resources/chromeos_resources.grd": { - "includes": [12540], + "includes": [2620], }, # END chromeos/ section. @@ -310,37 +306,37 @@ "components/components_chromium_strings.grd": { # Big alignment at start of section. "META": {"align": 100}, - "messages": [12600], + "messages": [2700], }, "components/components_google_chrome_strings.grd": { - "messages": [12600], + "messages": [2700], }, "components/components_locale_settings.grd": { "META": {"join": 2}, - "includes": [12620], - "messages": [12630], + "includes": [2720], + "messages": [2740], }, "components/components_strings.grd": { - "messages": [12640], + "messages": [2760], }, "components/omnibox/resources/omnibox_resources.grd": { - "includes": [14590], + "includes": [2780], }, "components/policy/resources/policy_templates.grd": { - "structures": [14600], + "structures": [2800], }, "components/resources/components_resources.grd": { - "includes": [14610], + "includes": [2820], }, "components/resources/components_scaled_resources.grd": { - "structures": [14690], + "structures": [2840], }, "components/embedder_support/android/java/strings/web_contents_delegate_android_strings.grd": { - "messages": [14730], + "messages": [2860], }, "components/autofill/core/browser/autofill_address_rewriter_resources.grd":{ - "includes": [14750] + "includes": [2880] }, # END components/ section. @@ -373,26 +369,26 @@ "ios/chrome/app/theme/ios_theme_resources.grd": { # Big alignment since strings (previous item) are frequently added. "META": {"align": 100}, - "structures": [1400], + "structures": [700], }, "ios/chrome/share_extension/strings/ios_share_extension_strings.grd": { - "messages": [1440], + "messages": [720], }, "ios/chrome/search_widget_extension/strings/ios_search_widget_extension_strings.grd": { - "messages": [1450], + "messages": [740], }, "ios/chrome/search_widget_extension/strings/ios_search_widget_extension_chromium_strings.grd": { - "messages": [1470], + "messages": [760], }, "ios/chrome/search_widget_extension/strings/ios_search_widget_extension_google_chrome_strings.grd": { - "messages": [1470], + "messages": [760], }, "ios/chrome/content_widget_extension/strings/ios_content_widget_extension_chromium_strings.grd": { "META": {"join": 2}, - "messages": [1480], + "messages": [780], }, "ios/chrome/content_widget_extension/strings/ios_content_widget_extension_google_chrome_strings.grd": { - "messages": [1480], + "messages": [780], }, # END ios/ section. @@ -403,19 +399,19 @@ "content/app/resources/content_resources.grd": { # Big alignment at start of section. "META": {"join": 3, "align": 100}, - "structures": [14800], + "structures": [2900], }, "content/content_resources.grd": { - "includes": [14830], + "includes": [2920], }, "content/shell/shell_resources.grd": { - "includes": [14870], + "includes": [2940], }, # This file is generated during the build. "<(SHARED_INTERMEDIATE_DIR)/content/browser/tracing/tracing_resources.grd": { "META": {"sizes": {"includes": [20],}}, - "includes": [14880], + "includes": [2960], }, # END content/ section. @@ -425,10 +421,10 @@ "ios/web/ios_web_resources.grd": { # Big alignment at start of section. "META": {"align": 100}, - "includes": [14800], + "includes": [2900], }, "ios/web/test/test_resources.grd": { - "includes": [14810], + "includes": [2920], }, # END ios/web/ section. @@ -437,143 +433,143 @@ "android_webview/ui/aw_resources.grd": { # Big alignment at start of section. "META": {"join": 2, "align": 100}, - "includes": [15000], + "includes": [3000], }, "android_webview/ui/aw_strings.grd": { - "messages": [15010], + "messages": [3020], }, "ash/app_list/resources/app_list_resources.grd": { - "structures": [15020], + "structures": [3040], }, "ash/ash_strings.grd": { - "messages": [15030], + "messages": [3060], }, "ash/components/ash_components_strings.grd": { - "messages": [15770], + "messages": [3080], }, "ash/keyboard/ui/keyboard_resources.grd": { - "includes": [16020], + "includes": [3100], }, "ash/login/resources/login_resources.grd": { - "structures": [16100], + "structures": [3120], }, "ash/public/cpp/resources/ash_public_unscaled_resources.grd": { - "includes": [16110], + "includes": [3140], }, "chromecast/renderer/resources/extensions_renderer_resources.grd": { - "includes": [16120], + "includes": [3160], }, "cloud_print/virtual_driver/win/install/virtual_driver_setup_resources.grd": { - "includes": [16130], - "messages": [16140], + "includes": [3180], + "messages": [3200], }, "device/bluetooth/bluetooth_strings.grd": { - "messages": [16150], + "messages": [3220], }, "device/fido/fido_strings.grd": { - "messages": [16190], + "messages": [3240], }, "extensions/browser/resources/extensions_browser_resources.grd": { - "structures": [16200], + "structures": [3260], }, "extensions/extensions_resources.grd": { - "includes": [16210], + "includes": [3280], }, "extensions/renderer/resources/extensions_renderer_resources.grd": { - "includes": [16220], - "structures": [16290], + "includes": [3300], + "structures": [3320], }, "extensions/shell/app_shell_resources.grd": { - "includes": [16300], + "includes": [3340], }, "extensions/strings/extensions_strings.grd": { - "messages": [16310], + "messages": [3360], }, "headless/lib/resources/headless_lib_resources.grd": { - "includes": [16390], + "includes": [3380], }, "mojo/public/js/mojo_bindings_resources.grd": { - "includes": [16400], + "includes": [3400], }, "net/base/net_resources.grd": { - "includes": [16420], + "includes": [3420], }, "remoting/resources/remoting_strings.grd": { - "messages": [16430], + "messages": [3440], }, "services/services_strings.grd": { - "messages": [16810], + "messages": [3460], }, "third_party/blink/public/blink_image_resources.grd": { - "structures": [16820], + "structures": [3480], }, "third_party/blink/public/blink_resources.grd": { - "includes": [16830], + "includes": [3500], }, "third_party/blink/renderer/modules/media_controls/resources/media_controls_resources.grd": { - "includes": [16910], - "structures": [16920], + "includes": [3520], + "structures": [3540], }, "third_party/blink/public/strings/blink_strings.grd": { - "messages": [16930], + "messages": [3560], }, "third_party/ink/ink_resources.grd": { - "includes": [17240], + "includes": [3580], }, "third_party/libaddressinput/chromium/address_input_strings.grd": { - "messages": [17250], + "messages": [3600], }, "ui/base/test/ui_base_test_resources.grd": { - "messages": [17300], + "messages": [3620], }, "ui/chromeos/resources/ui_chromeos_resources.grd": { - "structures": [17310], + "structures": [3640], }, "ui/chromeos/ui_chromeos_strings.grd": { - "messages": [17410], + "messages": [3660], }, "ui/file_manager/file_manager_resources.grd": { - "includes": [18330], + "includes": [3680], }, "ui/resources/ui_resources.grd": { - "structures": [18550], + "structures": [3700], }, "ui/resources/ui_unscaled_resources.grd": { - "includes": [18690], + "includes": [3720], }, "ui/strings/app_locale_settings.grd": { - "messages": [18720], + "messages": [3740], }, "ui/strings/ui_strings.grd": { - "messages": [18730], + "messages": [3760], }, "ui/views/resources/views_resources.grd": { - "structures": [19030], + "structures": [3780], }, "ui/webui/resources/webui_resources.grd": { - "includes": [19090], - "structures": [19250], + "includes": [3800], + "structures": [3820], }, "weblayer/weblayer_resources.grd": { - "includes": [19870], + "includes": [3840], }, # This file is generated during the build. "<(SHARED_INTERMEDIATE_DIR)/devtools/devtools_resources.grd": { "META": {"sizes": {"includes": [500],}}, - "includes": [19880], + "includes": [3860], }, # END "everything else" section.
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 85769e6f6..55a006a 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -1317,6 +1317,9 @@ </enum> <enum name="AndroidActivityStopReason"> + <obsolete> + Removed 2020-01 + </obsolete> <int value="0" label="Unknown"/> <int value="1" label="Chrome sent to background by system back"> The user pressed the system back button, sending Chrome to the background. @@ -1339,6 +1342,9 @@ </enum> <enum name="AndroidActivitySystemBackAction"> + <obsolete> + Removed 2020-01 + </obsolete> <int value="0" label="Nothing happened"/> <int value="1" label="The foreground tab contained a help article and was closed"/> @@ -11714,6 +11720,18 @@ <int value="2147483646" label="STATUS_DATATYPE_MISALIGNMENT"/> </enum> +<enum name="CrasHfpBatteryIndicator"> + <summary> + List of known battery indicator supports in Bluetooth Hands-free profile. + This list should be aligned with CRAS: + https://chromium.googlesource.com/chromiumos/third_party/adhd/+/master/cras/src/server/cras_hfp_slc.h + </summary> + <int value="0" label="CRAS_HFP_BATTERY_INDICATOR_NONE"/> + <int value="1" label="CRAS_HFP_BATTERY_INDICATOR_HFP"/> + <int value="2" label="CRAS_HFP_BATTERY_INDICATOR_APPLE"/> + <int value="3" label="CRAS_HFP_BATTERY_INDICATOR_BOTH"/> +</enum> + <enum name="CrasHfpCodec"> <summary> List of codec ids used for SCO audio, in Bluetooth Hands-free profile. This
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 4c5fef6a..a373e1cd 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -1613,6 +1613,9 @@ <histogram name="Android.Activity.ChromeTabbedActivity.StopReason" enum="AndroidActivityStopReason" expires_after="M81"> + <obsolete> + Removed 2020-01 + </obsolete> <owner>twellington@chromium.org</owner> <summary> What caused ChromeTabbedActivity#onStop() to be called, which indicates that @@ -1622,6 +1625,9 @@ <histogram name="Android.Activity.ChromeTabbedActivity.SystemBackAction" enum="AndroidActivitySystemBackAction" expires_after="2020-01-26"> + <obsolete> + Removed 2020-01 + </obsolete> <owner>twellington@chromium.org</owner> <summary> What happened when the user hit the system back button in @@ -5307,7 +5313,7 @@ <histogram name="Apps.AppList.DriveQuickAccessProvider.TimeFromFetchToZeroStateStart" - units="ms" expires_after="M82"> + units="ms" expires_after="2020-05-03"> <owner>wrong@chromium.org</owner> <owner>tby@chromium.org</owner> <owner>jiameng@chromium.org</owner> @@ -5436,7 +5442,7 @@ </histogram> <histogram name="Apps.AppList.ZeroStateResults.ReceivedScore.ZeroStateFile" - units="score"> + units="score" expires_after="2020-05-03"> <owner>wrong@chromium.org</owner> <owner>tby@chromium.org</owner> <owner>jiameng@chromium.org</owner> @@ -5471,7 +5477,7 @@ </histogram> <histogram name="Apps.AppList.ZeroStateResultsList.FileImpressions" - enum="AppListSearchResult" expires_after="M82"> + enum="AppListSearchResult" expires_after="2020-05-03"> <owner>wrong@chromium.org</owner> <owner>tby@chromium.org</owner> <owner>jiameng@chromium.org</owner> @@ -14759,7 +14765,7 @@ </histogram> <histogram name="BackgroundFetch.HasDuplicateRequests" enum="Boolean" - expires_after="M81"> + expires_after="M84"> <owner>rayankans@chromium.org</owner> <summary> Records whether the fetch requests contains any duplicate URLs. This is @@ -14780,7 +14786,7 @@ </histogram> <histogram name="BackgroundFetch.IncompleteFetchesOnStartup" units="units" - expires_after="M81"> + expires_after="M84"> <owner>rayankans@chromium.org</owner> <summary> Records the number of Background Fetch registrations found on browser @@ -14790,7 +14796,7 @@ </histogram> <histogram base="true" name="BackgroundFetch.Manager" units="ms" - expires_after="M81"> + expires_after="M84"> <!-- Name completed by histogram_suffixes name="BackgroundFetchManagerAPIsDuration" --> <owner>rayankans@chromium.org</owner> @@ -14876,7 +14882,7 @@ </histogram> <histogram base="true" name="BackgroundFetch.Storage" - enum="BackgroundFetchStorageError" expires_after="M81"> + enum="BackgroundFetchStorageError" expires_after="M84"> <!-- Name completed by histogram_suffixes name="BackgroundFetchDatabaseStorageErrors" --> <owner>rayankans@chromium.org</owner> @@ -27503,6 +27509,27 @@ </summary> </histogram> +<histogram name="Cras.HfpBatteryIndicatorSupported" + enum="CrasHfpBatteryIndicator" expires_after="2020-12-01"> + <owner>enshuo@chromium.org</owner> + <owner>chromeos-audio@google.com</owner> + <summary> + For each HFP audio device record whether it supports battery indicator. + </summary> +</histogram> + +<histogram name="Cras.HfpBatteryReport" enum="CrasHfpBatteryIndicator" + expires_after="2020-12-01"> + <owner>enshuo@chromium.org</owner> + <owner>chromeos-audio@google.com</owner> + <summary> + For each HFP battery level change event record if it comes from the command + defined by Apple's Spec or BT HFP spec. The count indicates how frequent + user might see this event and can help us decide which data source we prefer + to show if the headset supports both. + </summary> +</histogram> + <histogram name="Cras.HfpWidebandSpeechPacketLoss" units="units" expires_after="2020-12-01"> <owner>enshuo@chromium.org</owner> @@ -28500,8 +28527,9 @@ </summary> </histogram> -<histogram name="Crostini.AppLaunch" enum="CrostiniAppLaunchAppType"> - <owner>benwells@chromium.org</owner> +<histogram name="Crostini.AppLaunch" enum="CrostiniAppLaunchAppType" + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> <owner>tbuckley@chromium.org</owner> <summary> Recorded each time a Crostini app is launched, recording whether the app is @@ -28510,8 +28538,8 @@ </histogram> <histogram name="Crostini.AppsInstalledAtLogin" units="apps" - expires_after="M81"> - <owner>jopra@chromium.org</owner> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> <owner>tbuckley@chromium.org</owner> <summary> Records the number of Crostini apps that surface in the launcher at login @@ -28521,9 +28549,9 @@ </histogram> <histogram name="Crostini.AvailableDiskCancel" units="MiB" - expires_after="2020-04-16"> - <owner>sidereal@google.com</owner> - <owner>nverne@chromium.org</owner> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> + <owner>tbuckley@chromium.org</owner> <summary> The available disk space at the start of the crostini install flow, recorded when installation was canceled. This is recorded any time the user cancels @@ -28533,9 +28561,9 @@ </histogram> <histogram name="Crostini.AvailableDiskError" units="MiB" - expires_after="2020-04-16"> - <owner>sidereal@google.com</owner> - <owner>nverne@chromium.org</owner> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> + <owner>tbuckley@chromium.org</owner> <summary> The available disk space at the start of the crostini install flow, recorded when installation returned an error. This is recorded any time the user @@ -28545,9 +28573,9 @@ </histogram> <histogram name="Crostini.AvailableDiskSuccess" units="MiB" - expires_after="2020-04-16"> - <owner>sidereal@google.com</owner> - <owner>nverne@chromium.org</owner> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> + <owner>tbuckley@chromium.org</owner> <summary> The available disk space at the start of the crostini install flow, recorded when installation succeeded. This is recorded any time the user successfully @@ -28557,15 +28585,15 @@ </histogram> <histogram name="Crostini.Backup" enum="CrostiniExportContainerResult" - expires_after="2021-01-01"> - <owner>joelhockey@chromium.org</owner> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> <owner>tbuckley@chromium.org</owner> <summary>Result of crostini backup.</summary> </histogram> <histogram name="Crostini.BackupCompressedSizeLog2" units="units" - expires_after="2021-01-01"> - <owner>juwa@google.com</owner> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> <owner>tbuckley@chromium.org</owner> <summary> log base 2 of compressed container backup size in bytes, rounded to the @@ -28575,8 +28603,8 @@ </histogram> <histogram name="Crostini.BackupContainerSizeLog2" units="units" - expires_after="2021-01-01"> - <owner>juwa@google.com</owner> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> <owner>tbuckley@chromium.org</owner> <summary> log base 2 of uncompressed container image size in bytes, rounded to the @@ -28586,8 +28614,8 @@ </histogram> <histogram name="Crostini.BackupSizeRatio" units="units" - expires_after="2021-01-01"> - <owner>juwa@google.com</owner> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> <owner>tbuckley@chromium.org</owner> <summary> 100 * compressed size / container size. The conventional compression ratio @@ -28596,24 +28624,22 @@ </histogram> <histogram name="Crostini.BackupTimeFailed" units="ms" - expires_after="2021-01-01"> - <owner>joelhockey@chromium.org</owner> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> <owner>tbuckley@chromium.org</owner> <summary>Time taken for failed backup.</summary> </histogram> <histogram name="Crostini.BackupTimeSuccess" units="ms" - expires_after="2021-01-01"> - <owner>joelhockey@chromium.org</owner> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> <owner>tbuckley@chromium.org</owner> <summary>Time taken for successful backup.</summary> </histogram> <histogram name="Crostini.ContainerOsVersion" enum="CrostiniContainerOsVersion" - expires_after="2020-11-01"> - <owner>davidmunro@chromium.org</owner> - <owner>nverne@chromium.org</owner> - <owner>benwells@chromium.org</owner> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> <owner>tbuckley@chromium.org</owner> <summary> Recorded each time a Crostini container is launched, recording the OS @@ -28622,9 +28648,9 @@ </histogram> <histogram name="Crostini.Crosvm.CpuPercentage" units="%" - expires_after="2020-08-30"> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> <owner>tbuckley@chromium.org</owner> - <owner>timzheng@chromium.org</owner> <summary> The percentage of the system CPU that crosvm processes used during the 10-minute measuring period. This is recorded once every 10 minutes when @@ -28633,9 +28659,9 @@ </histogram> <histogram name="Crostini.Crosvm.Processes.Count" units="processes" - expires_after="2020-08-30"> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> <owner>tbuckley@chromium.org</owner> - <owner>timzheng@chromium.org</owner> <summary> The number of crosvm processes that are running at the end of the 10-minute interval. This is recorded once every 10 minutes when crosvm is running. @@ -28643,9 +28669,9 @@ </histogram> <histogram name="Crostini.Crosvm.RssPercentage" units="%" - expires_after="2020-08-30"> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> <owner>tbuckley@chromium.org</owner> - <owner>timzheng@chromium.org</owner> <summary> The percentage of the system memory that crosvm processes used at the end of the 10-minute measuring period. This is recorded once every 10 minutes when @@ -28666,9 +28692,9 @@ </histogram> <histogram name="Crostini.FilesystemCorruption" enum="CorruptionStates" - expires_after="2020-11-21"> - <owner>sidereal@google.com</owner> - <owner>tbuckley@google.com</owner> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> + <owner>tbuckley@chromium.org</owner> <summary> Filesystem corruption events in the crostini VM, recorded every time corruption is observed to affect the state of the system. @@ -28676,10 +28702,8 @@ </histogram> <histogram name="Crostini.Restarter.Started" enum="BooleanAttempted" - expires_after="2020-12-01"> - <owner>davidmunro@google.com</owner> - <owner>nverne@chromium.org</owner> - <owner>benwells@chromium.org</owner> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> <owner>tbuckley@chromium.org</owner> <summary> Emitted whenever a run of CrostiniRestarter is triggered except during the @@ -28688,10 +28712,9 @@ </histogram> <histogram name="Crostini.RestarterResult" enum="CrostiniResult" - expires_after="2020-09-01"> - <owner>sidereal@google.com</owner> - <owner>hollingum@google.com</owner> - <owner>nverne@chromium.org</owner> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> + <owner>tbuckley@chromium.org</owner> <summary> The result of a single run of CrostiniRestarter. This is recorded any time the crostini restart flow is triggered, except during the initial install. @@ -28699,38 +28722,37 @@ </histogram> <histogram name="Crostini.Restore" enum="CrostiniImportContainerResult" - expires_after="2021-01-01"> - <owner>joelhockey@chromium.org</owner> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> <owner>tbuckley@chromium.org</owner> <summary>Result of crostini restore.</summary> </histogram> <histogram name="Crostini.RestoreTimeFailed" units="ms" - expires_after="2021-01-01"> - <owner>joelhockey@chromium.org</owner> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> <owner>tbuckley@chromium.org</owner> <summary>Time taken for failed restore.</summary> </histogram> <histogram name="Crostini.RestoreTimeSuccess" units="ms" - expires_after="2021-01-01"> - <owner>joelhockey@chromium.org</owner> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> <owner>tbuckley@chromium.org</owner> <summary>Time taken for successful restore.</summary> </histogram> <histogram name="Crostini.SettingsEvent" enum="CrostiniSettingsEvent" - expires_after="M88"> - <owner>victorhsieh@chromium.org</owner> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> <owner>tbuckley@chromium.org</owner> + <owner>victorhsieh@chromium.org</owner> <summary>Record user's choice in Crostini Settings</summary> </histogram> <histogram name="Crostini.Setup.Started" enum="BooleanAttempted" - expires_after="2020-12-01"> - <owner>davidmunro@google.com</owner> - <owner>nverne@chromium.org</owner> - <owner>benwells@chromium.org</owner> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> <owner>tbuckley@chromium.org</owner> <summary> Emitted whenever a run of CrostiniRestarter is triggered during the initial @@ -28739,8 +28761,8 @@ </histogram> <histogram name="Crostini.SetupResult" enum="CrostiniSetupResult" - expires_after="M81"> - <owner>benwells@chromium.org</owner> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> <owner>tbuckley@chromium.org</owner> <summary> Recorded each time the user completes the Crostini setup UI, recording the @@ -28748,8 +28770,9 @@ </summary> </histogram> -<histogram name="Crostini.SetupSource" enum="CrostiniUISurface"> - <owner>benwells@chromium.org</owner> +<histogram name="Crostini.SetupSource" enum="CrostiniUISurface" + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> <owner>tbuckley@chromium.org</owner> <summary> Recorded each time the user initiates the Crostini setup UI, recording the @@ -28758,8 +28781,8 @@ </histogram> <histogram name="Crostini.TimeFromDeviceSetupToInstall" units="ms" - expires_after="M81"> - <owner>benwells@chromium.org</owner> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> <owner>tbuckley@chromium.org</owner> <summary> The time from a user setting up their device, to the user enabling Crostini. @@ -28767,9 +28790,9 @@ </histogram> <histogram name="Crostini.TimeToInstallCancel" units="ms" - expires_after="2020-04-16"> - <owner>sidereal@google.com</owner> - <owner>nverne@chromium.org</owner> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> + <owner>tbuckley@chromium.org</owner> <summary> The time taken for the crostini installer to be canceled by the user. This is recorded any time the user cancels the install before it finishes. This @@ -28778,9 +28801,9 @@ </histogram> <histogram name="Crostini.TimeToInstallError" units="ms" - expires_after="2020-04-16"> - <owner>sidereal@google.com</owner> - <owner>nverne@chromium.org</owner> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> + <owner>tbuckley@chromium.org</owner> <summary> The time taken for the crostini installer to fail due to an error. This is recorded any time the user tries to install install crostini and gets an @@ -28790,9 +28813,9 @@ </histogram> <histogram name="Crostini.TimeToInstallSuccess" units="ms" - expires_after="2020-04-16"> - <owner>sidereal@google.com</owner> - <owner>nverne@chromium.org</owner> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> + <owner>tbuckley@chromium.org</owner> <summary> The time taken for the crostini installer to finish successfully. This is recorded any time the user successfully installs crostini. This includes @@ -28801,8 +28824,8 @@ </histogram> <histogram name="Crostini.UninstallResult" enum="CrostiniUninstallResult" - expires_after="M81"> - <owner>benwells@chromium.org</owner> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> <owner>tbuckley@chromium.org</owner> <summary> Recorded each time the user completes the Crostini uninstall UI, recording @@ -28810,8 +28833,9 @@ </summary> </histogram> -<histogram name="Crostini.UninstallSource" enum="CrostiniUISurface"> - <owner>benwells@chromium.org</owner> +<histogram name="Crostini.UninstallSource" enum="CrostiniUISurface" + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> <owner>tbuckley@chromium.org</owner> <summary> Recorded each time the user initiates the Crostini uninstall UI, recording @@ -28820,10 +28844,8 @@ </histogram> <histogram base="true" name="Crostini.UnsupportedNotification.Reason" - enum="CrostiniUnsupportedNotificationReason" expires_after="2020-07-01"> - <owner>davidmunro@chromium.org</owner> - <owner>nverne@chromium.org</owner> - <owner>benwells@chromium.org</owner> + enum="CrostiniUnsupportedNotificationReason" expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> <owner>tbuckley@chromium.org</owner> <summary> Recorded each time we display (or would display, see suffixes) a @@ -28833,9 +28855,8 @@ </histogram> <histogram name="Crostini.UpgradeSource" enum="CrostiniUISurface" - expires_after="M81"> - <owner>benwells@chromium.org</owner> - <owner>nverne@chromium.org</owner> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> <owner>tbuckley@chromium.org</owner> <summary> Recorded each time the user sees the Crostini upgrade UI, recording the UI @@ -28844,9 +28865,8 @@ </histogram> <histogram name="CrosUsb.NotificationClosed" enum="CrosUsbNotificationClosed" - expires_after="2021-07-01"> - <owner>benwells@chromium.org</owner> - <owner>nverne@chromium.org</owner> + expires_after="2021-01-31"> + <owner>clumptini@google.com</owner> <owner>tbuckley@chromium.org</owner> <summary> Records the reason why the "Cros USB device detected" notification @@ -46884,8 +46904,10 @@ </summary> </histogram> -<histogram name="Extensions.AppLaunch" enum="AppLaunch" expires_after="M81"> +<histogram name="Extensions.AppLaunch" enum="AppLaunch" + expires_after="2021-01-31"> <owner>benwells@chromium.org</owner> + <owner>dominickn@chromium.org</owner> <owner>tapted@chromium.org</owner> <summary> The number of times v1 apps are launched grouped by @@ -47198,14 +47220,16 @@ </histogram> <histogram name="Extensions.BookmarkAppLaunchContainer" - enum="AppLaunchContainer" expires_after="M90"> + enum="AppLaunchContainer" expires_after="2021-01-31"> <owner>benwells@chromium.org</owner> + <owner>dominickn@chromium.org</owner> <summary>Records the container used for a bookmark app launch.</summary> </histogram> <histogram name="Extensions.BookmarkAppLaunchSource" enum="AppLaunchSource" - expires_after="M81"> + expires_after="2021-01-31"> <owner>benwells@chromium.org</owner> + <owner>dominickn@chromium.org</owner> <owner>mgiuca@chromium.org</owner> <owner>ortuno@chromium.org</owner> <summary> @@ -48156,8 +48180,11 @@ </histogram> <histogram name="Extensions.EventPageActiveTime2" units="ms" - expires_after="M81"> + expires_after="never"> +<!-- expires-never: Monitoring core extensions platform behavior. --> + <owner>rdevlin.cronin@chromium.org</owner> + <owner>extensions-core@chromium.org</owner> <summary> The time between an extension's event page loading its first URL and the event page later shutting down. @@ -48180,16 +48207,23 @@ <summary>The time for an extension's event page to load.</summary> </histogram> -<histogram name="Extensions.EventPageLoadTime2" units="ms" expires_after="M81"> +<histogram name="Extensions.EventPageLoadTime2" units="ms" + expires_after="never"> +<!-- expires-never: Monitoring core extensions platform behavior. --> + <owner>rdevlin.cronin@chromium.org</owner> + <owner>extensions-core@chromium.org</owner> <summary> The time taken for an extension's event page to load its initial URL. </summary> </histogram> <histogram name="Extensions.Events.Dispatch" enum="ExtensionEvents" - expires_after="M81"> + expires_after="never"> +<!-- expires-never: Monitoring core extensions platform behavior. --> + <owner>rdevlin.cronin@chromium.org</owner> + <owner>extensions-core@chromium.org</owner> <summary>Recorded every time an event is dispatched to an extension.</summary> </histogram> @@ -48212,8 +48246,11 @@ </histogram> <histogram name="Extensions.Events.DispatchWithPersistentBackgroundPage" - enum="ExtensionEvents" expires_after="M81"> + enum="ExtensionEvents" expires_after="never"> +<!-- expires-never: Monitoring core extensions platform behavior. --> + <owner>rdevlin.cronin@chromium.org</owner> + <owner>extensions-core@chromium.org</owner> <summary> Recorded every time an event is dispatched to an extension with a persistent background page. The event may or may not have been dispatched to the @@ -48224,8 +48261,11 @@ </histogram> <histogram name="Extensions.Events.DispatchWithRunningEventPage" - enum="ExtensionEvents" expires_after="M81"> + enum="ExtensionEvents" expires_after="never"> +<!-- expires-never: Monitoring core extensions platform behavior. --> + <owner>rdevlin.cronin@chromium.org</owner> + <owner>extensions-core@chromium.org</owner> <summary> Recorded every time an event is dispatched to an extension with an event page that was already running (i.e. at some point had been woken from its @@ -48237,8 +48277,11 @@ </histogram> <histogram name="Extensions.Events.DispatchWithSuspendedEventPage" - enum="ExtensionEvents" expires_after="M81"> + enum="ExtensionEvents" expires_after="never"> +<!-- expires-never: Monitoring core extensions platform behavior. --> + <owner>rdevlin.cronin@chromium.org</owner> + <owner>extensions-core@chromium.org</owner> <summary> Recorded every time an event is dispatched to an extension with an event page that was suspended. This implies that firing this event woke up the @@ -49088,8 +49131,9 @@ </histogram> <histogram name="Extensions.HostedAppLaunchContainer" enum="AppLaunchContainer" - expires_after="M81"> + expires_after="2021-01-31"> <owner>benwells@chromium.org</owner> + <owner>dominickn@chromium.org</owner> <summary> Records the container used for a hosted app launch. The definition of 'launch' for the purposes of this histogram is different to that used for @@ -49394,8 +49438,11 @@ </histogram> <histogram name="Extensions.InstallSource" enum="ExtensionLocation" - expires_after="M81"> + expires_after="never"> +<!-- expires-never: Monitoring core extension usage. --> + <owner>rdevlin.cronin@chromium.org</owner> + <owner>extensions-core@chromium.org</owner> <summary>Installs grouped by the location property in prefs.</summary> </histogram> @@ -50901,8 +50948,11 @@ </histogram> <histogram name="Extensions.UninstallSource" enum="ExtensionUninstallSource" - expires_after="M81"> + expires_after="never"> +<!-- expires-never: Monitoring core extension usage. --> + <owner>rdevlin.cronin@chromium.org</owner> + <owner>extensions-core@chromium.org</owner> <summary> The source for the extension uninstall. This is only recorded if an uninstall dialog is shown to the user (i.e., it is not recorded for internal @@ -51475,8 +51525,9 @@ </histogram> <histogram name="Extensions.WebRequestBlockingCount" units="extensions" - expires_after="M81"> + expires_after="2020-12-31"> <owner>karandeepb@chromium.org</owner> + <owner>extensions-core@chromium.org</owner> <summary> Number of enabled extensions which have requested the "webRequestBlocking" permission. Includes all kinds of extensions, @@ -51486,7 +51537,7 @@ </histogram> <histogram name="Extensions.WebRequestCount" units="extensions" - expires_after="M81"> + expires_after="2020-12-31"> <owner>karandeepb@chromium.org</owner> <owner>rdevlin.cronin@chromium.org</owner> <summary> @@ -58526,8 +58577,8 @@ </histogram> <histogram name="HistoryPage.OtherDevicesMenu.OpenAll.TabsPerWindow" - units="units" expires_after="M80"> - <owner>dbeam@chromium.org</owner> + units="units" expires_after="2020-07-01"> + <owner>markchang@chromium.org</owner> <summary> The number of tabs created in each window when a user executes "Open all" menu item from a session menu in the "Tabs from other @@ -58536,8 +58587,8 @@ </histogram> <histogram name="HistoryPage.OtherDevicesMenu.OpenAll.TotalTabs" units="units" - expires_after="M80"> - <owner>dbeam@chromium.org</owner> + expires_after="2020-07-01"> + <owner>markchang@chromium.org</owner> <summary> Total number of tabs opened when a user executes "Open all" menu item from a session menu in the "Tabs from other devices" section @@ -58546,8 +58597,8 @@ </histogram> <histogram name="HistoryPage.OtherDevicesMenu.OpenAll.TotalWindows" - units="units" expires_after="M80"> - <owner>dbeam@chromium.org</owner> + units="units" expires_after="2020-07-01"> + <owner>markchang@chromium.org</owner> <summary> Total number of windows opened when a user executes "Open all" menu item from a session menu in the "Tabs from other devices" @@ -82022,7 +82073,7 @@ </histogram> <histogram base="true" name="Net.DNS.DnsTransaction.Insecure.FailureTime" - units="ms" expires_after="M81"> + units="ms" expires_after="2020-08-31"> <!-- Name completed by histogram_suffixes name="DohProviderId" --> @@ -82034,7 +82085,7 @@ </histogram> <histogram base="true" name="Net.DNS.DnsTransaction.Insecure.SuccessTime" - units="ms" expires_after="M81"> + units="ms" expires_after="2020-08-31"> <!-- Name completed by histogram_suffixes name="DohProviderId" --> @@ -82047,7 +82098,7 @@ <histogram base="true" name="Net.DNS.DnsTransaction.SecureNotValidated.FailureError" - enum="NetErrorCodes" expires_after="M81"> + enum="NetErrorCodes" expires_after="2020-08-31"> <!-- Name completed by histogram_suffixes name="DohProviderId" --> @@ -82062,7 +82113,7 @@ <histogram base="true" name="Net.DNS.DnsTransaction.SecureNotValidated.FailureTime" units="ms" - expires_after="M81"> + expires_after="2020-08-31"> <!-- Name completed by histogram_suffixes name="DohProviderId" --> @@ -82077,7 +82128,7 @@ <histogram base="true" name="Net.DNS.DnsTransaction.SecureNotValidated.SuccessTime" units="ms" - expires_after="M81"> + expires_after="2020-08-31"> <!-- Name completed by histogram_suffixes name="DohProviderId" --> @@ -82092,7 +82143,7 @@ <histogram base="true" name="Net.DNS.DnsTransaction.SecureValidated.FailureError" - enum="NetErrorCodes" expires_after="M81"> + enum="NetErrorCodes" expires_after="2020-08-31"> <!-- Name completed by histogram_suffixes name="DohProviderId" --> @@ -82108,7 +82159,7 @@ <histogram base="true" name="Net.DNS.DnsTransaction.SecureValidated.FailureTime" units="ms" - expires_after="M81"> + expires_after="2020-08-31"> <!-- Name completed by histogram_suffixes name="DohProviderId" --> @@ -82123,7 +82174,7 @@ <histogram base="true" name="Net.DNS.DnsTransaction.SecureValidated.SuccessTime" units="ms" - expires_after="M81"> + expires_after="2020-08-31"> <!-- Name completed by histogram_suffixes name="DohProviderId" --> @@ -82137,7 +82188,7 @@ </histogram> <histogram name="Net.DNS.InsecureDnsTask.FailureTime" units="ms" - expires_after="M81"> + expires_after="2020-08-31"> <owner>dalyk@google.com</owner> <owner>doh-core@google.com</owner> <summary> @@ -82172,7 +82223,7 @@ </histogram> <histogram name="Net.DNS.ProbeSequence.ConfigChange.Failure.AttemptTime" - units="ms" expires_after="M81"> + units="ms" expires_after="2020-08-31"> <owner>dalyk@google.com</owner> <owner>doh-core@google.com</owner> <summary> @@ -82182,7 +82233,7 @@ </histogram> <histogram name="Net.DNS.ProbeSequence.ConfigChange.Success.AttemptTime" - units="ms" expires_after="M81"> + units="ms" expires_after="2020-08-31"> <owner>dalyk@google.com</owner> <owner>doh-core@google.com</owner> <summary> @@ -82192,7 +82243,7 @@ </histogram> <histogram name="Net.DNS.ProbeSequence.NetworkChange.Failure.AttemptTime" - units="ms" expires_after="M81"> + units="ms" expires_after="2020-08-31"> <owner>dalyk@google.com</owner> <owner>doh-core@google.com</owner> <summary> @@ -82202,7 +82253,7 @@ </histogram> <histogram name="Net.DNS.ProbeSequence.NetworkChange.Success.AttemptTime" - units="ms" expires_after="M81"> + units="ms" expires_after="2020-08-31"> <owner>dalyk@google.com</owner> <owner>doh-core@google.com</owner> <summary> @@ -82312,7 +82363,7 @@ </histogram> <histogram name="Net.DNS.SecureDnsMode.Automatic.TotalTime" units="ms" - expires_after="M81"> + expires_after="2020-08-31"> <owner>dalyk@google.com</owner> <owner>doh-core@google.com</owner> <summary> @@ -82324,7 +82375,7 @@ </histogram> <histogram name="Net.DNS.SecureDnsMode.Off.TotalTime" units="ms" - expires_after="M81"> + expires_after="2020-08-31"> <owner>dalyk@google.com</owner> <owner>doh-core@google.com</owner> <summary> @@ -82336,7 +82387,7 @@ </histogram> <histogram name="Net.DNS.SecureDnsMode.Secure.TotalTime" units="ms" - expires_after="M81"> + expires_after="2020-08-31"> <owner>dalyk@google.com</owner> <owner>doh-core@google.com</owner> <summary> @@ -82348,7 +82399,7 @@ </histogram> <histogram name="Net.DNS.SecureDnsTask.DnsModeAutomatic.FailureTime" units="ms" - expires_after="M81"> + expires_after="2020-08-31"> <owner>dalyk@google.com</owner> <owner>doh-core@google.com</owner> <summary> @@ -82359,7 +82410,7 @@ </histogram> <histogram name="Net.DNS.SecureDnsTask.DnsModeSecure.FailureTime" units="ms" - expires_after="M81"> + expires_after="2020-08-31"> <owner>dalyk@google.com</owner> <owner>doh-core@google.com</owner> <summary> @@ -82369,7 +82420,7 @@ </histogram> <histogram name="Net.DNS.SecureDnsTaskFailure.FallbackDnsTask.Error" - enum="NetErrorCodes" expires_after="M81"> + enum="NetErrorCodes" expires_after="2020-08-31"> <owner>dalyk@google.com</owner> <owner>doh-core@google.com</owner> <summary> @@ -82379,7 +82430,7 @@ </histogram> <histogram name="Net.DNS.SecureDnsTaskFailure.FallbackProcTask.Error" - enum="NetErrorCodes" expires_after="M81"> + enum="NetErrorCodes" expires_after="2020-08-31"> <owner>dalyk@google.com</owner> <owner>doh-core@google.com</owner> <summary> @@ -82427,7 +82478,7 @@ </histogram> <histogram name="Net.DNS.UpgradeConfig.DotUpgradeSucceeded" enum="Boolean" - expires_after="M81"> + expires_after="2020-08-31"> <owner>dalyk@google.com</owner> <owner>doh-core@google.com</owner> <summary> @@ -82437,7 +82488,7 @@ </histogram> <histogram name="Net.DNS.UpgradeConfig.HasPublicInsecureNameserver" - enum="Boolean" expires_after="M81"> + enum="Boolean" expires_after="2020-08-31"> <owner>dalyk@google.com</owner> <owner>doh-core@google.com</owner> <summary> @@ -82448,7 +82499,7 @@ </histogram> <histogram name="Net.DNS.UpgradeConfig.Ineligible.DohSpecified" enum="Boolean" - expires_after="M81"> + expires_after="2020-08-31"> <owner>dalyk@google.com</owner> <owner>doh-core@google.com</owner> <summary> @@ -82458,7 +82509,7 @@ </histogram> <histogram name="Net.DNS.UpgradeConfig.InsecureUpgradeSucceeded" enum="Boolean" - expires_after="M81"> + expires_after="2020-08-31"> <owner>dalyk@google.com</owner> <owner>doh-core@google.com</owner> <summary> @@ -118922,8 +118973,10 @@ </histogram> <histogram name="Previews.CacheControlNoTransform.BlockedPreview" - enum="PreviewsType" expires_after="M81"> + enum="PreviewsType" expires_after="2020-12-12"> <owner>dougarnett@chromium.org</owner> + <owner>mcrouse@chromium.org</owner> + <owner>src/components/data_reduction_proxy/OWNERS</owner> <summary> Blocked previews due to Cache-Control:no-transform directive. </summary> @@ -119623,8 +119676,10 @@ </histogram> <histogram name="Previews.Triggered.EffectiveConnectionType2" - enum="NQEEffectiveConnectionType" expires_after="2020-06-28"> + enum="NQEEffectiveConnectionType" expires_after="2020-12-12"> <owner>dougarnett@chromium.org</owner> + <owner>mcrouse@chromium.org</owner> + <owner>src/components/data_reduction_proxy/OWNERS</owner> <summary> Records the effective connection type of a navigation that triggers a preview. This is captured at commit time but uses the effective connection @@ -122696,6 +122751,10 @@ <histogram name="RecurrenceRanker.LogFileOpenType" enum="FileOpenType" expires_after="2019-12-31"> + <obsolete> + Deprecated December 2019. Distribution between file open types is + approximately 33% download, 26% launch, 26% open, 15% save as. + </obsolete> <owner>jiameng@chromium.org</owner> <owner>thanhdng@chromium.org</owner> <owner>tby@chromium.org</owner> @@ -141115,7 +141174,8 @@ </histogram> <histogram name="Sharing.MessageAckTime" units="ms" expires_after="M84"> -<!-- Name completed by histogram_suffixes name="SharingMessage" --> +<!-- Name completed by histogram_suffixes name="SharingDeviceType" and + name="SharingMessage" --> <owner>mvanouwerkerk@chromium.org</owner> <owner>knollr@chromium.org</owner> @@ -182971,7 +183031,10 @@ <histogram_suffixes name="OptimizationGuide.OptimizationTypes" separator="."> <suffix name="DeferAllScript" label="Defers execution of script"/> - <suffix name="LitePageRedirect" label="Lite page redirection"/> + <suffix name="LitePage" + label="HTTP server preview (served from the Data Reduction Proxy)"/> + <suffix name="LitePageRedirect" + label="HTTPS server preview (served from the litepages service)"/> <suffix name="None" label="No optimization type"/> <suffix name="NoScript" label="Disables the fetching and execution of JavaScript"/> @@ -187590,6 +187653,7 @@ <suffix name="Mac" label="Mac OS"/> <suffix name="Unknown" label="Device type unknown"/> <suffix name="Windows" label="Windows OS"/> + <affected-histogram name="Sharing.MessageAckTime"/> <affected-histogram name="Sharing.SendAckMessageResult"/> <affected-histogram name="Sharing.SendMessageResult"/> </histogram_suffixes> @@ -187607,6 +187671,13 @@ <affected-histogram name="Sharing.DeviceLastUpdatedAge"/> <affected-histogram name="Sharing.MajorVersionComparison"/> <affected-histogram name="Sharing.MessageAckTime"/> + <affected-histogram name="Sharing.MessageAckTime.Android"/> + <affected-histogram name="Sharing.MessageAckTime.ChromeOS"/> + <affected-histogram name="Sharing.MessageAckTime.iOS"/> + <affected-histogram name="Sharing.MessageAckTime.Linux"/> + <affected-histogram name="Sharing.MessageAckTime.Mac"/> + <affected-histogram name="Sharing.MessageAckTime.Unknown"/> + <affected-histogram name="Sharing.MessageAckTime.Windows"/> <affected-histogram name="Sharing.MessageReceivedType"/> <affected-histogram name="Sharing.SendAckMessageResult"/> <affected-histogram name="Sharing.SendAckMessageResult.Android"/>
diff --git a/ui/gfx/color_space_win.cc b/ui/gfx/color_space_win.cc index 45b97183..049989a 100644 --- a/ui/gfx/color_space_win.cc +++ b/ui/gfx/color_space_win.cc
@@ -212,6 +212,26 @@ } } +DXGI_FORMAT ColorSpaceWin::GetDXGIFormat(const gfx::ColorSpace& color_space, + bool needs_alpha) { + // Extended linear color spaces use half-float. + if (color_space.GetTransferID() == gfx::ColorSpace::TransferID::LINEAR_HDR) + return DXGI_FORMAT_R16G16B16A16_FLOAT; + + // The PQ transfer function needs 10 bits. If we need an alpha channel, then + // we will need to bump to 16 bits. + if (color_space.GetTransferID() == gfx::ColorSpace::TransferID::SMPTEST2084) { + if (needs_alpha) + return DXGI_FORMAT_R16G16B16A16_UNORM; + else + return DXGI_FORMAT_R10G10B10A2_UNORM; + } + + // For now just give everything else 8 bits. We will want to use 10 or 16 bits + // for BT2020 gamuts. + return DXGI_FORMAT_B8G8R8A8_UNORM; +} + D3D11_VIDEO_PROCESSOR_COLOR_SPACE ColorSpaceWin::GetD3D11ColorSpace( const ColorSpace& color_space) { D3D11_VIDEO_PROCESSOR_COLOR_SPACE ret = {0};
diff --git a/ui/gfx/color_space_win.h b/ui/gfx/color_space_win.h index 9a00bf5..cce9d2b 100644 --- a/ui/gfx/color_space_win.h +++ b/ui/gfx/color_space_win.h
@@ -35,6 +35,11 @@ static DXGI_COLOR_SPACE_TYPE GetDXGIColorSpace(const ColorSpace& color_space, bool force_yuv = false); + // Get DXGI format for swap chain. This will default to 8-bit, but will use + // 10-bit or half-float for HDR color spaces. + static DXGI_FORMAT GetDXGIFormat(const gfx::ColorSpace& color_space, + bool needs_alpha); + static D3D11_VIDEO_PROCESSOR_COLOR_SPACE GetD3D11ColorSpace( const ColorSpace& color_space); };
diff --git a/ui/gfx/paint_vector_icon.cc b/ui/gfx/paint_vector_icon.cc index d69b25b..79778a51 100644 --- a/ui/gfx/paint_vector_icon.cc +++ b/ui/gfx/paint_vector_icon.cc
@@ -75,8 +75,8 @@ const VectorIcon* b_icon = &b.icon; const VectorIcon* a_badge = &a.badge_icon; const VectorIcon* b_badge = &b.badge_icon; - return std::tie(a_icon, a.dip_size, a.color, a.elapsed_time, a_badge) < - std::tie(b_icon, b.dip_size, b.color, b.elapsed_time, b_badge); + return std::tie(a_icon, a.dip_size, a.color, a_badge) < + std::tie(b_icon, b.dip_size, b.color, b_badge); } }; @@ -119,7 +119,6 @@ return 2; case CIRCLE: - case TRANSITION_END: return 3; case PATH_COLOR_ARGB: @@ -144,8 +143,6 @@ case CLOSE: case DISABLE_AA: case FLIPS_IN_RTL: - case TRANSITION_FROM: - case TRANSITION_TO: return 0; } @@ -219,8 +216,7 @@ const PathElement* path_elements, size_t path_size, int dip_size, - SkColor color, - const base::TimeDelta& elapsed_time) { + SkColor color) { int canvas_size = kReferenceSizeDip; std::vector<SkPath> paths; std::vector<cc::PaintFlags> flags_array; @@ -405,68 +401,6 @@ case FLIPS_IN_RTL: flips_in_rtl = true; break; - - // Transitions work by pushing new paths and a new set of flags onto the - // stack. When TRANSITION_END is seen, the paths and flags are - // interpolated based on |elapsed_time| and the tween type. - case TRANSITION_FROM: { - start_new_path(); - break; - } - - case TRANSITION_TO: { - start_new_path(); - start_new_flags(); - break; - } - - case TRANSITION_END: { - DCHECK_GT(paths.size(), 2U); - // TODO(estade): check whether this operation (interpolation) is costly, - // and remove this TRACE log if not. - TRACE_EVENT0("ui", "PaintVectorIcon TRANSITION_END"); - - const base::TimeDelta delay = - base::TimeDelta::FromMillisecondsD(SkScalarToDouble(arg(0))); - const base::TimeDelta duration = - base::TimeDelta::FromMillisecondsD(SkScalarToDouble(arg(1))); - - double state = 0; - if (elapsed_time >= delay + duration) { - state = 1; - } else if (elapsed_time > delay) { - DCHECK(!duration.is_zero()); - state = (elapsed_time - delay).InMicroseconds() / - static_cast<double>(duration.InMicroseconds()); - } - - auto weight = Tween::CalculateValue( - static_cast<Tween::Type>(SkScalarTruncToInt(arg(2))), state); - - SkPath path1, path2; - path1.swap(paths.back()); - paths.pop_back(); - path2.swap(paths.back()); - paths.pop_back(); - - SkPath interpolated_path; - bool could_interpolate = - path1.interpolate(path2, weight, &interpolated_path); - DCHECK(could_interpolate); - paths.back().addPath(interpolated_path); - - // Perform manual interpolation of flags properties. TODO(estade): fill - // more of these in as necessary. - DCHECK_GT(flags_array.size(), 1U); - cc::PaintFlags& end_flags = flags_array.back(); - cc::PaintFlags& start_flags = flags_array[flags_array.size() - 2]; - - start_flags.setColor(Tween::ColorValueBetween( - weight, start_flags.getColor(), end_flags.getColor())); - - flags_array.pop_back(); - break; - } } previous_command_type = command_type; @@ -497,7 +431,7 @@ VectorIconSource(const std::string& definition, int dip_size, SkColor color) : CanvasImageSource(Size(dip_size, dip_size)), - data_(kNoneIcon, dip_size, color, base::TimeDelta(), kNoneIcon), + data_(kNoneIcon, dip_size, color, kNoneIcon), path_(PathFromSource(definition)) {} ~VectorIconSource() override {} @@ -509,13 +443,11 @@ void Draw(Canvas* canvas) override { if (path_.empty()) { - PaintVectorIcon(canvas, data_.icon, size_.width(), data_.color, - data_.elapsed_time); + PaintVectorIcon(canvas, data_.icon, size_.width(), data_.color); if (!data_.badge_icon.is_empty()) PaintVectorIcon(canvas, data_.badge_icon, size_.width(), data_.color); } else { - PaintPath(canvas, path_.data(), path_.size(), size_.width(), data_.color, - base::TimeDelta()); + PaintPath(canvas, path_.data(), path_.size(), size_.width(), data_.color); } } @@ -561,12 +493,10 @@ IconDescription::IconDescription(const VectorIcon& icon, int dip_size, SkColor color, - const base::TimeDelta& elapsed_time, const VectorIcon& badge_icon) : icon(icon), dip_size(dip_size), color(color), - elapsed_time(elapsed_time), badge_icon(badge_icon) { if (dip_size == 0) this->dip_size = GetDefaultSizeOfVectorIcon(icon); @@ -576,25 +506,20 @@ const VectorIcon kNoneIcon = {}; -void PaintVectorIcon(Canvas* canvas, - const VectorIcon& icon, - SkColor color, - const base::TimeDelta& elapsed_time) { - PaintVectorIcon(canvas, icon, GetDefaultSizeOfVectorIcon(icon), color, - elapsed_time); +void PaintVectorIcon(Canvas* canvas, const VectorIcon& icon, SkColor color) { + PaintVectorIcon(canvas, icon, GetDefaultSizeOfVectorIcon(icon), color); } void PaintVectorIcon(Canvas* canvas, const VectorIcon& icon, int dip_size, - SkColor color, - const base::TimeDelta& elapsed_time) { + SkColor color) { DCHECK(!icon.is_empty()); for (size_t i = 0; i < icon.reps_size; ++i) DCHECK(icon.reps[i].path_size > 0); const int px_size = gfx::ToCeiledInt(canvas->image_scale() * dip_size); const VectorIconRep* rep = GetRepForPxSize(icon, px_size); - PaintPath(canvas, rep->path, rep->path_size, dip_size, color, elapsed_time); + PaintPath(canvas, rep->path, rep->path_size, dip_size, color); } ImageSkia CreateVectorIcon(const IconDescription& params) { @@ -611,16 +536,14 @@ ImageSkia CreateVectorIcon(const VectorIcon& icon, int dip_size, SkColor color) { - return CreateVectorIcon( - IconDescription(icon, dip_size, color, base::TimeDelta(), kNoneIcon)); + return CreateVectorIcon(IconDescription(icon, dip_size, color, kNoneIcon)); } ImageSkia CreateVectorIconWithBadge(const VectorIcon& icon, int dip_size, SkColor color, const VectorIcon& badge_icon) { - return CreateVectorIcon( - IconDescription(icon, dip_size, color, base::TimeDelta(), badge_icon)); + return CreateVectorIcon(IconDescription(icon, dip_size, color, badge_icon)); } ImageSkia CreateVectorIconFromSource(const std::string& source, @@ -642,19 +565,4 @@ return GetCanvasDimensions(default_icon_path); } -base::TimeDelta GetDurationOfAnimation(const VectorIcon& icon) { - base::TimeDelta last_motion; - for (PathParser parser(icon.reps[0].path, icon.reps[0].path_size); - parser.HasCommandsRemaining(); parser.Advance()) { - if (parser.CurrentCommand() != TRANSITION_END) - continue; - - auto end_time = base::TimeDelta::FromMillisecondsD(parser.GetArgument(0)) + - base::TimeDelta::FromMillisecondsD(parser.GetArgument(1)); - if (end_time > last_motion) - last_motion = end_time; - } - return last_motion; -} - } // namespace gfx
diff --git a/ui/gfx/paint_vector_icon.h b/ui/gfx/paint_vector_icon.h index 2c6871b..9464726 100644 --- a/ui/gfx/paint_vector_icon.h +++ b/ui/gfx/paint_vector_icon.h
@@ -5,7 +5,6 @@ #ifndef UI_GFX_PAINT_VECTOR_ICON_H_ #define UI_GFX_PAINT_VECTOR_ICON_H_ -#include "base/time/time.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/gfx/gfx_export.h" #include "ui/gfx/image/image_skia.h" @@ -23,7 +22,6 @@ IconDescription(const VectorIcon& icon, int dip_size, SkColor color, - const base::TimeDelta& elapsed_time, const VectorIcon& badge_icon); ~IconDescription(); @@ -31,7 +29,6 @@ const VectorIcon& icon; int dip_size; SkColor color; - const base::TimeDelta elapsed_time; const VectorIcon& badge_icon; }; @@ -39,22 +36,17 @@ // Draws a vector icon identified by |id| onto |canvas| at (0, 0). |color| is // used as the fill. The size will come from the .icon file (the 1x version, if -// multiple versions exist). |elapsed_time| is used to determine the state of -// any transitions the icon may define. -GFX_EXPORT void PaintVectorIcon( - Canvas* canvas, - const VectorIcon& icon, - SkColor color, - const base::TimeDelta& elapsed_time = base::TimeDelta()); +// multiple versions exist). +GFX_EXPORT void PaintVectorIcon(Canvas* canvas, + const VectorIcon& icon, + SkColor color); -// As above, with a specificed size. |dip_size| is the length of a single edge +// As above, with a specified size. |dip_size| is the length of a single edge // of the square icon, in device independent pixels. -GFX_EXPORT void PaintVectorIcon( - Canvas* canvas, - const VectorIcon& icon, - int dip_size, - SkColor color, - const base::TimeDelta& elapsed_time = base::TimeDelta()); +GFX_EXPORT void PaintVectorIcon(Canvas* canvas, + const VectorIcon& icon, + int dip_size, + SkColor color); // Creates an ImageSkia which will render the icon on demand. // TODO(estade): update clients to use this version and remove the other @@ -90,10 +82,6 @@ // smallest icon size |icon| contains. GFX_EXPORT int GetDefaultSizeOfVectorIcon(const gfx::VectorIcon& icon); -// Calculates and returns the elapsed time at which all animations/transitions -// will be finished. -GFX_EXPORT base::TimeDelta GetDurationOfAnimation(const VectorIcon& icon); - } // namespace gfx #endif // UI_GFX_PAINT_VECTOR_ICON_H_
diff --git a/ui/gfx/vector_icon_types.h b/ui/gfx/vector_icon_types.h index e0a3e54..39ac664 100644 --- a/ui/gfx/vector_icon_types.h +++ b/ui/gfx/vector_icon_types.h
@@ -58,13 +58,7 @@ DECLARE_VECTOR_COMMAND(DISABLE_AA) \ /* Flips the x-axis in RTL locales. Default is false, this command sets */ \ /* it to true. */ \ - DECLARE_VECTOR_COMMAND(FLIPS_IN_RTL) \ - /* Defines a timed transition for other elements. */ \ - DECLARE_VECTOR_COMMAND(TRANSITION_FROM) \ - DECLARE_VECTOR_COMMAND(TRANSITION_TO) \ - /* Parameters are delay (ms), duration (ms), and tween type */ \ - /* (gfx::Tween::Type). */ \ - DECLARE_VECTOR_COMMAND(TRANSITION_END) + DECLARE_VECTOR_COMMAND(FLIPS_IN_RTL) #define DECLARE_VECTOR_COMMAND(x) x,
diff --git a/ui/gl/color_space_utils.cc b/ui/gl/color_space_utils.cc index c722dd2c..60d5496 100644 --- a/ui/gl/color_space_utils.cc +++ b/ui/gl/color_space_utils.cc
@@ -11,48 +11,39 @@ // static GLenum ColorSpaceUtils::GetGLColorSpace(const gfx::ColorSpace& color_space) { - switch (color_space.GetTransferID()) { - case gfx::ColorSpace::TransferID::LINEAR_HDR: - return GL_COLOR_SPACE_SCRGB_LINEAR_CHROMIUM; - case gfx::ColorSpace::TransferID::SMPTEST2084: - return GL_COLOR_SPACE_HDR10_CHROMIUM; - default: - return GL_COLOR_SPACE_UNSPECIFIED_CHROMIUM; - } + if (color_space == gfx::ColorSpace::CreateSCRGBLinear()) + return GL_COLOR_SPACE_SCRGB_LINEAR_CHROMIUM; + + if (color_space == gfx::ColorSpace::CreateHDR10()) + return GL_COLOR_SPACE_HDR10_CHROMIUM; + + if (color_space == gfx::ColorSpace::CreateSRGB()) + return GL_COLOR_SPACE_SRGB_CHROMIUM; + + if (color_space == gfx::ColorSpace::CreateDisplayP3D65()) + return GL_COLOR_SPACE_DISPLAY_P3_CHROMIUM; + + return GL_COLOR_SPACE_UNSPECIFIED_CHROMIUM; } // static -GLSurface::ColorSpace ColorSpaceUtils::GetGLSurfaceColorSpace( - const gfx::ColorSpace& color_space) { - switch (color_space.GetTransferID()) { - case gfx::ColorSpace::TransferID::LINEAR_HDR: - return GLSurface::ColorSpace::SCRGB_LINEAR; - case gfx::ColorSpace::TransferID::SMPTEST2084: - return GLSurface::ColorSpace::HDR10; +gfx::ColorSpace ColorSpaceUtils::GetColorSpace(GLenum color_space) { + switch (color_space) { + case GL_COLOR_SPACE_UNSPECIFIED_CHROMIUM: + break; + case GL_COLOR_SPACE_SCRGB_LINEAR_CHROMIUM: + return gfx::ColorSpace::CreateSCRGBLinear(); + case GL_COLOR_SPACE_HDR10_CHROMIUM: + return gfx::ColorSpace::CreateHDR10(); + case GL_COLOR_SPACE_SRGB_CHROMIUM: + return gfx::ColorSpace::CreateSRGB(); + case GL_COLOR_SPACE_DISPLAY_P3_CHROMIUM: + return gfx::ColorSpace::CreateDisplayP3D65(); default: - return GLSurface::ColorSpace::UNSPECIFIED; + DLOG(ERROR) << "Invalid color space."; + break; } + return gfx::ColorSpace(); } -#if defined(OS_WIN) -DXGI_COLOR_SPACE_TYPE ColorSpaceUtils::GetDXGIColorSpace( - GLSurface::ColorSpace color_space) { - if (color_space == GLSurface::ColorSpace::SCRGB_LINEAR) - return DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709; - else if (color_space == GLSurface::ColorSpace::HDR10) - return DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020; - else - return DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709; -} - -DXGI_FORMAT ColorSpaceUtils::GetDXGIFormat(GLSurface::ColorSpace color_space) { - if (color_space == GLSurface::ColorSpace::SCRGB_LINEAR) - return DXGI_FORMAT_R16G16B16A16_FLOAT; - else if (color_space == GLSurface::ColorSpace::HDR10) - return DXGI_FORMAT_R10G10B10A2_UNORM; - else - return DXGI_FORMAT_B8G8R8A8_UNORM; -} -#endif // OS_WIN - } // namespace gl
diff --git a/ui/gl/color_space_utils.h b/ui/gl/color_space_utils.h index ead0918c..c81d9e3 100644 --- a/ui/gl/color_space_utils.h +++ b/ui/gl/color_space_utils.h
@@ -7,12 +7,6 @@ #include "build/build_config.h" #include "ui/gl/gl_export.h" -#include "ui/gl/gl_surface.h" - -#if defined(OS_WIN) -#include <dxgicommon.h> -#include <dxgiformat.h> -#endif // OS_WIN typedef unsigned int GLenum; @@ -28,17 +22,7 @@ static GLenum GetGLColorSpace(const gfx::ColorSpace& color_space); // Get the color space used for GLSurface::Resize(). - static GLSurface::ColorSpace GetGLSurfaceColorSpace( - const gfx::ColorSpace& color_space); - -#if defined(OS_WIN) - // Get DXGI color space for swap chain. - static DXGI_COLOR_SPACE_TYPE GetDXGIColorSpace( - GLSurface::ColorSpace color_space); - - // Get DXGI format for swap chain. - static DXGI_FORMAT GetDXGIFormat(GLSurface::ColorSpace color_space); -#endif // OS_WIN + static gfx::ColorSpace GetColorSpace(GLenum color_space); }; } // namespace gl
diff --git a/ui/gl/direct_composition_child_surface_win.cc b/ui/gl/direct_composition_child_surface_win.cc index a9191423..7884cfd 100644 --- a/ui/gl/direct_composition_child_surface_win.cc +++ b/ui/gl/direct_composition_child_surface_win.cc
@@ -13,6 +13,7 @@ #include "base/trace_event/trace_event.h" #include "base/trace_event/traced_value.h" #include "base/win/windows_version.h" +#include "ui/gfx/color_space_win.h" #include "ui/gfx/native_widget_types.h" #include "ui/gl/color_space_utils.h" #include "ui/gl/direct_composition_surface_win.h" @@ -261,7 +262,8 @@ return false; } - DXGI_FORMAT dxgi_format = ColorSpaceUtils::GetDXGIFormat(color_space_); + DXGI_FORMAT dxgi_format = + gfx::ColorSpaceWin::GetDXGIFormat(color_space_, has_alpha_); if (!dcomp_surface_ && enable_dc_layers_) { TRACE_EVENT2("gpu", "DirectCompositionChildSurfaceWin::CreateSurface", @@ -318,7 +320,7 @@ Microsoft::WRL::ComPtr<IDXGISwapChain3> swap_chain; if (SUCCEEDED(swap_chain_.As(&swap_chain))) { swap_chain->SetColorSpace1( - ColorSpaceUtils::GetDXGIColorSpace(color_space_)); + gfx::ColorSpaceWin::GetDXGIColorSpace(color_space_)); } } @@ -383,10 +385,11 @@ vsync_enabled_ = enabled; } -bool DirectCompositionChildSurfaceWin::Resize(const gfx::Size& size, - float scale_factor, - ColorSpace color_space, - bool has_alpha) { +bool DirectCompositionChildSurfaceWin::Resize( + const gfx::Size& size, + float scale_factor, + const gfx::ColorSpace& color_space, + bool has_alpha) { if (size_ == size && has_alpha_ == has_alpha && color_space_ == color_space) return true; @@ -403,7 +406,8 @@ // ResizeBuffers can't change alpha blending mode. if (swap_chain_ && resize_only) { - DXGI_FORMAT format = ColorSpaceUtils::GetDXGIFormat(color_space_); + DXGI_FORMAT format = + gfx::ColorSpaceWin::GetDXGIFormat(color_space_, has_alpha_); UINT flags = DirectCompositionSurfaceWin::AllowTearing() ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0;
diff --git a/ui/gl/direct_composition_child_surface_win.h b/ui/gl/direct_composition_child_surface_win.h index fb9b35f..2b82f278 100644 --- a/ui/gl/direct_composition_child_surface_win.h +++ b/ui/gl/direct_composition_child_surface_win.h
@@ -34,7 +34,7 @@ void SetVSyncEnabled(bool enabled) override; bool Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) override; bool SetEnableDCLayers(bool enable) override; @@ -61,7 +61,7 @@ bool enable_dc_layers_ = false; bool has_alpha_ = true; bool vsync_enabled_ = true; - ColorSpace color_space_ = ColorSpace::UNSPECIFIED; + gfx::ColorSpace color_space_; // This is a placeholder surface used when not rendering to the // DirectComposition surface.
diff --git a/ui/gl/direct_composition_surface_win.cc b/ui/gl/direct_composition_surface_win.cc index 2d9032b..da62ecd 100644 --- a/ui/gl/direct_composition_surface_win.cc +++ b/ui/gl/direct_composition_surface_win.cc
@@ -512,7 +512,7 @@ bool DirectCompositionSurfaceWin::Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) { // Force a resize and redraw (but not a move, activate, etc.). if (!SetWindowPos(window_, nullptr, 0, 0, size.width(), size.height(),
diff --git a/ui/gl/direct_composition_surface_win.h b/ui/gl/direct_composition_surface_win.h index cbd33dd..ba89b881 100644 --- a/ui/gl/direct_composition_surface_win.h +++ b/ui/gl/direct_composition_surface_win.h
@@ -95,7 +95,7 @@ void* GetHandle() override; bool Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) override; gfx::SwapResult SwapBuffers(PresentationCallback callback) override; gfx::SwapResult PostSubBuffer(int x,
diff --git a/ui/gl/direct_composition_surface_win_unittest.cc b/ui/gl/direct_composition_surface_win_unittest.cc index 53c96c8..69029d96 100644 --- a/ui/gl/direct_composition_surface_win_unittest.cc +++ b/ui/gl/direct_composition_surface_win_unittest.cc
@@ -167,8 +167,8 @@ TEST_F(DirectCompositionSurfaceTest, TestMakeCurrent) { if (!surface_) return; - EXPECT_TRUE(surface_->Resize(gfx::Size(100, 100), 1.0, - GLSurface::ColorSpace::UNSPECIFIED, true)); + EXPECT_TRUE( + surface_->Resize(gfx::Size(100, 100), 1.0, gfx::ColorSpace(), true)); // First SetDrawRectangle must be full size of surface. EXPECT_FALSE(surface_->SetDrawRectangle(gfx::Rect(0, 0, 50, 50))); @@ -187,8 +187,8 @@ EXPECT_TRUE(surface_->SetDrawRectangle(gfx::Rect(0, 0, 100, 100))); EXPECT_TRUE(context_->IsCurrent(surface_.get())); - EXPECT_TRUE(surface_->Resize(gfx::Size(50, 50), 1.0, - GLSurface::ColorSpace::UNSPECIFIED, true)); + EXPECT_TRUE( + surface_->Resize(gfx::Size(50, 50), 1.0, gfx::ColorSpace(), true)); EXPECT_TRUE(context_->IsCurrent(surface_.get())); EXPECT_TRUE(surface_->SetDrawRectangle(gfx::Rect(0, 0, 50, 50))); EXPECT_TRUE(context_->IsCurrent(surface_.get())); @@ -198,8 +198,8 @@ scoped_refptr<GLContext> context2 = CreateGLContext(surface2.get()); surface2->SetEnableDCLayers(true); - EXPECT_TRUE(surface2->Resize(gfx::Size(100, 100), 1.0, - GLSurface::ColorSpace::UNSPECIFIED, true)); + EXPECT_TRUE( + surface2->Resize(gfx::Size(100, 100), 1.0, gfx::ColorSpace(), true)); // The previous IDCompositionSurface should be suspended when another // surface is being drawn to. EXPECT_TRUE(surface2->SetDrawRectangle(gfx::Rect(0, 0, 100, 100))); @@ -217,8 +217,8 @@ if (!surface_) return; surface_->SetEnableDCLayers(false); - EXPECT_TRUE(surface_->Resize(gfx::Size(100, 100), 1.0, - GLSurface::ColorSpace::UNSPECIFIED, true)); + EXPECT_TRUE( + surface_->Resize(gfx::Size(100, 100), 1.0, gfx::ColorSpace(), true)); EXPECT_FALSE(surface_->GetBackbufferSwapChainForTesting()); // First SetDrawRectangle must be full size of surface for DXGI swapchain. @@ -262,8 +262,8 @@ if (!surface_) return; surface_->SetEnableDCLayers(false); - EXPECT_TRUE(surface_->Resize(gfx::Size(100, 100), 1.0, - GLSurface::ColorSpace::UNSPECIFIED, true)); + EXPECT_TRUE( + surface_->Resize(gfx::Size(100, 100), 1.0, gfx::ColorSpace(), true)); EXPECT_FALSE(surface_->GetBackbufferSwapChainForTesting()); EXPECT_TRUE(surface_->SetDrawRectangle(gfx::Rect(0, 0, 100, 100))); @@ -275,12 +275,12 @@ EXPECT_EQ(DXGI_ALPHA_MODE_PREMULTIPLIED, desc.AlphaMode); // Resize to the same parameters should have no effect. - EXPECT_TRUE(surface_->Resize(gfx::Size(100, 100), 1.0, - GLSurface::ColorSpace::UNSPECIFIED, true)); + EXPECT_TRUE( + surface_->Resize(gfx::Size(100, 100), 1.0, gfx::ColorSpace(), true)); EXPECT_TRUE(surface_->GetBackbufferSwapChainForTesting()); - EXPECT_TRUE(surface_->Resize(gfx::Size(100, 100), 1.0, - GLSurface::ColorSpace::UNSPECIFIED, false)); + EXPECT_TRUE( + surface_->Resize(gfx::Size(100, 100), 1.0, gfx::ColorSpace(), false)); EXPECT_FALSE(surface_->GetBackbufferSwapChainForTesting()); EXPECT_TRUE(surface_->SetDrawRectangle(gfx::Rect(0, 0, 100, 100))); @@ -604,8 +604,7 @@ const gfx::Size& texture_size, const gfx::Rect& content_rect, const gfx::Rect& quad_rect) { - EXPECT_TRUE(surface_->Resize(window_size, 1.0, - GLSurface::ColorSpace::UNSPECIFIED, true)); + EXPECT_TRUE(surface_->Resize(window_size, 1.0, gfx::ColorSpace(), true)); EXPECT_TRUE(surface_->SetDrawRectangle(gfx::Rect(window_size))); glClearColor(0.0, 0.0, 0.0, 1.0); @@ -649,8 +648,7 @@ surface_->SetEnableDCLayers(false); gfx::Size window_size(100, 100); - EXPECT_TRUE(surface_->Resize(window_size, 1.0, - GLSurface::ColorSpace::UNSPECIFIED, true)); + EXPECT_TRUE(surface_->Resize(window_size, 1.0, gfx::ColorSpace(), true)); EXPECT_TRUE(surface_->SetDrawRectangle(gfx::Rect(window_size))); glClearColor(1.0, 0.0, 0.0, 1.0); @@ -703,8 +701,7 @@ return; gfx::Size window_size(100, 100); - EXPECT_TRUE(surface_->Resize(window_size, 1.0, - GLSurface::ColorSpace::UNSPECIFIED, true)); + EXPECT_TRUE(surface_->Resize(window_size, 1.0, gfx::ColorSpace(), true)); Microsoft::WRL::ComPtr<ID3D11Device> d3d11_device = QueryD3D11DeviceObjectFromANGLE(); @@ -777,8 +774,7 @@ return; gfx::Size window_size(100, 100); - EXPECT_TRUE(surface_->Resize(window_size, 1.0, - GLSurface::ColorSpace::UNSPECIFIED, true)); + EXPECT_TRUE(surface_->Resize(window_size, 1.0, gfx::ColorSpace(), true)); Microsoft::WRL::ComPtr<ID3D11Device> d3d11_device = QueryD3D11DeviceObjectFromANGLE(); @@ -864,8 +860,7 @@ DirectCompositionSurfaceWin::SetScaledOverlaysSupportedForTesting(true); gfx::Size window_size(100, 100); - EXPECT_TRUE(surface_->Resize(window_size, 1.0, - GLSurface::ColorSpace::UNSPECIFIED, true)); + EXPECT_TRUE(surface_->Resize(window_size, 1.0, gfx::ColorSpace(), true)); EXPECT_TRUE(surface_->SetDrawRectangle(gfx::Rect(window_size))); glClearColor(0.0, 0.0, 0.0, 1.0); @@ -1028,8 +1023,7 @@ DirectCompositionSurfaceWin::SetScaledOverlaysSupportedForTesting(true); gfx::Size window_size(100, 100); - EXPECT_TRUE(surface_->Resize(window_size, 1.0, - GLSurface::ColorSpace::UNSPECIFIED, true)); + EXPECT_TRUE(surface_->Resize(window_size, 1.0, gfx::ColorSpace(), true)); EXPECT_TRUE(surface_->SetDrawRectangle(gfx::Rect(window_size))); glClearColor(0.0, 0.0, 0.0, 1.0); @@ -1153,8 +1147,7 @@ ASSERT_TRUE(context); gfx::Size window_size(100, 100); - EXPECT_TRUE(surface_->Resize(window_size, 1.0, - GLSurface::ColorSpace::UNSPECIFIED, true)); + EXPECT_TRUE(surface_->Resize(window_size, 1.0, gfx::ColorSpace(), true)); EXPECT_TRUE(surface_->SetDrawRectangle(gfx::Rect(window_size))); glClearColor(0.0, 0.0, 0.0, 1.0);
diff --git a/ui/gl/gl_surface.cc b/ui/gl/gl_surface.cc index 2be035f..d5542b2 100644 --- a/ui/gl/gl_surface.cc +++ b/ui/gl/gl_surface.cc
@@ -39,7 +39,7 @@ bool GLSurface::Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) { NOTIMPLEMENTED(); return false; @@ -300,7 +300,7 @@ bool GLSurfaceAdapter::Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) { return surface_->Resize(size, scale_factor, color_space, has_alpha); }
diff --git a/ui/gl/gl_surface.h b/ui/gl/gl_surface.h index 3b0d26f..433b398 100644 --- a/ui/gl/gl_surface.h +++ b/ui/gl/gl_surface.h
@@ -26,14 +26,15 @@ #include "ui/gl/gl_surface_format.h" namespace gfx { +class ColorSpace; class GpuFence; class VSyncProvider; -} +} // namespace gfx namespace ui { struct CARendererLayerParams; struct DCRendererLayerParams; -} +} // namespace ui namespace gl { @@ -67,20 +68,11 @@ // opportunity for this cleanup. virtual void PrepareToDestroy(bool have_context); - // Color spaces that can be dynamically specified to the surface when resized. - enum class ColorSpace { - UNSPECIFIED, - SRGB, - DISPLAY_P3, - SCRGB_LINEAR, - HDR10, - }; - // Resizes the surface, returning success. If failed, it is possible that the // context is no longer current. virtual bool Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha); // Recreate the surface without changing the size, returning success. If @@ -341,7 +333,7 @@ void Destroy() override; bool Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) override; bool Recreate() override; bool DeferDraws() override;
diff --git a/ui/gl/gl_surface_egl.cc b/ui/gl/gl_surface_egl.cc index be0a7d3..8702d39 100644 --- a/ui/gl/gl_surface_egl.cc +++ b/ui/gl/gl_surface_egl.cc
@@ -1603,7 +1603,7 @@ bool NativeViewGLSurfaceEGL::Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) { if (size == GetSize()) return true; @@ -1998,7 +1998,7 @@ bool PbufferGLSurfaceEGL::Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) { if (size == size_) return true; @@ -2086,7 +2086,7 @@ bool SurfacelessEGL::Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) { size_ = size; return true;
diff --git a/ui/gl/gl_surface_egl.h b/ui/gl/gl_surface_egl.h index 9d8c119..8620e332 100644 --- a/ui/gl/gl_surface_egl.h +++ b/ui/gl/gl_surface_egl.h
@@ -124,7 +124,7 @@ void Destroy() override; bool Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) override; bool Recreate() override; bool IsOffscreen() override; @@ -236,7 +236,7 @@ gfx::Size GetSize() override; bool Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) override; EGLSurface GetHandle() override; void* GetShareHandle() override; @@ -267,7 +267,7 @@ gfx::Size GetSize() override; bool Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) override; EGLSurface GetHandle() override; void* GetShareHandle() override;
diff --git a/ui/gl/gl_surface_egl_surface_control.cc b/ui/gl/gl_surface_egl_surface_control.cc index bbbb965..cb3936d 100644 --- a/ui/gl/gl_surface_egl_surface_control.cc +++ b/ui/gl/gl_surface_egl_surface_control.cc
@@ -115,7 +115,7 @@ bool GLSurfaceEGLSurfaceControl::Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) { // TODO(khushalsagar): Update GLSurfaceFormat using the |color_space| above? // We don't do this for the NativeViewGLSurfaceEGL as well yet.
diff --git a/ui/gl/gl_surface_egl_surface_control.h b/ui/gl/gl_surface_egl_surface_control.h index 22275bd8..2d1541f4 100644 --- a/ui/gl/gl_surface_egl_surface_control.h +++ b/ui/gl/gl_surface_egl_surface_control.h
@@ -40,7 +40,7 @@ void Destroy() override; bool Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) override; bool IsOffscreen() override;
diff --git a/ui/gl/gl_surface_egl_unittest.cc b/ui/gl/gl_surface_egl_unittest.cc index cb7a861b..6346bf9 100644 --- a/ui/gl/gl_surface_egl_unittest.cc +++ b/ui/gl/gl_surface_egl_unittest.cc
@@ -100,7 +100,7 @@ EXPECT_TRUE(context->MakeCurrent(surface.get())); gfx::Size resize_size(200, 300); - surface->Resize(resize_size, 1.0, GLSurface::ColorSpace::UNSPECIFIED, false); + surface->Resize(resize_size, 1.0, gfx::ColorSpace(), false); EXPECT_EQ(resize_size, surface->GetSize()); }
diff --git a/ui/gl/gl_surface_egl_x11.cc b/ui/gl/gl_surface_egl_x11.cc index 4159844..028505b 100644 --- a/ui/gl/gl_surface_egl_x11.cc +++ b/ui/gl/gl_surface_egl_x11.cc
@@ -133,7 +133,7 @@ bool NativeViewGLSurfaceEGLX11::Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) { if (size == GetSize()) return true;
diff --git a/ui/gl/gl_surface_egl_x11.h b/ui/gl/gl_surface_egl_x11.h index 08365277..81f789c5 100644 --- a/ui/gl/gl_surface_egl_x11.h +++ b/ui/gl/gl_surface_egl_x11.h
@@ -25,7 +25,7 @@ void Destroy() override; bool Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) override; bool InitializeNativeWindow() override;
diff --git a/ui/gl/gl_surface_glx.cc b/ui/gl/gl_surface_glx.cc index 52261c1..7bdc0f81 100644 --- a/ui/gl/gl_surface_glx.cc +++ b/ui/gl/gl_surface_glx.cc
@@ -693,7 +693,7 @@ bool NativeViewGLSurfaceGLX::Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) { size_ = size; glXWaitGL();
diff --git a/ui/gl/gl_surface_glx.h b/ui/gl/gl_surface_glx.h index da295201..685b499 100644 --- a/ui/gl/gl_surface_glx.h +++ b/ui/gl/gl_surface_glx.h
@@ -75,7 +75,7 @@ void Destroy() override; bool Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) override; bool IsOffscreen() override; gfx::SwapResult SwapBuffers(PresentationCallback callback) override;
diff --git a/ui/gl/gl_surface_stub.cc b/ui/gl/gl_surface_stub.cc index 88f707f..59b750f 100644 --- a/ui/gl/gl_surface_stub.cc +++ b/ui/gl/gl_surface_stub.cc
@@ -17,7 +17,7 @@ bool GLSurfaceStub::Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) { return true; }
diff --git a/ui/gl/gl_surface_stub.h b/ui/gl/gl_surface_stub.h index 9da1890..e87cf66 100644 --- a/ui/gl/gl_surface_stub.h +++ b/ui/gl/gl_surface_stub.h
@@ -24,7 +24,7 @@ void Destroy() override; bool Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) override; bool IsOffscreen() override; gfx::SwapResult SwapBuffers(PresentationCallback callback) override;
diff --git a/ui/gl/gl_surface_wgl.cc b/ui/gl/gl_surface_wgl.cc index 884ea27..0bce93b5 100644 --- a/ui/gl/gl_surface_wgl.cc +++ b/ui/gl/gl_surface_wgl.cc
@@ -261,7 +261,7 @@ bool NativeViewGLSurfaceWGL::Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) { RECT rect; if (!GetClientRect(window_, &rect)) {
diff --git a/ui/gl/gl_surface_wgl.h b/ui/gl/gl_surface_wgl.h index ed3259a7..628b356a 100644 --- a/ui/gl/gl_surface_wgl.h +++ b/ui/gl/gl_surface_wgl.h
@@ -43,7 +43,7 @@ void Destroy() override; bool Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) override; bool Recreate() override; bool IsOffscreen() override;
diff --git a/ui/ozone/common/gl_surface_egl_readback.cc b/ui/ozone/common/gl_surface_egl_readback.cc index fd21b89..2774255f 100644 --- a/ui/ozone/common/gl_surface_egl_readback.cc +++ b/ui/ozone/common/gl_surface_egl_readback.cc
@@ -23,7 +23,7 @@ bool GLSurfaceEglReadback::Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) { pixels_.reset();
diff --git a/ui/ozone/common/gl_surface_egl_readback.h b/ui/ozone/common/gl_surface_egl_readback.h index c985eb52..4a21428e 100644 --- a/ui/ozone/common/gl_surface_egl_readback.h +++ b/ui/ozone/common/gl_surface_egl_readback.h
@@ -28,7 +28,7 @@ // GLSurface implementation. bool Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) override; bool IsOffscreen() override; gfx::SwapResult SwapBuffers(PresentationCallback callback) override;
diff --git a/ui/ozone/demo/gl_renderer.cc b/ui/ozone/demo/gl_renderer.cc index 35a51c5..8c266b6 100644 --- a/ui/ozone/demo/gl_renderer.cc +++ b/ui/ozone/demo/gl_renderer.cc
@@ -38,7 +38,7 @@ return false; } - gl_surface_->Resize(size_, 1.f, gl::GLSurface::ColorSpace::UNSPECIFIED, true); + gl_surface_->Resize(size_, 1.f, gfx::ColorSpace(), true); if (!context_->MakeCurrent(gl_surface_.get())) { LOG(ERROR) << "Failed to make GL context current";
diff --git a/ui/ozone/demo/skia/skia_gl_renderer.cc b/ui/ozone/demo/skia/skia_gl_renderer.cc index 6d2dd5d..11e39bcf 100644 --- a/ui/ozone/demo/skia/skia_gl_renderer.cc +++ b/ui/ozone/demo/skia/skia_gl_renderer.cc
@@ -64,7 +64,7 @@ return false; } - gl_surface_->Resize(size_, 1.f, gl::GLSurface::ColorSpace::UNSPECIFIED, true); + gl_surface_->Resize(size_, 1.f, gfx::ColorSpace(), true); if (!gl_context_->MakeCurrent(gl_surface_.get())) { LOG(FATAL) << "Failed to make GL context current";
diff --git a/ui/ozone/demo/surfaceless_gl_renderer.cc b/ui/ozone/demo/surfaceless_gl_renderer.cc index bda8d210..6117ac4 100644 --- a/ui/ozone/demo/surfaceless_gl_renderer.cc +++ b/ui/ozone/demo/surfaceless_gl_renderer.cc
@@ -151,7 +151,7 @@ return false; } - gl_surface_->Resize(size_, 1.f, gl::GLSurface::ColorSpace::UNSPECIFIED, true); + gl_surface_->Resize(size_, 1.f, gfx::ColorSpace(), true); if (!context_->MakeCurrent(gl_surface_.get())) { LOG(ERROR) << "Failed to make GL context current";
diff --git a/ui/ozone/platform/cast/gl_surface_cast.cc b/ui/ozone/platform/cast/gl_surface_cast.cc index d76bfac..9d62e73 100644 --- a/ui/ozone/platform/cast/gl_surface_cast.cc +++ b/ui/ozone/platform/cast/gl_surface_cast.cc
@@ -83,7 +83,7 @@ bool GLSurfaceCast::Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) { return parent_->ResizeDisplay(size) && NativeViewGLSurfaceEGL::Resize(size, scale_factor, color_space,
diff --git a/ui/ozone/platform/cast/gl_surface_cast.h b/ui/ozone/platform/cast/gl_surface_cast.h index e294802..30f19d5 100644 --- a/ui/ozone/platform/cast/gl_surface_cast.h +++ b/ui/ozone/platform/cast/gl_surface_cast.h
@@ -30,7 +30,7 @@ PresentationCallback callback) override; bool Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) override; bool ScheduleOverlayPlane(int z_order, gfx::OverlayTransform transform,
diff --git a/ui/ozone/platform/wayland/gpu/gl_surface_wayland.cc b/ui/ozone/platform/wayland/gpu/gl_surface_wayland.cc index 22d06a8..02ec5b80 100644 --- a/ui/ozone/platform/wayland/gpu/gl_surface_wayland.cc +++ b/ui/ozone/platform/wayland/gpu/gl_surface_wayland.cc
@@ -35,7 +35,7 @@ bool GLSurfaceWayland::Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) { if (size_ == size) return true;
diff --git a/ui/ozone/platform/wayland/gpu/gl_surface_wayland.h b/ui/ozone/platform/wayland/gpu/gl_surface_wayland.h index 4b9b15e..87a7da0d 100644 --- a/ui/ozone/platform/wayland/gpu/gl_surface_wayland.h +++ b/ui/ozone/platform/wayland/gpu/gl_surface_wayland.h
@@ -34,7 +34,7 @@ // gl::GLSurface: bool Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) override; EGLConfig GetConfig() override;
diff --git a/ui/ozone/platform/x11/gl_surface_egl_ozone_x11.cc b/ui/ozone/platform/x11/gl_surface_egl_ozone_x11.cc index b33cfb1..71d50ff 100644 --- a/ui/ozone/platform/x11/gl_surface_egl_ozone_x11.cc +++ b/ui/ozone/platform/x11/gl_surface_egl_ozone_x11.cc
@@ -79,7 +79,7 @@ bool GLSurfaceEGLOzoneX11::Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) { if (size == GetSize()) return true;
diff --git a/ui/ozone/platform/x11/gl_surface_egl_ozone_x11.h b/ui/ozone/platform/x11/gl_surface_egl_ozone_x11.h index dcb4190..eab987a 100644 --- a/ui/ozone/platform/x11/gl_surface_egl_ozone_x11.h +++ b/ui/ozone/platform/x11/gl_surface_egl_ozone_x11.h
@@ -21,7 +21,7 @@ EGLConfig GetConfig() override; bool Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) override; private:
diff --git a/ui/ozone/platform/x11/gl_surface_egl_readback_x11.cc b/ui/ozone/platform/x11/gl_surface_egl_readback_x11.cc index 3a38c4d..1806337 100644 --- a/ui/ozone/platform/x11/gl_surface_egl_readback_x11.cc +++ b/ui/ozone/platform/x11/gl_surface_egl_readback_x11.cc
@@ -52,7 +52,7 @@ bool GLSurfaceEglReadbackX11::Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) { if (!GLSurfaceEglReadback::Resize(size, scale_factor, color_space, has_alpha)) {
diff --git a/ui/ozone/platform/x11/gl_surface_egl_readback_x11.h b/ui/ozone/platform/x11/gl_surface_egl_readback_x11.h index 7bd5662c..ed56bca 100644 --- a/ui/ozone/platform/x11/gl_surface_egl_readback_x11.h +++ b/ui/ozone/platform/x11/gl_surface_egl_readback_x11.h
@@ -20,7 +20,7 @@ void Destroy() override; bool Resize(const gfx::Size& size, float scale_factor, - ColorSpace color_space, + const gfx::ColorSpace& color_space, bool has_alpha) override; private:
diff --git a/ui/views/controls/link.cc b/ui/views/controls/link.cc index b0fe4fc..18fead30 100644 --- a/ui/views/controls/link.cc +++ b/ui/views/controls/link.cc
@@ -14,7 +14,6 @@ #include "ui/events/event.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/gfx/canvas.h" -#include "ui/gfx/color_palette.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/font_list.h" #include "ui/native_theme/native_theme.h" @@ -28,25 +27,23 @@ constexpr gfx::Insets Link::kFocusBorderPadding; Link::Link(const base::string16& title, int text_context, int text_style) - : Label(title, text_context, text_style), - requested_enabled_color_(gfx::kPlaceholderColor), - requested_enabled_color_set_(false) { - Init(); + : Label(title, text_context, text_style) { + RecalculateFont(); + + enabled_changed_subscription_ = AddEnabledChangedCallback( + base::BindRepeating(&Link::RecalculateFont, base::Unretained(this))); + + // Label() indirectly calls SetText(), but at that point our virtual override + // will not be reached. Call it explicitly here to configure focus. + SetText(GetText()); } Link::~Link() = default; -// static -Link::FocusStyle Link::GetDefaultFocusStyle() { - return FocusStyle::kUnderline; -} - Link::FocusStyle Link::GetFocusStyle() const { - // Use the default, unless the link would "always" be underlined. - if (underline_ && GetDefaultFocusStyle() == FocusStyle::kUnderline) - return FocusStyle::kRing; - - return GetDefaultFocusStyle(); + // Use an underline to indicate focus unless the link is always drawn with an + // underline. + return underline_ ? FocusStyle::kRing : FocusStyle::kUnderline; } SkColor Link::GetColor() const { @@ -56,8 +53,8 @@ if (!GetEnabled()) return theme->GetSystemColor(ui::NativeTheme::kColorId_LinkDisabled); - if (requested_enabled_color_set_) - return requested_enabled_color_; + if (requested_enabled_color_.has_value()) + return requested_enabled_color_.value(); return GetNativeTheme()->GetSystemColor( pressed_ ? ui::NativeTheme::kColorId_LinkPressed @@ -210,7 +207,6 @@ } void Link::SetEnabledColor(SkColor color) { - requested_enabled_color_set_ = true; requested_enabled_color_ = color; Label::SetEnabledColor(GetColor()); } @@ -231,22 +227,6 @@ OnPropertyChanged(&underline_, kPropertyEffectsPreferredSizeChanged); } -void Link::Init() { - listener_ = nullptr; - pressed_ = false; - underline_ = GetDefaultFocusStyle() != FocusStyle::kUnderline; - RecalculateFont(); - - enabled_changed_subscription_ = AddEnabledChangedCallback( - base::BindRepeating(&Link::RecalculateFont, base::Unretained(this))); - - // Label::Init() calls SetText(), but if that's being called from Label(), our - // SetText() override will not be reached (because the constructed class is - // only a Label at the moment, not yet a Link). So explicitly configure focus - // here. - ConfigureFocus(); -} - void Link::SetPressed(bool pressed) { if (pressed_ != pressed) { pressed_ = pressed;
diff --git a/ui/views/controls/link.h b/ui/views/controls/link.h index b913db5..64d1e81 100644 --- a/ui/views/controls/link.h +++ b/ui/views/controls/link.h
@@ -8,7 +8,9 @@ #include <string> #include "base/macros.h" +#include "base/optional.h" #include "third_party/skia/include/core/SkColor.h" +#include "ui/gfx/color_palette.h" #include "ui/views/controls/label.h" #include "ui/views/style/typography.h" @@ -43,10 +45,6 @@ int text_style = style::STYLE_LINK); ~Link() override; - // Returns the default FocusStyle for a views::Link. Calling SetUnderline() - // may change it: E.g. SetUnderline(true) forces FocusStyle::kRing. - static FocusStyle GetDefaultFocusStyle(); - // Returns the current FocusStyle of this Link. FocusStyle GetFocusStyle() const; @@ -84,25 +82,22 @@ void SetUnderline(bool underline); private: - void Init(); - void SetPressed(bool pressed); void RecalculateFont(); void ConfigureFocus(); - LinkListener* listener_; + LinkListener* listener_ = nullptr; // Whether the link should be underlined when enabled. - bool underline_; + bool underline_ = false; // Whether the link is currently pressed. - bool pressed_; + bool pressed_ = false; // The color when the link is neither pressed nor disabled. - SkColor requested_enabled_color_; - bool requested_enabled_color_set_; + base::Optional<SkColor> requested_enabled_color_; PropertyChangedSubscription enabled_changed_subscription_;
diff --git a/ui/views/controls/message_box_view.cc b/ui/views/controls/message_box_view.cc index a2f3151..653685234 100644 --- a/ui/views/controls/message_box_view.cc +++ b/ui/views/controls/message_box_view.cc
@@ -119,25 +119,15 @@ void MessageBoxView::SetLink(const base::string16& text, LinkListener* listener) { - size_t child_count = children().size(); - if (text.empty()) { - DCHECK(!listener); - delete link_; - link_ = nullptr; - } else { - DCHECK(listener); - if (!link_) { - // See the comment above in SetCheckBoxLabel(); - SetLayoutManager(nullptr); - link_ = AddChildView(std::make_unique<Link>(text)); - link_->SetHorizontalAlignment(gfx::ALIGN_LEFT); - } else { - link_->SetText(text); - } - link_->set_listener(listener); - } - if (child_count != children().size()) - ResetLayoutManager(); + DCHECK(!text.empty()); + DCHECK(listener); + DCHECK(!link_); + // See the comment in SetCheckBoxLabel(); + SetLayoutManager(nullptr); + link_ = AddChildView(std::make_unique<Link>(text)); + link_->SetHorizontalAlignment(gfx::ALIGN_LEFT); + link_->set_listener(listener); + ResetLayoutManager(); } void MessageBoxView::GetAccessibleNodeData(ui::AXNodeData* node_data) {
diff --git a/ui/webui/resources/cr_components/chromeos/network/network_proxy.html b/ui/webui/resources/cr_components/chromeos/network/network_proxy.html index 1814ae1..213bf6b 100644 --- a/ui/webui/resources/cr_components/chromeos/network/network_proxy.html +++ b/ui/webui/resources/cr_components/chromeos/network/network_proxy.html
@@ -111,13 +111,6 @@ </network-proxy-input> <network-proxy-input on-proxy-input-change="onProxyInputChange_" - editable="[[isEditable_('manual.ftpProxy.host', managedProperties, - editable, useSharedProxies)]]" - value="{{proxy_.manual.ftpProxy}}" - label="[[i18n('networkProxyFtp')]]"> - </network-proxy-input> - <network-proxy-input - on-proxy-input-change="onProxyInputChange_" editable="[[isEditable_('manual.socks.host', managedProperties, editable, useSharedProxies)]]" value="{{proxy_.manual.socks}}"
diff --git a/ui/webui/resources/cr_components/chromeos/network/network_proxy.js b/ui/webui/resources/cr_components/chromeos/network/network_proxy.js index bf64dc09..f212e03 100644 --- a/ui/webui/resources/cr_components/chromeos/network/network_proxy.js +++ b/ui/webui/resources/cr_components/chromeos/network/network_proxy.js
@@ -180,9 +180,6 @@ if (!proxy.manual.secureHttpProxy) { proxy.manual.secureHttpProxy = this.createDefaultProxyLocation_(80); } - if (!proxy.manual.ftpProxy) { - proxy.manual.ftpProxy = this.createDefaultProxyLocation_(80); - } if (!proxy.manual.socks) { proxy.manual.socks = this.createDefaultProxyLocation_(1080); } @@ -236,13 +233,12 @@ const manual = proxy.manual; const httpProxy = manual.httpProxy; if (this.proxyMatches_(httpProxy, manual.secureHttpProxy) && - this.proxyMatches_(httpProxy, manual.ftpProxy) && this.proxyMatches_(httpProxy, manual.socks)) { // If all four proxies match, enable the 'use same proxy' toggle. this.useSameProxy_ = true; } else if ( !manual.secureHttpProxy.host.activeValue && - !manual.ftpProxy.host.activeValue && !manual.socks.host.activeValue) { + !manual.socks.host.activeValue) { // Otherwise if no proxies other than http have a host value, also // enable the 'use same proxy' toggle. this.useSameProxy_ = true; @@ -308,7 +304,6 @@ httpProxy: this.getProxyLocation_(this.proxy_.manual.httpProxy), secureHttpProxy: this.getProxyLocation_(this.proxy_.manual.secureHttpProxy), - ftpProxy: this.getProxyLocation_(this.proxy_.manual.ftpProxy), socks: this.getProxyLocation_(this.proxy_.manual.socks), }; } @@ -321,8 +316,6 @@ if (this.useSameProxy_) { manual.secureHttpProxy = /** @type {!mojom.ProxyLocation} */ ( Object.assign({}, defaultProxy)); - manual.ftpProxy = /** @type {!mojom.ProxyLocation} */ ( - Object.assign({}, defaultProxy)); manual.socks = /** @type {!mojom.ProxyLocation} */ ( Object.assign({}, defaultProxy)); } else { @@ -333,9 +326,6 @@ if (manual.secureHttpProxy && !manual.secureHttpProxy.host) { delete manual.secureHttpProxy; } - if (manual.ftpProxy && !manual.ftpProxy.host) { - delete manual.ftpProxy; - } if (manual.socks && !manual.socks.host) { delete manual.socks; } @@ -520,7 +510,6 @@ } return !!httpHost || !!this.get('secureHttpProxy.host.activeValue', manual) || - !!this.get('ftpProxy.host.activeValue', manual) || !!this.get('socks.host.activeValue', manual); },
diff --git a/ui/webui/resources/js/BUILD.gn b/ui/webui/resources/js/BUILD.gn index 4099959..5e7f7b64 100644 --- a/ui/webui/resources/js/BUILD.gn +++ b/ui/webui/resources/js/BUILD.gn
@@ -153,6 +153,7 @@ "web_ui_listener_behavior.js", ] namespace_rewrites = [ + "cr.search_highlight_utils.Range|Range", "cr.ui.KeyboardShortcutList|KeyboardShortcutList", "Polymer.ArraySplice.calculateSplices|calculateSplices", ]
diff --git a/ui/webui/resources/js/search_highlight_utils.js b/ui/webui/resources/js/search_highlight_utils.js index 1910528..6169350 100644 --- a/ui/webui/resources/js/search_highlight_utils.js +++ b/ui/webui/resources/js/search_highlight_utils.js
@@ -17,6 +17,9 @@ /** @type {string} */ const SEARCH_BUBBLE_CSS_CLASS = 'search-bubble'; + /** @typedef {{start: number, length: number}} */ + /* #export */ let Range; + /** * Replaces the the highlight wrappers given in |wrappers| with the original * search nodes. @@ -52,14 +55,12 @@ * Applies the highlight UI (yellow rectangle) around all matches in |node|. * @param {!Node} node The text node to be highlighted. |node| ends up * being hidden. - * @param {!Array<string>} tokens The string tokens after splitting on the - * relevant regExp. Even indices hold text that doesn't need highlighting, - * odd indices hold the text to be highlighted. For example: - * const r = new RegExp('(foo)', 'i'); - * 'barfoobar foo bar'.split(r) => ['bar', 'foo', 'bar ', 'foo', ' bar'] + * @param {!Array<!cr.search_highlight_utils.Range>} ranges * @return {!Node} The new highlight wrapper. */ - /* #export */ function highlight(node, tokens) { + /* #export */ function highlight(node, ranges) { + assert(ranges.length > 0); + const wrapper = document.createElement('span'); wrapper.classList.add(WRAPPER_CSS_CLASS); // Use existing node as placeholder to determine where to insert the @@ -75,6 +76,19 @@ span.appendChild(node); wrapper.appendChild(span); + const text = node.textContent; + /** @type {!Array<string>} */ const tokens = []; + for (let i = 0; i < ranges.length; ++i) { + const range = ranges[i]; + const prev = ranges[i - 1] || {start: 0, length: 0}; + const start = prev.start + prev.length; + const length = range.start - start; + tokens.push(text.substr(start, length)); + tokens.push(text.substr(range.start, range.length)); + } + const last = ranges.slice(-1)[0]; + tokens.push(text.substr(last.start + last.length)); + for (let i = 0; i < tokens.length; ++i) { if (i % 2 == 0) { wrapper.appendChild(document.createTextNode(tokens[i])); @@ -91,53 +105,47 @@ } /** - * Highlights an HTML element by displaying a search bubble. The element - * should already be visible or the bubble will render incorrectly. - * @param {!HTMLElement} element The element to be highlighted. - * @param {string} rawQuery The search query. + * Creates an empty search bubble (styled HTML element without text). + * |node| should already be visible or the bubble will render incorrectly. + * @param {!Node} node The node to be highlighted. * @param {boolean=} horizontallyCenter Whether or not to horizontally center - * the shown search bubble (if any) based on |element|'s left and width. - * @return {?Node} The search bubble that was added, or null if no new bubble + * the shown search bubble (if any) based on |node|'s left and width. + * @return {!Node} The search bubble that was added, or null if no new bubble * was added. */ - /* #export */ function highlightControlWithBubble( - element, rawQuery, horizontallyCenter) { - let anchor = element; - if (element.tagName === 'SELECT') { - anchor = element.parentNode; + /* #export */ function createEmptySearchBubble(node, horizontallyCenter) { + let anchor = node; + if (node.nodeName === 'SELECT') { + anchor = node.parentNode; } - // NOTE(dbeam): this is theoretically only possible in the select case, but - // callers are often fast and loose with regard to casting |element| from a - // parentNode (which can easily be a shadow root). So we leave this if for - // all branches (rather than solely inside the select branch). if (anchor instanceof ShadowRoot) { anchor = anchor.host.parentNode; } let searchBubble = anchor.querySelector(`.${SEARCH_BUBBLE_CSS_CLASS}`); - // If the element has already been highlighted, there is no need to do + // If the node has already been highlighted, there is no need to do // anything. if (searchBubble) { - return null; + return searchBubble; } searchBubble = document.createElement('div'); searchBubble.classList.add(SEARCH_BUBBLE_CSS_CLASS); const innards = document.createElement('div'); innards.classList.add('search-bubble-innards'); - innards.textContent = rawQuery; + innards.textContent = '\u00a0'; // Non-breaking space for offsetHeight. searchBubble.appendChild(innards); anchor.appendChild(searchBubble); const updatePosition = function() { - assert(typeof element.offsetTop === 'number'); - searchBubble.style.top = element.offsetTop + + assert(typeof node.offsetTop === 'number'); + searchBubble.style.top = node.offsetTop + (innards.classList.contains('above') ? -searchBubble.offsetHeight : - element.offsetHeight) + + node.offsetHeight) + 'px'; if (horizontallyCenter) { - const width = element.offsetWidth - searchBubble.offsetWidth; - searchBubble.style.left = element.offsetLeft + width / 2 + 'px'; + const width = node.offsetWidth - searchBubble.offsetWidth; + searchBubble.style.left = node.offsetLeft + width / 2 + 'px'; } }; updatePosition(); @@ -152,11 +160,21 @@ return searchBubble; } + /** + * @param {string} text + * @return {string} + */ + /* #export */ function stripDiacritics(text) { + return text.normalize('NFD').replace(/[\u0300-\u036f]/g, ''); + } + // #cr_define_end return { - removeHighlights: removeHighlights, - findAndRemoveHighlights: findAndRemoveHighlights, - highlight: highlight, - highlightControlWithBubble: highlightControlWithBubble, + Range, + createEmptySearchBubble, + findAndRemoveHighlights, + highlight, + removeHighlights, + stripDiacritics, }; });