code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/examples_color_mixer.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/color/color_mixer.h" #include "ui/color/color_recipe.h" #include "ui/color/color_transform.h" #include "ui/gfx/color_palette.h" #include "ui/views/examples/examples_color_id.h" namespace views::examples { void AddExamplesColorMixers(ui::ColorProvider* color_provider, const ui::ColorProviderManager::Key& key) { const bool dark_mode = key.color_mode == ui::ColorProviderManager::ColorMode::kDark; using Ids = ExamplesColorIds; ui::ColorMixer& mixer = color_provider->AddMixer(); mixer[Ids::kColorAnimatedImageViewExampleBorder] = {SK_ColorBLACK}; mixer[Ids::kColorAnimationExampleForeground] = {SK_ColorBLACK}; mixer[Ids::kColorAnimationExampleBackground] = {SK_ColorWHITE}; mixer[Ids::kColorAccessibilityExampleBackground] = {SK_ColorWHITE}; mixer[Ids::kColorBubbleExampleBackground1] = {SK_ColorWHITE}; mixer[Ids::kColorBubbleExampleBackground2] = {SK_ColorGRAY}; mixer[Ids::kColorBubbleExampleBackground3] = {SK_ColorCYAN}; mixer[Ids::kColorBubbleExampleBackground4] = { SkColorSetRGB(0xC1, 0xB1, 0xE1)}; mixer[Ids::kColorDesignerGrabHandle] = {gfx::kGoogleGrey500}; mixer[Ids::kColorDesignerGrid] = {SK_ColorBLACK}; mixer[Ids::kColorFadeAnimationExampleBorder] = {gfx::kGoogleGrey900}; mixer[Ids::kColorFadeAnimationExampleBackground] = {SK_ColorWHITE}; mixer[Ids::kColorFadeAnimationExampleForeground] = {gfx::kGoogleBlue800}; mixer[Ids::kColorInkDropExampleBase] = {SK_ColorBLACK}; mixer[Ids::kColorInkDropExampleBorder] = {SK_ColorBLACK}; mixer[Ids::kColorLabelExampleBlueLabel] = {SK_ColorBLUE}; mixer[Ids::kColorLabelExampleBorder] = {SK_ColorGRAY}; mixer[Ids::kColorLabelExampleThickBorder] = {SK_ColorRED}; mixer[Ids::kColorLabelExampleLowerShadow] = {SK_ColorGRAY}; mixer[Ids::kColorLabelExampleUpperShadow] = {SK_ColorRED}; mixer[Ids::kColorLabelExampleCustomBackground] = {SK_ColorLTGRAY}; mixer[Ids::kColorLabelExampleCustomBorder] = {SK_ColorGRAY}; mixer[Ids::kColorMenuButtonExampleBorder] = {SK_ColorGRAY}; mixer[Ids::kColorMultilineExampleBorder] = {SK_ColorGRAY}; mixer[Ids::kColorMultilineExampleColorRange] = {SK_ColorRED}; mixer[Ids::kColorMultilineExampleForeground] = {SK_ColorBLACK}; mixer[Ids::kColorMultilineExampleLabelBorder] = {SK_ColorCYAN}; mixer[Ids::kColorMultilineExampleSelectionBackground] = {SK_ColorGRAY}; mixer[Ids::kColorMultilineExampleSelectionForeground] = {SK_ColorBLACK}; mixer[Ids::kColorNotificationExampleImage] = {SK_ColorGREEN}; mixer[Ids::kColorScrollViewExampleBigSquareFrom] = {SK_ColorRED}; mixer[Ids::kColorScrollViewExampleBigSquareTo] = {SK_ColorGREEN}; mixer[Ids::kColorScrollViewExampleSmallSquareFrom] = {SK_ColorYELLOW}; mixer[Ids::kColorScrollViewExampleSmallSquareTo] = {SK_ColorGREEN}; mixer[Ids::kColorScrollViewExampleTallFrom] = {SK_ColorRED}; mixer[Ids::kColorScrollViewExampleTallTo] = {SK_ColorCYAN}; mixer[Ids::kColorScrollViewExampleWideFrom] = {SK_ColorYELLOW}; mixer[Ids::kColorScrollViewExampleWideTo] = {SK_ColorCYAN}; mixer[Ids::kColorTableExampleEvenRowIcon] = {SK_ColorRED}; mixer[Ids::kColorTableExampleOddRowIcon] = {SK_ColorBLUE}; mixer[Ids::kColorTextfieldExampleBigRange] = {SK_ColorBLUE}; mixer[Ids::kColorTextfieldExampleName] = {SK_ColorGREEN}; mixer[Ids::kColorTextfieldExampleSmallRange] = {SK_ColorRED}; mixer[Ids::kColorVectorExampleImageBorder] = {SK_ColorBLACK}; mixer[Ids::kColorWidgetExampleContentBorder] = {SK_ColorGRAY}; mixer[Ids::kColorWidgetExampleDialogBorder] = {SK_ColorGRAY}; mixer[Ids::kColorButtonBackgroundFab] = {dark_mode ? ui::kColorRefSecondary30 : ui::kColorRefPrimary90}; } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/examples_color_mixer.cc
C++
unknown
3,980
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_EXAMPLES_COLOR_MIXER_H_ #define UI_VIEWS_EXAMPLES_EXAMPLES_COLOR_MIXER_H_ #include "ui/color/color_provider.h" #include "ui/color/color_provider_manager.h" #include "ui/views/examples/views_examples_export.h" namespace views::examples { VIEWS_EXAMPLES_EXPORT void AddExamplesColorMixers( ui::ColorProvider* color_provider, const ui::ColorProviderManager::Key& key); } // namespace views::examples #endif // UI_VIEWS_EXAMPLES_EXAMPLES_COLOR_MIXER_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/examples_color_mixer.h
C++
unknown
634
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_EXAMPLES_EXIT_CODE_H_ #define UI_VIEWS_EXAMPLES_EXAMPLES_EXIT_CODE_H_ namespace views::examples { enum class ExamplesExitCode { // Comparison succeeded. kSucceeded = 0, // Screenshot image empty. kImageEmpty, // Comparison failed. kFailed, // No comparison attempted. kNone, }; } // namespace views::examples #endif // UI_VIEWS_EXAMPLES_EXAMPLES_EXIT_CODE_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/examples_exit_code.h
C++
unknown
551
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/at_exit.h" #include "base/command_line.h" #include "base/test/test_timeouts.h" #include "ui/views/examples/examples_main_proc.h" int main(int argc, char** argv) { base::CommandLine::Init(argc, argv); // The use of base::test::TaskEnvironment in the following function relies on // the timeout values from TestTimeouts. TestTimeouts::Initialize(); base::AtExitManager at_exit; return static_cast<int>(views::examples::ExamplesMainProc()); }
Zhao-PengFei35/chromium_src_4
ui/views/examples/examples_main.cc
C++
unknown
615
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/examples_main_proc.h" #include <memory> #include <string> #include "base/base_switches.h" #include "base/command_line.h" #include "base/feature_list.h" #include "base/files/file_path.h" #include "base/functional/bind.h" #include "base/i18n/icu_util.h" #include "base/lazy_instance.h" #include "base/memory/ptr_util.h" #include "base/path_service.h" #include "base/power_monitor/power_monitor.h" #include "base/power_monitor/power_monitor_device_source.h" #include "base/run_loop.h" #include "base/test/scoped_run_loop_timeout.h" #include "base/test/task_environment.h" #include "base/test/test_discardable_memory_allocator.h" #include "base/test/test_timeouts.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "components/viz/host/host_frame_sink_manager.h" #include "components/viz/service/display_embedder/server_shared_bitmap_manager.h" #include "components/viz/service/frame_sinks/frame_sink_manager_impl.h" #include "mojo/core/embedder/embedder.h" #include "ui/base/ime/init/input_method_initializer.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/ui_base_paths.h" #include "ui/color/color_provider_manager.h" #include "ui/compositor/compositor_switches.h" #include "ui/compositor/test/in_process_context_factory.h" #include "ui/compositor/test/test_context_factories.h" #include "ui/display/screen.h" #include "ui/gfx/font_util.h" #include "ui/gfx/image/image.h" #include "ui/gl/gl_utils.h" #include "ui/gl/init/gl_factory.h" #include "ui/views/buildflags.h" #include "ui/views/examples/example_base.h" #include "ui/views/examples/examples_color_mixer.h" #include "ui/views/examples/examples_window.h" #include "ui/views/test/desktop_test_views_delegate.h" #include "ui/views/widget/any_widget_observer.h" #include "ui/views/widget/widget.h" #if defined(USE_AURA) #include "ui/aura/env.h" #include "ui/wm/core/wm_state.h" #endif #if BUILDFLAG(IS_CHROMEOS_ASH) #include "ui/views/examples/examples_views_delegate_chromeos.h" #endif #if BUILDFLAG(ENABLE_DESKTOP_AURA) #include "ui/views/widget/desktop_aura/desktop_screen.h" #endif #if BUILDFLAG(IS_WIN) #include "ui/base/win/scoped_ole_initializer.h" #include "ui/views/examples/examples_skia_gold_pixel_diff.h" #endif #if BUILDFLAG(IS_OZONE) #include "ui/ozone/public/ozone_platform.h" #endif namespace views::examples { base::LazyInstance<base::TestDiscardableMemoryAllocator>::DestructorAtExit g_discardable_memory_allocator = LAZY_INSTANCE_INITIALIZER; ExamplesExitCode ExamplesMainProc(bool under_test) { #if BUILDFLAG(IS_WIN) ui::ScopedOleInitializer ole_initializer; #endif base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (CheckCommandLineUsage()) return ExamplesExitCode::kSucceeded; // Disabling Direct Composition works around the limitation that // InProcessContextFactory doesn't work with Direct Composition, causing the // window to not render. See http://crbug.com/936249. gl::SetGlWorkarounds(gl::GlWorkarounds{.disable_direct_composition = true}); base::FeatureList::InitializeInstance( command_line->GetSwitchValueASCII(switches::kEnableFeatures), command_line->GetSwitchValueASCII(switches::kDisableFeatures)); if (under_test) command_line->AppendSwitch(switches::kEnablePixelOutputInTests); mojo::core::Init(); #if BUILDFLAG(IS_OZONE) ui::OzonePlatform::InitParams params; params.single_process = true; ui::OzonePlatform::InitializeForGPU(params); #endif gl::init::InitializeGLOneOff(/*gpu_preference=*/gl::GpuPreference::kDefault); // Viz depends on the task environment to correctly tear down. base::test::TaskEnvironment task_environment( base::test::TaskEnvironment::MainThreadType::UI); // The ContextFactory must exist before any Compositors are created. auto context_factories = std::make_unique<ui::TestContextFactories>(under_test, /*output_to_window=*/true); base::i18n::InitializeICU(); ui::RegisterPathProvider(); base::FilePath ui_test_pak_path; CHECK(base::PathService::Get(ui::UI_TEST_PAK, &ui_test_pak_path)); ui::ResourceBundle::InitSharedInstanceWithPakPath(ui_test_pak_path); base::FilePath views_examples_resources_pak_path; CHECK(base::PathService::Get(base::DIR_ASSETS, &views_examples_resources_pak_path)); ui::ResourceBundle::GetSharedInstance().AddDataPackFromPath( views_examples_resources_pak_path.AppendASCII( "views_examples_resources.pak"), ui::k100Percent); base::DiscardableMemoryAllocator::SetInstance( g_discardable_memory_allocator.Pointer()); gfx::InitializeFonts(); ui::ColorProviderManager::Get().AppendColorProviderInitializer( base::BindRepeating(&AddExamplesColorMixers)); #if defined(USE_AURA) std::unique_ptr<aura::Env> env = aura::Env::CreateInstance(); aura::Env::GetInstance()->set_context_factory( context_factories->GetContextFactory()); #endif ui::InitializeInputMethodForTesting(); ExamplesExitCode compare_result = ExamplesExitCode::kSucceeded; { #if BUILDFLAG(IS_CHROMEOS_ASH) ExamplesViewsDelegateChromeOS views_delegate; #else views::DesktopTestViewsDelegate views_delegate; #if defined(USE_AURA) wm::WMState wm_state; #endif #endif #if BUILDFLAG(ENABLE_DESKTOP_AURA) std::unique_ptr<display::Screen> desktop_screen = views::CreateDesktopScreen(); #endif base::RunLoop run_loop(base::RunLoop::Type::kNestableTasksAllowed); #if BUILDFLAG(IS_WIN) ExamplesSkiaGoldPixelDiff pixel_diff; views::AnyWidgetObserver widget_observer{ views::test::AnyWidgetTestPasskey()}; // If this app isn't a test, it shouldn't timeout. auto disable_timeout = std::make_unique<base::test::ScopedDisableRunLoopTimeout>(); if (under_test) { pixel_diff.Init("ViewsExamples"); widget_observer.set_shown_callback( base::BindRepeating(&ExamplesSkiaGoldPixelDiff::OnExamplesWindowShown, base::Unretained(&pixel_diff))); // Enable the timeout since we're not running in a test. disable_timeout.reset(); } #else base::test::ScopedDisableRunLoopTimeout disable_timeout; #endif views::examples::ShowExamplesWindow(run_loop.QuitClosure()); run_loop.Run(); #if BUILDFLAG(IS_WIN) compare_result = pixel_diff.get_result(); #endif ui::ResourceBundle::CleanupSharedInstance(); } ui::ShutdownInputMethod(); #if defined(USE_AURA) env.reset(); #endif return compare_result; } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/examples_main_proc.cc
C++
unknown
6,773
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_EXAMPLES_MAIN_PROC_H_ #define UI_VIEWS_EXAMPLES_EXAMPLES_MAIN_PROC_H_ #include "ui/views/examples/examples_exit_code.h" namespace views::examples { ExamplesExitCode ExamplesMainProc(bool under_test = false); } // namespace views::examples #endif // UI_VIEWS_EXAMPLES_EXAMPLES_MAIN_PROC_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/examples_main_proc.h
C++
unknown
466
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/examples_skia_gold_pixel_diff.h" #include <utility> #include "base/run_loop.h" #include "ui/snapshot/snapshot.h" #include "ui/views/examples/examples_window.h" #if defined(USE_AURA) #include "ui/snapshot/snapshot_aura.h" #endif namespace views::examples { ExamplesSkiaGoldPixelDiff::ExamplesSkiaGoldPixelDiff() = default; ExamplesSkiaGoldPixelDiff::~ExamplesSkiaGoldPixelDiff() = default; ExamplesExitCode ExamplesSkiaGoldPixelDiff::CompareScreenshot( const std::string& screenshot_name, const views::Widget* widget) const { base::RunLoop run_loop(base::RunLoop::Type::kNestableTasksAllowed); gfx::Rect widget_bounds = widget->GetRootView()->bounds(); #if defined(USE_AURA) ui::GrabWindowSnapshotAsyncAura( #else ui::GrabWindowSnapshotAsync( #endif widget->GetNativeWindow(), widget_bounds, base::BindOnce( [](gfx::Image* screenshot, base::OnceClosure quit_loop, gfx::Image image) { *screenshot = image; std::move(quit_loop).Run(); }, &screenshot_, run_loop.QuitClosure())); run_loop.Run(); if (screenshot_.IsEmpty()) return ExamplesExitCode::kImageEmpty; return ui::test::SkiaGoldPixelDiff::CompareScreenshot( screenshot_name, *screenshot_.ToSkBitmap()) ? ExamplesExitCode::kSucceeded : ExamplesExitCode::kFailed; } void ExamplesSkiaGoldPixelDiff::DoScreenshot(views::Widget* widget) { result_ = CompareScreenshot("ExampleWindow", widget); widget->Close(); } void ExamplesSkiaGoldPixelDiff::OnExamplesWindowShown(views::Widget* widget) { if (widget->GetName() == views::examples::kExamplesWidgetName) { DoScreenshot(widget); } } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/examples_skia_gold_pixel_diff.cc
C++
unknown
1,899
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_EXAMPLES_SKIA_GOLD_PIXEL_DIFF_H_ #define UI_VIEWS_EXAMPLES_EXAMPLES_SKIA_GOLD_PIXEL_DIFF_H_ #include <string> #include "base/run_loop.h" #include "ui/base/test/skia_gold_pixel_diff.h" #include "ui/gfx/image/image.h" #include "ui/views/examples/examples_exit_code.h" #include "ui/views/widget/widget.h" namespace views::examples { class ExamplesSkiaGoldPixelDiff : public ui::test::SkiaGoldPixelDiff { public: ExamplesSkiaGoldPixelDiff(); ~ExamplesSkiaGoldPixelDiff() override; void OnExamplesWindowShown(views::Widget* widget); ExamplesExitCode get_result() const { return result_; } private: ExamplesExitCode CompareScreenshot(const std::string& screenshot_name, const views::Widget* widget) const; void DoScreenshot(views::Widget* widget); mutable gfx::Image screenshot_; ExamplesExitCode result_ = ExamplesExitCode::kNone; }; } // namespace views::examples #endif // UI_VIEWS_EXAMPLES_EXAMPLES_SKIA_GOLD_PIXEL_DIFF_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/examples_skia_gold_pixel_diff.h
C++
unknown
1,158
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/examples_themed_label.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/color/color_provider.h" namespace views::examples { ThemedLabel::ThemedLabel() = default; ThemedLabel::~ThemedLabel() = default; absl::optional<ui::ColorId> ThemedLabel::GetEnabledColorId() const { return enabled_color_id_; } void ThemedLabel::SetEnabledColorId( absl::optional<ui::ColorId> enabled_color_id) { if (enabled_color_id == enabled_color_id_) return; enabled_color_id_ = enabled_color_id; OnPropertyChanged(&enabled_color_id_, kPropertyEffectsPaint); } // View: void ThemedLabel::OnThemeChanged() { Label::OnThemeChanged(); if (enabled_color_id_) SetEnabledColor(GetColorProvider()->GetColor(enabled_color_id_.value())); } BEGIN_METADATA(ThemedLabel, Label) ADD_PROPERTY_METADATA(absl::optional<ui::ColorId>, EnabledColorId) END_METADATA } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/examples_themed_label.cc
C++
unknown
1,075
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_EXAMPLES_THEMED_LABEL_H_ #define UI_VIEWS_EXAMPLES_EXAMPLES_THEMED_LABEL_H_ #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/color/color_id.h" #include "ui/views/controls/label.h" #include "ui/views/metadata/view_factory.h" #include "ui/views/view.h" namespace views::examples { class ThemedLabel : public Label { public: METADATA_HEADER(ThemedLabel); ThemedLabel(); ThemedLabel(const ThemedLabel&) = delete; ThemedLabel& operator=(const ThemedLabel&) = delete; ~ThemedLabel() override; absl::optional<ui::ColorId> GetEnabledColorId() const; void SetEnabledColorId(absl::optional<ui::ColorId> enabled_color_id); // View: void OnThemeChanged() override; private: absl::optional<ui::ColorId> enabled_color_id_; }; BEGIN_VIEW_BUILDER(, ThemedLabel, Label) VIEW_BUILDER_PROPERTY(ui::ColorId, EnabledColorId) END_VIEW_BUILDER } // namespace views::examples DEFINE_VIEW_BUILDER(, views::examples::ThemedLabel) #endif // UI_VIEWS_EXAMPLES_EXAMPLES_THEMED_LABEL_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/examples_themed_label.h
C++
unknown
1,234
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/views/examples/examples_exit_code.h" #include "ui/views/examples/examples_main_proc.h" #if BUILDFLAG(IS_WIN) #include "ui/native_theme/native_theme_win.h" #endif namespace views::examples { TEST(ExamplesTest, TestViewsExamplesLaunches) { #if BUILDFLAG(IS_WIN) if (ui::NativeTheme::GetInstanceForNativeUi()->ShouldUseDarkColors()) { GTEST_SKIP() << "Host is in dark mode; skipping test"; } #endif const ExamplesExitCode exit_code = ExamplesMainProc(true); // Check the status of the Skia Gold comparison. EXPECT_EQ(ExamplesExitCode::kSucceeded, exit_code); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/examples_unittest.cc
C++
unknown
844
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/functional/bind.h" #include "base/test/launcher/unit_test_launcher.h" #include "base/test/test_suite.h" int main(int argc, char** argv) { base::TestSuite test_suite(argc, argv); return base::LaunchUnitTests( argc, argv, base::BindOnce(&base::TestSuite::Run, base::Unretained(&test_suite))); }
Zhao-PengFei35/chromium_src_4
ui/views/examples/examples_unittest_main.cc
C++
unknown
469
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/examples_views_delegate_chromeos.h" #include "ui/views/examples/examples_window.h" #include "ui/wm/test/wm_test_helper.h" namespace views::examples { namespace { constexpr gfx::Size kDefaultSize(1024, 768); } // namespace ExamplesViewsDelegateChromeOS::ExamplesViewsDelegateChromeOS() = default; ExamplesViewsDelegateChromeOS::~ExamplesViewsDelegateChromeOS() = default; void ExamplesViewsDelegateChromeOS::OnBeforeWidgetInit( Widget::InitParams* params, internal::NativeWidgetDelegate* delegate) { views::TestViewsDelegate::OnBeforeWidgetInit(params, delegate); if (!params->parent && !params->context) { DCHECK(!wm_helper_); wm_helper_ = std::make_unique<wm::WMTestHelper>(kDefaultSize); wm_helper_->host()->Show(); observation_.Observe(wm_helper_->host()); params->context = wm_helper_->host()->window(); } } void ExamplesViewsDelegateChromeOS::OnHostCloseRequested( aura::WindowTreeHost* host) { Widget* widget = GetExamplesWidget(); if (widget) { DCHECK(observation_.IsObservingSource(host)); observation_.Reset(); widget->Close(); } } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/examples_views_delegate_chromeos.cc
C++
unknown
1,311
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_EXAMPLES_VIEWS_DELEGATE_CHROMEOS_H_ #define UI_VIEWS_EXAMPLES_EXAMPLES_VIEWS_DELEGATE_CHROMEOS_H_ #include <memory> #include "base/scoped_observation.h" #include "ui/aura/window_tree_host.h" #include "ui/aura/window_tree_host_observer.h" #include "ui/views/test/desktop_test_views_delegate.h" namespace wm { class WMTestHelper; } namespace views::examples { class ExamplesViewsDelegateChromeOS : public DesktopTestViewsDelegate, public aura::WindowTreeHostObserver { public: ExamplesViewsDelegateChromeOS(); ~ExamplesViewsDelegateChromeOS() override; private: // ViewsDelegate: void OnBeforeWidgetInit(Widget::InitParams* params, internal::NativeWidgetDelegate* delegate) override; // aura::WindowTreeHostObserver: void OnHostCloseRequested(aura::WindowTreeHost* host) override; base::ScopedObservation<aura::WindowTreeHost, aura::WindowTreeHostObserver> observation_{this}; std::unique_ptr<wm::WMTestHelper> wm_helper_; }; } // namespace views::examples #endif // UI_VIEWS_EXAMPLES_EXAMPLES_VIEWS_DELEGATE_CHROMEOS_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/examples_views_delegate_chromeos.h
C++
unknown
1,289
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/examples_window.h" #include <algorithm> #include <iostream> #include <iterator> #include <memory> #include <string> #include <utility> #include "base/command_line.h" #include "base/containers/contains.h" #include "base/containers/cxx20_erase.h" #include "base/memory/raw_ptr.h" #include "base/ranges/algorithm.h" #include "base/run_loop.h" #include "base/stl_util.h" #include "base/strings/string_split.h" #include "base/strings/utf_string_conversions.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/ui_base_paths.h" #include "ui/color/color_id.h" #include "ui/views/background.h" #include "ui/views/controls/label.h" #include "ui/views/controls/tabbed_pane/tabbed_pane.h" #include "ui/views/controls/tabbed_pane/tabbed_pane_listener.h" #include "ui/views/examples/create_examples.h" #include "ui/views/examples/grit/views_examples_resources.h" #include "ui/views/layout/box_layout.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_delegate.h" namespace views::examples { const char kExamplesWidgetName[] = "ExamplesWidget"; static const char kEnableExamples[] = "enable-examples"; bool CheckCommandLineUsage() { base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch("help")) { // Print the program usage. std::cout << "Usage: " << command_line->GetProgram() << " [--" << kEnableExamples << "=<example1,[example2...]>]\n"; return true; } return false; } namespace { ExampleVector GetExamplesToShow(ExampleVector examples) { using StringVector = std::vector<std::string>; base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); std::sort(examples.begin(), examples.end(), [](const auto& a, const auto& b) { return a->example_title() < b->example_title(); }); std::string enable_examples = command_line->GetSwitchValueASCII(kEnableExamples); if (!enable_examples.empty()) { // Filter examples to show based on the command line switch. StringVector enabled = base::SplitString(enable_examples, ";,", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); // Transform list of examples to just the list of names. StringVector example_names; base::ranges::transform(examples, std::back_inserter(example_names), &ExampleBase::example_title); base::ranges::sort(enabled); // Get an intersection of list of titles between the full list and the list // from the command-line. StringVector valid_examples = base::STLSetIntersection<StringVector>(enabled, example_names); // If there are still example names in the list, only include the examples // from the list. if (!valid_examples.empty()) { base::EraseIf(examples, [valid_examples](auto& example) { return !base::Contains(valid_examples, example->example_title()); }); } } else if (command_line->HasSwitch(kEnableExamples)) { std::string titles; for (auto& example : examples) { titles += "\n\t"; titles += example->example_title(); } titles += "\n"; std::cout << "By default, all examples will be shown."; std::cout << "You may want to specify the example(s) you want to run:" << titles; } return examples; } } // namespace class ExamplesWindowContents : public WidgetDelegateView, public TabbedPaneListener { public: ExamplesWindowContents(base::OnceClosure on_close, ExampleVector examples) : on_close_(std::move(on_close)) { SetHasWindowSizeControls(true); SetBackground(CreateThemedSolidBackground(ui::kColorDialogBackground)); auto* layout = SetLayoutManager(std::make_unique<views::BoxLayout>( BoxLayout::Orientation::kVertical, gfx::Insets(0))); auto tabbed_pane = std::make_unique<TabbedPane>(TabbedPane::Orientation::kVertical, TabbedPane::TabStripStyle::kBorder, true); tabbed_pane_ = AddChildView(std::move(tabbed_pane)); layout->SetFlexForView(tabbed_pane_, 1); CreateSidePanel(std::move(examples)); status_label_ = AddChildView(std::make_unique<Label>()); status_label_->SetVisible(false); tabbed_pane_->set_listener(this); instance_ = this; } ExamplesWindowContents(const ExamplesWindowContents&) = delete; ExamplesWindowContents& operator=(const ExamplesWindowContents&) = delete; ~ExamplesWindowContents() override = default; // Sets the status area (at the bottom of the window) to |status|. void SetStatus(const std::string& status) { status_label_->SetText(base::UTF8ToUTF16(status)); status_label_->SetVisible(!status.empty()); } void TabSelectedAt(int index) override { status_label_->SetVisible(false); } static ExamplesWindowContents* instance() { return instance_; } private: // WidgetDelegateView: std::u16string GetWindowTitle() const override { return u"Views Examples"; } void WindowClosing() override { instance_ = nullptr; if (on_close_) std::move(on_close_).Run(); } gfx::Size CalculatePreferredSize() const override { gfx::Size size(800, 300); for (size_t i = 0; i < tabbed_pane_->GetTabCount(); i++) { size.set_height(std::max( size.height(), tabbed_pane_->GetTabAt(i)->contents()->GetHeightForWidth(800))); } return size; } gfx::Size GetMinimumSize() const override { return gfx::Size(50, 50); } void CreateSidePanel(ExampleVector examples) { for (auto& example : examples) { auto tab_contents = std::make_unique<View>(); example->CreateExampleView(tab_contents.get()); example->SetContainer( tabbed_pane_->AddTab(base::UTF8ToUTF16(example->example_title()), std::move(tab_contents))); } examples_ = std::move(examples); } static ExamplesWindowContents* instance_; raw_ptr<Label> status_label_ = nullptr; base::OnceClosure on_close_; raw_ptr<TabbedPane> tabbed_pane_ = nullptr; ExampleVector examples_; }; // static ExamplesWindowContents* ExamplesWindowContents::instance_ = nullptr; Widget* GetExamplesWidget() { return ExamplesWindowContents::instance() ? ExamplesWindowContents::instance()->GetWidget() : nullptr; } void ShowExamplesWindow(base::OnceClosure on_close, ExampleVector examples, gfx::NativeWindow window_context) { if (ExamplesWindowContents::instance()) { ExamplesWindowContents::instance()->GetWidget()->Activate(); } else { examples = GetExamplesToShow(std::move(examples)); Widget* widget = new Widget; Widget::InitParams params; params.delegate = new ExamplesWindowContents(std::move(on_close), std::move(examples)); params.context = window_context; params.name = kExamplesWidgetName; widget->Init(std::move(params)); widget->Show(); } } void LogStatus(const std::string& string) { if (ExamplesWindowContents::instance()) ExamplesWindowContents::instance()->SetStatus(string); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/examples_window.cc
C++
unknown
7,357
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_EXAMPLES_WINDOW_H_ #define UI_VIEWS_EXAMPLES_EXAMPLES_WINDOW_H_ #include <memory> #include <string> #include <vector> #include "base/functional/callback_forward.h" #include "base/strings/stringprintf.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/examples/create_examples.h" #include "ui/views/examples/example_base.h" #include "ui/views/examples/views_examples_export.h" namespace views { class Widget; namespace examples { VIEWS_EXAMPLES_EXPORT extern const char kExamplesWidgetName[]; VIEWS_EXAMPLES_EXPORT bool CheckCommandLineUsage(); // Returns the current widget. VIEWS_EXAMPLES_EXPORT Widget* GetExamplesWidget(); // Shows a window with the views examples in it. |extra_examples| contains any // additional examples to add. |window_context| is used to determine where the // window should be created (see |Widget::InitParams::context| for details). VIEWS_EXAMPLES_EXPORT void ShowExamplesWindow( base::OnceClosure on_close, ExampleVector examples = CreateExamples(), gfx::NativeWindow window_context = nullptr); // Prints |string| in the status area, at the bottom of the window. VIEWS_EXAMPLES_EXPORT void LogStatus(const std::string& string); // Same as LogStatus(), but with a format string. template <typename... Args> void PrintStatus(const char* format, Args... args) { LogStatus(base::StringPrintf(format, args...)); } } // namespace examples } // namespace views #endif // UI_VIEWS_EXAMPLES_EXAMPLES_WINDOW_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/examples_window.h
C++
unknown
1,640
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/examples_window_with_content.h" #include <memory> #include <utility> #include <vector> #include "content/public/browser/browser_context.h" #include "ui/views/examples/create_examples.h" #include "ui/views/examples/example_base.h" #include "ui/views/examples/webview_example.h" namespace views::examples { void ShowExamplesWindowWithContent(base::OnceClosure on_close, content::BrowserContext* browser_context, gfx::NativeWindow window_context) { ExampleVector examples; examples.push_back(std::make_unique<WebViewExample>(browser_context)); ShowExamplesWindow(std::move(on_close), CreateExamples(std::move(examples)), window_context); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/examples_window_with_content.cc
C++
unknown
943
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_EXAMPLES_WINDOW_WITH_CONTENT_H_ #define UI_VIEWS_EXAMPLES_EXAMPLES_WINDOW_WITH_CONTENT_H_ #include "base/functional/callback_forward.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/examples/examples_window.h" #include "ui/views/examples/views_examples_with_content_export.h" namespace content { class BrowserContext; } namespace views::examples { // Shows a window with the views examples in it. VIEWS_EXAMPLES_WITH_CONTENT_EXPORT void ShowExamplesWindowWithContent( base::OnceClosure on_close, content::BrowserContext* browser_context, gfx::NativeWindow window_context); } // namespace views::examples #endif // UI_VIEWS_EXAMPLES_EXAMPLES_WINDOW_WITH_CONTENT_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/examples_window_with_content.h
C++
unknown
867
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/files/file_path.h" #include "base/functional/bind.h" #include "base/path_service.h" #include "build/build_config.h" #include "content/public/browser/browser_context.h" #include "ui/base/resource/resource_bundle.h" #include "ui/views/examples/examples_color_mixer.h" #include "ui/views/examples/examples_window.h" #include "ui/views/examples/examples_window_with_content.h" #include "ui/views_content_client/views_content_client.h" #if BUILDFLAG(IS_MAC) #include "sandbox/mac/seatbelt_exec.h" #include "ui/display/screen.h" #endif #if BUILDFLAG(IS_WIN) #include "base/win/windows_types.h" #include "content/public/app/sandbox_helper_win.h" #include "sandbox/win/src/sandbox_types.h" #endif namespace { void OnResourcesLoaded() { base::FilePath views_examples_resources_pak_path; CHECK(base::PathService::Get(base::DIR_ASSETS, &views_examples_resources_pak_path)); ui::ResourceBundle::GetSharedInstance().AddDataPackFromPath( views_examples_resources_pak_path.AppendASCII( "views_examples_resources.pak"), ui::k100Percent); } void ShowContentExampleWindow(ui::ViewsContentClient* views_content_client, content::BrowserContext* browser_context, gfx::NativeWindow window_context) { views::examples::ShowExamplesWindowWithContent( std::move(views_content_client->quit_closure()), browser_context, window_context); // These lines serve no purpose other than to introduce an explicit content // dependency. If the main executable doesn't have this dependency, the linker // has more flexibility to reorder library dependencies in a shared component // build. On linux, this can cause libc to appear before libcontent in the // dlsym search path, which breaks (usually valid) assumptions made in // sandbox::InitLibcUrandomOverrides(). See http://crbug.com/374712. if (!browser_context) { browser_context->SaveSessionState(); NOTREACHED_NORETURN(); } } } // namespace #if BUILDFLAG(IS_WIN) int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t*, int) { base::CommandLine::Init(0, nullptr); sandbox::SandboxInterfaceInfo sandbox_info = {nullptr}; content::InitializeSandboxInfo(&sandbox_info); ui::ViewsContentClient views_content_client(instance, &sandbox_info); #else int main(int argc, const char** argv) { base::CommandLine::Init(argc, argv); #if BUILDFLAG(IS_MAC) display::ScopedNativeScreen desktop_screen; #endif ui::ColorProviderManager::Get().AppendColorProviderInitializer( base::BindRepeating(&views::examples::AddExamplesColorMixers)); ui::ViewsContentClient views_content_client(argc, argv); #endif if (views::examples::CheckCommandLineUsage()) return 0; #if BUILDFLAG(IS_MAC) base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); // ViewsContentClient expects a const char** argv and // CreateFromArgumentsResult expects a regular char** argv. Given this is a // test program, a refactor from either end didn't seem worth it. As a result, // use a const_cast instead. sandbox::SeatbeltExecServer::CreateFromArgumentsResult seatbelt = sandbox::SeatbeltExecServer::CreateFromArguments( command_line->GetProgram().value().c_str(), argc, const_cast<char**>(argv)); if (seatbelt.sandbox_required) CHECK(seatbelt.server->InitializeSandbox()); #endif views_content_client.set_on_resources_loaded_callback( base::BindOnce(&OnResourcesLoaded)); views_content_client.set_on_pre_main_message_loop_run_callback(base::BindOnce( &ShowContentExampleWindow, base::Unretained(&views_content_client))); return views_content_client.RunMain(); }
Zhao-PengFei35/chromium_src_4
ui/views/examples/examples_with_content_main.cc
C++
unknown
3,909
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/fade_animation.h" #include <algorithm> #include <memory> #include "base/functional/bind.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/compositor/layer.h" #include "ui/compositor/layer_animation_element.h" #include "ui/compositor/layer_animation_sequence.h" #include "ui/compositor/layer_animator.h" #include "ui/compositor/layer_delegate.h" #include "ui/compositor/paint_recorder.h" #include "ui/gfx/font.h" #include "ui/gfx/font_list.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/rect_f.h" #include "ui/gfx/geometry/rounded_corners_f.h" #include "ui/gfx/geometry/size.h" #include "ui/views/animation/animation_builder.h" #include "ui/views/background.h" #include "ui/views/border.h" #include "ui/views/controls/label.h" #include "ui/views/examples/examples_color_id.h" #include "ui/views/examples/examples_themed_label.h" #include "ui/views/layout/box_layout_view.h" #include "ui/views/layout/layout_manager_base.h" #include "ui/views/layout/layout_provider.h" #include "ui/views/metadata/view_factory.h" #include "ui/views/style/typography.h" #include "ui/views/style/typography_provider.h" namespace views::examples { class CenteringLayoutManager : public LayoutManagerBase { public: CenteringLayoutManager() = default; ~CenteringLayoutManager() override = default; protected: // LayoutManagerBase: ProposedLayout CalculateProposedLayout( const SizeBounds& size_bounds) const override; }; constexpr gfx::Size FadingView::kSize; FadingView::FadingView() { Builder<FadingView>(this) .SetUseDefaultFillLayout(true) .SetPreferredSize(kSize) .AddChildren( Builder<BoxLayoutView>() .CopyAddressTo(&primary_view_) .SetBorder(CreateThemedRoundedRectBorder( 1, kCornerRadius, ExamplesColorIds::kColorFadeAnimationExampleBorder)) .SetBackground(CreateThemedRoundedRectBackground( ExamplesColorIds::kColorFadeAnimationExampleBackground, kCornerRadius, 1)) .SetPaintToLayer() .SetOrientation(BoxLayout::Orientation::kVertical) .SetMainAxisAlignment(BoxLayout::MainAxisAlignment::kCenter) .SetBetweenChildSpacing(kSpacing) .AddChildren(Builder<Label>() .SetText(u"Primary Title") .SetTextContext(style::CONTEXT_DIALOG_TITLE) .SetTextStyle(style::STYLE_PRIMARY) .SetVerticalAlignment(gfx::ALIGN_MIDDLE), Builder<Label>() .SetText(u"Secondary Title") .SetTextContext(style::CONTEXT_LABEL) .SetTextStyle(style::STYLE_SECONDARY) .SetVerticalAlignment(gfx::ALIGN_MIDDLE)), Builder<BoxLayoutView>() .CopyAddressTo(&secondary_view_) .SetBorder(CreateThemedRoundedRectBorder( 1, kCornerRadius, ExamplesColorIds::kColorFadeAnimationExampleBorder)) .SetBackground(CreateThemedRoundedRectBackground( ExamplesColorIds::kColorFadeAnimationExampleBackground, kCornerRadius, 1)) .SetPaintToLayer() .SetOrientation(BoxLayout::Orientation::kVertical) .SetMainAxisAlignment(BoxLayout::MainAxisAlignment::kCenter) .SetBetweenChildSpacing(kSpacing) .AddChild(Builder<ThemedLabel>() .SetText(u"Working...") .SetTextContext(style::CONTEXT_DIALOG_TITLE) .SetTextStyle(style::STYLE_PRIMARY) .SetVerticalAlignment(gfx::ALIGN_MIDDLE) .SetEnabledColorId( ExamplesColorIds:: kColorFadeAnimationExampleForeground))) .BuildChildren(); primary_view_->layer()->SetRoundedCornerRadius( gfx::RoundedCornersF(kCornerRadiusF)); secondary_view_->layer()->SetRoundedCornerRadius( gfx::RoundedCornersF(kCornerRadiusF)); secondary_view_->layer()->SetOpacity(0.0f); AnimationBuilder() .Repeatedly() .Offset(base::Seconds(2)) .SetDuration(base::Seconds(1)) .SetOpacity(primary_view_, 0.0f) .SetOpacity(secondary_view_, 1.0f) .Offset(base::Seconds(2)) .SetDuration(base::Seconds(1)) .SetOpacity(primary_view_, 1.0f) .SetOpacity(secondary_view_, 0.0f); } FadingView::~FadingView() = default; ProposedLayout CenteringLayoutManager::CalculateProposedLayout( const SizeBounds& size_bounds) const { ProposedLayout layout; const auto& children = host_view()->children(); gfx::Rect host_bounds(size_bounds.width().min_of(host_view()->width()), size_bounds.height().min_of(host_view()->height())); for (auto* child : children) { gfx::Size preferred_size = child->GetPreferredSize(); gfx::Rect child_bounds = host_bounds; child_bounds.ClampToCenteredSize(preferred_size); layout.child_layouts.push_back( {child, true, child_bounds, SizeBounds(preferred_size)}); } layout.host_size = host_bounds.size(); return layout; } FadeAnimationExample::FadeAnimationExample() : ExampleBase("Fade Animation") {} FadeAnimationExample::~FadeAnimationExample() = default; void FadeAnimationExample::CreateExampleView(View* container) { container->SetBackground(CreateThemedSolidBackground( ExamplesColorIds::kColorFadeAnimationExampleBackground)); container->SetLayoutManager(std::make_unique<CenteringLayoutManager>()); container->AddChildView(std::make_unique<FadingView>()); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/fade_animation.cc
C++
unknown
6,274
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_FADE_ANIMATION_H_ #define UI_VIEWS_EXAMPLES_FADE_ANIMATION_H_ #include "base/memory/raw_ptr_exclusion.h" #include "ui/gfx/geometry/size.h" #include "ui/views/examples/example_base.h" #include "ui/views/metadata/view_factory.h" #include "ui/views/view.h" namespace views { class BoxLayoutView; namespace examples { class FadingView : public View { public: FadingView(); FadingView(const FadingView&) = delete; FadingView& operator=(const FadingView&) = delete; ~FadingView() override; private: static constexpr int kCornerRadius = 12; static constexpr float kCornerRadiusF = float{kCornerRadius}; static constexpr int kSpacing = 2; static constexpr gfx::Size kSize = {200, 50}; // This field is not a raw_ptr<> because it was filtered by the rewriter for: // #addr-of RAW_PTR_EXCLUSION BoxLayoutView* primary_view_; // This field is not a raw_ptr<> because it was filtered by the rewriter for: // #addr-of RAW_PTR_EXCLUSION BoxLayoutView* secondary_view_; }; BEGIN_VIEW_BUILDER(, FadingView, View) END_VIEW_BUILDER class VIEWS_EXAMPLES_EXPORT FadeAnimationExample : public ExampleBase { public: FadeAnimationExample(); FadeAnimationExample(const FadeAnimationExample&) = delete; FadeAnimationExample& operator=(const FadeAnimationExample&) = delete; ~FadeAnimationExample() override; // ExampleBase: void CreateExampleView(View* container) override; }; } // namespace examples } // namespace views DEFINE_VIEW_BUILDER(, views::examples::FadingView) #endif // UI_VIEWS_EXAMPLES_FADE_ANIMATION_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/fade_animation.h
C++
unknown
1,723
// Copyright 2018 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/flex_layout_example.h" #include <memory> #include <string> #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/base/models/combobox_model.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/rect.h" #include "ui/views/border.h" #include "ui/views/controls/button/checkbox.h" #include "ui/views/controls/button/md_text_button.h" #include "ui/views/controls/combobox/combobox.h" #include "ui/views/controls/label.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/examples/example_combobox_model.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/view.h" #include "ui/views/view_class_properties.h" namespace views::examples { FlexLayoutExample::FlexLayoutExample() : LayoutExampleBase("Flex Layout") {} FlexLayoutExample::~FlexLayoutExample() = default; void FlexLayoutExample::ContentsChanged(Textfield* sender, const std::u16string& new_contents) { layout_->SetInteriorMargin( LayoutExampleBase::TextfieldsToInsets(interior_margin_)); layout_->SetDefault(views::kMarginsKey, LayoutExampleBase::TextfieldsToInsets( default_child_margins_)); RefreshLayoutPanel(false); } void FlexLayoutExample::CreateAdditionalControls() { constexpr const char* kOrientationValues[2] = {"Horizontal", "Vertical"}; orientation_ = CreateAndAddCombobox( u"Orientation", kOrientationValues, std::size(kOrientationValues), base::BindRepeating(&FlexLayoutExample::OrientationChanged, base::Unretained(this))); constexpr const char* kMainAxisValues[3] = {"Start", "Center", "End"}; main_axis_alignment_ = CreateAndAddCombobox( u"Main axis", kMainAxisValues, std::size(kMainAxisValues), base::BindRepeating(&FlexLayoutExample::MainAxisAlignmentChanged, base::Unretained(this))); constexpr const char* kCrossAxisValues[4] = {"Stretch", "Start", "Center", "End"}; cross_axis_alignment_ = CreateAndAddCombobox( u"Cross axis", kCrossAxisValues, std::size(kCrossAxisValues), base::BindRepeating(&FlexLayoutExample::CrossAxisAlignmentChanged, base::Unretained(this))); CreateMarginsTextFields(u"Interior margin", &interior_margin_); CreateMarginsTextFields(u"Default margins", &default_child_margins_); collapse_margins_ = CreateAndAddCheckbox( u"Collapse margins", base::BindRepeating( [](FlexLayoutExample* example) { example->layout_->SetCollapseMargins( example->collapse_margins_->GetChecked()); example->RefreshLayoutPanel(false); }, base::Unretained(this))); ignore_default_main_axis_margins_ = CreateAndAddCheckbox( u"Ignore main axis margins", base::BindRepeating( [](FlexLayoutExample* example) { example->layout_->SetIgnoreDefaultMainAxisMargins( example->ignore_default_main_axis_margins_->GetChecked()); example->RefreshLayoutPanel(false); }, base::Unretained(this))); layout_ = layout_panel()->SetLayoutManager(std::make_unique<FlexLayout>()); } void FlexLayoutExample::UpdateLayoutManager() { for (View* child : layout_panel()->children()) { const int flex = static_cast<ChildPanel*>(child)->GetFlex(); if (flex < 0) child->ClearProperty(views::kFlexBehaviorKey); else child->SetProperty(views::kFlexBehaviorKey, GetFlexSpecification(flex)); } } FlexSpecification FlexLayoutExample::GetFlexSpecification(int weight) const { return weight > 0 ? FlexSpecification(MinimumFlexSizeRule::kScaleToZero, MaximumFlexSizeRule::kUnbounded) .WithWeight(weight) : FlexSpecification(MinimumFlexSizeRule::kPreferredSnapToZero, MaximumFlexSizeRule::kPreferred) .WithWeight(0); } void FlexLayoutExample::OrientationChanged() { constexpr LayoutOrientation kOrientations[2] = { LayoutOrientation::kHorizontal, LayoutOrientation::kVertical}; layout_->SetOrientation( kOrientations[orientation_->GetSelectedIndex().value()]); RefreshLayoutPanel(false); } void FlexLayoutExample::MainAxisAlignmentChanged() { constexpr LayoutAlignment kMainAxisAlignments[3] = { LayoutAlignment::kStart, LayoutAlignment::kCenter, LayoutAlignment::kEnd}; layout_->SetMainAxisAlignment( kMainAxisAlignments[main_axis_alignment_->GetSelectedIndex().value()]); RefreshLayoutPanel(false); } void FlexLayoutExample::CrossAxisAlignmentChanged() { constexpr LayoutAlignment kCrossAxisAlignments[4] = { LayoutAlignment::kStretch, LayoutAlignment::kStart, LayoutAlignment::kCenter, LayoutAlignment::kEnd}; layout_->SetCrossAxisAlignment( kCrossAxisAlignments[cross_axis_alignment_->GetSelectedIndex().value()]); RefreshLayoutPanel(false); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/flex_layout_example.cc
C++
unknown
5,480
// Copyright 2017 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_FLEX_LAYOUT_EXAMPLE_H_ #define UI_VIEWS_EXAMPLES_FLEX_LAYOUT_EXAMPLE_H_ #include "base/memory/raw_ptr.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/textfield/textfield_controller.h" #include "ui/views/examples/layout_example_base.h" #include "ui/views/layout/flex_layout.h" namespace views { class Checkbox; class Combobox; class Textfield; namespace examples { class VIEWS_EXAMPLES_EXPORT FlexLayoutExample : public LayoutExampleBase { public: FlexLayoutExample(); FlexLayoutExample(const FlexLayoutExample&) = delete; FlexLayoutExample& operator=(const FlexLayoutExample&) = delete; ~FlexLayoutExample() override; private: // LayoutExampleBase: void ContentsChanged(Textfield* sender, const std::u16string& new_contents) override; void CreateAdditionalControls() override; void UpdateLayoutManager() override; FlexSpecification GetFlexSpecification(int weight) const; void OrientationChanged(); void MainAxisAlignmentChanged(); void CrossAxisAlignmentChanged(); raw_ptr<FlexLayout> layout_ = nullptr; raw_ptr<Combobox> orientation_ = nullptr; raw_ptr<Combobox> main_axis_alignment_ = nullptr; raw_ptr<Combobox> cross_axis_alignment_ = nullptr; raw_ptr<Checkbox> collapse_margins_ = nullptr; InsetTextfields interior_margin_; InsetTextfields default_child_margins_; raw_ptr<Checkbox> ignore_default_main_axis_margins_ = nullptr; }; } // namespace examples } // namespace views #endif // UI_VIEWS_EXAMPLES_FLEX_LAYOUT_EXAMPLE_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/flex_layout_example.h
C++
unknown
1,759
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/ink_drop_example.h" #include <memory> #include <utility> #include "base/functional/bind.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/compositor/scoped_animation_duration_scale_mode.h" #include "ui/events/event.h" #include "ui/events/types/event_type.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/point_f.h" #include "ui/gfx/geometry/size.h" #include "ui/views/animation/flood_fill_ink_drop_ripple.h" #include "ui/views/animation/ink_drop_host.h" #include "ui/views/animation/ink_drop_state.h" #include "ui/views/border.h" #include "ui/views/controls/button/md_text_button.h" #include "ui/views/examples/examples_color_id.h" #include "ui/views/layout/box_layout_view.h" #include "ui/views/metadata/view_factory.h" #include "ui/views/view.h" #include "ui/views/view_class_properties.h" namespace views::examples { class InkDropView : public View { public: METADATA_HEADER(InkDropView); InkDropView() = default; InkDropView(const InkDropView&) = delete; InkDropView& operator=(const InkDropView&) = delete; ~InkDropView() override = default; // View: void OnThemeChanged() override { View::OnThemeChanged(); InkDrop::Get(this)->SetBaseColor(GetColorProvider()->GetColor( ExamplesColorIds::kColorInkDropExampleBase)); } }; BEGIN_METADATA(InkDropView, View) END_METADATA BEGIN_VIEW_BUILDER(, InkDropView, View) END_VIEW_BUILDER } // namespace views::examples DEFINE_VIEW_BUILDER(, views::examples::InkDropView) namespace views::examples { InkDropExample::InkDropExample() : ExampleBase("FloodFill Ink Drop") {} InkDropExample::InkDropExample(const char* title) : ExampleBase(title) {} InkDropExample::~InkDropExample() = default; void InkDropExample::CreateExampleView(View* container) { BoxLayoutView* box_layout_view = nullptr; auto get_callback = [this](InkDropState state) { return base::BindRepeating(&InkDropExample::SetInkDropState, base::Unretained(this), state); }; Builder<View>(container) .SetUseDefaultFillLayout(true) .AddChild( Builder<BoxLayoutView>() .CopyAddressTo(&box_layout_view) .SetOrientation(BoxLayout::Orientation::kVertical) .SetMainAxisAlignment(BoxLayout::MainAxisAlignment::kEnd) .AddChildren( Builder<InkDropView>() .CopyAddressTo(&ink_drop_view_) .SetBorder(CreateThemedRoundedRectBorder( 1, 4, ExamplesColorIds::kColorInkDropExampleBorder)) .SetProperty(kMarginsKey, gfx::Insets(10)), Builder<BoxLayoutView>() .SetOrientation(BoxLayout::Orientation::kHorizontal) .SetCrossAxisAlignment( BoxLayout::CrossAxisAlignment::kCenter) .SetPreferredSize(gfx::Size(0, 50)) .AddChildren( Builder<MdTextButton>() .SetText(base::ASCIIToUTF16( ToString(InkDropState::HIDDEN))) .SetCallback(get_callback(InkDropState::HIDDEN)) .SetProperty(kMarginsKey, gfx::Insets::VH(0, 5)), Builder<MdTextButton>() .SetText(base::ASCIIToUTF16( ToString(InkDropState::ACTION_PENDING))) .SetCallback( get_callback(InkDropState::ACTION_PENDING)) .SetProperty(kMarginsKey, gfx::Insets::VH(0, 5)), Builder<MdTextButton>() .SetText(base::ASCIIToUTF16( ToString(InkDropState::ACTION_TRIGGERED))) .SetCallback( get_callback(InkDropState::ACTION_TRIGGERED)) .SetProperty(kMarginsKey, gfx::Insets::VH(0, 5)), Builder<MdTextButton>() .SetText(base::ASCIIToUTF16(ToString( InkDropState::ALTERNATE_ACTION_PENDING))) .SetCallback(get_callback( InkDropState::ALTERNATE_ACTION_PENDING)) .SetProperty(kMarginsKey, gfx::Insets::VH(0, 5)), Builder<MdTextButton>() .SetText(base::ASCIIToUTF16(ToString( InkDropState::ALTERNATE_ACTION_TRIGGERED))) .SetCallback(get_callback( InkDropState::ALTERNATE_ACTION_TRIGGERED)) .SetProperty(kMarginsKey, gfx::Insets::VH(0, 5)), Builder<MdTextButton>() .SetText(base::ASCIIToUTF16( ToString(InkDropState::ACTIVATED))) .SetCallback( get_callback(InkDropState::ACTIVATED)) .SetProperty(kMarginsKey, gfx::Insets::VH(0, 5)), Builder<MdTextButton>() .SetText(base::ASCIIToUTF16( ToString(InkDropState::DEACTIVATED))) .SetCallback( get_callback(InkDropState::DEACTIVATED)) .SetProperty(kMarginsKey, gfx::Insets::VH(0, 5))))) .BuildChildren(); box_layout_view->SetFlexForView(ink_drop_view_, 1); CreateInkDrop(); } void InkDropExample::CreateInkDrop() { auto ink_drop_host = std::make_unique<InkDropHost>(ink_drop_view_); ink_drop_host->SetMode(InkDropHost::InkDropMode::ON); InkDrop::Install(ink_drop_view_, std::move(ink_drop_host)); } void InkDropExample::SetInkDropState(InkDropState state) { ui::MouseEvent event( ui::ET_MOUSE_PRESSED, gfx::PointF(ink_drop_view_->GetLocalBounds().CenterPoint()), gfx::PointF(ink_drop_view_->origin()), base::TimeTicks(), 0, 0); ui::ScopedAnimationDurationScaleMode scale( ui::ScopedAnimationDurationScaleMode::SLOW_DURATION); InkDrop::Get(ink_drop_view_)->AnimateToState(state, &event); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/ink_drop_example.cc
C++
unknown
6,769
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_INK_DROP_EXAMPLE_H_ #define UI_VIEWS_EXAMPLES_INK_DROP_EXAMPLE_H_ #include "base/functional/callback.h" #include "base/memory/raw_ptr_exclusion.h" #include "ui/views/animation/ink_drop.h" #include "ui/views/animation/ink_drop_state.h" #include "ui/views/examples/example_base.h" namespace views::examples { class VIEWS_EXAMPLES_EXPORT InkDropExample : public ExampleBase { public: InkDropExample(); InkDropExample(const InkDropExample&) = delete; InkDropExample& operator=(const InkDropExample&) = delete; ~InkDropExample() override; // ExampleBase: void CreateExampleView(View* container) override; protected: explicit InkDropExample(const char* title); virtual void CreateInkDrop(); View* ink_drop_view() { return ink_drop_view_; } private: void SetInkDropState(InkDropState state); // This field is not a raw_ptr<> because it was filtered by the rewriter for: // #addr-of RAW_PTR_EXCLUSION View* ink_drop_view_ = nullptr; }; } // namespace views::examples #endif // UI_VIEWS_EXAMPLES_INK_DROP_EXAMPLE_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/ink_drop_example.h
C++
unknown
1,219
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/label_example.h" #include <memory> #include <utility> #include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/vector2d.h" #include "ui/views/background.h" #include "ui/views/border.h" #include "ui/views/controls/button/checkbox.h" #include "ui/views/controls/combobox/combobox.h" #include "ui/views/controls/label.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/examples/example_combobox_model.h" #include "ui/views/examples/examples_color_id.h" #include "ui/views/examples/examples_themed_label.h" #include "ui/views/examples/grit/views_examples_resources.h" #include "ui/views/layout/box_layout.h" #include "ui/views/layout/box_layout_view.h" #include "ui/views/layout/table_layout.h" #include "ui/views/view.h" using base::ASCIIToUTF16; namespace views::examples { namespace { const char* kAlignments[] = {"Left", "Center", "Right", "Head"}; // A Label with a clamped preferred width to demonstrate eliding or wrapping. class ExamplePreferredSizeLabel : public Label { public: ExamplePreferredSizeLabel() { SetBorder( CreateThemedSolidBorder(1, ExamplesColorIds::kColorLabelExampleBorder)); } ExamplePreferredSizeLabel(const ExamplePreferredSizeLabel&) = delete; ExamplePreferredSizeLabel& operator=(const ExamplePreferredSizeLabel&) = delete; ~ExamplePreferredSizeLabel() override = default; // Label: gfx::Size CalculatePreferredSize() const override { return gfx::Size(50, Label::CalculatePreferredSize().height()); } static const char* kElideBehaviors[]; }; // static const char* ExamplePreferredSizeLabel::kElideBehaviors[] = { "No Elide", "Truncate", "Elide Head", "Elide Middle", "Elide Tail", "Elide Email", "Fade Tail"}; } // namespace LabelExample::LabelExample() : ExampleBase(l10n_util::GetStringUTF8(IDS_LABEL_SELECT_LABEL).c_str()) {} LabelExample::~LabelExample() { observer_.Reset(); } void LabelExample::CreateExampleView(View* container) { observer_.Observe(container); // A very simple label example, followed by additional helpful examples. container->SetLayoutManager(std::make_unique<BoxLayout>( BoxLayout::Orientation::kVertical, gfx::Insets(), 10)); container->AddChildView(std::make_unique<Label>(u"Hello world!")); const char16_t hello_world_hebrew[] = u"\x5e9\x5dc\x5d5\x5dd \x5d4\x5e2\x5d5\x5dc\x5dd!"; auto label = std::make_unique<Label>(hello_world_hebrew); label->SetHorizontalAlignment(gfx::ALIGN_RIGHT); container->AddChildView(std::move(label)); label = std::make_unique<Label>(u"A UTF16 surrogate pair: \x5d0\x5b0"); label->SetHorizontalAlignment(gfx::ALIGN_RIGHT); container->AddChildView(std::move(label)); auto themed_label = std::make_unique<ThemedLabel>(); themed_label->SetText(u"A left-aligned blue label."); themed_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); themed_label->SetEnabledColorId( ExamplesColorIds::kColorLabelExampleBlueLabel); container->AddChildView(std::move(themed_label)); label = std::make_unique<Label>(u"Password!"); label->SetObscured(true); container->AddChildView(std::move(label)); label = std::make_unique<Label>(u"A Courier-18 label with shadows."); label->SetFontList(gfx::FontList("Courier, 18px")); label_ = container->AddChildView(std::move(label)); label = std::make_unique<ExamplePreferredSizeLabel>(); label->SetText( u"A long label will elide toward its logical end if the text's width " u"exceeds the label's available width."); container->AddChildView(std::move(label)); label = std::make_unique<ExamplePreferredSizeLabel>(); label->SetText( u"A multi-line label will wrap onto subsequent lines if the text's width " u"exceeds the label's available width, which is helpful for extemely " u"long text used to demonstrate line wrapping."); label->SetMultiLine(true); container->AddChildView(std::move(label)); label = std::make_unique<Label>(u"Label with thick border"); label->SetBorder(CreateThemedSolidBorder( 20, ExamplesColorIds::kColorLabelExampleThickBorder)); container->AddChildView(std::move(label)); label = std::make_unique<Label>( u"A multiline label...\n\n...which supports text selection"); label->SetSelectable(true); label->SetMultiLine(true); container->AddChildView(std::move(label)); AddCustomLabel(container); } void LabelExample::MultilineCheckboxPressed() { custom_label_->SetMultiLine(multiline_->GetChecked()); } void LabelExample::ShadowsCheckboxPressed() { gfx::ShadowValues shadows; if (shadows_->GetChecked()) { auto* const cp = custom_label_->GetColorProvider(); shadows = { gfx::ShadowValue( gfx::Vector2d(), 1, cp->GetColor(ExamplesColorIds::kColorLabelExampleUpperShadow)), gfx::ShadowValue( gfx::Vector2d(2, 2), 0, cp->GetColor(ExamplesColorIds::kColorLabelExampleLowerShadow))}; } custom_label_->SetShadows(shadows); } void LabelExample::SelectableCheckboxPressed() { custom_label_->SetSelectable(selectable_->GetChecked()); } void LabelExample::ContentsChanged(Textfield* sender, const std::u16string& new_contents) { custom_label_->SetText(new_contents); custom_label_->parent()->parent()->InvalidateLayout(); } void LabelExample::AddCustomLabel(View* container) { std::unique_ptr<View> control_container = std::make_unique<View>(); control_container->SetBorder(CreateThemedSolidBorder( 2, ExamplesColorIds::kColorLabelExampleCustomBorder)); control_container->SetBackground(CreateThemedSolidBackground( ExamplesColorIds::kColorLabelExampleCustomBackground)); control_container->SetLayoutManager( std::make_unique<BoxLayout>(BoxLayout::Orientation::kVertical)); auto* table = control_container->AddChildView(std::make_unique<View>()); table->SetLayoutManager(std::make_unique<TableLayout>()) ->AddColumn(LayoutAlignment::kStart, LayoutAlignment::kStretch, TableLayout::kFixedSize, TableLayout::ColumnSize::kUsePreferred, 0, 0) .AddColumn(LayoutAlignment::kStretch, LayoutAlignment::kStretch, 1.0f, TableLayout::ColumnSize::kUsePreferred, 0, 0) .AddRows(3, TableLayout::kFixedSize); Label* content_label = table->AddChildView(std::make_unique<Label>(u"Content: ")); textfield_ = table->AddChildView(std::make_unique<Textfield>()); textfield_->SetText( u"Use the provided controls to configure the content and presentation of " u"this custom label."); textfield_->SetEditableSelectionRange(gfx::Range()); textfield_->set_controller(this); textfield_->SetAccessibleName(content_label); alignment_ = AddCombobox(table, u"Alignment: ", kAlignments, std::size(kAlignments), &LabelExample::AlignmentChanged); elide_behavior_ = AddCombobox( table, u"Elide Behavior: ", ExamplePreferredSizeLabel::kElideBehaviors, std::size(ExamplePreferredSizeLabel::kElideBehaviors), &LabelExample::ElidingChanged); auto* checkboxes = control_container->AddChildView(std::make_unique<BoxLayoutView>()); multiline_ = checkboxes->AddChildView(std::make_unique<Checkbox>( u"Multiline", base::BindRepeating(&LabelExample::MultilineCheckboxPressed, base::Unretained(this)))); shadows_ = checkboxes->AddChildView(std::make_unique<Checkbox>( u"Shadows", base::BindRepeating(&LabelExample::ShadowsCheckboxPressed, base::Unretained(this)))); selectable_ = checkboxes->AddChildView(std::make_unique<Checkbox>( u"Selectable", base::BindRepeating(&LabelExample::SelectableCheckboxPressed, base::Unretained(this)))); control_container->AddChildView(std::make_unique<View>()) ->SetPreferredSize(gfx::Size(1, 8)); custom_label_ = control_container->AddChildView( std::make_unique<ExamplePreferredSizeLabel>()); custom_label_->SetHorizontalAlignment(gfx::ALIGN_LEFT); custom_label_->SetElideBehavior(gfx::NO_ELIDE); custom_label_->SetText(textfield_->GetText()); // Disable the text selection checkbox if |custom_label_| does not support // text selection. selectable_->SetEnabled(custom_label_->IsSelectionSupported()); container->AddChildView(std::move(control_container)); } Combobox* LabelExample::AddCombobox(View* parent, std::u16string name, const char** strings, int count, void (LabelExample::*function)()) { parent->AddChildView(std::make_unique<Label>(name)); auto* combobox = parent->AddChildView(std::make_unique<Combobox>( std::make_unique<ExampleComboboxModel>(strings, count))); combobox->SetSelectedIndex(0); combobox->SetAccessibleName(name); combobox->SetCallback(base::BindRepeating(function, base::Unretained(this))); return parent->AddChildView(std::move(combobox)); } void LabelExample::AlignmentChanged() { custom_label_->SetHorizontalAlignment(static_cast<gfx::HorizontalAlignment>( alignment_->GetSelectedIndex().value())); } void LabelExample::ElidingChanged() { custom_label_->SetElideBehavior(static_cast<gfx::ElideBehavior>( elide_behavior_->GetSelectedIndex().value())); } void LabelExample::OnViewThemeChanged(View* observed_view) { auto* const cp = observed_view->GetColorProvider(); gfx::ShadowValues shadows = { gfx::ShadowValue( gfx::Vector2d(), 1, cp->GetColor(ExamplesColorIds::kColorLabelExampleUpperShadow)), gfx::ShadowValue( gfx::Vector2d(2, 2), 0, cp->GetColor(ExamplesColorIds::kColorLabelExampleLowerShadow))}; label_->SetShadows(shadows); } void LabelExample::OnViewIsDeleting(View* observed_view) { observer_.Reset(); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/label_example.cc
C++
unknown
10,253
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_LABEL_EXAMPLE_H_ #define UI_VIEWS_EXAMPLES_LABEL_EXAMPLE_H_ #include "base/memory/raw_ptr.h" #include "base/scoped_observation.h" #include "ui/views/controls/textfield/textfield_controller.h" #include "ui/views/examples/example_base.h" #include "ui/views/view_observer.h" namespace views { class Checkbox; class Combobox; class Label; class View; namespace examples { class VIEWS_EXAMPLES_EXPORT LabelExample : public ExampleBase, public TextfieldController, public ViewObserver { public: LabelExample(); LabelExample(const LabelExample&) = delete; LabelExample& operator=(const LabelExample&) = delete; ~LabelExample() override; // ExampleBase: void CreateExampleView(View* container) override; void MultilineCheckboxPressed(); void ShadowsCheckboxPressed(); void SelectableCheckboxPressed(); // TextfieldController: void ContentsChanged(Textfield* sender, const std::u16string& new_contents) override; // ViewObserver: void OnViewThemeChanged(View* observed_view) override; void OnViewIsDeleting(View* observed_view) override; private: // Add a customizable label and various controls to modify its presentation. void AddCustomLabel(View* container); // Creates and adds a combobox to the layout. Combobox* AddCombobox(View* parent, std::u16string name, const char** strings, int count, void (LabelExample::*function)()); void AlignmentChanged(); void ElidingChanged(); raw_ptr<Textfield> textfield_ = nullptr; raw_ptr<Combobox> alignment_ = nullptr; raw_ptr<Combobox> elide_behavior_ = nullptr; raw_ptr<Checkbox> multiline_ = nullptr; raw_ptr<Checkbox> shadows_ = nullptr; raw_ptr<Checkbox> selectable_ = nullptr; raw_ptr<Label> label_ = nullptr; raw_ptr<Label> custom_label_ = nullptr; base::ScopedObservation<View, ViewObserver> observer_{this}; }; } // namespace examples } // namespace views #endif // UI_VIEWS_EXAMPLES_LABEL_EXAMPLE_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/label_example.h
C++
unknown
2,300
// Copyright 2018 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/layout_example_base.h" #include <algorithm> #include <memory> #include <string> #include <utility> #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "ui/base/l10n/l10n_util.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/views/border.h" #include "ui/views/controls/button/checkbox.h" #include "ui/views/controls/button/md_text_button.h" #include "ui/views/controls/combobox/combobox.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/examples/example_combobox_model.h" #include "ui/views/examples/grit/views_examples_resources.h" #include "ui/views/layout/box_layout.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/view_class_properties.h" namespace views::examples { namespace { constexpr int kLayoutExampleVerticalSpacing = 3; constexpr int kLayoutExampleLeftPadding = 8; constexpr gfx::Size kLayoutExampleDefaultChildSize(180, 90); class LayoutPanel : public View { protected: void OnThemeChanged() override { View::OnThemeChanged(); SetBorder(CreateSolidBorder( 1, GetColorProvider()->GetColor(ui::kColorFocusableBorderUnfocused))); } }; // This View holds two other views which consists of a view on the left onto // which the BoxLayout is attached for demonstrating its features. The view // on the right contains all the various controls which allow the user to // interactively control the various features/properties of BoxLayout. Layout() // will ensure the left view takes 75% and the right view fills the remaining // 25%. class FullPanel : public View { public: FullPanel() = default; FullPanel(const FullPanel&) = delete; FullPanel& operator=(const FullPanel&) = delete; ~FullPanel() override = default; }; std::unique_ptr<Textfield> CreateCommonTextfield( TextfieldController* container) { auto textfield = std::make_unique<Textfield>(); textfield->SetDefaultWidthInChars(3); textfield->SetTextInputType(ui::TEXT_INPUT_TYPE_NUMBER); textfield->SetText(u"0"); textfield->set_controller(container); return textfield; } std::unique_ptr<Textfield> CreateCommonTextfieldWithAXName( TextfieldController* container, std::u16string name) { auto text_field = CreateCommonTextfield(container); text_field->SetAccessibleName(name); return text_field; } } // namespace LayoutExampleBase::ChildPanel::ChildPanel(LayoutExampleBase* example) : example_(example) { margin_.left = CreateTextfield(u"Left margin"); margin_.top = CreateTextfield(u"Top margin"); margin_.right = CreateTextfield(u"Right margin"); margin_.bottom = CreateTextfield(u"Bottom margin"); flex_ = CreateTextfield(u"Flex"); flex_->SetText(std::u16string()); } LayoutExampleBase::ChildPanel::~ChildPanel() = default; void LayoutExampleBase::ChildPanel::Layout() { constexpr int kSpacing = 2; if (selected_) { const gfx::Rect client = GetContentsBounds(); margin_.top->SetPosition( gfx::Point((client.width() - margin_.top->width()) / 2, kSpacing)); margin_.left->SetPosition( gfx::Point(kSpacing, (client.height() - margin_.left->height()) / 2)); margin_.bottom->SetPosition( gfx::Point((client.width() - margin_.bottom->width()) / 2, client.height() - margin_.bottom->height() - kSpacing)); margin_.right->SetPosition( gfx::Point(client.width() - margin_.right->width() - kSpacing, (client.height() - margin_.right->height()) / 2)); flex_->SetPosition(gfx::Point((client.width() - flex_->width()) / 2, (client.height() - flex_->height()) / 2)); } } bool LayoutExampleBase::ChildPanel::OnMousePressed( const ui::MouseEvent& event) { if (event.IsOnlyLeftMouseButton()) SetSelected(true); return true; } void LayoutExampleBase::ChildPanel::SetSelected(bool value) { if (value != selected_) { selected_ = value; OnThemeChanged(); if (selected_ && parent()) { for (View* child : parent()->children()) { if (child != this && child->GetGroup() == GetGroup()) static_cast<ChildPanel*>(child)->SetSelected(false); } } margin_.left->SetVisible(selected_); margin_.top->SetVisible(selected_); margin_.right->SetVisible(selected_); margin_.bottom->SetVisible(selected_); flex_->SetVisible(selected_); InvalidateLayout(); example_->RefreshLayoutPanel(false); } } int LayoutExampleBase::ChildPanel::GetFlex() const { int flex; return base::StringToInt(flex_->GetText(), &flex) ? flex : -1; } void LayoutExampleBase::ChildPanel::OnThemeChanged() { View::OnThemeChanged(); SetBorder(CreateSolidBorder( 1, GetColorProvider()->GetColor( selected_ ? ui::kColorFocusableBorderFocused : ui::kColorFocusableBorderUnfocused))); } void LayoutExampleBase::ChildPanel::ContentsChanged( Textfield* sender, const std::u16string& new_contents) { const gfx::Insets margins = LayoutExampleBase::TextfieldsToInsets(margin_); if (!margins.IsEmpty()) SetProperty(kMarginsKey, margins); else ClearProperty(kMarginsKey); example_->RefreshLayoutPanel(sender == flex_); } Textfield* LayoutExampleBase::ChildPanel::CreateTextfield( const std::u16string& name) { return AddChildView(CreateCommonTextfieldWithAXName(this, name)); } LayoutExampleBase::LayoutExampleBase(const char* title) : ExampleBase(title) {} LayoutExampleBase::~LayoutExampleBase() = default; void LayoutExampleBase::RefreshLayoutPanel(bool update_layout) { if (update_layout) UpdateLayoutManager(); layout_panel_->InvalidateLayout(); layout_panel_->SchedulePaint(); } gfx::Insets LayoutExampleBase::TextfieldsToInsets( const InsetTextfields& textfields, const gfx::Insets& default_insets) { int top, left, bottom, right; if (!base::StringToInt(textfields.top->GetText(), &top)) top = default_insets.top(); if (!base::StringToInt(textfields.left->GetText(), &left)) left = default_insets.left(); if (!base::StringToInt(textfields.bottom->GetText(), &bottom)) bottom = default_insets.bottom(); if (!base::StringToInt(textfields.right->GetText(), &right)) right = default_insets.right(); return gfx::Insets::TLBR(std::max(0, top), std::max(0, left), std::max(0, bottom), std::max(0, right)); } Combobox* LayoutExampleBase::CreateAndAddCombobox( const std::u16string& label_text, const char* const* items, int count, base::RepeatingClosure combobox_callback) { auto* const row = control_panel_->AddChildView(std::make_unique<View>()); row->SetLayoutManager(std::make_unique<BoxLayout>( BoxLayout::Orientation::kHorizontal, gfx::Insets(), kLayoutExampleVerticalSpacing)); row->AddChildView(std::make_unique<Label>(label_text)); auto* const combobox = row->AddChildView(std::make_unique<Combobox>( std::make_unique<ExampleComboboxModel>(items, count))); combobox->SetCallback(std::move(combobox_callback)); combobox->SetAccessibleName(label_text); return combobox; } Textfield* LayoutExampleBase::CreateAndAddTextfield( const std::u16string& label_text) { auto* const row = control_panel_->AddChildView(std::make_unique<View>()); row->SetLayoutManager(std::make_unique<BoxLayout>( BoxLayout::Orientation::kHorizontal, gfx::Insets(), kLayoutExampleVerticalSpacing)); auto* label = row->AddChildView(std::make_unique<Label>(label_text)); auto* text_field = row->AddChildView(CreateCommonTextfield(this)); text_field->SetAccessibleName(label); return text_field; } void LayoutExampleBase::CreateMarginsTextFields(const std::u16string& label, InsetTextfields* textfields) { auto* const row = control_panel_->AddChildView(std::make_unique<View>()); row->SetLayoutManager(std::make_unique<BoxLayout>( BoxLayout::Orientation::kHorizontal, gfx::Insets(), kLayoutExampleVerticalSpacing)); row->AddChildView(std::make_unique<Label>(label)); auto* const container = row->AddChildView(std::make_unique<View>()); container ->SetLayoutManager(std::make_unique<BoxLayout>( BoxLayout::Orientation::kVertical, gfx::Insets(), kLayoutExampleVerticalSpacing)) ->set_cross_axis_alignment(BoxLayout::CrossAxisAlignment::kCenter); textfields->top = container->AddChildView(CreateCommonTextfieldWithAXName( this, label + u" " + l10n_util::GetStringUTF16(IDS_LAYOUT_BASE_TOP_LABEL))); auto* const middle_row = container->AddChildView(std::make_unique<View>()); middle_row->SetLayoutManager(std::make_unique<BoxLayout>( BoxLayout::Orientation::kHorizontal, gfx::Insets(), kLayoutExampleVerticalSpacing)); textfields->left = middle_row->AddChildView(CreateCommonTextfieldWithAXName( this, label + u" " + l10n_util::GetStringUTF16(IDS_LAYOUT_BASE_LEFT_LABEL))); textfields->right = middle_row->AddChildView(CreateCommonTextfieldWithAXName( this, label + u" " + l10n_util::GetStringUTF16(IDS_LAYOUT_BASE_RIGHT_LABEL))); textfields->bottom = container->AddChildView(CreateCommonTextfieldWithAXName( this, label + u" " + l10n_util::GetStringUTF16(IDS_LAYOUT_BASE_BOTTOM_LABEL))); } Checkbox* LayoutExampleBase::CreateAndAddCheckbox( const std::u16string& label_text, base::RepeatingClosure checkbox_callback) { return control_panel_->AddChildView( std::make_unique<Checkbox>(label_text, std::move(checkbox_callback))); } void LayoutExampleBase::CreateExampleView(View* container) { container->SetLayoutManager(std::make_unique<FillLayout>()); View* full_panel = container->AddChildView(std::make_unique<FullPanel>()); auto* const manager = full_panel->SetLayoutManager( std::make_unique<BoxLayout>(views::BoxLayout::Orientation::kHorizontal)); layout_panel_ = full_panel->AddChildView(std::make_unique<LayoutPanel>()); manager->SetFlexForView(layout_panel_, 3); control_panel_ = full_panel->AddChildView(std::make_unique<View>()); manager->SetFlexForView(control_panel_, 1); control_panel_->SetLayoutManager(std::make_unique<BoxLayout>( BoxLayout::Orientation::kVertical, gfx::Insets::VH(kLayoutExampleVerticalSpacing, kLayoutExampleLeftPadding), kLayoutExampleVerticalSpacing)); auto* const row = control_panel_->AddChildView(std::make_unique<View>()); row->SetLayoutManager(std::make_unique<BoxLayout>( BoxLayout::Orientation::kHorizontal, gfx::Insets(), kLayoutExampleVerticalSpacing)) ->set_cross_axis_alignment(BoxLayout::CrossAxisAlignment::kCenter); add_button_ = row->AddChildView(std::make_unique<MdTextButton>( base::BindRepeating(&LayoutExampleBase::AddButtonPressed, base::Unretained(this)), l10n_util::GetStringUTF16(IDS_LAYOUT_BASE_ADD_LABEL))); preferred_width_view_ = row->AddChildView(CreateCommonTextfieldWithAXName( this, l10n_util::GetStringUTF16(IDS_LAYOUT_BASE_PREFERRED_WIDTH_LABEL))); preferred_width_view_->SetText( base::NumberToString16(kLayoutExampleDefaultChildSize.width())); preferred_height_view_ = row->AddChildView(CreateCommonTextfieldWithAXName( this, l10n_util::GetStringUTF16(IDS_LAYOUT_BASE_PREFERRED_HEIGHT_LABEL))); preferred_height_view_->SetText( base::NumberToString16(kLayoutExampleDefaultChildSize.height())); CreateAdditionalControls(); } gfx::Size LayoutExampleBase::GetNewChildPanelPreferredSize() { int width; if (!base::StringToInt(preferred_width_view_->GetText(), &width)) width = kLayoutExampleDefaultChildSize.width(); int height; if (!base::StringToInt(preferred_height_view_->GetText(), &height)) height = kLayoutExampleDefaultChildSize.height(); return gfx::Size(std::max(0, width), std::max(0, height)); } void LayoutExampleBase::AddButtonPressed() { auto* const panel = layout_panel_->AddChildView(std::make_unique<ChildPanel>(this)); panel->SetPreferredSize(GetNewChildPanelPreferredSize()); constexpr int kChildPanelGroup = 100; panel->SetGroup(kChildPanelGroup); RefreshLayoutPanel(false); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/layout_example_base.cc
C++
unknown
12,429
// Copyright 2018 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_LAYOUT_EXAMPLE_BASE_H_ #define UI_VIEWS_EXAMPLES_LAYOUT_EXAMPLE_BASE_H_ #include "base/memory/raw_ptr.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/size.h" #include "ui/views/controls/button/checkbox.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/textfield/textfield_controller.h" #include "ui/views/examples/example_base.h" #include "ui/views/view.h" namespace views { class Combobox; namespace examples { // Provides an example of a layout manager with arbitrary specific manager and // controls. Lays out a sequence of ChildPanels in a view using the layout // manager of choice. class VIEWS_EXAMPLES_EXPORT LayoutExampleBase : public ExampleBase, public TextfieldController { public: // Grouping of multiple textfields that provide insets. struct InsetTextfields { raw_ptr<Textfield> left = nullptr; raw_ptr<Textfield> top = nullptr; raw_ptr<Textfield> right = nullptr; raw_ptr<Textfield> bottom = nullptr; }; // This view is created and added to the left-side view in the FullPanel each // time the "Add" button is pressed. It also will display Textfield controls // when the mouse is pressed over the view. These Textfields allow the user to // interactively set each margin and the "flex" for the given view. class ChildPanel : public View, public TextfieldController { public: explicit ChildPanel(LayoutExampleBase* example); ChildPanel(const ChildPanel&) = delete; ChildPanel& operator=(const ChildPanel&) = delete; ~ChildPanel() override; // View: void Layout() override; bool OnMousePressed(const ui::MouseEvent& event) override; void SetSelected(bool value); bool selected() const { return selected_; } int GetFlex() const; protected: // View: void OnThemeChanged() override; private: // TextfieldController void ContentsChanged(Textfield* sender, const std::u16string& new_contents) override; Textfield* CreateTextfield(const std::u16string& name); raw_ptr<LayoutExampleBase> example_; bool selected_ = false; raw_ptr<Textfield> flex_; InsetTextfields margin_; gfx::Size preferred_size_; }; explicit LayoutExampleBase(const char* title); LayoutExampleBase(const LayoutExampleBase&) = delete; LayoutExampleBase& operator=(const LayoutExampleBase&) = delete; ~LayoutExampleBase() override; // Force the box_layout_panel_ to layout and repaint. void RefreshLayoutPanel(bool update_layout); static gfx::Insets TextfieldsToInsets( const InsetTextfields& textfields, const gfx::Insets& default_insets = gfx::Insets()); protected: View* layout_panel() { return layout_panel_; } // Creates and adds a Combobox with a label with |label_text| to the left. // Sets |combobox_callback| as the callback for the created combobox. Combobox* CreateAndAddCombobox(const std::u16string& label_text, const char* const* items, int count, base::RepeatingClosure combobox_callback); // Creates and adds a Textfield with a label with |label_text| to the left. Textfield* CreateAndAddTextfield(const std::u16string& label_text); // Creates a set of labeled Textfields with |label_text|, and four text fields // arranged at compass points representing a set of insets. |textfields| is // populated with the fields that are created. void CreateMarginsTextFields(const std::u16string& label_text, InsetTextfields* textfields); // Creates and adds a Checkbox with label |label_text|. Sets // |checkbox_callback| as the callback for the created checkbox. Checkbox* CreateAndAddCheckbox(const std::u16string& label_text, base::RepeatingClosure checkbox_callback); // ExampleBase: // Be sure to call LayoutExampleBase::CreateExampleView() to ensure default // controls are created correctly. void CreateExampleView(View* container) final; gfx::Size GetNewChildPanelPreferredSize(); // Called by CreateExampleView() to create any additional controls required by // the specific layout. virtual void CreateAdditionalControls() = 0; // Performs layout-specific update of the layout manager. virtual void UpdateLayoutManager() = 0; private: void AddButtonPressed(); raw_ptr<View> layout_panel_ = nullptr; raw_ptr<View> control_panel_ = nullptr; raw_ptr<LabelButton> add_button_ = nullptr; raw_ptr<Textfield> preferred_width_view_ = nullptr; raw_ptr<Textfield> preferred_height_view_ = nullptr; }; } // namespace examples } // namespace views #endif // UI_VIEWS_EXAMPLES_LAYOUT_EXAMPLE_BASE_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/layout_example_base.h
C++
unknown
4,972
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/link_example.h" #include <memory> #include <utility> #include "base/strings/utf_string_conversions.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/controls/link.h" #include "ui/views/examples/examples_window.h" #include "ui/views/examples/grit/views_examples_resources.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/metadata/view_factory.h" #include "ui/views/view.h" using l10n_util::GetStringUTF16; using l10n_util::GetStringUTF8; namespace views::examples { LinkExample::LinkExample() : ExampleBase(GetStringUTF8(IDS_LINK_SELECT_LABEL).c_str()) {} LinkExample::~LinkExample() = default; void LinkExample::CreateExampleView(View* container) { auto link = views::Builder<Link>() .SetText(GetStringUTF16(IDS_LINK_CLICK_PROMPT_LABEL)) .Build(); link->SetCallback(base::BindRepeating( &LogStatus, GetStringUTF8(IDS_LINK_CLICK_CONFIRMED_LABEL))); container->SetLayoutManager(std::make_unique<FillLayout>()); container->AddChildView(std::move(link)); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/link_example.cc
C++
unknown
1,242
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_LINK_EXAMPLE_H_ #define UI_VIEWS_EXAMPLES_LINK_EXAMPLE_H_ #include "ui/views/examples/example_base.h" namespace views::examples { class VIEWS_EXAMPLES_EXPORT LinkExample : public ExampleBase { public: LinkExample(); LinkExample(const LinkExample&) = delete; LinkExample& operator=(const LinkExample&) = delete; ~LinkExample() override; // ExampleBase: void CreateExampleView(View* container) override; }; } // namespace views::examples #endif // UI_VIEWS_EXAMPLES_LINK_EXAMPLE_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/link_example.h
C++
unknown
671
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/login_bubble_dialog_example.h" #include <memory> #include <string> #include <utility> #include "base/functional/bind.h" #include "base/strings/strcat.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/border.h" #include "ui/views/controls/button/md_text_button.h" #include "ui/views/controls/label.h" #include "ui/views/examples/grit/views_examples_resources.h" #include "ui/views/layout/box_layout.h" #include "ui/views/layout/layout_provider.h" #include "ui/views/layout/table_layout.h" using l10n_util::GetStringUTF16; using l10n_util::GetStringUTF8; namespace views::examples { namespace { // Adds a label textfield pair to the login dialog's layout. Textfield* AddFormRow(LoginBubbleDialogView* bubble, const std::u16string& label_text) { Label* label = bubble->AddChildView(std::make_unique<Label>(label_text)); Textfield* textfield = bubble->AddChildView(std::make_unique<Textfield>()); textfield->SetAccessibleName(label); textfield->set_controller(bubble); constexpr int kDefaultTextfieldWidth = 30; constexpr int kMinimumTextfieldWidth = 5; textfield->SetDefaultWidthInChars(kDefaultTextfieldWidth); textfield->SetMinimumWidthInChars(kMinimumTextfieldWidth); return textfield; } } // namespace // static void LoginBubbleDialogView::Show(View* anchor_view, BubbleBorder::Arrow anchor_position, OnSubmitCallback accept_callback) { // LoginBubbleDialogView will be destroyed by the widget when the created // widget is destroyed. BubbleDialogDelegateView::CreateBubble( new LoginBubbleDialogView(anchor_view, anchor_position, std::move(accept_callback))) ->Show(); } LoginBubbleDialogView::~LoginBubbleDialogView() = default; void LoginBubbleDialogView::ContentsChanged( Textfield* sender, const std::u16string& new_contents) { SetButtonEnabled(ui::DIALOG_BUTTON_OK, !username_->GetText().empty() && !password_->GetText().empty()); DialogModelChanged(); } LoginBubbleDialogView::LoginBubbleDialogView( View* anchor_view, BubbleBorder::Arrow anchor_position, OnSubmitCallback accept_callback) : BubbleDialogDelegateView(anchor_view, anchor_position) { SetButtonEnabled(ui::DIALOG_BUTTON_OK, false); const auto on_submit = [](const LoginBubbleDialogView* bubble_view, OnSubmitCallback accept_callback) { std::move(accept_callback) .Run(bubble_view->username_->GetText(), bubble_view->password_->GetText()); }; SetAcceptCallback(base::BindOnce(on_submit, base::Unretained(this), std::move(accept_callback))); SetTitle(l10n_util::GetStringUTF16(IDS_LOGIN_TITLE_LABEL)); SetButtonLabel(ui::DIALOG_BUTTON_OK, l10n_util::GetStringUTF16(IDS_LOGIN_OK_BUTTON_LABEL)); const LayoutProvider* provider = LayoutProvider::Get(); set_margins(provider->GetDialogInsetsForContentType( views::DialogContentType::kControl, views::DialogContentType::kControl)); const int related_control_padding = provider->GetDistanceMetric(views::DISTANCE_RELATED_CONTROL_VERTICAL); const int label_padding = provider->GetDistanceMetric(views::DISTANCE_RELATED_LABEL_HORIZONTAL); SetLayoutManager(std::make_unique<TableLayout>()) ->AddColumn(LayoutAlignment::kStart, LayoutAlignment::kStretch, TableLayout::kFixedSize, TableLayout::ColumnSize::kUsePreferred, 0, 0) .AddPaddingColumn(TableLayout::kFixedSize, label_padding) .AddColumn(LayoutAlignment::kStretch, LayoutAlignment::kStretch, 1.0, TableLayout::ColumnSize::kUsePreferred, 0, 0) .AddRows(1, TableLayout::kFixedSize) .AddPaddingRow(TableLayout::kFixedSize, related_control_padding) .AddRows(1, TableLayout::kFixedSize); username_ = AddFormRow(this, l10n_util::GetStringUTF16(IDS_LOGIN_USERNAME_LABEL)); password_ = AddFormRow(this, l10n_util::GetStringUTF16(IDS_LOGIN_PASSWORD_LABEL)); password_->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD); } LoginBubbleDialogExample::LoginBubbleDialogExample() : ExampleBase(GetStringUTF8(IDS_LOGIN_SELECT_LABEL).c_str()) {} LoginBubbleDialogExample::~LoginBubbleDialogExample() = default; void LoginBubbleDialogExample::CreateExampleView(View* container) { const int related_control_padding = LayoutProvider::Get()->GetDistanceMetric( views::DISTANCE_RELATED_CONTROL_VERTICAL); const int label_padding = LayoutProvider::Get()->GetDistanceMetric( views::DISTANCE_RELATED_LABEL_HORIZONTAL); container->SetLayoutManager(std::make_unique<TableLayout>()) ->AddColumn(LayoutAlignment::kStart, LayoutAlignment::kStretch, TableLayout::kFixedSize, TableLayout::ColumnSize::kUsePreferred, 0, 0) .AddPaddingColumn(TableLayout::kFixedSize, label_padding) .AddColumn(LayoutAlignment::kStart, LayoutAlignment::kStretch, 1.0, TableLayout::ColumnSize::kUsePreferred, 0, 0) .AddPaddingRow(TableLayout::kFixedSize, related_control_padding) .AddRows(1, TableLayout::kFixedSize) .AddPaddingRow(TableLayout::kFixedSize, related_control_padding) .AddRows(1, TableLayout::kFixedSize) .AddPaddingRow(TableLayout::kFixedSize, related_control_padding) .AddRows(1, TableLayout::kFixedSize); button_ = container->AddChildView(std::make_unique<MdTextButton>( Button::PressedCallback(), GetStringUTF16(IDS_LOGIN_SHOW_BUTTON_LABEL))); button_->SetCallback(base::BindRepeating( &LoginBubbleDialogView::Show, button_, BubbleBorder::TOP_LEFT, base::BindRepeating(&LoginBubbleDialogExample::OnSubmit, base::Unretained(this)))); container->AddChildView(std::make_unique<View>()); username_label_ = container->AddChildView(std::make_unique<Label>( l10n_util::GetStringUTF16(IDS_LOGIN_USERNAME_LABEL))); username_label_->SetVisible(false); username_input_ = container->AddChildView(std::make_unique<Label>()); password_label_ = container->AddChildView(std::make_unique<Label>( l10n_util::GetStringUTF16(IDS_LOGIN_PASSWORD_LABEL))); password_label_->SetVisible(false); password_input_ = container->AddChildView(std::make_unique<Label>()); } void LoginBubbleDialogExample::OnSubmit(std::u16string username, std::u16string password) { username_label_->SetVisible(true); username_input_->SetText(username); password_label_->SetVisible(true); password_input_->SetText(password); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/login_bubble_dialog_example.cc
C++
unknown
6,878
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_LOGIN_BUBBLE_DIALOG_EXAMPLE_H_ #define UI_VIEWS_EXAMPLES_LOGIN_BUBBLE_DIALOG_EXAMPLE_H_ #include <string> #include "base/memory/raw_ptr.h" #include "ui/views/bubble/bubble_border.h" #include "ui/views/bubble/bubble_dialog_delegate_view.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/controls/textfield/textfield_controller.h" #include "ui/views/examples/example_base.h" namespace views { class LabelButton; namespace examples { class LoginBubbleDialogView : public BubbleDialogDelegateView, public TextfieldController { public: using OnSubmitCallback = base::OnceCallback<void(std::u16string username, std::u16string password)>; static void Show(View* anchor_view, BubbleBorder::Arrow anchor_position, OnSubmitCallback accept_callback); ~LoginBubbleDialogView() override; // TextfieldController: void ContentsChanged(Textfield* sender, const std::u16string& new_contents) override; private: LoginBubbleDialogView(View* anchor_view, BubbleBorder::Arrow anchor_position, OnSubmitCallback accept_callback); raw_ptr<Textfield> username_ = nullptr; raw_ptr<Textfield> password_ = nullptr; }; // Instantiates the login dialog example. class LoginBubbleDialogExample : public ExampleBase { public: LoginBubbleDialogExample(); ~LoginBubbleDialogExample() override; // ExampleBase: void CreateExampleView(View* container) override; // LoginBubbleDialogController: void OnSubmit(std::u16string username, std::u16string password); private: raw_ptr<LabelButton> button_ = nullptr; raw_ptr<Label> username_label_ = nullptr; raw_ptr<Label> username_input_ = nullptr; raw_ptr<Label> password_label_ = nullptr; raw_ptr<Label> password_input_ = nullptr; }; } // namespace examples } // namespace views #endif // UI_VIEWS_EXAMPLES_LOGIN_BUBBLE_DIALOG_EXAMPLE_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/login_bubble_dialog_example.h
C++
unknown
2,192
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/menu_example.h" #include <memory> #include <set> #include <utility> #include "base/logging.h" #include "base/strings/utf_string_conversions.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/models/simple_menu_model.h" #include "ui/views/border.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/button/menu_button.h" #include "ui/views/controls/menu/menu_runner.h" #include "ui/views/examples/examples_color_id.h" #include "ui/views/examples/grit/views_examples_resources.h" #include "ui/views/layout/flex_layout.h" #include "ui/views/layout/layout_provider.h" #include "ui/views/metadata/view_factory.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" using l10n_util::GetStringUTF16; using l10n_util::GetStringUTF8; namespace views::examples { class ExampleMenuModel : public ui::SimpleMenuModel, public ui::SimpleMenuModel::Delegate { public: ExampleMenuModel(); ExampleMenuModel(const ExampleMenuModel&) = delete; ExampleMenuModel& operator=(const ExampleMenuModel&) = delete; // ui::SimpleMenuModel::Delegate: bool IsCommandIdChecked(int command_id) const override; bool IsCommandIdEnabled(int command_id) const override; void ExecuteCommand(int command_id, int event_flags) override; private: enum GroupID { GROUP_MAKE_DECISION, }; enum CommandID { COMMAND_DO_SOMETHING, COMMAND_SELECT_ASCII, COMMAND_SELECT_UTF8, COMMAND_SELECT_UTF16, COMMAND_CHECK_APPLE, COMMAND_CHECK_ORANGE, COMMAND_CHECK_KIWI, COMMAND_GO_HOME, }; std::unique_ptr<ui::SimpleMenuModel> submenu_; std::set<int> checked_fruits_; int current_encoding_command_id_ = COMMAND_SELECT_ASCII; }; class ExampleMenuButton : public MenuButton { public: explicit ExampleMenuButton(const std::u16string& test = std::u16string()); ExampleMenuButton(const ExampleMenuButton&) = delete; ExampleMenuButton& operator=(const ExampleMenuButton&) = delete; ~ExampleMenuButton() override; private: void ButtonPressed(); ui::SimpleMenuModel* GetMenuModel(); std::unique_ptr<ExampleMenuModel> menu_model_; std::unique_ptr<MenuRunner> menu_runner_; }; BEGIN_VIEW_BUILDER(/* no export */, ExampleMenuButton, MenuButton) END_VIEW_BUILDER } // namespace views::examples DEFINE_VIEW_BUILDER(/* no export */, views::examples::ExampleMenuButton) namespace views::examples { // ExampleMenuModel --------------------------------------------------------- ExampleMenuModel::ExampleMenuModel() : ui::SimpleMenuModel(this) { AddItem(COMMAND_DO_SOMETHING, GetStringUTF16(IDS_MENU_DO_SOMETHING_LABEL)); AddSeparator(ui::NORMAL_SEPARATOR); AddRadioItem(COMMAND_SELECT_ASCII, GetStringUTF16(IDS_MENU_ASCII_LABEL), GROUP_MAKE_DECISION); AddRadioItem(COMMAND_SELECT_UTF8, GetStringUTF16(IDS_MENU_UTF8_LABEL), GROUP_MAKE_DECISION); AddRadioItem(COMMAND_SELECT_UTF16, GetStringUTF16(IDS_MENU_UTF16_LABEL), GROUP_MAKE_DECISION); AddSeparator(ui::NORMAL_SEPARATOR); AddCheckItem(COMMAND_CHECK_APPLE, GetStringUTF16(IDS_MENU_APPLE_LABEL)); AddCheckItem(COMMAND_CHECK_ORANGE, GetStringUTF16(IDS_MENU_ORANGE_LABEL)); AddCheckItem(COMMAND_CHECK_KIWI, GetStringUTF16(IDS_MENU_KIWI_LABEL)); AddSeparator(ui::NORMAL_SEPARATOR); AddItem(COMMAND_GO_HOME, GetStringUTF16(IDS_MENU_GO_HOME_LABEL)); submenu_ = std::make_unique<ui::SimpleMenuModel>(this); submenu_->AddItem(COMMAND_DO_SOMETHING, GetStringUTF16(IDS_MENU_DO_SOMETHING_2_LABEL)); AddSubMenu(0, GetStringUTF16(IDS_MENU_SUBMENU_LABEL), submenu_.get()); } bool ExampleMenuModel::IsCommandIdChecked(int command_id) const { // Radio items. if (command_id == current_encoding_command_id_) return true; // Check items. if (checked_fruits_.find(command_id) != checked_fruits_.end()) return true; return false; } bool ExampleMenuModel::IsCommandIdEnabled(int command_id) const { // All commands are enabled except for COMMAND_GO_HOME. return command_id != COMMAND_GO_HOME; } void ExampleMenuModel::ExecuteCommand(int command_id, int event_flags) { switch (command_id) { case COMMAND_DO_SOMETHING: { VLOG(0) << "Done something"; break; } // Radio items. case COMMAND_SELECT_ASCII: { current_encoding_command_id_ = COMMAND_SELECT_ASCII; VLOG(0) << "Selected ASCII"; break; } case COMMAND_SELECT_UTF8: { current_encoding_command_id_ = COMMAND_SELECT_UTF8; VLOG(0) << "Selected UTF-8"; break; } case COMMAND_SELECT_UTF16: { current_encoding_command_id_ = COMMAND_SELECT_UTF16; VLOG(0) << "Selected UTF-16"; break; } // Check items. case COMMAND_CHECK_APPLE: case COMMAND_CHECK_ORANGE: case COMMAND_CHECK_KIWI: { // Print what fruit is checked. const char* checked_fruit = ""; if (command_id == COMMAND_CHECK_APPLE) checked_fruit = "Apple"; else if (command_id == COMMAND_CHECK_ORANGE) checked_fruit = "Orange"; else if (command_id == COMMAND_CHECK_KIWI) checked_fruit = "Kiwi"; // Update the check status. auto iter = checked_fruits_.find(command_id); if (iter == checked_fruits_.end()) { DVLOG(1) << "Checked " << checked_fruit; checked_fruits_.insert(command_id); } else { DVLOG(1) << "Unchecked " << checked_fruit; checked_fruits_.erase(iter); } break; } } } // ExampleMenuButton ----------------------------------------------------------- ExampleMenuButton::ExampleMenuButton(const std::u16string& test) : MenuButton(base::BindRepeating(&ExampleMenuButton::ButtonPressed, base::Unretained(this)), test) {} ExampleMenuButton::~ExampleMenuButton() = default; void ExampleMenuButton::ButtonPressed() { menu_runner_ = std::make_unique<MenuRunner>(GetMenuModel(), MenuRunner::HAS_MNEMONICS); gfx::Point screen_loc; views::View::ConvertPointToScreen(this, &screen_loc); gfx::Rect bounds(screen_loc, this->size()); menu_runner_->RunMenuAt(GetWidget()->GetTopLevelWidget(), button_controller(), bounds, MenuAnchorPosition::kTopLeft, ui::MENU_SOURCE_NONE); } ui::SimpleMenuModel* ExampleMenuButton::GetMenuModel() { if (!menu_model_) menu_model_ = std::make_unique<ExampleMenuModel>(); return menu_model_.get(); } MenuExample::MenuExample() : ExampleBase(GetStringUTF8(IDS_MENU_SELECT_LABEL).c_str()) {} MenuExample::~MenuExample() = default; void MenuExample::CreateExampleView(View* container) { container->SetLayoutManager(std::make_unique<FlexLayout>()) ->SetInteriorMargin(gfx::Insets(10)) .SetCrossAxisAlignment(LayoutAlignment::kStart); // We add a button to open a menu. auto example_menu_button = Builder<ExampleMenuButton>() .SetText(GetStringUTF16(IDS_MENU_BUTTON_LABEL)) .Build(); example_menu_button->SetBorder(CreatePaddedBorder( CreateThemedRoundedRectBorder(1, 5, kColorMenuButtonExampleBorder), LayoutProvider::Get()->GetInsetsMetric( InsetsMetric::INSETS_LABEL_BUTTON))); container->AddChildView(std::move(example_menu_button)); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/menu_example.cc
C++
unknown
7,527
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_MENU_EXAMPLE_H_ #define UI_VIEWS_EXAMPLES_MENU_EXAMPLE_H_ #include "ui/views/examples/example_base.h" namespace views::examples { // MenuExample demonstrates how to use the MenuModelAdapter and MenuRunner // classes. class VIEWS_EXAMPLES_EXPORT MenuExample : public ExampleBase { public: MenuExample(); MenuExample(const MenuExample&) = delete; MenuExample& operator=(const MenuExample&) = delete; ~MenuExample() override; // ExampleBase: void CreateExampleView(View* container) override; }; } // namespace views::examples #endif // UI_VIEWS_EXAMPLES_MENU_EXAMPLE_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/menu_example.h
C++
unknown
760
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/message_box_example.h" #include <memory> #include <utility> #include "base/strings/utf_string_conversions.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/message_box_view.h" #include "ui/views/examples/examples_window.h" #include "ui/views/examples/grit/views_examples_resources.h" #include "ui/views/layout/box_layout.h" #include "ui/views/layout/flex_layout.h" #include "ui/views/view.h" using l10n_util::GetStringUTF16; using l10n_util::GetStringUTF8; namespace views::examples { MessageBoxExample::MessageBoxExample() : ExampleBase(GetStringUTF8(IDS_MESSAGE_SELECT_LABEL).c_str()) {} MessageBoxExample::~MessageBoxExample() = default; void MessageBoxExample::CreateExampleView(View* container) { container->SetLayoutManager( std::make_unique<BoxLayout>(BoxLayout::Orientation::kVertical)); message_box_view_ = container->AddChildView(std::make_unique<MessageBoxView>( GetStringUTF16(IDS_MESSAGE_INTRO_LABEL))); message_box_view_->SetCheckBoxLabel( GetStringUTF16(IDS_MESSAGE_CHECK_BOX_LABEL)); View* button_panel = container->AddChildView(std::make_unique<View>()); button_panel->SetLayoutManager(std::make_unique<FlexLayout>()) ->SetOrientation(LayoutOrientation::kHorizontal) .SetMainAxisAlignment(LayoutAlignment::kStart); button_panel->AddChildView(std::make_unique<LabelButton>( base::BindRepeating(&MessageBoxExample::StatusButtonPressed, base::Unretained(this)), GetStringUTF16(IDS_MESSAGE_STATUS_LABEL))); button_panel->AddChildView(std::make_unique<LabelButton>( base::BindRepeating( [](MessageBoxView* message_box) { message_box->SetCheckBoxSelected( !message_box->IsCheckBoxSelected()); }, base::Unretained(message_box_view_)), GetStringUTF16(IDS_MESSAGE_TOGGLE_LABEL))); } void MessageBoxExample::StatusButtonPressed() { const bool selected = message_box_view_->IsCheckBoxSelected(); message_box_view_->SetCheckBoxLabel( GetStringUTF16(selected ? IDS_MESSAGE_ON_LABEL : IDS_MESSAGE_OFF_LABEL)); LogStatus(GetStringUTF8(selected ? IDS_MESSAGE_CHECK_SELECTED_LABEL : IDS_MESSAGE_CHECK_NOT_SELECTED_LABEL) .c_str()); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/message_box_example.cc
C++
unknown
2,537
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_MESSAGE_BOX_EXAMPLE_H_ #define UI_VIEWS_EXAMPLES_MESSAGE_BOX_EXAMPLE_H_ #include "base/memory/raw_ptr.h" #include "ui/views/examples/example_base.h" namespace views { class MessageBoxView; namespace examples { // A MessageBoxView example. This tests some of checkbox features as well. class VIEWS_EXAMPLES_EXPORT MessageBoxExample : public ExampleBase { public: MessageBoxExample(); MessageBoxExample(const MessageBoxExample&) = delete; MessageBoxExample& operator=(const MessageBoxExample&) = delete; ~MessageBoxExample() override; // ExampleBase: void CreateExampleView(View* container) override; private: void StatusButtonPressed(); // The MessageBoxView to be tested. raw_ptr<MessageBoxView> message_box_view_; }; } // namespace examples } // namespace views #endif // UI_VIEWS_EXAMPLES_MESSAGE_BOX_EXAMPLE_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/message_box_example.h
C++
unknown
1,018
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/multiline_example.h" #include <stddef.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include "third_party/skia/include/core/SkColor.h" #include "ui/base/l10n/l10n_util.h" #include "ui/events/event.h" #include "ui/gfx/range/range.h" #include "ui/gfx/render_text.h" #include "ui/views/background.h" #include "ui/views/border.h" #include "ui/views/controls/button/checkbox.h" #include "ui/views/controls/label.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/examples/examples_color_id.h" #include "ui/views/examples/grit/views_examples_resources.h" #include "ui/views/layout/table_layout.h" #include "ui/views/view.h" using l10n_util::GetStringUTF16; using l10n_util::GetStringUTF8; namespace views::examples { namespace { gfx::Range ClampRange(gfx::Range range, size_t max) { range.set_start(std::min(range.start(), max)); range.set_end(std::min(range.end(), max)); return range; } // A Label with a clamped preferred width to demonstrate wrapping. class PreferredSizeLabel : public Label { public: PreferredSizeLabel() = default; PreferredSizeLabel(const PreferredSizeLabel&) = delete; PreferredSizeLabel& operator=(const PreferredSizeLabel&) = delete; ~PreferredSizeLabel() override = default; // Label: gfx::Size CalculatePreferredSize() const override { return gfx::Size(50, Label::CalculatePreferredSize().height()); } }; } // namespace // A simple View that hosts a RenderText object. class MultilineExample::RenderTextView : public View { public: RenderTextView() : render_text_(gfx::RenderText::CreateRenderText()) { render_text_->SetHorizontalAlignment(gfx::ALIGN_TO_HEAD); render_text_->SetMultiline(true); SetBorder(CreateThemedSolidBorder( 2, ExamplesColorIds::kColorMultilineExampleBorder)); } RenderTextView(const RenderTextView&) = delete; RenderTextView& operator=(const RenderTextView&) = delete; void OnPaint(gfx::Canvas* canvas) override { View::OnPaint(canvas); render_text_->Draw(canvas); } gfx::Size CalculatePreferredSize() const override { // Turn off multiline mode to get the single-line text size, which is the // preferred size for this view. render_text_->SetMultiline(false); gfx::Size size(render_text_->GetContentWidth(), render_text_->GetStringSize().height()); size.Enlarge(GetInsets().width(), GetInsets().height()); render_text_->SetMultiline(true); return size; } int GetHeightForWidth(int w) const override { // TODO(ckocagil): Why does this happen? if (w == 0) return View::GetHeightForWidth(w); const gfx::Rect old_rect = render_text_->display_rect(); gfx::Rect rect = old_rect; rect.set_width(w - GetInsets().width()); render_text_->SetDisplayRect(rect); int height = render_text_->GetStringSize().height() + GetInsets().height(); render_text_->SetDisplayRect(old_rect); return height; } void OnThemeChanged() override { View::OnThemeChanged(); UpdateColors(); } void SetText(const std::u16string& new_contents) { // Color and style the text inside |test_range| to test colors and styles. const size_t range_max = new_contents.length(); gfx::Range bold_range = ClampRange(gfx::Range(4, 10), range_max); gfx::Range italic_range = ClampRange(gfx::Range(7, 13), range_max); render_text_->SetText(new_contents); render_text_->SetStyle(gfx::TEXT_STYLE_UNDERLINE, false); render_text_->ApplyStyle(gfx::TEXT_STYLE_ITALIC, true, italic_range); render_text_->ApplyWeight(gfx::Font::Weight::BOLD, bold_range); UpdateColors(); InvalidateLayout(); } void SetMaxLines(int max_lines) { render_text_->SetMaxLines(max_lines); render_text_->SetElideBehavior(max_lines ? gfx::ELIDE_TAIL : gfx::NO_ELIDE); } private: void OnBoundsChanged(const gfx::Rect& previous_bounds) override { render_text_->SetDisplayRect(GetContentsBounds()); } void UpdateColors() { const auto* cp = GetColorProvider(); if (!cp) return; render_text_->SetColor( cp->GetColor(ExamplesColorIds::kColorMultilineExampleForeground)); render_text_->set_selection_color(cp->GetColor( ExamplesColorIds::kColorMultilineExampleSelectionForeground)); render_text_->set_selection_background_focused_color(cp->GetColor( ExamplesColorIds::kColorMultilineExampleSelectionBackground)); const size_t range_max = render_text_->text().length(); gfx::Range color_range = ClampRange(gfx::Range(1, 21), range_max); render_text_->ApplyColor( cp->GetColor(ExamplesColorIds::kColorMultilineExampleColorRange), color_range); render_text_->ApplyStyle(gfx::TEXT_STYLE_UNDERLINE, true, color_range); } std::unique_ptr<gfx::RenderText> render_text_; }; MultilineExample::MultilineExample() : ExampleBase(GetStringUTF8(IDS_MULTILINE_SELECT_LABEL).c_str()) {} MultilineExample::~MultilineExample() = default; void MultilineExample::CreateExampleView(View* container) { container->SetLayoutManager(std::make_unique<views::TableLayout>()) ->AddColumn(LayoutAlignment::kStart, LayoutAlignment::kCenter, TableLayout::kFixedSize, TableLayout::ColumnSize::kUsePreferred, 0, 0) .AddColumn(LayoutAlignment::kStretch, LayoutAlignment::kStretch, 1.0f, TableLayout::ColumnSize::kFixed, 0, 0) .AddRows(4, TableLayout::kFixedSize); const std::u16string kTestString = u"qwertyالرئيسيةasdfgh"; container->AddChildView( std::make_unique<Label>(GetStringUTF16(IDS_MULTILINE_RENDER_TEXT_LABEL))); render_text_view_ = container->AddChildView(std::make_unique<RenderTextView>()); render_text_view_->SetText(kTestString); label_checkbox_ = container->AddChildView(std::make_unique<Checkbox>( GetStringUTF16(IDS_MULTILINE_LABEL), base::BindRepeating( [](MultilineExample* example) { example->label_->SetText(example->label_checkbox_->GetChecked() ? example->textfield_->GetText() : std::u16string()); }, base::Unretained(this)))); label_checkbox_->SetChecked(true); label_checkbox_->SetRequestFocusOnPress(false); label_ = container->AddChildView(std::make_unique<PreferredSizeLabel>()); label_->SetText(kTestString); label_->SetMultiLine(true); label_->SetBorder(CreateThemedSolidBorder( 2, ExamplesColorIds::kColorMultilineExampleLabelBorder)); elision_checkbox_ = container->AddChildView(std::make_unique<Checkbox>( GetStringUTF16(IDS_MULTILINE_ELIDE_LABEL), base::BindRepeating( [](MultilineExample* example) { example->render_text_view_->SetMaxLines( example->elision_checkbox_->GetChecked() ? 3 : 0); }, base::Unretained(this)))); elision_checkbox_->SetChecked(false); elision_checkbox_->SetRequestFocusOnPress(false); container->AddChildView(std::make_unique<View>()); auto* label = container->AddChildView( std::make_unique<Label>(GetStringUTF16(IDS_MULTILINE_SAMPLE_TEXT_LABEL))); textfield_ = container->AddChildView(std::make_unique<Textfield>()); textfield_->set_controller(this); textfield_->SetText(kTestString); textfield_->SetAccessibleName(label); } void MultilineExample::ContentsChanged(Textfield* sender, const std::u16string& new_contents) { render_text_view_->SetText(new_contents); if (label_checkbox_->GetChecked()) label_->SetText(new_contents); example_view()->InvalidateLayout(); example_view()->SchedulePaint(); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/multiline_example.cc
C++
unknown
7,913
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_MULTILINE_EXAMPLE_H_ #define UI_VIEWS_EXAMPLES_MULTILINE_EXAMPLE_H_ #include "base/memory/raw_ptr.h" #include "ui/views/controls/textfield/textfield_controller.h" #include "ui/views/examples/example_base.h" namespace views { class Checkbox; class Label; namespace examples { // An example that compares the multiline rendering of different controls. class VIEWS_EXAMPLES_EXPORT MultilineExample : public ExampleBase, public TextfieldController { public: MultilineExample(); MultilineExample(const MultilineExample&) = delete; MultilineExample& operator=(const MultilineExample&) = delete; ~MultilineExample() override; // ExampleBase: void CreateExampleView(View* container) override; private: class RenderTextView; // TextfieldController: void ContentsChanged(Textfield* sender, const std::u16string& new_contents) override; raw_ptr<RenderTextView> render_text_view_ = nullptr; raw_ptr<Label> label_ = nullptr; raw_ptr<Textfield> textfield_ = nullptr; // Checkbox to enable and disable text rendering in |label_|. raw_ptr<Checkbox> label_checkbox_ = nullptr; // Checkbox to toggle text elision in |render_text_view_|. raw_ptr<Checkbox> elision_checkbox_ = nullptr; }; } // namespace examples } // namespace views #endif // UI_VIEWS_EXAMPLES_MULTILINE_EXAMPLE_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/multiline_example.h
C++
unknown
1,555
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/notification_example.h" #include <algorithm> #include <memory> #include <string> #include <vector> #include "base/memory/scoped_refptr.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkPaint.h" #include "ui/base/l10n/l10n_util.h" #include "ui/color/color_provider.h" #include "ui/gfx/image/image.h" #include "ui/message_center/message_center.h" #include "ui/message_center/public/cpp/notification.h" #include "ui/message_center/public/cpp/notification_delegate.h" #include "ui/message_center/public/cpp/notification_types.h" #include "ui/message_center/public/cpp/notifier_id.h" #include "ui/message_center/views/notification_view.h" #include "ui/views/examples/examples_color_id.h" #include "ui/views/examples/grit/views_examples_resources.h" #include "ui/views/layout/flex_layout.h" #include "ui/views/layout/flex_layout_types.h" #include "url/gurl.h" namespace { gfx::Image CreateTestImage(const gfx::Size& size, const ui::ColorProvider* provider) { SkBitmap bitmap; bitmap.allocN32Pixels(size.width(), size.height()); bitmap.eraseColor(SK_ColorTRANSPARENT); SkCanvas canvas(bitmap); SkScalar radius = std::min(size.width(), size.height()) * SK_ScalarHalf; SkPaint paint; paint.setColor(provider->GetColor( views::examples::ExamplesColorIds::kColorNotificationExampleImage)); paint.setStyle(SkPaint::kFill_Style); paint.setAntiAlias(true); canvas.drawCircle(radius, radius, radius, paint); return gfx::Image::CreateFrom1xBitmap(bitmap); } } // namespace namespace views::examples { NotificationExample::NotificationExample() : ExampleBase( l10n_util::GetStringUTF8(IDS_NOTIFICATION_SELECT_LABEL).c_str()) { message_center::MessageCenter::Initialize(); } NotificationExample::~NotificationExample() { message_center::MessageCenter::Shutdown(); observer_.Reset(); } void NotificationExample::CreateExampleView(View* container) { container->SetLayoutManager(std::make_unique<FlexLayout>()) ->SetCrossAxisAlignment(LayoutAlignment::kStart); observer_.Observe(container); } void NotificationExample::OnViewAddedToWidget(View* observed_view) { auto* const cp = observed_view->GetColorProvider(); message_center::RichNotificationData data; data.settings_button_handler = message_center::SettingsButtonHandler::INLINE; message_center::Notification notification( message_center::NOTIFICATION_TYPE_SIMPLE, "id", u"Title", u"Message", ui::ImageModel::FromImage(CreateTestImage(gfx::Size(80, 80), cp)), std::u16string(), GURL(), message_center::NotifierId( GURL(), l10n_util::GetStringUTF16(IDS_NOTIFICATION_TITLE_LABEL)), data, base::MakeRefCounted<message_center::NotificationDelegate>()); notification.set_small_image(CreateTestImage(gfx::Size(16, 16), cp)); notification.set_image(CreateTestImage(gfx::Size(320, 240), cp)); std::vector<message_center::ButtonInfo> buttons = { message_center::ButtonInfo(u"No-op"), message_center::ButtonInfo(u"Text input")}; buttons[1].placeholder = u"Placeholder"; notification.set_buttons(buttons); message_center::MessageCenter::Get()->AddNotification( std::make_unique<message_center::Notification>(notification)); auto* const notification_view = observed_view->AddChildView( std::make_unique<message_center::NotificationView>(notification)); notification_view->SetProperty( views::kFlexBehaviorKey, FlexSpecification(MinimumFlexSizeRule::kPreferredSnapToMinimum, MaximumFlexSizeRule::kPreferred)); } void NotificationExample::OnViewIsDeleting(View* observed_view) { observer_.Reset(); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/notification_example.cc
C++
unknown
3,947
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_NOTIFICATION_EXAMPLE_H_ #define UI_VIEWS_EXAMPLES_NOTIFICATION_EXAMPLE_H_ #include "base/scoped_observation.h" #include "ui/views/examples/example_base.h" #include "ui/views/view.h" #include "ui/views/view_observer.h" namespace views::examples { class VIEWS_EXAMPLES_EXPORT NotificationExample : public ExampleBase, public ViewObserver { public: NotificationExample(); NotificationExample(const NotificationExample&) = delete; NotificationExample& operator=(const NotificationExample&) = delete; ~NotificationExample() override; // ExampleBase: void CreateExampleView(View* container) override; // ViewObserver: void OnViewAddedToWidget(View* observed_view) override; void OnViewIsDeleting(View* observed_view) override; private: base::ScopedObservation<View, ViewObserver> observer_{this}; }; } // namespace views::examples #endif // UI_VIEWS_EXAMPLES_NOTIFICATION_EXAMPLE_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/notification_example.h
C++
unknown
1,129
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/progress_bar_example.h" #include <algorithm> #include <memory> #include <utility> #include "base/strings/utf_string_conversions.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/controls/button/md_text_button.h" #include "ui/views/controls/progress_bar.h" #include "ui/views/examples/grit/views_examples_resources.h" #include "ui/views/layout/table_layout.h" #include "ui/views/view.h" using l10n_util::GetStringUTF16; using l10n_util::GetStringUTF8; namespace views::examples { ProgressBarExample::ProgressBarExample() : ExampleBase(GetStringUTF8(IDS_PROGRESS_SELECT_LABEL).c_str()) {} ProgressBarExample::~ProgressBarExample() = default; void ProgressBarExample::CreateExampleView(View* container) { container->SetLayoutManager(std::make_unique<views::TableLayout>()) ->AddColumn(LayoutAlignment::kEnd, LayoutAlignment::kCenter, TableLayout::kFixedSize, TableLayout::ColumnSize::kUsePreferred, 0, 0) .AddPaddingColumn(0, 8) .AddColumn(LayoutAlignment::kStretch, LayoutAlignment::kCenter, 1.0f, TableLayout::ColumnSize::kFixed, 200, 0) .AddPaddingColumn(0, 8) .AddColumn(LayoutAlignment::kStart, LayoutAlignment::kCenter, TableLayout::kFixedSize, TableLayout::ColumnSize::kUsePreferred, 0, 0) .AddRows(1, TableLayout::kFixedSize) .AddPaddingRow(TableLayout::kFixedSize, 10) .AddRows(1, TableLayout::kFixedSize) .AddPaddingRow(TableLayout::kFixedSize, 10) .AddRows(1, TableLayout::kFixedSize); container->AddChildView(std::make_unique<views::MdTextButton>( base::BindRepeating(&ProgressBarExample::ButtonPressed, base::Unretained(this), -0.1), u"-")); progress_bar_ = container->AddChildView(std::make_unique<ProgressBar>()); container->AddChildView(std::make_unique<views::MdTextButton>( base::BindRepeating(&ProgressBarExample::ButtonPressed, base::Unretained(this), 0.1), u"+")); container->AddChildView( std::make_unique<Label>(GetStringUTF16(IDS_PROGRESS_LOADER_LABEL))); container->AddChildView(std::make_unique<ProgressBar>())->SetValue(-1); container->AddChildView(std::make_unique<View>()); container->AddChildView( std::make_unique<Label>(GetStringUTF16(IDS_PROGRESS_LOADER_SHORT_LABEL))); container->AddChildView(std::make_unique<ProgressBar>(2))->SetValue(-1); } void ProgressBarExample::ButtonPressed(double step) { current_percent_ = std::clamp(current_percent_ + step, 0.0, 1.0); progress_bar_->SetValue(current_percent_); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/progress_bar_example.cc
C++
unknown
2,825
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_PROGRESS_BAR_EXAMPLE_H_ #define UI_VIEWS_EXAMPLES_PROGRESS_BAR_EXAMPLE_H_ #include "base/memory/raw_ptr.h" #include "ui/views/examples/example_base.h" namespace views { class ProgressBar; namespace examples { class VIEWS_EXAMPLES_EXPORT ProgressBarExample : public ExampleBase { public: ProgressBarExample(); ProgressBarExample(const ProgressBarExample&) = delete; ProgressBarExample& operator=(const ProgressBarExample&) = delete; ~ProgressBarExample() override; // ExampleBase: void CreateExampleView(View* container) override; private: void ButtonPressed(double step); raw_ptr<ProgressBar> progress_bar_ = nullptr; double current_percent_ = 0.0; }; } // namespace examples } // namespace views #endif // UI_VIEWS_EXAMPLES_PROGRESS_BAR_EXAMPLE_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/progress_bar_example.h
C++
unknown
953
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/radio_button_example.h" #include <stddef.h> #include <memory> #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/button/radio_button.h" #include "ui/views/examples/examples_window.h" #include "ui/views/examples/grit/views_examples_resources.h" #include "ui/views/layout/box_layout.h" #include "ui/views/view.h" using l10n_util::GetStringUTF16; using l10n_util::GetStringUTF8; namespace views::examples { namespace { const char* BoolToOnOff(bool value) { return value ? "on" : "off"; } } // namespace RadioButtonExample::RadioButtonExample() : ExampleBase(GetStringUTF8(IDS_RADIO_BUTTON_SELECT_LABEL).c_str()) {} RadioButtonExample::~RadioButtonExample() = default; void RadioButtonExample::CreateExampleView(View* container) { container->SetLayoutManager( std::make_unique<views::BoxLayout>(BoxLayout::Orientation::kVertical)); const int group = 1; for (size_t i = 0; i < 3; ++i) { radio_buttons_.push_back( container->AddChildView(std::make_unique<RadioButton>( base::UTF8ToUTF16(base::StringPrintf( "Radio %d in group %d", static_cast<int>(i) + 1, group)), group))); } container->AddChildView(std::make_unique<LabelButton>( base::BindRepeating(&RadioButton::SetChecked, base::Unretained(radio_buttons_[2]), true), GetStringUTF16(IDS_RADIO_BUTTON_SELECT_BUTTON_LABEL))); container->AddChildView(std::make_unique<LabelButton>( base::BindRepeating(&RadioButtonExample::StatusButtonPressed, base::Unretained(this)), GetStringUTF16(IDS_RADIO_BUTTON_STATUS_LABEL))); } void RadioButtonExample::StatusButtonPressed() { // Show the state of radio buttons. PrintStatus("Group: 1:%s, 2:%s, 3:%s", BoolToOnOff(radio_buttons_[0]->GetChecked()), BoolToOnOff(radio_buttons_[1]->GetChecked()), BoolToOnOff(radio_buttons_[2]->GetChecked())); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/radio_button_example.cc
C++
unknown
2,352
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_RADIO_BUTTON_EXAMPLE_H_ #define UI_VIEWS_EXAMPLES_RADIO_BUTTON_EXAMPLE_H_ #include <vector> #include "ui/views/examples/example_base.h" namespace views { class RadioButton; namespace examples { class VIEWS_EXAMPLES_EXPORT RadioButtonExample : public ExampleBase { public: RadioButtonExample(); RadioButtonExample(const RadioButtonExample&) = delete; RadioButtonExample& operator=(const RadioButtonExample&) = delete; ~RadioButtonExample() override; // ExampleBase: void CreateExampleView(View* container) override; private: void StatusButtonPressed(); // Group of 3 radio buttons. std::vector<RadioButton*> radio_buttons_; }; } // namespace examples } // namespace views #endif // UI_VIEWS_EXAMPLES_RADIO_BUTTON_EXAMPLE_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/radio_button_example.h
C++
unknown
929
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/scroll_view_example.h" #include <memory> #include <utility> #include "base/strings/utf_string_conversions.h" #include "cc/paint/paint_flags.h" #include "ui/base/l10n/l10n_util.h" #include "ui/color/color_provider.h" #include "ui/gfx/canvas.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/skia_paint_util.h" #include "ui/views/background.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/button/radio_button.h" #include "ui/views/examples/examples_color_id.h" #include "ui/views/examples/grit/views_examples_resources.h" #include "ui/views/layout/box_layout_view.h" #include "ui/views/layout/flex_layout.h" #include "ui/views/layout/flex_layout_types.h" #include "ui/views/view.h" #include "ui/views/view_class_properties.h" using l10n_util::GetStringUTF16; using l10n_util::GetStringUTF8; namespace views::examples { // ScrollView's content, which draws gradient color on background. // TODO(oshima): add child views as well. class ScrollViewExample::ScrollableView : public BoxLayoutView { public: ScrollableView() { SetColor(ExamplesColorIds::kColorScrollViewExampleTallFrom, ExamplesColorIds::kColorScrollViewExampleTallTo); SetOrientation(views::BoxLayout::Orientation::kVertical); SetInsideBorderInsets(gfx::Insets()); SetBetweenChildSpacing(0); const auto add_child = [this](std::unique_ptr<View> view) { auto* container = AddChildView(std::make_unique<BoxLayoutView>()); container->SetOrientation(views::BoxLayout::Orientation::kVertical); container->AddChildView(std::move(view)); }; add_child(std::make_unique<LabelButton>( Button::PressedCallback(), GetStringUTF16(IDS_SCROLL_VIEW_BUTTON_LABEL))); add_child(std::make_unique<RadioButton>( GetStringUTF16(IDS_SCROLL_VIEW_RADIO_BUTTON_LABEL), 0)); SetDefaultFlex(1); } ScrollableView(const ScrollableView&) = delete; ScrollableView& operator=(const ScrollableView&) = delete; void SetColor(ui::ColorId from_id, ui::ColorId to_id) { from_color_id_ = from_id; to_color_id_ = to_id; } std::pair<SkColor, SkColor> GetColors() const { auto* const cp = GetColorProvider(); if (!cp) return {gfx::kPlaceholderColor, gfx::kPlaceholderColor}; return {cp->GetColor(from_color_id_), cp->GetColor(to_color_id_)}; } void OnPaintBackground(gfx::Canvas* canvas) override { cc::PaintFlags flags; std::pair<SkColor, SkColor> gradient_colors = GetColors(); flags.setShader(gfx::CreateGradientShader( gfx::Point(), gfx::Point(0, height()), gradient_colors.first, gradient_colors.second)); flags.setStyle(cc::PaintFlags::kFill_Style); canvas->DrawRect(GetLocalBounds(), flags); } private: ui::ColorId from_color_id_; ui::ColorId to_color_id_; }; ScrollViewExample::ScrollViewExample() : ExampleBase(GetStringUTF8(IDS_SCROLL_VIEW_SELECT_LABEL).c_str()) {} ScrollViewExample::~ScrollViewExample() = default; void ScrollViewExample::CreateExampleView(View* container) { auto scroll_view = std::make_unique<ScrollView>(); scrollable_ = scroll_view->SetContents(std::make_unique<ScrollableView>()); scrollable_->SetBounds(0, 0, 1000, 100); scrollable_->SetColor(ExamplesColorIds::kColorScrollViewExampleWideFrom, ExamplesColorIds::kColorScrollViewExampleWideTo); container->SetLayoutManager(std::make_unique<FlexLayout>()) ->SetOrientation(LayoutOrientation::kVertical); auto full_flex = FlexSpecification(MinimumFlexSizeRule::kScaleToZero, MaximumFlexSizeRule::kUnbounded) .WithWeight(1); // Add scroll view. scroll_view_ = container->AddChildView(std::move(scroll_view)); scroll_view_->SetProperty(views::kFlexBehaviorKey, full_flex); // Add control buttons. auto* button_panel = container->AddChildView(std::make_unique<View>()); button_panel->SetLayoutManager(std::make_unique<FlexLayout>()) ->SetOrientation(LayoutOrientation::kHorizontal); button_panel->AddChildView(std::make_unique<LabelButton>( base::BindRepeating(&ScrollViewExample::ButtonPressed, base::Unretained(this), gfx::Rect(0, 0, 1000, 100), ExamplesColorIds::kColorScrollViewExampleWideFrom, ExamplesColorIds::kColorScrollViewExampleWideTo), GetStringUTF16(IDS_SCROLL_VIEW_WIDE_LABEL))); button_panel->AddChildView(std::make_unique<LabelButton>( base::BindRepeating(&ScrollViewExample::ButtonPressed, base::Unretained(this), gfx::Rect(0, 0, 100, 1000), ExamplesColorIds::kColorScrollViewExampleTallFrom, ExamplesColorIds::kColorScrollViewExampleTallTo), GetStringUTF16(IDS_SCROLL_VIEW_TALL_LABEL))); button_panel->AddChildView(std::make_unique<LabelButton>( base::BindRepeating( &ScrollViewExample::ButtonPressed, base::Unretained(this), gfx::Rect(0, 0, 1000, 1000), ExamplesColorIds::kColorScrollViewExampleBigSquareFrom, ExamplesColorIds::kColorScrollViewExampleBigSquareTo), GetStringUTF16(IDS_SCROLL_VIEW_BIG_SQUARE_LABEL))); button_panel->AddChildView(std::make_unique<LabelButton>( base::BindRepeating( &ScrollViewExample::ButtonPressed, base::Unretained(this), gfx::Rect(0, 0, 100, 100), ExamplesColorIds::kColorScrollViewExampleSmallSquareFrom, ExamplesColorIds::kColorScrollViewExampleSmallSquareTo), GetStringUTF16(IDS_SCROLL_VIEW_SMALL_SQUARE_LABEL))); button_panel->AddChildView(std::make_unique<LabelButton>( base::BindRepeating(&View::ScrollRectToVisible, base::Unretained(scroll_view_->contents()), gfx::Rect(20, 500, 1000, 500)), GetStringUTF16(IDS_SCROLL_VIEW_SCROLL_TO_LABEL))); for (View* child : button_panel->children()) child->SetProperty(views::kFlexBehaviorKey, full_flex); } void ScrollViewExample::ButtonPressed(gfx::Rect bounds, ui::ColorId from, ui::ColorId to) { scrollable_->SetBoundsRect(std::move(bounds)); scrollable_->SetColor(from, to); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/scroll_view_example.cc
C++
unknown
6,520
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_SCROLL_VIEW_EXAMPLE_H_ #define UI_VIEWS_EXAMPLES_SCROLL_VIEW_EXAMPLE_H_ #include "base/memory/raw_ptr.h" #include "ui/color/color_id.h" #include "ui/views/controls/scroll_view.h" #include "ui/views/examples/example_base.h" namespace views::examples { class VIEWS_EXAMPLES_EXPORT ScrollViewExample : public ExampleBase { public: ScrollViewExample(); ScrollViewExample(const ScrollViewExample&) = delete; ScrollViewExample& operator=(const ScrollViewExample&) = delete; ~ScrollViewExample() override; // ExampleBase: void CreateExampleView(View* container) override; private: class ScrollableView; void ButtonPressed(gfx::Rect bounds, ui::ColorId from, ui::ColorId to); // The content of the scroll view. raw_ptr<ScrollableView> scrollable_; // The scroll view to test. raw_ptr<ScrollView> scroll_view_; }; } // namespace views::examples #endif // UI_VIEWS_EXAMPLES_SCROLL_VIEW_EXAMPLE_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/scroll_view_example.h
C++
unknown
1,097
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/slider_example.h" #include <memory> #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/geometry/insets.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/controls/label.h" #include "ui/views/controls/slider.h" #include "ui/views/examples/grit/views_examples_resources.h" #include "ui/views/layout/box_layout.h" #include "ui/views/layout/box_layout_view.h" #include "ui/views/view.h" namespace views::examples { SliderExample::SliderExample() : ExampleBase(l10n_util::GetStringUTF8(IDS_SLIDER_SELECT_LABEL).c_str()) {} SliderExample::~SliderExample() = default; void SliderExample::CreateExampleView(View* container) { container->SetLayoutManager(std::make_unique<BoxLayout>( BoxLayout::Orientation::kVertical, gfx::Insets(3), 3)); auto* const container_default = container->AddChildView(std::make_unique<BoxLayoutView>()); container_default->SetBetweenChildSpacing(3); std::u16string default_name = l10n_util::GetStringUTF16(IDS_SLIDER_DEFAULT_SLIDER_LABEL); label_default_ = container_default->AddChildView(std::make_unique<Label>(default_name)); slider_default_ = container_default->AddChildView(std::make_unique<Slider>(this)); slider_default_->SetValue(0.5); slider_default_->GetViewAccessibility().OverrideName(default_name); auto* const container_minimal = container->AddChildView(std::make_unique<BoxLayoutView>()); container_minimal->SetBetweenChildSpacing(3); std::u16string minimal_name = l10n_util::GetStringUTF16(IDS_SLIDER_MINIMAL_SLIDER_LABEL); label_minimal_ = container_minimal->AddChildView(std::make_unique<Label>(minimal_name)); slider_minimal_ = container_minimal->AddChildView(std::make_unique<Slider>(this)); slider_minimal_->SetValue(0.5); slider_minimal_->SetRenderingStyle(Slider::RenderingStyle::kMinimalStyle); slider_minimal_->GetViewAccessibility().OverrideName(minimal_name); } void SliderExample::SliderValueChanged(Slider* sender, float value, float old_value, SliderChangeReason reason) { auto* const label = (sender == slider_default_) ? label_default_.get() : label_minimal_.get(); label->SetText(base::ASCIIToUTF16(base::StringPrintf("%.3lf", value))); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/slider_example.cc
C++
unknown
2,638
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_SLIDER_EXAMPLE_H_ #define UI_VIEWS_EXAMPLES_SLIDER_EXAMPLE_H_ #include "base/memory/raw_ptr.h" #include "ui/views/controls/slider.h" #include "ui/views/examples/example_base.h" namespace views { class Label; namespace examples { class VIEWS_EXAMPLES_EXPORT SliderExample : public ExampleBase, public SliderListener { public: SliderExample(); SliderExample(const SliderExample&) = delete; SliderExample& operator=(const SliderExample&) = delete; ~SliderExample() override; // ExampleBase: void CreateExampleView(View* container) override; private: // SliderListener: void SliderValueChanged(Slider* sender, float value, float old_value, SliderChangeReason reason) override; raw_ptr<Slider> slider_default_ = nullptr; raw_ptr<Slider> slider_minimal_ = nullptr; raw_ptr<Label> label_default_ = nullptr; raw_ptr<Label> label_minimal_ = nullptr; }; } // namespace examples } // namespace views #endif // UI_VIEWS_EXAMPLES_SLIDER_EXAMPLE_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/slider_example.h
C++
unknown
1,267
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/square_ink_drop_example.h" #include <memory> #include <utility> #include "base/functional/bind.h" #include "ui/views/animation/ink_drop_host.h" #include "ui/views/animation/ink_drop_ripple.h" #include "ui/views/animation/ink_drop_state.h" #include "ui/views/view.h" namespace views::examples { SquareInkDropExample::SquareInkDropExample() : InkDropExample("Square Ink Drop") {} SquareInkDropExample::~SquareInkDropExample() = default; void SquareInkDropExample::CreateInkDrop() { auto ink_drop_host = std::make_unique<InkDropHost>(ink_drop_view()); ink_drop_host->SetMode(InkDropHost::InkDropMode::ON); InkDrop::UseInkDropForSquareRipple(ink_drop_host.get()); ink_drop_host->SetCreateRippleCallback(base::BindRepeating( [](InkDropHost* ink_drop_host, SquareInkDropExample* example) { return ink_drop_host->CreateSquareRipple( example->ink_drop_view()->GetLocalBounds().CenterPoint(), example->ink_drop_view()->GetContentsBounds().size()); }, ink_drop_host.get(), base::Unretained(this))); InkDrop::Install(ink_drop_view(), std::move(ink_drop_host)); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/square_ink_drop_example.cc
C++
unknown
1,327
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_SQUARE_INK_DROP_EXAMPLE_H_ #define UI_VIEWS_EXAMPLES_SQUARE_INK_DROP_EXAMPLE_H_ #include "ui/views/examples/ink_drop_example.h" namespace views::examples { class VIEWS_EXAMPLES_EXPORT SquareInkDropExample : public InkDropExample { public: SquareInkDropExample(); SquareInkDropExample(const SquareInkDropExample&) = delete; SquareInkDropExample& operator=(const SquareInkDropExample&) = delete; ~SquareInkDropExample() override; protected: void CreateInkDrop() override; }; } // namespace views::examples #endif // UI_VIEWS_EXAMPLES_SQUARE_INK_DROP_EXAMPLE_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/square_ink_drop_example.h
C++
unknown
749
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/tabbed_pane_example.h" #include <memory> #include <utility> #include "base/format_macros.h" #include "base/strings/utf_string_conversions.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/tabbed_pane/tabbed_pane.h" #include "ui/views/examples/examples_window.h" #include "ui/views/examples/grit/views_examples_resources.h" #include "ui/views/layout/flex_layout.h" #include "ui/views/layout/flex_layout_types.h" #include "ui/views/view_class_properties.h" using l10n_util::GetStringUTF16; using l10n_util::GetStringUTF8; namespace views::examples { TabbedPaneExample::TabbedPaneExample() : ExampleBase(GetStringUTF8(IDS_TABBED_PANE_SELECT_LABEL).c_str()) {} TabbedPaneExample::~TabbedPaneExample() = default; void TabbedPaneExample::CreateExampleView(View* container) { container->SetLayoutManager(std::make_unique<views::FlexLayout>()) ->SetOrientation(LayoutOrientation::kVertical); // Add control buttons horizontally. auto* const button_panel = container->AddChildView(std::make_unique<View>()); button_panel->SetLayoutManager(std::make_unique<views::FlexLayout>()); button_panel->AddChildView(std::make_unique<LabelButton>( base::BindRepeating(&TabbedPaneExample::SwapLayout, base::Unretained(this)), GetStringUTF16(IDS_TABBED_PANE_SWAP_LAYOUT_LABEL))); toggle_highlighted_ = button_panel->AddChildView(std::make_unique<LabelButton>( base::BindRepeating(&TabbedPaneExample::ToggleHighlighted, base::Unretained(this)), GetStringUTF16(IDS_TABBED_PANE_TOGGLE_HIGHLIGHTED_LABEL))); button_panel->AddChildView(std::make_unique<LabelButton>( base::BindRepeating(&TabbedPaneExample::AddTab, base::Unretained(this), GetStringUTF16(IDS_TABBED_PANE_ADDED_LABEL)), GetStringUTF16(IDS_TABBED_PANE_ADD_LABEL))); button_panel->AddChildView(std::make_unique<LabelButton>( base::BindRepeating(&TabbedPaneExample::AddAt, base::Unretained(this)), GetStringUTF16(IDS_TABBED_PANE_ADD_1_LABEL))); button_panel->AddChildView(std::make_unique<LabelButton>( base::BindRepeating(&TabbedPaneExample::SelectAt, base::Unretained(this)), GetStringUTF16(IDS_TABBED_PANE_SELECT_1_LABEL))); const auto full_flex = FlexSpecification(MinimumFlexSizeRule::kScaleToZero, MaximumFlexSizeRule::kUnbounded) .WithWeight(1); for (View* view : button_panel->children()) view->SetProperty(views::kFlexBehaviorKey, full_flex); CreateTabbedPane(container, TabbedPane::Orientation::kHorizontal, TabbedPane::TabStripStyle::kBorder); } void TabbedPaneExample::TabSelectedAt(int index) { // Just print the status when selection changes. PrintCurrentStatus(); } void TabbedPaneExample::CreateTabbedPane(View* container, TabbedPane::Orientation orientation, TabbedPane::TabStripStyle style) { // Tabbed panes only support highlighted style for vertical tabs. if (orientation == TabbedPane::Orientation::kHorizontal) style = TabbedPane::TabStripStyle::kBorder; tabbed_pane_ = container->AddChildViewAt( std::make_unique<TabbedPane>(orientation, style), 0); tabbed_pane_->set_listener(this); toggle_highlighted_->SetEnabled(orientation == TabbedPane::Orientation::kVertical); const auto full_flex = FlexSpecification(MinimumFlexSizeRule::kScaleToZero, MaximumFlexSizeRule::kUnbounded) .WithWeight(1); tabbed_pane_->SetProperty(views::kFlexBehaviorKey, full_flex); AddTab(GetStringUTF16(IDS_TABBED_PANE_TAB_1_LABEL)); AddTab(GetStringUTF16(IDS_TABBED_PANE_TAB_2_LABEL)); AddTab(GetStringUTF16(IDS_TABBED_PANE_TAB_3_LABEL)); } void TabbedPaneExample::PrintCurrentStatus() { PrintStatus("Tab Count:%" PRIuS ", Selected Tab:%" PRIuS, tabbed_pane_->GetTabCount(), tabbed_pane_->GetSelectedTabIndex()); } void TabbedPaneExample::SwapLayout() { auto* const container = tabbed_pane_->parent(); const auto orientation = (tabbed_pane_->GetOrientation() == TabbedPane::Orientation::kHorizontal) ? TabbedPane::Orientation::kVertical : TabbedPane::Orientation::kHorizontal; const auto style = tabbed_pane_->GetStyle(); container->RemoveChildView(tabbed_pane_); CreateTabbedPane(container, orientation, style); } void TabbedPaneExample::ToggleHighlighted() { auto* const container = tabbed_pane_->parent(); const auto orientation = tabbed_pane_->GetOrientation(); const auto style = (tabbed_pane_->GetStyle() == TabbedPane::TabStripStyle::kBorder) ? TabbedPane::TabStripStyle::kHighlight : TabbedPane::TabStripStyle::kBorder; container->RemoveChildView(tabbed_pane_); CreateTabbedPane(container, orientation, style); } void TabbedPaneExample::AddTab(const std::u16string& label) { tabbed_pane_->AddTab( label, std::make_unique<LabelButton>(Button::PressedCallback(), label)); PrintCurrentStatus(); } void TabbedPaneExample::AddAt() { const std::u16string label = GetStringUTF16(IDS_TABBED_PANE_ADDED_1_LABEL); tabbed_pane_->AddTabAtIndex( 1, label, std::make_unique<LabelButton>(Button::PressedCallback(), label)); PrintCurrentStatus(); } void TabbedPaneExample::SelectAt() { if (tabbed_pane_->GetTabCount() > 1) tabbed_pane_->SelectTabAt(1); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/tabbed_pane_example.cc
C++
unknown
5,803
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_TABBED_PANE_EXAMPLE_H_ #define UI_VIEWS_EXAMPLES_TABBED_PANE_EXAMPLE_H_ #include <string> #include "base/memory/raw_ptr.h" #include "ui/views/controls/tabbed_pane/tabbed_pane.h" #include "ui/views/controls/tabbed_pane/tabbed_pane_listener.h" #include "ui/views/examples/example_base.h" namespace views { class Button; namespace examples { // A TabbedPane example tests adding and selecting tabs. class VIEWS_EXAMPLES_EXPORT TabbedPaneExample : public ExampleBase, public TabbedPaneListener { public: TabbedPaneExample(); TabbedPaneExample(const TabbedPaneExample&) = delete; TabbedPaneExample& operator=(const TabbedPaneExample&) = delete; ~TabbedPaneExample() override; // ExampleBase: void CreateExampleView(View* container) override; private: // TabbedPaneListener: void TabSelectedAt(int index) override; void CreateTabbedPane(View* container, TabbedPane::Orientation orientation, TabbedPane::TabStripStyle style); void PrintCurrentStatus(); void SwapLayout(); void ToggleHighlighted(); void AddTab(const std::u16string& label); void AddAt(); void SelectAt(); // The tabbed pane to be tested. raw_ptr<TabbedPane> tabbed_pane_; // The button that toggles highlighted style. raw_ptr<Button> toggle_highlighted_; }; } // namespace examples } // namespace views #endif // UI_VIEWS_EXAMPLES_TABBED_PANE_EXAMPLE_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/tabbed_pane_example.h
C++
unknown
1,634
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/table_example.h" #include <memory> #include <utility> #include <vector> #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkCanvas.h" #include "ui/color/color_provider.h" #include "ui/gfx/image/image_skia.h" #include "ui/views/controls/button/checkbox.h" #include "ui/views/controls/scroll_view.h" #include "ui/views/examples/examples_color_id.h" #include "ui/views/examples/examples_window.h" #include "ui/views/layout/flex_layout.h" #include "ui/views/layout/flex_layout_types.h" #include "ui/views/layout/flex_layout_view.h" #include "ui/views/view_class_properties.h" using base::ASCIIToUTF16; namespace views::examples { namespace { ui::TableColumn TestTableColumn( int id, const std::u16string& title, ui::TableColumn::Alignment alignment = ui::TableColumn::LEFT, float percent = 0.0) { ui::TableColumn column; column.id = id; column.title = title; column.sortable = true; column.alignment = alignment; column.percent = percent; return column; } } // namespace TableExample::TableExample() : ExampleBase("Table") {} TableExample::~TableExample() { observer_.Reset(); // Delete the view before the model. if (table_ && table_->parent()) { table_->parent()->RemoveChildViewT(table_); table_ = nullptr; } } void TableExample::CreateExampleView(View* container) { container->SetLayoutManager(std::make_unique<views::FlexLayout>()) ->SetOrientation(LayoutOrientation::kVertical); observer_.Observe(container); auto full_flex = FlexSpecification(MinimumFlexSizeRule::kScaleToZero, MaximumFlexSizeRule::kUnbounded) .WithWeight(1); const auto make_checkbox = [](const std::u16string& label, int id, raw_ptr<TableView>* table, raw_ptr<Checkbox>* checkbox, FlexSpecification full_flex) { return Builder<Checkbox>() .CopyAddressTo(checkbox) .SetText(label) .SetCallback(base::BindRepeating( [](int id, TableView* table, Checkbox* checkbox) { table->SetColumnVisibility(id, checkbox->GetChecked()); }, id, *table, *checkbox)) .SetChecked(true) .SetProperty(kFlexBehaviorKey, full_flex); }; // Make table Builder<View>(container) .AddChildren( TableView::CreateScrollViewBuilderWithTable( Builder<TableView>() .CopyAddressTo(&table_) .SetModel(this) .SetTableType(ICON_AND_TEXT) .SetColumns( {TestTableColumn(0, u"Fruit", ui::TableColumn::LEFT, 1.0), TestTableColumn(1, u"Color"), TestTableColumn(2, u"Origin"), TestTableColumn(3, u"Price", ui::TableColumn::RIGHT)}) .SetGrouper(this) .SetObserver(this)) .SetProperty(kFlexBehaviorKey, full_flex), Builder<FlexLayoutView>() .SetOrientation(LayoutOrientation::kHorizontal) .AddChildren( make_checkbox(u"Fruit column visible", 0, &table_, &column1_visible_checkbox_, full_flex), make_checkbox(u"Color column visible", 1, &table_, &column2_visible_checkbox_, full_flex), make_checkbox(u"Origin column visible", 2, &table_, &column3_visible_checkbox_, full_flex), make_checkbox(u"Price column visible", 3, &table_, &column4_visible_checkbox_, full_flex))) .BuildChildren(); } size_t TableExample::RowCount() { return 10; } std::u16string TableExample::GetText(size_t row, int column_id) { const char* const cells[5][4] = { {"Orange", "Orange", "South America", "$5"}, {"Apple", "Green", "Canada", "$3"}, {"Blueberries", "Blue", "Mexico", "$10.30"}, {"Strawberries", "Red", "California", "$7"}, {"Cantaloupe", "Orange", "South America", "$5"}, }; return ASCIIToUTF16(cells[row % 5][column_id]); } ui::ImageModel TableExample::GetIcon(size_t row) { SkBitmap row_icon = row % 2 ? icon1_ : icon2_; return ui::ImageModel::FromImageSkia( gfx::ImageSkia::CreateFrom1xBitmap(row_icon)); } std::u16string TableExample::GetTooltip(size_t row) { const char* const tooltips[5] = { "Orange - Orange you glad I didn't say banana?", "Apple - An apple a day keeps the doctor away", "Blueberries - Bet you can't eat just one", "Strawberries - Always better when homegrown", "Cantaloupe - So nice when perfectly ripe"}; return ASCIIToUTF16(tooltips[row % 5]); } void TableExample::SetObserver(ui::TableModelObserver* observer) {} void TableExample::GetGroupRange(size_t model_index, GroupRange* range) { if (model_index < 2) { range->start = 0; range->length = 2; } else if (model_index > 6) { range->start = 7; range->length = 3; } else { range->start = model_index; range->length = 1; } } void TableExample::OnSelectionChanged() { PrintStatus("Selected: %s", SelectedColumnName().c_str()); } void TableExample::OnDoubleClick() { PrintStatus("Double Click: %s", SelectedColumnName().c_str()); } void TableExample::OnMiddleClick() {} void TableExample::OnKeyDown(ui::KeyboardCode virtual_keycode) {} void TableExample::OnViewThemeChanged(View* observed_view) { icon1_.allocN32Pixels(16, 16); icon2_.allocN32Pixels(16, 16); auto* const cp = observed_view->GetColorProvider(); SkCanvas canvas1(icon1_, SkSurfaceProps{}), canvas2(icon2_, SkSurfaceProps{}); canvas1.drawColor( cp->GetColor(ExamplesColorIds::kColorTableExampleEvenRowIcon)); canvas2.drawColor( cp->GetColor(ExamplesColorIds::kColorTableExampleOddRowIcon)); } void TableExample::OnViewIsDeleting(View* observed_view) { observer_.Reset(); } std::string TableExample::SelectedColumnName() { return table_->selection_model().active().has_value() ? base::UTF16ToASCII( GetText(table_->selection_model().active().value(), 0)) : std::string("<None>"); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/table_example.cc
C++
unknown
6,550
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_TABLE_EXAMPLE_H_ #define UI_VIEWS_EXAMPLES_TABLE_EXAMPLE_H_ #include <string> #include "base/memory/raw_ptr.h" #include "base/scoped_observation.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/models/table_model.h" #include "ui/views/controls/table/table_grouper.h" #include "ui/views/controls/table/table_view.h" #include "ui/views/controls/table/table_view_observer.h" #include "ui/views/examples/example_base.h" #include "ui/views/view_observer.h" namespace views { class Checkbox; class View; namespace examples { class VIEWS_EXAMPLES_EXPORT TableExample : public ExampleBase, public ui::TableModel, public TableGrouper, public TableViewObserver, public ViewObserver { public: TableExample(); TableExample(const TableExample&) = delete; TableExample& operator=(const TableExample&) = delete; ~TableExample() override; // ExampleBase: void CreateExampleView(View* container) override; // ui::TableModel: size_t RowCount() override; std::u16string GetText(size_t row, int column_id) override; ui::ImageModel GetIcon(size_t row) override; std::u16string GetTooltip(size_t row) override; void SetObserver(ui::TableModelObserver* observer) override; // TableGrouper: void GetGroupRange(size_t model_index, GroupRange* range) override; // TableViewObserver: void OnSelectionChanged() override; void OnDoubleClick() override; void OnMiddleClick() override; void OnKeyDown(ui::KeyboardCode virtual_keycode) override; // ViewObserver: void OnViewThemeChanged(View* observed_view) override; void OnViewIsDeleting(View* observed_view) override; private: std::string SelectedColumnName(); // The table to be tested. raw_ptr<TableView> table_ = nullptr; raw_ptr<Checkbox> column1_visible_checkbox_ = nullptr; raw_ptr<Checkbox> column2_visible_checkbox_ = nullptr; raw_ptr<Checkbox> column3_visible_checkbox_ = nullptr; raw_ptr<Checkbox> column4_visible_checkbox_ = nullptr; SkBitmap icon1_; SkBitmap icon2_; base::ScopedObservation<View, ViewObserver> observer_{this}; }; } // namespace examples } // namespace views #endif // UI_VIEWS_EXAMPLES_TABLE_EXAMPLE_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/table_example.h
C++
unknown
2,509
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/text_example.h" #include <memory> #include <utility> #include "base/strings/utf_string_conversions.h" #include "ui/base/l10n/l10n_util.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/gfx/canvas.h" #include "ui/gfx/font_list.h" #include "ui/views/border.h" #include "ui/views/controls/button/checkbox.h" #include "ui/views/controls/combobox/combobox.h" #include "ui/views/controls/label.h" #include "ui/views/examples/example_combobox_model.h" #include "ui/views/examples/grit/views_examples_resources.h" #include "ui/views/layout/box_layout.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/layout/table_layout.h" #include "ui/views/view.h" #include "ui/views/view_class_properties.h" namespace views::examples { namespace { // Number of columns in the view layout. constexpr int kNumColumns = 10; // Toggles bit |flag| on |flags| based on state of |checkbox|. void SetFlagFromCheckbox(Checkbox* checkbox, int* flags, int flag) { if (checkbox->GetChecked()) *flags |= flag; else *flags &= ~flag; } } // namespace // TextExample's content view, which draws stylized string. class TextExample::TextExampleView : public View { public: TextExampleView() = default; TextExampleView(const TextExampleView&) = delete; TextExampleView& operator=(const TextExampleView&) = delete; ~TextExampleView() override = default; void OnPaint(gfx::Canvas* canvas) override { View::OnPaint(canvas); const gfx::Rect bounds = GetContentsBounds(); const SkColor color = GetColorProvider()->GetColor(ui::kColorTextfieldForeground); canvas->DrawStringRectWithFlags(text_, font_list_, color, bounds, flags_); } int GetFlags() const { return flags_; } void SetFlags(int flags) { flags_ = flags; SchedulePaint(); } void SetText(const std::u16string& text) { text_ = text; SchedulePaint(); } void SetElide(gfx::ElideBehavior elide) { elide_ = elide; SchedulePaint(); } int GetStyle() const { return font_list_.GetFontStyle(); } void SetStyle(int style) { base_font_ = base_font_.DeriveWithStyle(style); font_list_ = font_list_.DeriveWithStyle(style); SchedulePaint(); } gfx::Font::Weight GetWeight() const { return font_list_.GetFontWeight(); } void SetWeight(gfx::Font::Weight weight) { font_list_ = base_font_.DeriveWithWeight(weight); SchedulePaint(); } protected: void OnThemeChanged() override { View::OnThemeChanged(); SetBorder(CreateSolidBorder( 1, GetColorProvider()->GetColor(ui::kColorFocusableBorderUnfocused))); } private: // The font used for drawing the text. gfx::FontList font_list_; // The font without any bold attributes. Mac font APIs struggle to derive UI // fonts from a base font that isn't NORMAL or BOLD. gfx::FontList base_font_; // The text to draw. std::u16string text_; // Text flags for passing to |DrawStringRect()|. int flags_ = 0; // The eliding, fading, or truncating behavior. gfx::ElideBehavior elide_ = gfx::NO_ELIDE; }; TextExample::TextExample() : ExampleBase(l10n_util::GetStringUTF8(IDS_TEXT_STYLE_LABEL).c_str()) {} TextExample::~TextExample() = default; Checkbox* TextExample::AddCheckbox(View* parent, const char* name) { return parent->AddChildView(std::make_unique<Checkbox>( base::ASCIIToUTF16(name), base::BindRepeating(&TextExample::UpdateStyle, base::Unretained(this)))); } Combobox* TextExample::AddCombobox(View* parent, std::u16string name, const char* const* strings, int count, void (TextExample::*combobox_callback)()) { parent->AddChildView(std::make_unique<Label>(name)); auto* combobox = parent->AddChildView(std::make_unique<Combobox>( std::make_unique<ExampleComboboxModel>(strings, count))); combobox->SetProperty(kTableColAndRowSpanKey, gfx::Size(kNumColumns - 1, 1)); combobox->SetCallback( base::BindRepeating(combobox_callback, base::Unretained(this))); combobox->SetAccessibleName(name); return combobox; } void TextExample::CreateExampleView(View* container) { auto* box_layout = container->SetLayoutManager(std::make_unique<BoxLayout>( BoxLayout::Orientation::kVertical, gfx::Insets(8), 20, false)); auto* table_container = container->AddChildView(std::make_unique<View>()); TableLayout* layout = table_container->SetLayoutManager(std::make_unique<TableLayout>()); layout->AddColumn(LayoutAlignment::kStart, LayoutAlignment::kStretch, 0.1f, TableLayout::ColumnSize::kUsePreferred, 0, 0); for (int i = 0; i < kNumColumns - 1; i++) { layout->AddColumn(LayoutAlignment::kStretch, LayoutAlignment::kStretch, 0.1f, TableLayout::ColumnSize::kUsePreferred, 0, 0); } layout->AddRows(6, TableLayout::kFixedSize); constexpr const char* kHorizontalAligments[] = { "Default", "Left", "Center", "Right", }; h_align_cb_ = AddCombobox(table_container, u"H-Align", kHorizontalAligments, std::size(kHorizontalAligments), &TextExample::AlignComboboxChanged); constexpr const char* kElideBehaviors[] = {"Elide", "No Elide"}; eliding_cb_ = AddCombobox(table_container, u"Eliding", kElideBehaviors, std::size(kElideBehaviors), &TextExample::ElideComboboxChanged); constexpr const char* kPrefixOptions[] = { "Default", "Show", "Hide", }; prefix_cb_ = AddCombobox(table_container, u"Prefix", kPrefixOptions, std::size(kPrefixOptions), &TextExample::PrefixComboboxChanged); constexpr const char* kTextExamples[] = { "Short", "Long", "Ampersands", "RTL Hebrew", }; text_cb_ = AddCombobox(table_container, u"Example Text", kTextExamples, std::size(kTextExamples), &TextExample::TextComboboxChanged); constexpr const char* kWeightLabels[] = { "Thin", "Extra Light", "Light", "Normal", "Medium", "Semibold", "Bold", "Extra Bold", "Black", }; weight_cb_ = AddCombobox(table_container, u"Font Weight", kWeightLabels, std::size(kWeightLabels), &TextExample::WeightComboboxChanged); weight_cb_->SelectValue(u"Normal"); multiline_checkbox_ = AddCheckbox(table_container, "Multiline"); break_checkbox_ = AddCheckbox(table_container, "Character Break"); italic_checkbox_ = AddCheckbox(table_container, "Italic"); underline_checkbox_ = AddCheckbox(table_container, "Underline"); auto* fill_container = container->AddChildView(std::make_unique<View>()); box_layout->SetFlexForView(fill_container, 1); fill_container->SetLayoutManager(std::make_unique<FillLayout>()); fill_container->SetBorder(CreateEmptyBorder(gfx::Insets::VH(0, 8))); text_view_ = fill_container->AddChildView(std::make_unique<TextExampleView>()); TextComboboxChanged(); // Sets initial text content. } void TextExample::UpdateStyle() { int flags = text_view_->GetFlags(); int style = text_view_->GetStyle(); SetFlagFromCheckbox(multiline_checkbox_, &flags, gfx::Canvas::MULTI_LINE); SetFlagFromCheckbox(break_checkbox_, &flags, gfx::Canvas::CHARACTER_BREAKABLE); SetFlagFromCheckbox(italic_checkbox_, &style, gfx::Font::ITALIC); SetFlagFromCheckbox(underline_checkbox_, &style, gfx::Font::UNDERLINE); text_view_->SetFlags(flags); text_view_->SetStyle(style); } void TextExample::AlignComboboxChanged() { int flags = text_view_->GetFlags() & ~(gfx::Canvas::TEXT_ALIGN_LEFT | gfx::Canvas::TEXT_ALIGN_CENTER | gfx::Canvas::TEXT_ALIGN_RIGHT); switch (h_align_cb_->GetSelectedIndex().value()) { case 0: break; case 1: flags |= gfx::Canvas::TEXT_ALIGN_LEFT; break; case 2: flags |= gfx::Canvas::TEXT_ALIGN_CENTER; break; case 3: flags |= gfx::Canvas::TEXT_ALIGN_RIGHT; break; } text_view_->SetFlags(flags); } void TextExample::TextComboboxChanged() { switch (text_cb_->GetSelectedIndex().value()) { case 0: text_view_->SetText(u"The quick brown fox jumps over the lazy dog."); break; case 1: text_view_->SetText( u"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do " u"eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut " u"enim ad minim veniam, quis nostrud exercitation ullamco laboris " u"nisi ut aliquip ex ea commodo consequat.\n" u"Duis aute irure dolor in reprehenderit in voluptate velit esse " u"cillum dolore eu fugiat nulla pariatur.\n" u"\n" u"Excepteur sint occaecat cupidatat non proident, sunt in culpa qui " u"officia deserunt mollit anim id est laborum."); break; case 2: text_view_->SetText(u"The quick && &brown fo&x jumps over the lazy dog."); break; case 3: text_view_->SetText( u"\x5e9\x5dc\x5d5\x5dd \x5d4\x5e2\x5d5\x5dc\x5dd! " u"\x5e9\x5dc\x5d5\x5dd \x5d4\x5e2\x5d5\x5dc\x5dd! " u"\x5e9\x5dc\x5d5\x5dd \x5d4\x5e2\x5d5\x5dc\x5dd! " u"\x5e9\x5dc\x5d5\x5dd \x5d4\x5e2\x5d5\x5dc\x5dd! " u"\x5e9\x5dc\x5d5\x5dd \x5d4\x5e2\x5d5\x5dc\x5dd! " u"\x5e9\x5dc\x5d5\x5dd \x5d4\x5e2\x5d5\x5dc\x5dd! " u"\x5e9\x5dc\x5d5\x5dd \x5d4\x5e2\x5d5\x5dc\x5dd! " u"\x5e9\x5dc\x5d5\x5dd \x5d4\x5e2\x5d5\x5dc\x5dd!"); break; } } void TextExample::ElideComboboxChanged() { switch (eliding_cb_->GetSelectedIndex().value()) { case 0: text_view_->SetElide(gfx::ELIDE_TAIL); break; case 1: text_view_->SetElide(gfx::NO_ELIDE); break; } } void TextExample::PrefixComboboxChanged() { int flags = text_view_->GetFlags() & ~(gfx::Canvas::SHOW_PREFIX | gfx::Canvas::HIDE_PREFIX); switch (prefix_cb_->GetSelectedIndex().value()) { case 0: break; case 1: flags |= gfx::Canvas::SHOW_PREFIX; break; case 2: flags |= gfx::Canvas::HIDE_PREFIX; break; } text_view_->SetFlags(flags); } void TextExample::WeightComboboxChanged() { constexpr gfx::Font::Weight kFontWeights[]{ gfx::Font::Weight::THIN, gfx::Font::Weight::EXTRA_LIGHT, gfx::Font::Weight::LIGHT, gfx::Font::Weight::NORMAL, gfx::Font::Weight::MEDIUM, gfx::Font::Weight::SEMIBOLD, gfx::Font::Weight::BOLD, gfx::Font::Weight::EXTRA_BOLD, gfx::Font::Weight::BLACK, }; text_view_->SetWeight(kFontWeights[weight_cb_->GetSelectedIndex().value()]); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/text_example.cc
C++
unknown
10,999
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_TEXT_EXAMPLE_H_ #define UI_VIEWS_EXAMPLES_TEXT_EXAMPLE_H_ #include "base/memory/raw_ptr.h" #include "ui/views/examples/example_base.h" namespace views { class Checkbox; class Combobox; class View; namespace examples { class VIEWS_EXAMPLES_EXPORT TextExample : public ExampleBase { public: TextExample(); TextExample(const TextExample&) = delete; TextExample& operator=(const TextExample&) = delete; ~TextExample() override; // ExampleBase: void CreateExampleView(View* container) override; private: class TextExampleView; // Creates and adds a check box to the layout. Checkbox* AddCheckbox(View* parent, const char* name); // Creates and adds a combobox to the layout. Sets |this|' instance of // |combobox_callback| as the callback for the created combobox. Combobox* AddCombobox(View* parent, std::u16string name, const char* const* strings, int count, void (TextExample::*combobox_callback)()); void AlignComboboxChanged(); void TextComboboxChanged(); void ElideComboboxChanged(); void PrefixComboboxChanged(); void WeightComboboxChanged(); void UpdateStyle(); // The content of the scroll view. raw_ptr<TextExampleView> text_view_; // Combo box for horizontal text alignment. raw_ptr<Combobox> h_align_cb_; // Combo box for text eliding style. raw_ptr<Combobox> eliding_cb_; // Combo box for ampersand prefix show / hide behavior. raw_ptr<Combobox> prefix_cb_; // Combo box to choose one of the sample texts. raw_ptr<Combobox> text_cb_; // Combo box to choose a font weight. raw_ptr<Combobox> weight_cb_; // Check box to enable/disable multiline text drawing. raw_ptr<Checkbox> multiline_checkbox_; // Check box to enable/disable character break behavior. raw_ptr<Checkbox> break_checkbox_; // Check box to enable/disable italic style. raw_ptr<Checkbox> italic_checkbox_; // Check box to enable/disable underline style. raw_ptr<Checkbox> underline_checkbox_; }; } // namespace examples } // namespace views #endif // UI_VIEWS_EXAMPLES_TEXT_EXAMPLE_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/text_example.h
C++
unknown
2,327
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/textarea_example.h" #include <memory> #include <utility> #include "base/strings/utf_string_conversions.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/controls/textarea/textarea.h" #include "ui/views/examples/grit/views_examples_resources.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/view.h" namespace views::examples { TextareaExample::TextareaExample() : ExampleBase(l10n_util::GetStringUTF8(IDS_TEXTAREA_SELECT_LABEL).c_str()) { } void TextareaExample::CreateExampleView(View* container) { constexpr char16_t kLongText[] = u"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do " u"eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad " u"minim veniam, quis nostrud exercitation ullamco laboris nisi ut " u"aliquip ex ea commodo consequat.\nDuis aute irure dolor in " u"reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla " u"pariatur.\n\nExcepteur sint occaecat cupidatat non proident, sunt in " u"culpa qui officia deserunt mollit anim id est laborum."; auto textarea = std::make_unique<Textarea>(); textarea->SetText(kLongText); textarea->SetAccessibleName(l10n_util::GetStringUTF16(IDS_TEXTAREA_NAME)); container->SetLayoutManager(std::make_unique<views::FillLayout>()); container->AddChildView(std::move(textarea)); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/textarea_example.cc
C++
unknown
1,568
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_TEXTAREA_EXAMPLE_H_ #define UI_VIEWS_EXAMPLES_TEXTAREA_EXAMPLE_H_ #include "ui/views/examples/example_base.h" namespace views::examples { class VIEWS_EXAMPLES_EXPORT TextareaExample : public ExampleBase { public: TextareaExample(); ~TextareaExample() override = default; // ExampleBase: void CreateExampleView(View* container) override; }; } // namespace views::examples #endif // UI_VIEWS_EXAMPLES_TEXTAREA_EXAMPLE_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/textarea_example.h
C++
unknown
606
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/textfield_example.h" #include <stddef.h> #include <memory> #include <utility> #include "base/strings/utf_string_conversions.h" #include "ui/base/l10n/l10n_util.h" #include "ui/color/color_provider.h" #include "ui/events/event.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/range/range.h" #include "ui/gfx/render_text.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/label.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/examples/examples_color_id.h" #include "ui/views/examples/examples_window.h" #include "ui/views/examples/grit/views_examples_resources.h" #include "ui/views/layout/table_layout.h" #include "ui/views/view.h" using l10n_util::GetStringUTF16; using l10n_util::GetStringUTF8; namespace views::examples { TextfieldExample::TextfieldExample() : ExampleBase(GetStringUTF8(IDS_TEXTFIELD_SELECT_LABEL).c_str()) {} TextfieldExample::~TextfieldExample() = default; void TextfieldExample::CreateExampleView(View* container) { TableLayout* layout = container->SetLayoutManager(std::make_unique<views::TableLayout>()); layout ->AddColumn(LayoutAlignment::kStart, LayoutAlignment::kStretch, 0.2f, TableLayout::ColumnSize::kUsePreferred, 0, 0) .AddColumn(LayoutAlignment::kStretch, LayoutAlignment::kStretch, 0.8f, TableLayout::ColumnSize::kUsePreferred, 0, 0); for (int i = 0; i < 12; ++i) { layout->AddPaddingRow(TableLayout::kFixedSize, 5) .AddRows(1, TableLayout::kFixedSize); } container->AddChildView( std::make_unique<Label>(GetStringUTF16(IDS_TEXTFIELD_NAME_LABEL))); name_ = container->AddChildView(std::make_unique<Textfield>()); name_->set_controller(this); name_->SetAccessibleName(l10n_util::GetStringUTF16(IDS_TEXTFIELD_NAME_LABEL)); container->AddChildView( std::make_unique<Label>(GetStringUTF16(IDS_TEXTFIELD_PASSWORD_LABEL))); password_ = container->AddChildView(std::make_unique<Textfield>()); password_->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD); password_->SetPlaceholderText( GetStringUTF16(IDS_TEXTFIELD_PASSWORD_PLACEHOLDER)); password_->set_controller(this); password_->SetAccessibleName( l10n_util::GetStringUTF16(IDS_TEXTFIELD_PASSWORD_LABEL)); container->AddChildView( std::make_unique<Label>(GetStringUTF16(IDS_TEXTFIELD_DISABLED_LABEL))); disabled_ = container->AddChildView(std::make_unique<Textfield>()); disabled_->SetEnabled(false); disabled_->SetText(GetStringUTF16(IDS_TEXTFIELD_DISABLED_PLACEHOLDER)); disabled_->SetAccessibleName( l10n_util::GetStringUTF16(IDS_TEXTFIELD_DISABLED_LABEL)); container->AddChildView( std::make_unique<Label>(GetStringUTF16(IDS_TEXTFIELD_READ_ONLY_LABEL))); read_only_ = container->AddChildView(std::make_unique<Textfield>()); read_only_->SetReadOnly(true); read_only_->SetText(GetStringUTF16(IDS_TEXTFIELD_READ_ONLY_PLACEHOLDER)); read_only_->SetAccessibleName( l10n_util::GetStringUTF16(IDS_TEXTFIELD_READ_ONLY_LABEL)); container->AddChildView( std::make_unique<Label>(GetStringUTF16(IDS_TEXTFIELD_INVALID_LABEL))); invalid_ = container->AddChildView(std::make_unique<Textfield>()); invalid_->SetInvalid(true); invalid_->SetAccessibleName( l10n_util::GetStringUTF16(IDS_TEXTFIELD_INVALID_LABEL)); invalid_->SetPlaceholderText( l10n_util::GetStringUTF16(IDS_TEXTFIELD_INVALID_PLACEHOLDER)); container->AddChildView( std::make_unique<Label>(GetStringUTF16(IDS_TEXTFIELD_RTL_LABEL))); rtl_ = container->AddChildView(std::make_unique<Textfield>()); rtl_->ChangeTextDirectionAndLayoutAlignment(base::i18n::RIGHT_TO_LEFT); rtl_->SetAccessibleName(l10n_util::GetStringUTF16(IDS_TEXTFIELD_RTL_LABEL)); show_password_ = container->AddChildView(std::make_unique<LabelButton>( base::BindRepeating( [](TextfieldExample* example) { PrintStatus( "Password [%s]", base::UTF16ToUTF8(example->password_->GetText()).c_str()); }, base::Unretained(this)), GetStringUTF16(IDS_TEXTFIELD_SHOW_PASSWORD_LABEL))); container->AddChildView(std::make_unique<View>()); set_background_ = container->AddChildView(std::make_unique<LabelButton>( base::BindRepeating(&Textfield::SetBackgroundColor, base::Unretained(password_), gfx::kGoogleRed300), GetStringUTF16(IDS_TEXTFIELD_BACKGROUND_LABEL))); container->AddChildView(std::make_unique<View>()); clear_all_ = container->AddChildView(std::make_unique<LabelButton>( base::BindRepeating(&TextfieldExample::ClearAllButtonPressed, base::Unretained(this)), GetStringUTF16(IDS_TEXTFIELD_CLEAR_LABEL))); container->AddChildView(std::make_unique<View>()); append_ = container->AddChildView(std::make_unique<LabelButton>( base::BindRepeating(&TextfieldExample::AppendButtonPressed, base::Unretained(this)), GetStringUTF16(IDS_TEXTFIELD_APPEND_LABEL))); container->AddChildView(std::make_unique<View>()); set_ = container->AddChildView(std::make_unique<LabelButton>( base::BindRepeating(&TextfieldExample::SetButtonPressed, base::Unretained(this)), GetStringUTF16(IDS_TEXTFIELD_SET_LABEL))); container->AddChildView(std::make_unique<View>()); set_style_ = container->AddChildView(std::make_unique<LabelButton>( base::BindRepeating(&TextfieldExample::SetStyleButtonPressed, base::Unretained(this)), GetStringUTF16(IDS_TEXTFIELD_SET_STYLE_LABEL))); } bool TextfieldExample::HandleKeyEvent(Textfield* sender, const ui::KeyEvent& key_event) { return false; } bool TextfieldExample::HandleMouseEvent(Textfield* sender, const ui::MouseEvent& mouse_event) { PrintStatus("HandleMouseEvent click count=%d", mouse_event.GetClickCount()); return false; } void TextfieldExample::ClearAllButtonPressed() { name_->SetText(std::u16string()); password_->SetText(std::u16string()); disabled_->SetText(std::u16string()); read_only_->SetText(std::u16string()); invalid_->SetText(std::u16string()); rtl_->SetText(std::u16string()); } void TextfieldExample::AppendButtonPressed() { const std::u16string append_text = GetStringUTF16(IDS_TEXTFIELD_APPEND_UPDATE_TEXT); name_->AppendText(append_text); password_->AppendText(append_text); disabled_->SetText(append_text); read_only_->AppendText(append_text); invalid_->AppendText(append_text); rtl_->AppendText(append_text); } void TextfieldExample::SetButtonPressed() { const std::u16string set_text = GetStringUTF16(IDS_TEXTFIELD_SET_UPDATE_TEXT); name_->SetText(set_text); password_->SetText(set_text); disabled_->SetText(set_text); read_only_->SetText(set_text); invalid_->SetText(set_text); rtl_->SetText(set_text); } void TextfieldExample::SetStyleButtonPressed() { if (name_->GetText().empty()) return; auto* const cp = name_->GetColorProvider(); name_->SetColor(cp->GetColor(ExamplesColorIds::kColorTextfieldExampleName)); const size_t fifth = name_->GetText().length() / 5; if (!fifth) return; const gfx::Range big_range(1 * fifth, 4 * fifth); name_->ApplyStyle(gfx::TEXT_STYLE_UNDERLINE, true, big_range); name_->ApplyColor( cp->GetColor(ExamplesColorIds::kColorTextfieldExampleBigRange), big_range); const gfx::Range small_range(2 * fifth, 3 * fifth); name_->ApplyStyle(gfx::TEXT_STYLE_ITALIC, true, small_range); name_->ApplyStyle(gfx::TEXT_STYLE_UNDERLINE, false, small_range); name_->ApplyColor( cp->GetColor(ExamplesColorIds::kColorTextfieldExampleSmallRange), small_range); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/textfield_example.cc
C++
unknown
8,026
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_TEXTFIELD_EXAMPLE_H_ #define UI_VIEWS_EXAMPLES_TEXTFIELD_EXAMPLE_H_ #include "base/memory/raw_ptr.h" #include "ui/views/controls/textfield/textfield_controller.h" #include "ui/views/examples/example_base.h" namespace views { class LabelButton; namespace examples { // TextfieldExample mimics login screen. class VIEWS_EXAMPLES_EXPORT TextfieldExample : public ExampleBase, public TextfieldController { public: TextfieldExample(); TextfieldExample(const TextfieldExample&) = delete; TextfieldExample& operator=(const TextfieldExample&) = delete; ~TextfieldExample() override; // ExampleBase: void CreateExampleView(View* container) override; private: // TextfieldController: bool HandleKeyEvent(Textfield* sender, const ui::KeyEvent& key_event) override; bool HandleMouseEvent(Textfield* sender, const ui::MouseEvent& mouse_event) override; void ClearAllButtonPressed(); void AppendButtonPressed(); void SetButtonPressed(); void SetStyleButtonPressed(); // Textfields for name and password. raw_ptr<Textfield> name_ = nullptr; raw_ptr<Textfield> password_ = nullptr; raw_ptr<Textfield> disabled_ = nullptr; raw_ptr<Textfield> read_only_ = nullptr; raw_ptr<Textfield> invalid_ = nullptr; raw_ptr<Textfield> rtl_ = nullptr; // Various buttons to control textfield. raw_ptr<LabelButton> show_password_ = nullptr; raw_ptr<LabelButton> set_background_ = nullptr; raw_ptr<LabelButton> clear_all_ = nullptr; raw_ptr<LabelButton> append_ = nullptr; raw_ptr<LabelButton> set_ = nullptr; raw_ptr<LabelButton> set_style_ = nullptr; }; } // namespace examples } // namespace views #endif // UI_VIEWS_EXAMPLES_TEXTFIELD_EXAMPLE_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/textfield_example.h
C++
unknown
1,953
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/throbber_example.h" #include <memory> #include "base/memory/raw_ptr.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/controls/throbber.h" #include "ui/views/examples/grit/views_examples_resources.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/view.h" namespace views::examples { namespace { class ThrobberView : public View { public: ThrobberView() { throbber_ = AddChildView(std::make_unique<Throbber>()); throbber_->Start(); } ThrobberView(const ThrobberView&) = delete; ThrobberView& operator=(const ThrobberView&) = delete; // View:: gfx::Size CalculatePreferredSize() const override { return gfx::Size(width(), height()); } void Layout() override { int diameter = 16; throbber_->SetBounds((width() - diameter) / 2, (height() - diameter) / 2, diameter, diameter); SizeToPreferredSize(); } bool OnMousePressed(const ui::MouseEvent& event) override { if (GetEventHandlerForPoint(event.location()) != throbber_) return false; if (is_checked_) throbber_->Start(); else throbber_->Stop(); throbber_->SetChecked(!is_checked_); is_checked_ = !is_checked_; return true; } private: raw_ptr<Throbber> throbber_; bool is_checked_ = false; }; } // namespace ThrobberExample::ThrobberExample() : ExampleBase(l10n_util::GetStringUTF8(IDS_THROBBER_SELECT_LABEL).c_str()) { } ThrobberExample::~ThrobberExample() = default; void ThrobberExample::CreateExampleView(View* container) { container->SetLayoutManager(std::make_unique<FillLayout>()); container->AddChildView(std::make_unique<ThrobberView>()); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/throbber_example.cc
C++
unknown
1,865
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_THROBBER_EXAMPLE_H_ #define UI_VIEWS_EXAMPLES_THROBBER_EXAMPLE_H_ #include "ui/views/examples/example_base.h" namespace views::examples { class VIEWS_EXAMPLES_EXPORT ThrobberExample : public ExampleBase { public: ThrobberExample(); ThrobberExample(const ThrobberExample&) = delete; ThrobberExample& operator=(const ThrobberExample&) = delete; ~ThrobberExample() override; // ExampleBase: void CreateExampleView(View* container) override; }; } // namespace views::examples #endif // UI_VIEWS_EXAMPLES_THROBBER_EXAMPLE_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/throbber_example.h
C++
unknown
713
// Copyright 2016 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/toggle_button_example.h" #include <memory> #include <utility> #include "base/strings/utf_string_conversions.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/geometry/insets.h" #include "ui/views/controls/button/toggle_button.h" #include "ui/views/examples/examples_window.h" #include "ui/views/examples/grit/views_examples_resources.h" #include "ui/views/layout/box_layout.h" namespace views::examples { ToggleButtonExample::ToggleButtonExample() : ExampleBase( l10n_util::GetStringUTF8(IDS_TOGGLE_BUTTON_SELECT_LABEL).c_str()) {} ToggleButtonExample::~ToggleButtonExample() = default; void ToggleButtonExample::CreateExampleView(View* container) { auto layout = std::make_unique<BoxLayout>(BoxLayout::Orientation::kVertical); layout->set_cross_axis_alignment(BoxLayout::CrossAxisAlignment::kCenter); container->SetLayoutManager(std::move(layout)); container ->AddChildView(std::make_unique<ToggleButton>(base::BindRepeating( [](ToggleButtonExample* example) { PrintStatus("Pressed 1! count: %d", ++example->count_1_); }, base::Unretained(this)))) ->SetAccessibleName(l10n_util::GetStringUTF16(IDS_TOGGLE_BUTTON_NAME_1)); auto* button = container->AddChildView( std::make_unique<ToggleButton>(base::BindRepeating( [](ToggleButtonExample* example) { PrintStatus("Pressed 2! count: %d", ++example->count_2_); }, base::Unretained(this)))); button->SetAccessibleName( l10n_util::GetStringUTF16(IDS_TOGGLE_BUTTON_NAME_2)); button->SetIsOn(true); button = container->AddChildView( std::make_unique<ToggleButton>(base::BindRepeating( [](ToggleButtonExample* example) { PrintStatus("Pressed 3! count: %d", ++example->count_2_); }, base::Unretained(this)))); button->SetAccessibleName( l10n_util::GetStringUTF16(IDS_TOGGLE_BUTTON_NAME_3)); button->SetEnabled(false); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/toggle_button_example.cc
C++
unknown
2,174
// Copyright 2016 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_TOGGLE_BUTTON_EXAMPLE_H_ #define UI_VIEWS_EXAMPLES_TOGGLE_BUTTON_EXAMPLE_H_ #include "ui/views/examples/example_base.h" namespace views { class ToggleButton; namespace examples { // ToggleButtonExample exercises a ToggleButton control. class VIEWS_EXAMPLES_EXPORT ToggleButtonExample : public ExampleBase { public: ToggleButtonExample(); ToggleButtonExample(const ToggleButtonExample&) = delete; ToggleButtonExample& operator=(const ToggleButtonExample&) = delete; ~ToggleButtonExample() override; // ExampleBase: void CreateExampleView(View* container) override; private: int count_1_ = 0; int count_2_ = 0; }; } // namespace examples } // namespace views #endif // UI_VIEWS_EXAMPLES_TOGGLE_BUTTON_EXAMPLE_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/toggle_button_example.h
C++
unknown
911
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/tree_view_example.h" #include <utility> #include "base/strings/utf_string_conversions.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/menu/menu_model_adapter.h" #include "ui/views/controls/menu/menu_runner.h" #include "ui/views/controls/scroll_view.h" #include "ui/views/controls/tree/tree_view.h" #include "ui/views/controls/tree/tree_view_drawing_provider.h" #include "ui/views/examples/grit/views_examples_resources.h" #include "ui/views/layout/flex_layout.h" #include "ui/views/layout/flex_layout_types.h" #include "ui/views/view_class_properties.h" using l10n_util::GetStringUTF16; using l10n_util::GetStringUTF8; namespace { class ExampleTreeViewDrawingProvider : public views::TreeViewDrawingProvider { public: ExampleTreeViewDrawingProvider() = default; ~ExampleTreeViewDrawingProvider() override = default; std::u16string GetAuxiliaryTextForNode(views::TreeView* tree_view, ui::TreeModelNode* node) override { if (tree_view->GetSelectedNode() == node) return GetStringUTF16(IDS_TREE_VIEW_SELECTED_LABEL); return views::TreeViewDrawingProvider::GetAuxiliaryTextForNode(tree_view, node); } bool ShouldDrawIconForNode(views::TreeView* tree_view, ui::TreeModelNode* node) override { return tree_view->GetSelectedNode() != node; } }; } // namespace namespace views::examples { TreeViewExample::TreeViewExample() : ExampleBase(GetStringUTF8(IDS_TREE_VIEW_SELECT_LABEL).c_str()), model_(std::make_unique<NodeType>( GetStringUTF16(IDS_TREE_VIEW_ROOT_NODE_LABEL), 1)) {} TreeViewExample::~TreeViewExample() { // Remove the model from the view. if (tree_view_) tree_view_->SetModel(nullptr); } void TreeViewExample::CreateExampleView(View* container) { // Add some sample data. NodeType* colors_node = model_.GetRoot()->Add( std::make_unique<NodeType>(GetStringUTF16(IDS_TREE_VIEW_COLOR_NODE_LABEL), 1), 0); colors_node->Add(std::make_unique<NodeType>( GetStringUTF16(IDS_TREE_VIEW_COLOR_RED_LABEL), 1), 0); colors_node->Add(std::make_unique<NodeType>( GetStringUTF16(IDS_TREE_VIEW_COLOR_GREEN_LABEL), 1), 1); colors_node->Add(std::make_unique<NodeType>( GetStringUTF16(IDS_TREE_VIEW_COLOR_BLUE_LABEL), 1), 2); NodeType* sheep_node = model_.GetRoot()->Add( std::make_unique<NodeType>(GetStringUTF16(IDS_TREE_VIEW_SHEEP_NODE_LABEL), 1), 0); sheep_node->Add( std::make_unique<NodeType>(GetStringUTF16(IDS_TREE_VIEW_SHEEP1_LABEL), 1), 0); sheep_node->Add( std::make_unique<NodeType>(GetStringUTF16(IDS_TREE_VIEW_SHEEP2_LABEL), 1), 1); auto tree_view = std::make_unique<TreeView>(); tree_view->set_context_menu_controller(this); tree_view->SetRootShown(false); tree_view->SetModel(&model_); tree_view->SetController(this); tree_view->SetDrawingProvider( std::make_unique<ExampleTreeViewDrawingProvider>()); auto add = std::make_unique<LabelButton>( base::BindRepeating(&TreeViewExample::AddNewNode, base::Unretained(this)), GetStringUTF16(IDS_TREE_VIEW_ADD_BUTTON_LABEL)); add->SetRequestFocusOnPress(true); auto remove = std::make_unique<LabelButton>( base::BindRepeating(&TreeViewExample::RemoveSelectedNode, base::Unretained(this)), GetStringUTF16(IDS_TREE_VIEW_REMOVE_BUTTON_LABEL)); remove->SetRequestFocusOnPress(true); auto change_title = std::make_unique<LabelButton>( base::BindRepeating(&TreeViewExample::SetSelectedNodeTitle, base::Unretained(this)), GetStringUTF16(IDS_TREE_VIEW_CHANGE_TITLE_LABEL)); change_title->SetRequestFocusOnPress(true); container->SetLayoutManager(std::make_unique<views::FlexLayout>()) ->SetOrientation(LayoutOrientation::kVertical); auto full_flex = FlexSpecification(MinimumFlexSizeRule::kScaleToZero, MaximumFlexSizeRule::kUnbounded) .WithWeight(1); tree_view_ = tree_view.get(); container ->AddChildView(TreeView::CreateScrollViewWithTree(std::move(tree_view))) ->SetProperty(views::kFlexBehaviorKey, full_flex); // Add control buttons horizontally. auto* button_panel = container->AddChildView(std::make_unique<View>()); button_panel->SetLayoutManager(std::make_unique<FlexLayout>()) ->SetOrientation(LayoutOrientation::kHorizontal); add_ = button_panel->AddChildView(std::move(add)); remove_ = button_panel->AddChildView(std::move(remove)); change_title_ = button_panel->AddChildView(std::move(change_title)); for (View* view : button_panel->children()) view->SetProperty(views::kFlexBehaviorKey, full_flex); } void TreeViewExample::AddNewNode() { NodeType* selected_node = static_cast<NodeType*>(tree_view_->GetSelectedNode()); if (!selected_node) selected_node = model_.GetRoot(); NodeType* new_node = model_.Add( selected_node, std::make_unique<NodeType>(selected_node->GetTitle(), 1)); tree_view_->SetSelectedNode(new_node); } void TreeViewExample::RemoveSelectedNode() { auto* selected_node = static_cast<NodeType*>(tree_view_->GetSelectedNode()); DCHECK(selected_node); DCHECK_NE(model_.GetRoot(), selected_node); model_.Remove(selected_node->parent(), selected_node); } void TreeViewExample::SetSelectedNodeTitle() { auto* selected_node = static_cast<NodeType*>(tree_view_->GetSelectedNode()); DCHECK(selected_node); model_.SetTitle( selected_node, selected_node->GetTitle() + GetStringUTF16(IDS_TREE_VIEW_NEW_NODE_LABEL)); } bool TreeViewExample::IsCommandIdEnabled(int command_id) { return command_id != ID_REMOVE || tree_view_->GetSelectedNode() != model_.GetRoot(); } void TreeViewExample::OnTreeViewSelectionChanged(TreeView* tree_view) { ui::TreeModelNode* node = tree_view_->GetSelectedNode(); if (node) { change_title_->SetEnabled(true); remove_->SetEnabled(node != model_.GetRoot()); } else { change_title_->SetEnabled(false); remove_->SetEnabled(false); } } bool TreeViewExample::CanEdit(TreeView* tree_view, ui::TreeModelNode* node) { return true; } void TreeViewExample::ShowContextMenuForViewImpl( View* source, const gfx::Point& point, ui::MenuSourceType source_type) { context_menu_model_ = std::make_unique<ui::SimpleMenuModel>(this); context_menu_model_->AddItem(ID_EDIT, GetStringUTF16(IDS_TREE_VIEW_EDIT_BUTTON_LABEL)); context_menu_model_->AddItem( ID_REMOVE, GetStringUTF16(IDS_TREE_VIEW_REMOVE_BUTTON_LABEL)); context_menu_model_->AddItem(ID_ADD, GetStringUTF16(IDS_TREE_VIEW_ADD_BUTTON_LABEL)); context_menu_runner_ = std::make_unique<MenuRunner>(context_menu_model_.get(), 0); context_menu_runner_->RunMenuAt(source->GetWidget(), nullptr, gfx::Rect(point, gfx::Size()), MenuAnchorPosition::kTopLeft, source_type); } bool TreeViewExample::IsCommandIdChecked(int command_id) const { return false; } bool TreeViewExample::IsCommandIdEnabled(int command_id) const { return const_cast<TreeViewExample*>(this)->IsCommandIdEnabled(command_id); } void TreeViewExample::ExecuteCommand(int command_id, int event_flags) { NodeType* selected_node = static_cast<NodeType*>(tree_view_->GetSelectedNode()); switch (command_id) { case ID_EDIT: tree_view_->StartEditing(selected_node); break; case ID_REMOVE: model_.Remove(selected_node->parent(), selected_node); break; case ID_ADD: AddNewNode(); break; default: NOTREACHED_NORETURN(); } } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/tree_view_example.cc
C++
unknown
8,217
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_TREE_VIEW_EXAMPLE_H_ #define UI_VIEWS_EXAMPLES_TREE_VIEW_EXAMPLE_H_ #include <memory> #include "base/memory/raw_ptr.h" #include "ui/base/models/simple_menu_model.h" #include "ui/base/models/tree_node_model.h" #include "ui/views/context_menu_controller.h" #include "ui/views/controls/tree/tree_view.h" #include "ui/views/controls/tree/tree_view_controller.h" #include "ui/views/examples/example_base.h" namespace ui { class SimpleMenuModel; } namespace views { class LabelButton; class MenuRunner; namespace examples { class VIEWS_EXAMPLES_EXPORT TreeViewExample : public ExampleBase, public TreeViewController, public ContextMenuController, public ui::SimpleMenuModel::Delegate { public: TreeViewExample(); TreeViewExample(const TreeViewExample&) = delete; TreeViewExample& operator=(const TreeViewExample&) = delete; ~TreeViewExample() override; // ExampleBase: void CreateExampleView(View* container) override; private: // IDs used by the context menu. enum MenuIDs { ID_EDIT, ID_REMOVE, ID_ADD }; void AddNewNode(); void RemoveSelectedNode(); void SetSelectedNodeTitle(); // Non-const version of IsCommandIdEnabled. bool IsCommandIdEnabled(int command_id); // TreeViewController: void OnTreeViewSelectionChanged(TreeView* tree_view) override; bool CanEdit(TreeView* tree_view, ui::TreeModelNode* node) override; // ContextMenuController: void ShowContextMenuForViewImpl(View* source, const gfx::Point& point, ui::MenuSourceType source_type) override; // SimpleMenuModel::Delegate: bool IsCommandIdChecked(int command_id) const override; bool IsCommandIdEnabled(int command_id) const override; void ExecuteCommand(int command_id, int event_flags) override; // The tree view to be tested. raw_ptr<TreeView> tree_view_ = nullptr; // Control buttons to modify the model. raw_ptr<LabelButton> add_ = nullptr; raw_ptr<LabelButton> remove_ = nullptr; raw_ptr<LabelButton> change_title_ = nullptr; using NodeType = ui::TreeNodeWithValue<int>; ui::TreeNodeModel<NodeType> model_; std::unique_ptr<ui::SimpleMenuModel> context_menu_model_; std::unique_ptr<MenuRunner> context_menu_runner_; }; } // namespace examples } // namespace views #endif // UI_VIEWS_EXAMPLES_TREE_VIEW_EXAMPLE_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/tree_view_example.h
C++
unknown
2,531
// Copyright 2015 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/vector_example.h" #include <memory> #include <string> #include <utility> #include <vector> #include "base/files/file_enumerator.h" #include "base/files/file_util.h" #include "base/memory/raw_ptr.h" #include "base/path_service.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_restrictions.h" #include "build/build_config.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/models/simple_combobox_model.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/views/border.h" #include "ui/views/controls/button/md_text_button.h" #include "ui/views/controls/editable_combobox/editable_combobox.h" #include "ui/views/controls/image_view.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/controls/textfield/textfield_controller.h" #include "ui/views/examples/examples_color_id.h" #include "ui/views/examples/grit/views_examples_resources.h" #include "ui/views/layout/box_layout.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/layout/table_layout.h" #include "ui/views/view.h" using l10n_util::GetStringUTF16; using l10n_util::GetStringUTF8; namespace views::examples { namespace { class VectorIconGallery : public View, public TextfieldController { public: VectorIconGallery() { size_input_ = AddChildView(std::make_unique<Textfield>()); color_input_ = AddChildView(std::make_unique<Textfield>()); image_view_container_ = AddChildView(std::make_unique<views::View>()); BoxLayout* box = SetLayoutManager(std::make_unique<BoxLayout>( BoxLayout::Orientation::kVertical, gfx::Insets(10), 10)); box->SetFlexForView(image_view_container_, 1); base::FilePath test_dir; base::PathService::Get(base::DIR_SOURCE_ROOT, &test_dir); std::u16string base_path = test_dir.AsUTF16Unsafe(); std::vector<std::u16string> icon_dir = { base::FilePath(test_dir.AppendASCII("ash") .AppendASCII("resources") .AppendASCII("vector_icons")) .AsUTF16Unsafe(), base::FilePath( test_dir.AppendASCII("chrome").AppendASCII("app").AppendASCII( "vector_icons")) .AsUTF16Unsafe(), base::FilePath(test_dir.AppendASCII("chromeos") .AppendASCII("ui") .AppendASCII("vector_icons")) .AsUTF16Unsafe(), base::FilePath( test_dir.AppendASCII("components").AppendASCII("vector_icons")) .AsUTF16Unsafe(), base::FilePath(test_dir.AppendASCII("components") .AppendASCII("omnibox") .AppendASCII("browser") .AppendASCII("vector_icons")) .AsUTF16Unsafe(), base::FilePath( test_dir.AppendASCII("ui").AppendASCII("views").AppendASCII( "vector_icons")) .AsUTF16Unsafe(), }; auto editable_combobox = std::make_unique<views::EditableCombobox>(); editable_combobox->SetModel(std::make_unique<ui::SimpleComboboxModel>( std::vector<ui::SimpleComboboxModel::Item>(icon_dir.begin(), icon_dir.end()))); editable_combobox->SetPlaceholderText( GetStringUTF16(IDS_VECTOR_FILE_SELECT_LABEL)); editable_combobox->SetAccessibleName(u"Editable Combobox"); auto file_container = std::make_unique<View>(); BoxLayout* file_box = file_container->SetLayoutManager(std::make_unique<BoxLayout>( BoxLayout::Orientation::kHorizontal, gfx::Insets(10), 10)); file_chooser_combobox_ = file_container->AddChildView(std::move(editable_combobox)); file_go_button_ = file_container->AddChildView(std::make_unique<MdTextButton>( base::BindRepeating(&VectorIconGallery::FileGoButtonPressed, base::Unretained(this)), GetStringUTF16(IDS_VECTOR_RENDER_LABEL))); file_box->SetFlexForView(file_chooser_combobox_, 1); AddChildView(std::move(file_container)); size_input_->SetPlaceholderText( GetStringUTF16(IDS_VECTOR_DIP_SIZE_DESC_LABEL)); size_input_->set_controller(this); color_input_->SetPlaceholderText( GetStringUTF16(IDS_VECTOR_COLOR_DESC_LABEL)); color_input_->set_controller(this); } VectorIconGallery(const VectorIconGallery&) = delete; VectorIconGallery& operator=(const VectorIconGallery&) = delete; ~VectorIconGallery() override = default; // TextfieldController implementation. void ContentsChanged(Textfield* sender, const std::u16string& new_contents) override { if (sender == size_input_) { if (base::StringToInt(new_contents, &size_) && (size_ > 0)) Update(); else size_input_->SetText(std::u16string()); return; } DCHECK_EQ(color_input_, sender); if (new_contents.size() != 8u) return; unsigned new_color = strtoul(base::UTF16ToASCII(new_contents).c_str(), nullptr, 16); if (new_color <= 0xffffffff) { color_ = new_color; Update(); } } private: void FileGoButtonPressed() { #if BUILDFLAG(IS_WIN) base::FilePath path(base::UTF16ToWide(file_chooser_combobox_->GetText())); #else base::FilePath path(base::UTF16ToUTF8(file_chooser_combobox_->GetText())); #endif // If there is an extension, then it would not be a folder. if (path.Extension().size() == 0) { GenerateAllIconInFolder(path); } else { GenerateSingleIcon(path); } } void GenerateSingleIcon(const base::FilePath& path) { image_view_container_->RemoveAllChildViews(); image_view_ = image_view_container_->AddChildView(std::make_unique<ImageView>()); image_view_->SetBorder(CreateThemedSolidBorder( 1, ExamplesColorIds::kColorVectorExampleImageBorder)); auto image_layout = std::make_unique<BoxLayout>(BoxLayout::Orientation::kHorizontal); image_layout->set_cross_axis_alignment( BoxLayout::CrossAxisAlignment::kCenter); image_layout->set_main_axis_alignment( BoxLayout::MainAxisAlignment::kCenter); image_view_container_->SetLayoutManager(std::move(image_layout)); base::ScopedAllowBlockingForTesting allow_blocking; base::ReadFileToString(path, &contents_); // Skip over comments. for (size_t slashes = contents_.find("//"); slashes != std::string::npos; slashes = contents_.find("//")) { size_t eol = contents_.find("\n", slashes); contents_.erase(slashes, eol - slashes); } Update(); } void GenerateAllIconInFolder(const base::FilePath& path) { image_view_container_->RemoveAllChildViews(); int nCols = image_view_container_->width() / size_; int kColumnWidth = size_; views::TableLayout* layout = image_view_container_->SetLayoutManager( std::make_unique<views::TableLayout>()); for (int i = 0; i < nCols; ++i) { layout->AddColumn(LayoutAlignment::kStretch, LayoutAlignment::kStretch, TableLayout::kFixedSize, TableLayout::ColumnSize::kFixed, kColumnWidth, kColumnWidth); } int nRows = image_view_container_->height() / size_; for (int i = 0; i < nRows; ++i) { layout->AddRows(1, TableLayout::kFixedSize); } size_t max = nCols * nRows; size_t count = 0; { base::ScopedAllowBlockingForTesting allow_blocking; base::FileEnumerator file_iter(path, false, base::FileEnumerator::FILES, FILE_PATH_LITERAL("*.icon")); base::FilePath file = file_iter.Next(); while (!file.empty() && count < max) { count++; std::string file_content; base::ReadFileToString(file, &file_content); // Skip over comments. // This handles very basic cases of // and /*. More complicated edge // cases such as /* /* */ */ are not handled. for (size_t slashes = file_content.find("//"); slashes != std::string::npos; slashes = file_content.find("//")) { size_t eol = file_content.find("\n", slashes); file_content.erase(slashes, eol - slashes); } for (size_t slashes = file_content.find("/*"); slashes != std::string::npos; slashes = file_content.find("/*")) { size_t eol = file_content.find("*/", slashes); file_content.erase(slashes, eol - slashes + 2); } ImageView* icon_view = image_view_container_->AddChildView(std::make_unique<ImageView>()); icon_view->SetImage( gfx::CreateVectorIconFromSource(file_content, size_, color_)); icon_view->SetTooltipText(file.BaseName().AsUTF16Unsafe()); file = file_iter.Next(); } } InvalidateLayout(); } void Update() { if (!contents_.empty() && image_view_ != nullptr) { image_view_->SetImage( gfx::CreateVectorIconFromSource(contents_, size_, color_)); } InvalidateLayout(); } // 36dp is one of the natural sizes for MD icons, and corresponds roughly to a // 32dp usable area. int size_ = 36; SkColor color_ = gfx::kPlaceholderColor; raw_ptr<ImageView> image_view_; raw_ptr<View> image_view_container_; raw_ptr<Textfield> size_input_; raw_ptr<Textfield> color_input_; raw_ptr<EditableCombobox> file_chooser_combobox_; raw_ptr<Button> file_go_button_; std::string contents_; }; } // namespace VectorExample::VectorExample() : ExampleBase(GetStringUTF8(IDS_VECTOR_SELECT_LABEL).c_str()) {} VectorExample::~VectorExample() = default; void VectorExample::CreateExampleView(View* container) { container->SetLayoutManager(std::make_unique<FillLayout>()); container->AddChildView(std::make_unique<VectorIconGallery>()); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/vector_example.cc
C++
unknown
10,172
// Copyright 2015 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_VECTOR_EXAMPLE_H_ #define UI_VIEWS_EXAMPLES_VECTOR_EXAMPLE_H_ #include "ui/views/examples/example_base.h" namespace views::examples { class VIEWS_EXAMPLES_EXPORT VectorExample : public ExampleBase { public: VectorExample(); VectorExample(const VectorExample&) = delete; VectorExample& operator=(const VectorExample&) = delete; ~VectorExample() override; // ExampleBase: void CreateExampleView(View* container) override; }; } // namespace views::examples #endif // UI_VIEWS_EXAMPLES_VECTOR_EXAMPLE_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/vector_example.h
C++
unknown
693
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_VIEWS_EXAMPLES_EXPORT_H_ #define UI_VIEWS_EXAMPLES_VIEWS_EXAMPLES_EXPORT_H_ // Defines VIEWS_EXAMPLES_EXPORT so that functionality implemented by the // views_examples_with_content_lib module can be exported to consumers. #if defined(COMPONENT_BUILD) #if defined(WIN32) #if defined(VIEWS_EXAMPLES_IMPLEMENTATION) #define VIEWS_EXAMPLES_EXPORT __declspec(dllexport) #else #define VIEWS_EXAMPLES_EXPORT __declspec(dllimport) #endif // defined(VIEWS_EXAMPLES_IMPLEMENTATION) #else // defined(WIN32) #if defined(VIEWS_EXAMPLES_IMPLEMENTATION) #define VIEWS_EXAMPLES_EXPORT __attribute__((visibility("default"))) #else #define VIEWS_EXAMPLES_EXPORT #endif #endif #else // defined(COMPONENT_BUILD) #define VIEWS_EXAMPLES_EXPORT #endif #endif // UI_VIEWS_EXAMPLES_VIEWS_EXAMPLES_EXPORT_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/views_examples_export.h
C
unknown
962
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_VIEWS_EXAMPLES_WITH_CONTENT_EXPORT_H_ #define UI_VIEWS_EXAMPLES_VIEWS_EXAMPLES_WITH_CONTENT_EXPORT_H_ // Defines VIEWS_EXAMPLES_WITH_CONTENT_EXPORT so that functionality implemented // by the views_examples_with_content_lib module can be exported to consumers. #if defined(COMPONENT_BUILD) #if defined(WIN32) #if defined(VIEWS_EXAMPLES_WITH_CONTENT_IMPLEMENTATION) #define VIEWS_EXAMPLES_WITH_CONTENT_EXPORT __declspec(dllexport) #else #define VIEWS_EXAMPLES_WITH_CONTENT_EXPORT __declspec(dllimport) #endif // defined(VIEWS_EXAMPLES_WITH_CONTENT_IMPLEMENTATION) #else // defined(WIN32) #if defined(VIEWS_EXAMPLES_WITH_CONTENT_IMPLEMENTATION) #define VIEWS_EXAMPLES_WITH_CONTENT_EXPORT \ __attribute__((visibility("default"))) #else #define VIEWS_EXAMPLES_WITH_CONTENT_EXPORT #endif #endif #else // defined(COMPONENT_BUILD) #define VIEWS_EXAMPLES_WITH_CONTENT_EXPORT #endif #endif // UI_VIEWS_EXAMPLES_VIEWS_EXAMPLES_WITH_CONTENT_EXPORT_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/views_examples_with_content_export.h
C
unknown
1,122
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/webview_example.h" #include <memory> #include "content/public/browser/browser_context.h" #include "content/public/browser/web_contents.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/examples/grit/views_examples_resources.h" #include "ui/views/layout/fill_layout.h" namespace views::examples { WebViewExample::WebViewExample(content::BrowserContext* browser_context) : ExampleBase(l10n_util::GetStringUTF8(IDS_WEBVIEW_SELECT_LABEL).c_str()), webview_(nullptr), browser_context_(browser_context) {} WebViewExample::~WebViewExample() = default; void WebViewExample::CreateExampleView(View* container) { webview_ = container->AddChildView(std::make_unique<WebView>(browser_context_)); webview_->GetWebContents()->SetDelegate(this); container->SetLayoutManager(std::make_unique<FillLayout>()); webview_->LoadInitialURL(GURL("http://www.google.com/")); webview_->GetWebContents()->Focus(); } bool WebViewExample::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { return unhandled_keyboard_event_handler_.HandleKeyboardEvent( event, webview_->GetFocusManager()); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/webview_example.cc
C++
unknown
1,426
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_WEBVIEW_EXAMPLE_H_ #define UI_VIEWS_EXAMPLES_WEBVIEW_EXAMPLE_H_ #include "base/memory/raw_ptr.h" #include "content/public/browser/web_contents_delegate.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/examples/example_base.h" namespace content { class BrowserContext; } namespace views { class WebView; namespace examples { class WebViewExample : public ExampleBase, public content::WebContentsDelegate { public: explicit WebViewExample(content::BrowserContext* browser_context); WebViewExample(const WebViewExample&) = delete; WebViewExample& operator=(const WebViewExample&) = delete; ~WebViewExample() override; // ExampleBase: void CreateExampleView(View* container) override; // content::WebContentsDelegate: bool HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) override; private: raw_ptr<WebView> webview_; raw_ptr<content::BrowserContext> browser_context_; views::UnhandledKeyboardEventHandler unhandled_keyboard_event_handler_; }; } // namespace examples } // namespace views #endif // UI_VIEWS_EXAMPLES_WEBVIEW_EXAMPLE_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/webview_example.h
C++
unknown
1,346
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/widget_example.h" #include <memory> #include <utility> #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/geometry/insets.h" #include "ui/views/background.h" #include "ui/views/controls/button/md_text_button.h" #include "ui/views/controls/label.h" #include "ui/views/examples/examples_color_id.h" #include "ui/views/examples/grit/views_examples_resources.h" #include "ui/views/layout/box_layout.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" #include "ui/views/window/dialog_delegate.h" using l10n_util::GetStringUTF16; using l10n_util::GetStringUTF8; namespace views::examples { WidgetExample::WidgetExample() : ExampleBase(GetStringUTF8(IDS_WIDGET_SELECT_LABEL).c_str()) {} WidgetExample::~WidgetExample() = default; void WidgetExample::CreateExampleView(View* container) { container->SetLayoutManager(std::make_unique<BoxLayout>( BoxLayout::Orientation::kHorizontal, gfx::Insets(), 10)); LabelButton* popup_button = BuildButton(container, GetStringUTF16(IDS_WIDGET_POPUP_BUTTON_LABEL)); popup_button->SetCallback( base::BindRepeating(&WidgetExample::ShowWidget, base::Unretained(this), popup_button, Widget::InitParams::TYPE_POPUP)); LabelButton* dialog_button = BuildButton(container, GetStringUTF16(IDS_WIDGET_DIALOG_BUTTON_LABEL)); dialog_button->SetCallback( base::BindRepeating(&WidgetExample::CreateDialogWidget, base::Unretained(this), dialog_button, false)); LabelButton* modal_button = BuildButton(container, GetStringUTF16(IDS_WIDGET_MODAL_BUTTON_LABEL)); modal_button->SetCallback( base::BindRepeating(&WidgetExample::CreateDialogWidget, base::Unretained(this), modal_button, true)); #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // Windows does not support TYPE_CONTROL top-level widgets. LabelButton* control_button = BuildButton( container, GetStringUTF16(IDS_WIDGET_CHILD_WIDGET_BUTTON_LABEL)); control_button->SetCallback( base::BindRepeating(&WidgetExample::ShowWidget, base::Unretained(this), control_button, Widget::InitParams::TYPE_CONTROL)); #endif } LabelButton* WidgetExample::BuildButton(View* container, const std::u16string& label) { LabelButton* button = container->AddChildView( std::make_unique<LabelButton>(Button::PressedCallback(), label)); button->SetRequestFocusOnPress(true); return button; } void WidgetExample::CreateDialogWidget(View* sender, bool modal) { auto dialog = std::make_unique<DialogDelegateView>(); dialog->SetTitle(IDS_WIDGET_WINDOW_TITLE); dialog->SetBackground(CreateThemedSolidBackground( ExamplesColorIds::kColorWidgetExampleDialogBorder)); dialog->SetLayoutManager(std::make_unique<BoxLayout>( BoxLayout::Orientation::kVertical, gfx::Insets(10), 10)); dialog->SetExtraView(std::make_unique<MdTextButton>( Button::PressedCallback(), GetStringUTF16(IDS_WIDGET_EXTRA_BUTTON))); dialog->SetFootnoteView( std::make_unique<Label>(GetStringUTF16(IDS_WIDGET_FOOTNOTE_LABEL))); dialog->AddChildView(std::make_unique<Label>( GetStringUTF16(IDS_WIDGET_DIALOG_CONTENTS_LABEL))); if (modal) dialog->SetModalType(ui::MODAL_TYPE_WINDOW); DialogDelegate::CreateDialogWidget(dialog.release(), nullptr, sender->GetWidget()->GetNativeView()) ->Show(); } void WidgetExample::ShowWidget(View* sender, Widget::InitParams::Type type) { // Setup shared Widget hierarchy and bounds parameters. Widget::InitParams params(type); params.parent = sender->GetWidget()->GetNativeView(); params.bounds = gfx::Rect(sender->GetBoundsInScreen().CenterPoint(), gfx::Size(300, 200)); // A widget handles its own lifetime. Widget* widget = new Widget(); widget->Init(std::move(params)); // If the Widget has no contents by default, add a view with a 'Close' button. if (!widget->GetContentsView()) { View* contents = widget->SetContentsView(std::make_unique<View>()); contents->SetLayoutManager( std::make_unique<BoxLayout>(BoxLayout::Orientation::kHorizontal)); contents->SetBackground(CreateThemedSolidBackground( ExamplesColorIds::kColorWidgetExampleContentBorder)); BuildButton(contents, GetStringUTF16(IDS_WIDGET_CLOSE_BUTTON_LABEL)) ->SetCallback( base::BindRepeating(&Widget::Close, base::Unretained(widget))); } widget->Show(); } } // namespace views::examples
Zhao-PengFei35/chromium_src_4
ui/views/examples/widget_example.cc
C++
unknown
4,792
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_EXAMPLES_WIDGET_EXAMPLE_H_ #define UI_VIEWS_EXAMPLES_WIDGET_EXAMPLE_H_ #include <string> #include "ui/views/examples/example_base.h" #include "ui/views/widget/widget.h" namespace views { class LabelButton; namespace examples { // WidgetExample demonstrates how to create a popup widget. class VIEWS_EXAMPLES_EXPORT WidgetExample : public ExampleBase { public: WidgetExample(); WidgetExample(const WidgetExample&) = delete; WidgetExample& operator=(const WidgetExample&) = delete; ~WidgetExample() override; // ExampleBase: void CreateExampleView(View* container) override; private: // Construct a button with the specified |label| in |container|. LabelButton* BuildButton(View* container, const std::u16string& label); void CreateDialogWidget(View* sender, bool modal); // Construct a Widget for |sender|, initialize with |type|, and call Show(). void ShowWidget(View* sender, Widget::InitParams::Type type); }; } // namespace examples } // namespace views #endif // UI_VIEWS_EXAMPLES_WIDGET_EXAMPLE_H_
Zhao-PengFei35/chromium_src_4
ui/views/examples/widget_example.h
C++
unknown
1,205
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/focus/external_focus_tracker.h" #include <memory> #include "base/check.h" #include "ui/views/view.h" #include "ui/views/view_tracker.h" namespace views { ExternalFocusTracker::ExternalFocusTracker(View* parent_view, FocusManager* focus_manager) : focus_manager_(focus_manager), parent_view_(parent_view), last_focused_view_tracker_(std::make_unique<ViewTracker>()) { DCHECK(parent_view); // Store the view which is focused when we're created. if (focus_manager_) StartTracking(); } ExternalFocusTracker::~ExternalFocusTracker() { if (focus_manager_) focus_manager_->RemoveFocusChangeListener(this); } void ExternalFocusTracker::OnWillChangeFocus(View* focused_before, View* focused_now) { if (focused_now && !parent_view_->Contains(focused_now) && parent_view_ != focused_now) { // Store the newly focused view. StoreLastFocusedView(focused_now); } } void ExternalFocusTracker::OnDidChangeFocus(View* focused_before, View* focused_now) {} void ExternalFocusTracker::FocusLastFocusedExternalView() { View* last_focused_view = last_focused_view_tracker_->view(); if (last_focused_view) last_focused_view->RequestFocus(); } void ExternalFocusTracker::SetFocusManager(FocusManager* focus_manager) { if (focus_manager_) focus_manager_->RemoveFocusChangeListener(this); focus_manager_ = focus_manager; if (focus_manager_) StartTracking(); } void ExternalFocusTracker::StoreLastFocusedView(View* view) { last_focused_view_tracker_->SetView(view); } void ExternalFocusTracker::StartTracking() { View* current_focused_view = focus_manager_->GetFocusedView(); // During focus restore events, it's possible for focus to already be within // the parent_view_. if (!parent_view_->Contains(current_focused_view)) StoreLastFocusedView(current_focused_view); focus_manager_->AddFocusChangeListener(this); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/focus/external_focus_tracker.cc
C++
unknown
2,209
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_FOCUS_EXTERNAL_FOCUS_TRACKER_H_ #define UI_VIEWS_FOCUS_EXTERNAL_FOCUS_TRACKER_H_ #include <memory> #include "base/memory/raw_ptr.h" #include "ui/views/focus/focus_manager.h" namespace views { class View; class ViewTracker; // ExternalFocusTracker tracks the last focused view which belongs to the // provided focus manager and is not either the provided parent view or one of // its descendants. This is generally used if the parent view want to return // focus to some other view once it is dismissed. The parent view and the focus // manager must exist for the duration of the tracking. If the focus manager // must be deleted before this object is deleted, make sure to call // SetFocusManager(NULL) first. // // Typical use: When a view is added to the view hierarchy, it instantiates an // ExternalFocusTracker and passes in itself and its focus manager. Then, // when that view wants to return focus to the last focused view which is not // itself and not a descandant of itself, (usually when it is being closed) // it calls FocusLastFocusedExternalView. class VIEWS_EXPORT ExternalFocusTracker : public FocusChangeListener { public: ExternalFocusTracker(View* parent_view, FocusManager* focus_manager); ExternalFocusTracker(const ExternalFocusTracker&) = delete; ExternalFocusTracker& operator=(const ExternalFocusTracker&) = delete; ~ExternalFocusTracker() override; // FocusChangeListener: void OnWillChangeFocus(View* focused_before, View* focused_now) override; void OnDidChangeFocus(View* focused_before, View* focused_now) override; // Focuses last focused view which is not a child of parent view and is not // parent view itself. Returns true if focus for a view was requested, false // otherwise. void FocusLastFocusedExternalView(); // Sets the focus manager whose focus we are tracking. |focus_manager| can // be NULL, but no focus changes will be tracked. This is useful if the focus // manager went away, but you might later want to start tracking with a new // manager later, or call FocusLastFocusedExternalView to focus the previous // view. void SetFocusManager(FocusManager* focus_manager); private: // Store the provided view. This view will be focused when // FocusLastFocusedExternalView is called. void StoreLastFocusedView(View* view); // Store the currently focused view for our view manager and register as a // listener for future focus changes. void StartTracking(); // Focus manager which we are a listener for. raw_ptr<FocusManager, DanglingUntriaged> focus_manager_; // The parent view of views which we should not track focus changes to. We // also do not track changes to parent_view_ itself. raw_ptr<View, DanglingUntriaged> parent_view_; // Holds the last focused view. std::unique_ptr<ViewTracker> last_focused_view_tracker_; }; } // namespace views #endif // UI_VIEWS_FOCUS_EXTERNAL_FOCUS_TRACKER_H_
Zhao-PengFei35/chromium_src_4
ui/views/focus/external_focus_tracker.h
C++
unknown
3,085
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/focus/focus_manager.h" #include <utility> #include <vector> #include "base/auto_reset.h" #include "base/check_op.h" #include "base/containers/cxx20_erase.h" #include "base/i18n/rtl.h" #include "base/observer_list.h" #include "base/ranges/algorithm.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "ui/base/accelerators/accelerator.h" #include "ui/base/ime/input_method.h" #include "ui/base/ime/text_input_client.h" #include "ui/events/event.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/views/bubble/bubble_dialog_delegate_view.h" #include "ui/views/focus/focus_manager_delegate.h" #include "ui/views/focus/focus_search.h" #include "ui/views/focus/widget_focus_manager.h" #include "ui/views/view.h" #include "ui/views/view_class_properties.h" #include "ui/views/view_tracker.h" #include "ui/views/widget/root_view.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_delegate.h" namespace views { bool FocusManager::arrow_key_traversal_enabled_ = false; FocusManager::FocusManager(Widget* widget, std::unique_ptr<FocusManagerDelegate> delegate) : widget_(widget), delegate_(std::move(delegate)), view_tracker_for_stored_view_(std::make_unique<ViewTracker>()) { DCHECK(widget_); } FocusManager::~FocusManager() { if (focused_view_) focused_view_->RemoveObserver(this); } bool FocusManager::OnKeyEvent(const ui::KeyEvent& event) { const int key_code = event.key_code(); if (event.type() != ui::ET_KEY_PRESSED && event.type() != ui::ET_KEY_RELEASED) return false; if (shortcut_handling_suspended()) return true; ui::Accelerator accelerator(event); if (event.type() == ui::ET_KEY_PRESSED) { // If the focused view wants to process the key event as is, let it be. if (focused_view_ && focused_view_->SkipDefaultKeyEventProcessing(event) && !accelerator_manager_.HasPriorityHandler(accelerator)) return true; // Intercept Tab related messages for focus traversal. // Note that we don't do focus traversal if the root window is not part of // the active window hierarchy as this would mean we have no focused view // and would focus the first focusable view. if (IsTabTraversalKeyEvent(event)) { AdvanceFocus(event.IsShiftDown()); return false; } if (IsArrowKeyTraversalEnabledForWidget() && ProcessArrowKeyTraversal(event)) { return false; } // Intercept arrow key messages to switch between grouped views. bool is_left = key_code == ui::VKEY_LEFT || key_code == ui::VKEY_UP; bool is_right = key_code == ui::VKEY_RIGHT || key_code == ui::VKEY_DOWN; if (focused_view_ && focused_view_->GetGroup() != -1 && (is_left || is_right)) { bool next = is_right; View::Views views; focused_view_->parent()->GetViewsInGroup(focused_view_->GetGroup(), &views); // Remove any views except current, which are disabled or hidden. base::EraseIf(views, [this](View* v) { return v != focused_view_ && !v->IsAccessibilityFocusable(); }); View::Views::const_iterator i = base::ranges::find(views, focused_view_); DCHECK(i != views.end()); auto index = static_cast<size_t>(i - views.begin()); if (next && index == views.size() - 1) index = 0; else if (!next && index == 0) index = views.size() - 1; else index = next ? (index + 1) : (index - 1); SetFocusedViewWithReason(views[index], FocusChangeReason::kFocusTraversal); return false; } } // Process keyboard accelerators. // If the key combination matches an accelerator, the accelerator is // triggered, otherwise the key event is processed as usual. if (ProcessAccelerator(accelerator)) { // If a shortcut was activated for this keydown message, do not propagate // the event further. return false; } return true; } // Tests whether a view is valid, whether it still belongs to the window // hierarchy of the FocusManager. bool FocusManager::ContainsView(View* view) { Widget* widget = view->GetWidget(); return widget && widget->GetFocusManager() == this; } void FocusManager::AdvanceFocus(bool reverse) { View* v = GetNextFocusableView(focused_view_, nullptr, reverse, false); // Note: Do not skip this next block when v == focused_view_. If the user // tabs past the last focusable element in a webpage, we'll get here, and if // the TabContentsContainerView is the only focusable view (possible in // fullscreen mode), we need to run this block in order to cycle around to the // first element on the page. if (v) { views::View* focused_view = focused_view_; v->AboutToRequestFocusFromTabTraversal(reverse); // AboutToRequestFocusFromTabTraversal() may have changed focus. If it did, // don't change focus again. if (focused_view != focused_view_) return; // Note that GetNextFocusableView may have returned a View in a different // FocusManager. DCHECK(v->GetWidget()); v->GetWidget()->GetFocusManager()->SetFocusedViewWithReason( v, FocusChangeReason::kFocusTraversal); // When moving focus from a child widget to a top-level widget, // the top-level widget may report IsActive()==true because it's // active even though it isn't focused. Explicitly activate the // widget to ensure that case is handled. if (v->GetWidget()->GetFocusManager() != this) v->GetWidget()->Activate(); } } void FocusManager::ClearNativeFocus() { // Keep the top root window focused so we get keyboard events. widget_->ClearNativeFocus(); } bool FocusManager::RotatePaneFocus(Direction direction, FocusCycleWrapping wrapping) { // Get the list of all accessible panes. std::vector<View*> panes; widget_->widget_delegate()->GetAccessiblePanes(&panes); // Count the number of panes and set the default index if no pane // is initially focused. const size_t count = panes.size(); if (!count) return false; // Initialize |index| to an appropriate starting index if nothing is // focused initially. size_t index = (direction == Direction::kBackward) ? 0 : (count - 1); // Check to see if a pane already has focus and update the index accordingly. const views::View* focused_view = GetFocusedView(); if (focused_view) { const auto i = base::ranges::find_if(panes, [focused_view](const auto* pane) { return pane && pane->Contains(focused_view); }); if (i != panes.cend()) index = static_cast<size_t>(i - panes.cbegin()); } // Rotate focus. for (const size_t start_index = index;;) { index = ((direction == Direction::kBackward) ? (index + count - 1) : (index + 1)) % count; if ((wrapping == FocusCycleWrapping::kDisabled) && (index == ((direction == Direction::kBackward) ? (count - 1) : 0))) { return false; } // Ensure that we don't loop more than once. if (index == start_index) return false; views::View* pane = panes[index]; DCHECK(pane); if (pane->GetVisible()) { pane->RequestFocus(); // |pane| may be in a different widget, so don't assume its focus manager // is |this|. focused_view = pane->GetWidget()->GetFocusManager()->GetFocusedView(); if (pane == focused_view || pane->Contains(focused_view)) return true; } } } View* FocusManager::GetNextFocusableView(View* original_starting_view, Widget* starting_widget, bool reverse, bool dont_loop) { DCHECK(!focused_view_ || ContainsView(focused_view_)) << " focus_view=" << focused_view_; FocusTraversable* focus_traversable = nullptr; View* starting_view = nullptr; if (original_starting_view) { // Search up the containment hierarchy to see if a view is acting as // a pane, and wants to implement its own focus traversable to keep // the focus trapped within that pane. View* pane_search = original_starting_view; while (pane_search) { focus_traversable = pane_search->GetPaneFocusTraversable(); if (focus_traversable) { starting_view = original_starting_view; break; } pane_search = pane_search->parent(); } if (!focus_traversable) { if (!reverse) { // If the starting view has a focus traversable, use it. // This is the case with NativeWidgetWins for example. focus_traversable = original_starting_view->GetFocusTraversable(); // Otherwise default to the root view. if (!focus_traversable) { focus_traversable = original_starting_view->GetWidget()->GetFocusTraversable(); starting_view = original_starting_view; } } else { // When you are going back, starting view's FocusTraversable // should not be used. focus_traversable = original_starting_view->GetWidget()->GetFocusTraversable(); starting_view = original_starting_view; } } } else { Widget* widget = starting_widget ? starting_widget : widget_.get(); focus_traversable = widget->GetFocusTraversable(); } // Traverse the FocusTraversable tree down to find the focusable view. View* v = FindFocusableView(focus_traversable, starting_view, reverse); if (v) return v; // Let's go up in the FocusTraversable tree. FocusTraversable* parent_focus_traversable = focus_traversable->GetFocusTraversableParent(); starting_view = focus_traversable->GetFocusTraversableParentView(); while (parent_focus_traversable) { FocusTraversable* new_focus_traversable = nullptr; View* new_starting_view = nullptr; // When we are going backward, the parent view might gain the next focus. auto check_starting_view = reverse ? FocusSearch::StartingViewPolicy::kCheckStartingView : FocusSearch::StartingViewPolicy::kSkipStartingView; v = parent_focus_traversable->GetFocusSearch()->FindNextFocusableView( starting_view, reverse ? FocusSearch::SearchDirection::kBackwards : FocusSearch::SearchDirection::kForwards, FocusSearch::TraversalDirection::kUp, check_starting_view, FocusSearch::AnchoredDialogPolicy::kSkipAnchoredDialog, &new_focus_traversable, &new_starting_view); if (new_focus_traversable) { DCHECK(!v); // There is a FocusTraversable, traverse it down. v = FindFocusableView(new_focus_traversable, nullptr, reverse); } if (v) return v; starting_view = focus_traversable->GetFocusTraversableParentView(); parent_focus_traversable = parent_focus_traversable->GetFocusTraversableParent(); } // If we get here, we have reached the end of the focus hierarchy, let's // loop. Make sure there was at least a view to start with, to prevent // infinitely looping in empty windows. if (dont_loop || !original_starting_view) return nullptr; // Easy, just clear the selection and press tab again. // By calling with nullptr as the starting view, we'll start from either // the starting views widget or |widget_|. Widget* widget = starting_view ? starting_view->GetWidget() : original_starting_view->GetWidget(); if (widget->widget_delegate()->focus_traverses_out()) widget = widget_; return GetNextFocusableView(nullptr, widget, reverse, true); } void FocusManager::SetKeyboardAccessible(bool keyboard_accessible) { if (keyboard_accessible == keyboard_accessible_) return; keyboard_accessible_ = keyboard_accessible; // Disabling keyboard accessibility may cause the focused view to become not // focusable. Hence advance focus if necessary. AdvanceFocusIfNecessary(); } bool FocusManager::IsSettingFocusedView() const { return setting_focused_view_entrance_count_ > 0; } void FocusManager::SetFocusedViewWithReason(View* view, FocusChangeReason reason) { if (focused_view_ == view) return; // TODO(oshima|achuith): This is to diagnose crbug.com/687232. // Change this to DCHECK once it's resolved. CHECK(!view || ContainsView(view)); #if !BUILDFLAG(IS_MAC) // TODO(warx): There are some AccessiblePaneViewTest failed on macosx. // crbug.com/650859. Remove !BUILDFLAG(IS_MAC) once that is fixed. // // If the widget isn't active store the focused view and then attempt to // activate the widget. If activation succeeds |view| will be focused. // If activation fails |view| will be focused the next time the widget is // made active. if (view && !widget_->IsActive()) { SetStoredFocusView(view); widget_->Activate(); return; } #endif // Update the reason for the focus change (since this is checked by // some listeners), then notify all listeners. focus_change_reason_ = reason; for (FocusChangeListener& observer : focus_change_listeners_) observer.OnWillChangeFocus(focused_view_, view); View* old_focused_view = focused_view_; focused_view_ = view; base::AutoReset<int> entrance_count_resetter( &setting_focused_view_entrance_count_, setting_focused_view_entrance_count_ + 1); if (old_focused_view) { old_focused_view->RemoveObserver(this); old_focused_view->Blur(); } // Also make |focused_view_| the stored focus view. This way the stored focus // view is remembered if focus changes are requested prior to a show or while // hidden. SetStoredFocusView(focused_view_); if (focused_view_) { focused_view_->AddObserver(this); focused_view_->Focus(); } for (FocusChangeListener& observer : focus_change_listeners_) observer.OnDidChangeFocus(old_focused_view, focused_view_); } void FocusManager::SetFocusedView(View* view) { FocusChangeReason reason = FocusChangeReason::kDirectFocusChange; if (in_restoring_focused_view_) reason = FocusChangeReason::kFocusRestore; SetFocusedViewWithReason(view, reason); } void FocusManager::ClearFocus() { // SetFocusedView(nullptr) is going to clear out the stored view to. We need // to persist it in this case. views::View* focused_view = GetStoredFocusView(); SetFocusedView(nullptr); ClearNativeFocus(); SetStoredFocusView(focused_view); } void FocusManager::AdvanceFocusIfNecessary() { // If widget is inactive, there is no focused view to check. The stored view // will also be checked for focusability when it is being restored. if (!widget_->IsActive()) return; // If widget is active and focused view is not focusable, advance focus or, // if not possible, clear focus. if (focused_view_ && !IsFocusable(focused_view_)) { AdvanceFocus(false); if (focused_view_ && !IsFocusable(focused_view_)) ClearFocus(); } } void FocusManager::StoreFocusedView(bool clear_native_focus) { View* focused_view = focused_view_; // Don't do anything if no focused view. Storing the view (which is nullptr), // in this case, would clobber the view that was previously saved. if (!focused_view_) return; View* v = focused_view_; if (clear_native_focus) { // Temporarily disable notification. ClearFocus() will set the focus to the // main browser window. This extra focus bounce which happens during // deactivation can confuse registered WidgetFocusListeners, as the focus // is not changing due to a user-initiated event. AutoNativeNotificationDisabler local_notification_disabler; // ClearFocus() also stores the focused view. ClearFocus(); } else { SetFocusedView(nullptr); SetStoredFocusView(focused_view); } if (v) v->SchedulePaint(); // Remove focus border. } bool FocusManager::RestoreFocusedView() { View* view = GetStoredFocusView(); if (view) { if (ContainsView(view)) { if (!view->IsFocusable() && view->IsAccessibilityFocusable()) { // RequestFocus would fail, but we want to restore focus to controls // that had focus in accessibility mode. SetFocusedViewWithReason(view, FocusChangeReason::kFocusRestore); } else { // This usually just sets the focus if this view is focusable, but // let the view override RequestFocus if necessary. base::AutoReset<bool> in_restore_bit(&in_restoring_focused_view_, true); view->RequestFocus(); } } // The |keyboard_accessible_| mode may have changed while the widget was // inactive. AdvanceFocusIfNecessary(); } return view && view == focused_view_; } void FocusManager::SetStoredFocusView(View* focus_view) { view_tracker_for_stored_view_->SetView(focus_view); } View* FocusManager::GetStoredFocusView() { return view_tracker_for_stored_view_->view(); } // Find the next (previous if reverse is true) focusable view for the specified // FocusTraversable, starting at the specified view, traversing down the // FocusTraversable hierarchy. View* FocusManager::FindFocusableView(FocusTraversable* focus_traversable, View* starting_view, bool reverse) { FocusTraversable* new_focus_traversable = nullptr; View* new_starting_view = nullptr; const FocusSearch::AnchoredDialogPolicy can_go_into_anchored_dialog = FocusSearch::AnchoredDialogPolicy::kCanGoIntoAnchoredDialog; const FocusSearch::SearchDirection search_direction = reverse ? FocusSearch::SearchDirection::kBackwards : FocusSearch::SearchDirection::kForwards; View* v = nullptr; // Let's go down the FocusTraversable tree as much as we can. do { v = focus_traversable->GetFocusSearch()->FindNextFocusableView( starting_view, search_direction, FocusSearch::TraversalDirection::kDown, FocusSearch::StartingViewPolicy::kSkipStartingView, can_go_into_anchored_dialog, &new_focus_traversable, &new_starting_view); DCHECK(!new_focus_traversable || !v); focus_traversable = std::exchange(new_focus_traversable, nullptr); starting_view = nullptr; } while (focus_traversable); return v; } void FocusManager::RegisterAccelerator( const ui::Accelerator& accelerator, ui::AcceleratorManager::HandlerPriority priority, ui::AcceleratorTarget* target) { accelerator_manager_.Register({accelerator}, priority, target); } void FocusManager::UnregisterAccelerator(const ui::Accelerator& accelerator, ui::AcceleratorTarget* target) { accelerator_manager_.Unregister(accelerator, target); } void FocusManager::UnregisterAccelerators(ui::AcceleratorTarget* target) { accelerator_manager_.UnregisterAll(target); } bool FocusManager::ProcessAccelerator(const ui::Accelerator& accelerator) { if (accelerator_manager_.Process(accelerator)) return true; if (delegate_ && delegate_->ProcessAccelerator(accelerator)) return true; #if BUILDFLAG(IS_MAC) // On MacOS accelerators are processed when a bubble is opened without // manual redirection to bubble anchor widget. Including redirect on MacOS // breaks processing accelerators by the bubble itself. return false; #else return RedirectAcceleratorToBubbleAnchorWidget(accelerator); #endif } bool FocusManager::IsAcceleratorRegistered( const ui::Accelerator& accelerator) const { return accelerator_manager_.IsRegistered(accelerator); } bool FocusManager::HasPriorityHandler( const ui::Accelerator& accelerator) const { return accelerator_manager_.HasPriorityHandler(accelerator); } // static bool FocusManager::IsTabTraversalKeyEvent(const ui::KeyEvent& key_event) { return key_event.key_code() == ui::VKEY_TAB && (!key_event.IsControlDown() && !key_event.IsAltDown()); } void FocusManager::ViewRemoved(View* removed) { // If the view being removed contains (or is) the focused view, // clear the focus. However, it's not safe to call ClearFocus() // (and in turn ClearNativeFocus()) here because ViewRemoved() can // be called while the top level widget is being destroyed. DCHECK(removed); if (removed->Contains(focused_view_)) SetFocusedView(nullptr); } void FocusManager::AddFocusChangeListener(FocusChangeListener* listener) { focus_change_listeners_.AddObserver(listener); } void FocusManager::RemoveFocusChangeListener(FocusChangeListener* listener) { focus_change_listeners_.RemoveObserver(listener); } bool FocusManager::ProcessArrowKeyTraversal(const ui::KeyEvent& event) { if (event.IsShiftDown() || event.IsControlDown() || event.IsAltDown() || event.IsAltGrDown()) return false; const ui::KeyboardCode key = event.key_code(); if (key != ui::VKEY_UP && key != ui::VKEY_DOWN && key != ui::VKEY_LEFT && key != ui::VKEY_RIGHT) { return false; } const ui::KeyboardCode reverse = base::i18n::IsRTL() ? ui::VKEY_RIGHT : ui::VKEY_LEFT; AdvanceFocus(key == reverse || key == ui::VKEY_UP); return true; } bool FocusManager::IsFocusable(View* view) const { DCHECK(view); // |keyboard_accessible_| is only used on Mac. #if BUILDFLAG(IS_MAC) return keyboard_accessible_ ? view->IsAccessibilityFocusable() : view->IsFocusable(); #else return view->IsAccessibilityFocusable(); #endif } void FocusManager::OnViewIsDeleting(View* view) { // Typically ViewRemoved() is called and all the cleanup happens there. With // child widgets it's possible to change the parent out from under the Widget // such that ViewRemoved() is never called. CHECK_EQ(view, focused_view_); SetFocusedView(nullptr); } bool FocusManager::RedirectAcceleratorToBubbleAnchorWidget( const ui::Accelerator& accelerator) { if (!widget_->widget_delegate()) return false; views::BubbleDialogDelegate* widget_delegate = widget_->widget_delegate()->AsBubbleDialogDelegate(); Widget* anchor_widget = widget_delegate ? widget_delegate->anchor_widget() : nullptr; if (!anchor_widget) return false; FocusManager* focus_manager = anchor_widget->GetFocusManager(); if (!focus_manager->IsAcceleratorRegistered(accelerator)) return false; // TODO(crbug.com/1052397): Revisit the macro expression once build flag switch // of lacros-chrome is complete. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) // Processing an accelerator can delete things. Because we // need these objects afterwards on Linux, save widget_ as weak pointer and // save the close_on_deactivate property value of widget_delegate in a // variable. base::WeakPtr<Widget> widget_weak_ptr = widget_->GetWeakPtr(); const bool close_widget_on_deactivate = widget_delegate->ShouldCloseOnDeactivate(); #endif // The parent view must be focused for it to process events. focus_manager->SetFocusedView(anchor_widget->GetRootView()); const bool accelerator_processed = focus_manager->ProcessAccelerator(accelerator); // TODO(crbug.com/1052397): Revisit the macro expression once build flag switch // of lacros-chrome is complete. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) // Need to manually close the bubble widget on Linux. On Linux when the // bubble is shown, the main widget remains active. Because of that when // focus is set to the main widget to process accelerator, the main widget // isn't activated and the bubble widget isn't deactivated and closed. if (accelerator_processed && close_widget_on_deactivate) { widget_weak_ptr->CloseWithReason(views::Widget::ClosedReason::kLostFocus); } #endif return accelerator_processed; } bool FocusManager::IsArrowKeyTraversalEnabledForWidget() const { if (arrow_key_traversal_enabled_) return true; Widget* const widget = (focused_view_ && focused_view_->GetWidget()) ? focused_view_->GetWidget() : widget_.get(); return widget && widget->widget_delegate() && widget->widget_delegate()->enable_arrow_key_traversal(); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/focus/focus_manager.cc
C++
unknown
24,422
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_FOCUS_FOCUS_MANAGER_H_ #define UI_VIEWS_FOCUS_FOCUS_MANAGER_H_ #include <memory> #include "base/memory/raw_ptr.h" #include "base/observer_list.h" #include "ui/base/accelerators/accelerator_manager.h" #include "ui/views/view_observer.h" #include "ui/views/views_export.h" // FocusManager handles focus traversal, stores and restores focused views, and // handles keyboard accelerators. This class is an implementation detail of // views::. Most callers should use methods of views:: classes rather than using // FocusManager directly. // // There are 2 types of focus: // // - The native focus, which is the focus that a gfx::NativeView has. // - The view focus, which is the focus that a views::View has. // // When a top window (derived from views::Widget) that is not a child window is // created, it creates and owns a FocusManager to manage the focus for itself // and all its child windows. // // To be able to be focus-traversed when the Tab key is pressed, a class should // implement the FocusTraversable interface. RootViews implement // FocusTraversable. The FocusManager contains a top FocusTraversable instance, // which is the top RootView. // // If you just use Views, then the RootView handles focus traversal for you. The // default traversal order is the order in which the views have been added to // their container. You can call View::SetNextFocusableView to modify this // order. // // If you are embedding a native view containing a nested RootView (for example // by adding a view that contains a native widget as its native component), // then you need to: // // - Override the View::GetFocusTraversable method in your outer component. // It should return the RootView of the inner component. This is used when // the focus traversal traverse down the focus hierarchy to enter the nested // RootView. In the example mentioned above, the NativeControl overrides // GetFocusTraversable and returns hwnd_view_container_->GetRootView(). // // - Call Widget::SetFocusTraversableParent on the nested RootView and point // it to the outer RootView. This is used when the focus goes out of the // nested RootView. In the example: // // hwnd_view_container_->GetWidget()->SetFocusTraversableParent( // native_control->GetRootView()); // // - Call RootView::SetFocusTraversableParentView on the nested RootView with // the parent view that directly contains the native window. This is needed // when traversing up from the nested RootView to know which view to start // with when going to the next/previous view. In the example: // // hwnd_view_container_->GetWidget()->SetFocusTraversableParent( // native_control); // // Note that FocusTraversable views do not have to be RootViews: // AccessibleToolbarView is FocusTraversable. namespace ui { class Accelerator; class AcceleratorTarget; class KeyEvent; } // namespace ui namespace views { class FocusManagerDelegate; class FocusSearch; class View; class ViewTracker; class Widget; // The FocusTraversable interface is used by components that want to process // focus traversal events (due to Tab/Shift-Tab key events). class VIEWS_EXPORT FocusTraversable { public: // Return a FocusSearch object that implements the algorithm to find // the next or previous focusable view. virtual FocusSearch* GetFocusSearch() = 0; // Should return the parent FocusTraversable. // The top RootView which is the top FocusTraversable returns NULL. virtual FocusTraversable* GetFocusTraversableParent() = 0; // This should return the View this FocusTraversable belongs to. // It is used when walking up the view hierarchy tree to find which view // should be used as the starting view for finding the next/previous view. virtual View* GetFocusTraversableParentView() = 0; protected: virtual ~FocusTraversable() = default; }; // This interface should be implemented by classes that want to be notified when // the focus is about to change. See the Add/RemoveFocusChangeListener methods. class VIEWS_EXPORT FocusChangeListener { public: // No change to focus state has occurred yet when this function is called. virtual void OnWillChangeFocus(View* focused_before, View* focused_now) = 0; // Called after focus state has changed. virtual void OnDidChangeFocus(View* focused_before, View* focused_now) = 0; protected: virtual ~FocusChangeListener() = default; }; // FocusManager adds itself as a ViewObserver to the currently focused view. class VIEWS_EXPORT FocusManager : public ViewObserver { public: // The reason why the focus changed. enum class FocusChangeReason { // The focus changed because the user traversed focusable views using // keys like Tab or Shift+Tab. kFocusTraversal, // The focus changed due to restoring the focus. kFocusRestore, // The focus changed due to a click or a shortcut to jump directly to // a particular view. kDirectFocusChange }; // TODO(dmazzoni): use Direction in place of bool reverse throughout. enum class Direction { kForward, kBackward }; enum class FocusCycleWrapping { kEnabled, kDisabled }; FocusManager(Widget* widget, std::unique_ptr<FocusManagerDelegate> delegate); FocusManager(const FocusManager&) = delete; FocusManager& operator=(const FocusManager&) = delete; ~FocusManager() override; // Processes the passed key event for accelerators and keyboard traversal. // Returns false if the event has been consumed and should not be processed // further. bool OnKeyEvent(const ui::KeyEvent& event); // Returns true is the specified is part of the hierarchy of the window // associated with this FocusManager. bool ContainsView(View* view); // Advances the focus (backward if reverse is true). void AdvanceFocus(bool reverse); // The FocusManager keeps track of the focused view within a RootView. View* GetFocusedView() { return focused_view_; } const View* GetFocusedView() const { return focused_view_; } // Low-level methods to force the focus to change (and optionally provide // a reason). If the focus change should only happen if the view is // currenty focusable, enabled, and visible, call view->RequestFocus(). void SetFocusedViewWithReason(View* view, FocusChangeReason reason); void SetFocusedView(View* view); // Get the reason why the focus most recently changed. FocusChangeReason focus_change_reason() const { return focus_change_reason_; } // Clears the focused view. The window associated with the top root view gets // the native focus (so we still get keyboard events). void ClearFocus(); // Tries to advance focus if the focused view has become unfocusable. If there // is no view available to advance focus to, focus will be cleared. void AdvanceFocusIfNecessary(); // Stores the focused view. Used when the widget loses activation. // |clear_native_focus| indicates whether this should invoke ClearFocus(). // Typically |true| should be passed in. void StoreFocusedView(bool clear_native_focus); // Restore the view saved with a previous call to StoreFocusedView(). Used // when the widget becomes active. Returns true when the previous view was // successfully refocused. In case the stored view is no longer focusable, // it advances focus and returns false. bool RestoreFocusedView(); // Sets the |view| to be restored when calling RestoreFocusView. This is used // to set where the focus should go on restoring a Window created without // focus being set. void SetStoredFocusView(View* view); // Returns the View that either currently has focus, or if no view has focus // the view that last had focus. View* GetStoredFocusView(); // Disable shortcut handling. void set_shortcut_handling_suspended(bool suspended) { shortcut_handling_suspended_ = suspended; } // Returns whether shortcut handling is currently suspended. bool shortcut_handling_suspended() { return shortcut_handling_suspended_; } // Register a keyboard accelerator for the specified target. If multiple // targets are registered for an accelerator, a target registered later has // higher priority. // |accelerator| is the accelerator to register. // |priority| denotes the priority of the handler. // NOTE: In almost all cases, you should specify kNormalPriority for this // parameter. Setting it to kHighPriority prevents Chrome from sending the // shortcut to the webpage if the renderer has focus, which is not desirable // except for very isolated cases. // |target| is the AcceleratorTarget that handles the event once the // accelerator is pressed. // Note that we are currently limited to accelerators that are either: // - a key combination including Ctrl or Alt // - the escape key // - the enter key // - any F key (F1, F2, F3 ...) // - any browser specific keys (as available on special keyboards) void RegisterAccelerator(const ui::Accelerator& accelerator, ui::AcceleratorManager::HandlerPriority priority, ui::AcceleratorTarget* target); // Unregister the specified keyboard accelerator for the specified target. void UnregisterAccelerator(const ui::Accelerator& accelerator, ui::AcceleratorTarget* target); // Unregister all keyboard accelerator for the specified target. void UnregisterAccelerators(ui::AcceleratorTarget* target); // Activate the target associated with the specified accelerator. // First, AcceleratorPressed handler of the most recently registered target // is called, and if that handler processes the event (i.e. returns true), // this method immediately returns. If not, we do the same thing on the next // target, and so on. // Returns true if an accelerator was activated. bool ProcessAccelerator(const ui::Accelerator& accelerator); // Resets menu key state if |event| is not menu key release. // This is effective only on x11. void MaybeResetMenuKeyState(const ui::KeyEvent& key); // Called by a RootView when a view within its hierarchy is removed // from its parent. This will only be called by a RootView in a // hierarchy of Widgets that this FocusManager is attached to the // parent Widget of. void ViewRemoved(View* removed); // Adds/removes a listener. The FocusChangeListener is notified every time // the focused view is about to change. void AddFocusChangeListener(FocusChangeListener* listener); void RemoveFocusChangeListener(FocusChangeListener* listener); // Whether the given |accelerator| is registered. bool IsAcceleratorRegistered(const ui::Accelerator& accelerator) const; // Whether the given |accelerator| has a priority handler associated with it. bool HasPriorityHandler(const ui::Accelerator& accelerator) const; // Clears the native view having the focus. virtual void ClearNativeFocus(); // Focuses the next keyboard-accessible pane, taken from the list of // views returned by WidgetDelegate::GetAccessiblePanes(). If there are // no panes, the widget's root view is treated as a single pane. // A keyboard-accessible pane should subclass from AccessiblePaneView in // order to trap keyboard focus within that pane. If |wrap| is kWrap, // it keeps cycling within this widget, otherwise it returns false after // reaching the last pane so that focus can cycle to another widget. bool RotatePaneFocus(Direction direction, FocusCycleWrapping wrapping); // Convenience method that returns true if the passed |key_event| should // trigger tab traversal (if it is a TAB key press with or without SHIFT // pressed). static bool IsTabTraversalKeyEvent(const ui::KeyEvent& key_event); // Sets whether arrow key traversal is enabled. When enabled, right/down key // behaves like tab and left/up key behaves like shift-tab. Note when this // is enabled, the arrow key movement within grouped views are disabled. static void set_arrow_key_traversal_enabled(bool enabled) { arrow_key_traversal_enabled_ = enabled; } // Returns whether arrow key traversal is enabled. static bool arrow_key_traversal_enabled() { return arrow_key_traversal_enabled_; } // Returns the next focusable view. Traversal starts at |starting_view|. If // |starting_view| is null, |starting_widget| is consulted to determine which // Widget to start from. See WidgetDelegate::Params::focus_traverses_out for // details. If both |starting_view| and |starting_widget| are null, traversal // starts at |widget_|. View* GetNextFocusableView(View* starting_view, Widget* starting_widget, bool reverse, bool dont_loop); bool keyboard_accessible() const { return keyboard_accessible_; } // Updates |keyboard_accessible_| to the given value and advances focus if // necessary. void SetKeyboardAccessible(bool keyboard_accessible); // Checks if a focused view is being set. bool IsSettingFocusedView() const; private: // Returns the focusable view found in the FocusTraversable specified starting // at the specified view. This traverses down along the FocusTraversable // hierarchy. // Returns NULL if no focusable view were found. View* FindFocusableView(FocusTraversable* focus_traversable, View* starting_view, bool reverse); // Process arrow key traversal. Returns true if the event has been consumed // and should not be processed further. bool ProcessArrowKeyTraversal(const ui::KeyEvent& event); // Whether |view| is currently focusable as per the platform's interpretation // of |keyboard_accesible_|. bool IsFocusable(View* view) const; // ViewObserver: void OnViewIsDeleting(View* view) override; // Try to redirect the accelerator to bubble's anchor widget to process it if // the bubble didn't. bool RedirectAcceleratorToBubbleAnchorWidget( const ui::Accelerator& accelerator); // Returns true if arrow key traversal is enabled for the current widget. bool IsArrowKeyTraversalEnabledForWidget() const; // Whether arrow key traversal is enabled globally. static bool arrow_key_traversal_enabled_; // The top-level Widget this FocusManager is associated with. raw_ptr<Widget> widget_; // The object which handles an accelerator when |accelerator_manager_| doesn't // handle it. std::unique_ptr<FocusManagerDelegate> delegate_; // The view that currently is focused. raw_ptr<View> focused_view_ = nullptr; // The AcceleratorManager this FocusManager is associated with. ui::AcceleratorManager accelerator_manager_; // Keeps track of whether shortcut handling is currently suspended. bool shortcut_handling_suspended_ = false; std::unique_ptr<ViewTracker> view_tracker_for_stored_view_; // The reason why the focus most recently changed. FocusChangeReason focus_change_reason_ = FocusChangeReason::kDirectFocusChange; // The list of registered FocusChange listeners. base::ObserverList<FocusChangeListener, true>::Unchecked focus_change_listeners_; // This is true if full keyboard accessibility is needed. This causes // IsAccessibilityFocusable() to be checked rather than IsFocusable(). This // can be set depending on platform constraints. FocusSearch uses this in // addition to its own accessibility mode, which handles accessibility at the // FocusTraversable level. Currently only used on Mac, when Full Keyboard // access is enabled. bool keyboard_accessible_ = false; // Whether FocusManager is currently trying to restore a focused view. bool in_restoring_focused_view_ = false; // Count of SetFocusedViewWithReason() in the current stack. // This value is ideally 0 or 1, i.e. no nested focus change. // See crbug.com/1203960. int setting_focused_view_entrance_count_ = 0; }; } // namespace views #endif // UI_VIEWS_FOCUS_FOCUS_MANAGER_H_
Zhao-PengFei35/chromium_src_4
ui/views/focus/focus_manager.h
C++
unknown
16,139
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_FOCUS_FOCUS_MANAGER_DELEGATE_H_ #define UI_VIEWS_FOCUS_FOCUS_MANAGER_DELEGATE_H_ #include "ui/views/views_export.h" namespace ui { class Accelerator; } namespace views { // Delegate interface for views::FocusManager. class VIEWS_EXPORT FocusManagerDelegate { public: virtual ~FocusManagerDelegate() = default; // Activate the target associated with the specified accelerator. // First, AcceleratorPressed handler of the most recently registered target // is called, and if that handler processes the event (i.e. returns true), // this method immediately returns. If not, we do the same thing on the next // target, and so on. // Returns true if an accelerator was activated. virtual bool ProcessAccelerator(const ui::Accelerator& accelerator) = 0; }; } // namespace views #endif // UI_VIEWS_FOCUS_FOCUS_MANAGER_DELEGATE_H_
Zhao-PengFei35/chromium_src_4
ui/views/focus/focus_manager_delegate.h
C++
unknown
1,010
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/focus/focus_manager_factory.h" #include "ui/views/focus/focus_manager.h" #include "ui/views/focus/focus_manager_delegate.h" namespace views { namespace { class DefaultFocusManagerFactory : public FocusManagerFactory { public: DefaultFocusManagerFactory() = default; DefaultFocusManagerFactory(const DefaultFocusManagerFactory&) = delete; DefaultFocusManagerFactory& operator=(const DefaultFocusManagerFactory&) = delete; ~DefaultFocusManagerFactory() override = default; protected: std::unique_ptr<FocusManager> CreateFocusManager(Widget* widget) override { return std::make_unique<FocusManager>(widget, nullptr /* delegate */); } }; FocusManagerFactory* g_focus_manager_factory = nullptr; } // namespace FocusManagerFactory::FocusManagerFactory() = default; FocusManagerFactory::~FocusManagerFactory() = default; // static std::unique_ptr<FocusManager> FocusManagerFactory::Create(Widget* widget) { if (!g_focus_manager_factory) g_focus_manager_factory = new DefaultFocusManagerFactory(); return g_focus_manager_factory->CreateFocusManager(widget); } // static void FocusManagerFactory::Install(FocusManagerFactory* f) { if (f == g_focus_manager_factory) return; delete g_focus_manager_factory; g_focus_manager_factory = f ? f : new DefaultFocusManagerFactory(); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/focus/focus_manager_factory.cc
C++
unknown
1,507
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_FOCUS_FOCUS_MANAGER_FACTORY_H_ #define UI_VIEWS_FOCUS_FOCUS_MANAGER_FACTORY_H_ #include <memory> #include "ui/views/views_export.h" namespace views { class FocusManager; class Widget; // A factory to create FocusManager. This can be used to inject a custom // factory. class VIEWS_EXPORT FocusManagerFactory { public: // Create a FocusManager for the given |widget| using the installed Factory. static std::unique_ptr<FocusManager> Create(Widget* widget); // Installs FocusManagerFactory. If |factory| is NULL, it resets // to the default factory which creates plain FocusManager. static void Install(FocusManagerFactory* factory); FocusManagerFactory(const FocusManagerFactory&) = delete; FocusManagerFactory& operator=(const FocusManagerFactory&) = delete; protected: FocusManagerFactory(); virtual ~FocusManagerFactory(); // Create a FocusManager for the given |widget|. virtual std::unique_ptr<FocusManager> CreateFocusManager(Widget* widget) = 0; }; } // namespace views #endif // UI_VIEWS_FOCUS_FOCUS_MANAGER_FACTORY_H_
Zhao-PengFei35/chromium_src_4
ui/views/focus/focus_manager_factory.h
C++
unknown
1,224
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/focus/focus_manager.h" #include <stddef.h> #include <string> #include <utility> #include <vector> #include "base/command_line.h" #include "base/memory/raw_ptr.h" #include "base/strings/utf_string_conversions.h" #include "base/test/icu_test_util.h" #include "build/build_config.h" #include "ui/base/accelerators/accelerator.h" #include "ui/base/accelerators/test_accelerator_target.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/accessible_pane_view.h" #include "ui/views/bubble/bubble_dialog_delegate_view.h" #include "ui/views/buildflags.h" #include "ui/views/focus/focus_manager_delegate.h" #include "ui/views/focus/focus_manager_factory.h" #include "ui/views/focus/widget_focus_manager.h" #include "ui/views/test/focus_manager_test.h" #include "ui/views/test/native_widget_factory.h" #include "ui/views/test/test_platform_native_widget.h" #include "ui/views/test/widget_test.h" #include "ui/views/view_class_properties.h" #include "ui/views/widget/unique_widget_ptr.h" #include "ui/views/widget/widget.h" #if defined(USE_AURA) #include "ui/aura/client/focus_client.h" #include "ui/views/widget/native_widget_aura.h" #endif // USE_AURA namespace views { enum FocusTestEventType { ON_FOCUS = 0, ON_BLUR }; struct FocusTestEvent { FocusTestEventType type; int view_id; FocusManager::FocusChangeReason focus_change_reason; }; class SimpleTestView : public View { public: SimpleTestView(std::vector<FocusTestEvent>* event_list, int view_id) : event_list_(event_list) { SetFocusBehavior(FocusBehavior::ALWAYS); set_suppress_default_focus_handling(); SetID(view_id); } SimpleTestView(const SimpleTestView&) = delete; SimpleTestView& operator=(const SimpleTestView&) = delete; void OnFocus() override { event_list_->push_back({ ON_FOCUS, GetID(), GetFocusManager()->focus_change_reason(), }); } void OnBlur() override { event_list_->push_back({ ON_BLUR, GetID(), GetFocusManager()->focus_change_reason(), }); } private: raw_ptr<std::vector<FocusTestEvent>> event_list_; }; // Tests that the appropriate Focus related methods are called when a View // gets/loses focus. TEST_F(FocusManagerTest, ViewFocusCallbacks) { std::vector<FocusTestEvent> event_list; const int kView1ID = 1; const int kView2ID = 2; SimpleTestView* view1 = new SimpleTestView(&event_list, kView1ID); SimpleTestView* view2 = new SimpleTestView(&event_list, kView2ID); GetContentsView()->AddChildView(view1); GetContentsView()->AddChildView(view2); view1->RequestFocus(); ASSERT_EQ(1, static_cast<int>(event_list.size())); EXPECT_EQ(ON_FOCUS, event_list[0].type); EXPECT_EQ(kView1ID, event_list[0].view_id); EXPECT_EQ(FocusChangeReason::kDirectFocusChange, event_list[0].focus_change_reason); event_list.clear(); view2->RequestFocus(); ASSERT_EQ(2, static_cast<int>(event_list.size())); EXPECT_EQ(ON_BLUR, event_list[0].type); EXPECT_EQ(kView1ID, event_list[0].view_id); EXPECT_EQ(ON_FOCUS, event_list[1].type); EXPECT_EQ(kView2ID, event_list[1].view_id); EXPECT_EQ(FocusChangeReason::kDirectFocusChange, event_list[0].focus_change_reason); EXPECT_EQ(FocusChangeReason::kDirectFocusChange, event_list[1].focus_change_reason); event_list.clear(); GetFocusManager()->ClearFocus(); ASSERT_EQ(1, static_cast<int>(event_list.size())); EXPECT_EQ(ON_BLUR, event_list[0].type); EXPECT_EQ(kView2ID, event_list[0].view_id); EXPECT_EQ(FocusChangeReason::kDirectFocusChange, event_list[0].focus_change_reason); } TEST_F(FocusManagerTest, FocusChangeListener) { View* view1 = new View(); view1->SetFocusBehavior(View::FocusBehavior::ALWAYS); View* view2 = new View(); view2->SetFocusBehavior(View::FocusBehavior::ALWAYS); GetContentsView()->AddChildView(view1); GetContentsView()->AddChildView(view2); TestFocusChangeListener listener; AddFocusChangeListener(&listener); // Required for VS2010: // http://connect.microsoft.com/VisualStudio/feedback/details/520043/error-converting-from-null-to-a-pointer-type-in-std-pair views::View* null_view = nullptr; view1->RequestFocus(); ASSERT_EQ(1, static_cast<int>(listener.focus_changes().size())); EXPECT_TRUE(listener.focus_changes()[0] == ViewPair(null_view, view1)); listener.ClearFocusChanges(); view2->RequestFocus(); ASSERT_EQ(1, static_cast<int>(listener.focus_changes().size())); EXPECT_TRUE(listener.focus_changes()[0] == ViewPair(view1, view2)); listener.ClearFocusChanges(); GetFocusManager()->ClearFocus(); ASSERT_EQ(1, static_cast<int>(listener.focus_changes().size())); EXPECT_TRUE(listener.focus_changes()[0] == ViewPair(view2, null_view)); } TEST_F(FocusManagerTest, WidgetFocusChangeListener) { // First, ensure the simulator is aware of the Widget created in SetUp() being // currently active. test::WidgetTest::SimulateNativeActivate(GetWidget()); TestWidgetFocusChangeListener widget_listener; AddWidgetFocusChangeListener(&widget_listener); Widget::InitParams params1 = CreateParams(Widget::InitParams::TYPE_WINDOW); params1.bounds = gfx::Rect(10, 10, 100, 100); params1.parent = GetWidget()->GetNativeView(); UniqueWidgetPtr widget1 = std::make_unique<Widget>(); widget1->Init(std::move(params1)); widget1->Show(); Widget::InitParams params2 = CreateParams(Widget::InitParams::TYPE_WINDOW); params2.bounds = gfx::Rect(10, 10, 100, 100); params2.parent = GetWidget()->GetNativeView(); UniqueWidgetPtr widget2 = std::make_unique<Widget>(); widget2->Init(std::move(params2)); widget2->Show(); widget_listener.ClearFocusChanges(); gfx::NativeView native_view1 = widget1->GetNativeView(); test::WidgetTest::SimulateNativeActivate(widget1.get()); ASSERT_EQ(2u, widget_listener.focus_changes().size()); EXPECT_EQ(gfx::kNullNativeView, widget_listener.focus_changes()[0]); EXPECT_EQ(native_view1, widget_listener.focus_changes()[1]); widget_listener.ClearFocusChanges(); gfx::NativeView native_view2 = widget2->GetNativeView(); test::WidgetTest::SimulateNativeActivate(widget2.get()); ASSERT_EQ(2u, widget_listener.focus_changes().size()); EXPECT_EQ(gfx::kNullNativeView, widget_listener.focus_changes()[0]); EXPECT_EQ(native_view2, widget_listener.focus_changes()[1]); } TEST_F(FocusManagerTest, CallsNormalAcceleratorTarget) { FocusManager* focus_manager = GetFocusManager(); ui::Accelerator return_accelerator(ui::VKEY_RETURN, ui::EF_NONE); ui::Accelerator escape_accelerator(ui::VKEY_ESCAPE, ui::EF_NONE); ui::TestAcceleratorTarget return_target(true); ui::TestAcceleratorTarget escape_target(true); EXPECT_EQ(return_target.accelerator_count(), 0); EXPECT_EQ(escape_target.accelerator_count(), 0); // Register targets. focus_manager->RegisterAccelerator(return_accelerator, ui::AcceleratorManager::kNormalPriority, &return_target); focus_manager->RegisterAccelerator(escape_accelerator, ui::AcceleratorManager::kNormalPriority, &escape_target); // Hitting the return key. EXPECT_TRUE(focus_manager->ProcessAccelerator(return_accelerator)); EXPECT_EQ(return_target.accelerator_count(), 1); EXPECT_EQ(escape_target.accelerator_count(), 0); // Hitting the escape key. EXPECT_TRUE(focus_manager->ProcessAccelerator(escape_accelerator)); EXPECT_EQ(return_target.accelerator_count(), 1); EXPECT_EQ(escape_target.accelerator_count(), 1); // Register another target for the return key. ui::TestAcceleratorTarget return_target2(true); EXPECT_EQ(return_target2.accelerator_count(), 0); focus_manager->RegisterAccelerator(return_accelerator, ui::AcceleratorManager::kNormalPriority, &return_target2); // Hitting the return key; return_target2 has the priority. EXPECT_TRUE(focus_manager->ProcessAccelerator(return_accelerator)); EXPECT_EQ(return_target.accelerator_count(), 1); EXPECT_EQ(return_target2.accelerator_count(), 1); // Register a target that does not process the accelerator event. ui::TestAcceleratorTarget return_target3(false); EXPECT_EQ(return_target3.accelerator_count(), 0); focus_manager->RegisterAccelerator(return_accelerator, ui::AcceleratorManager::kNormalPriority, &return_target3); // Hitting the return key. // Since the event handler of return_target3 returns false, return_target2 // should be called too. EXPECT_TRUE(focus_manager->ProcessAccelerator(return_accelerator)); EXPECT_EQ(return_target.accelerator_count(), 1); EXPECT_EQ(return_target2.accelerator_count(), 2); EXPECT_EQ(return_target3.accelerator_count(), 1); // Unregister return_target2. focus_manager->UnregisterAccelerator(return_accelerator, &return_target2); // Hitting the return key. return_target3 and return_target should be called. EXPECT_TRUE(focus_manager->ProcessAccelerator(return_accelerator)); EXPECT_EQ(return_target.accelerator_count(), 2); EXPECT_EQ(return_target2.accelerator_count(), 2); EXPECT_EQ(return_target3.accelerator_count(), 2); // Unregister targets. focus_manager->UnregisterAccelerator(return_accelerator, &return_target); focus_manager->UnregisterAccelerator(return_accelerator, &return_target3); focus_manager->UnregisterAccelerator(escape_accelerator, &escape_target); // Hitting the return key and the escape key. Nothing should happen. EXPECT_FALSE(focus_manager->ProcessAccelerator(return_accelerator)); EXPECT_EQ(return_target.accelerator_count(), 2); EXPECT_EQ(return_target2.accelerator_count(), 2); EXPECT_EQ(return_target3.accelerator_count(), 2); EXPECT_FALSE(focus_manager->ProcessAccelerator(escape_accelerator)); EXPECT_EQ(escape_target.accelerator_count(), 1); } TEST_F(FocusManagerTest, HighPriorityHandlers) { FocusManager* focus_manager = GetFocusManager(); ui::Accelerator escape_accelerator(ui::VKEY_ESCAPE, ui::EF_NONE); ui::TestAcceleratorTarget escape_target_high(true); ui::TestAcceleratorTarget escape_target_normal(true); EXPECT_EQ(escape_target_high.accelerator_count(), 0); EXPECT_EQ(escape_target_normal.accelerator_count(), 0); EXPECT_FALSE(focus_manager->HasPriorityHandler(escape_accelerator)); // Register high priority target. focus_manager->RegisterAccelerator(escape_accelerator, ui::AcceleratorManager::kHighPriority, &escape_target_high); EXPECT_TRUE(focus_manager->HasPriorityHandler(escape_accelerator)); // Hit the escape key. EXPECT_TRUE(focus_manager->ProcessAccelerator(escape_accelerator)); EXPECT_EQ(escape_target_high.accelerator_count(), 1); EXPECT_EQ(escape_target_normal.accelerator_count(), 0); // Add a normal priority target and make sure it doesn't see the key. focus_manager->RegisterAccelerator(escape_accelerator, ui::AcceleratorManager::kNormalPriority, &escape_target_normal); // Checks if the correct target is registered (same as before, the high // priority one). EXPECT_TRUE(focus_manager->HasPriorityHandler(escape_accelerator)); // Hit the escape key. EXPECT_TRUE(focus_manager->ProcessAccelerator(escape_accelerator)); EXPECT_EQ(escape_target_high.accelerator_count(), 2); EXPECT_EQ(escape_target_normal.accelerator_count(), 0); // Unregister the high priority accelerator. focus_manager->UnregisterAccelerator(escape_accelerator, &escape_target_high); EXPECT_FALSE(focus_manager->HasPriorityHandler(escape_accelerator)); // Hit the escape key. EXPECT_TRUE(focus_manager->ProcessAccelerator(escape_accelerator)); EXPECT_EQ(escape_target_high.accelerator_count(), 2); EXPECT_EQ(escape_target_normal.accelerator_count(), 1); // Add the high priority target back and make sure it starts seeing the key. focus_manager->RegisterAccelerator(escape_accelerator, ui::AcceleratorManager::kHighPriority, &escape_target_high); EXPECT_TRUE(focus_manager->HasPriorityHandler(escape_accelerator)); // Hit the escape key. EXPECT_TRUE(focus_manager->ProcessAccelerator(escape_accelerator)); EXPECT_EQ(escape_target_high.accelerator_count(), 3); EXPECT_EQ(escape_target_normal.accelerator_count(), 1); // Unregister the normal priority accelerator. focus_manager->UnregisterAccelerator(escape_accelerator, &escape_target_normal); EXPECT_TRUE(focus_manager->HasPriorityHandler(escape_accelerator)); // Hit the escape key. EXPECT_TRUE(focus_manager->ProcessAccelerator(escape_accelerator)); EXPECT_EQ(escape_target_high.accelerator_count(), 4); EXPECT_EQ(escape_target_normal.accelerator_count(), 1); // Unregister the high priority accelerator. focus_manager->UnregisterAccelerator(escape_accelerator, &escape_target_high); EXPECT_FALSE(focus_manager->HasPriorityHandler(escape_accelerator)); // Hit the escape key (no change, no targets registered). EXPECT_FALSE(focus_manager->ProcessAccelerator(escape_accelerator)); EXPECT_EQ(escape_target_high.accelerator_count(), 4); EXPECT_EQ(escape_target_normal.accelerator_count(), 1); } TEST_F(FocusManagerTest, CallsEnabledAcceleratorTargetsOnly) { FocusManager* focus_manager = GetFocusManager(); ui::Accelerator return_accelerator(ui::VKEY_RETURN, ui::EF_NONE); ui::TestAcceleratorTarget return_target1(true); ui::TestAcceleratorTarget return_target2(true); focus_manager->RegisterAccelerator(return_accelerator, ui::AcceleratorManager::kNormalPriority, &return_target1); focus_manager->RegisterAccelerator(return_accelerator, ui::AcceleratorManager::kNormalPriority, &return_target2); EXPECT_TRUE(focus_manager->ProcessAccelerator(return_accelerator)); EXPECT_EQ(0, return_target1.accelerator_count()); EXPECT_EQ(1, return_target2.accelerator_count()); // If CanHandleAccelerators() return false, FocusManager shouldn't call // AcceleratorPressed(). return_target2.set_can_handle_accelerators(false); EXPECT_TRUE(focus_manager->ProcessAccelerator(return_accelerator)); EXPECT_EQ(1, return_target1.accelerator_count()); EXPECT_EQ(1, return_target2.accelerator_count()); // If no accelerator targets are enabled, ProcessAccelerator() should fail. return_target1.set_can_handle_accelerators(false); EXPECT_FALSE(focus_manager->ProcessAccelerator(return_accelerator)); EXPECT_EQ(1, return_target1.accelerator_count()); EXPECT_EQ(1, return_target2.accelerator_count()); // Enabling the target again causes the accelerators to be processed again. return_target1.set_can_handle_accelerators(true); return_target2.set_can_handle_accelerators(true); EXPECT_TRUE(focus_manager->ProcessAccelerator(return_accelerator)); EXPECT_EQ(1, return_target1.accelerator_count()); EXPECT_EQ(2, return_target2.accelerator_count()); } // Unregisters itself when its accelerator is invoked. class SelfUnregisteringAcceleratorTarget : public ui::TestAcceleratorTarget { public: SelfUnregisteringAcceleratorTarget(const ui::Accelerator& accelerator, FocusManager* focus_manager) : accelerator_(accelerator), focus_manager_(focus_manager) {} SelfUnregisteringAcceleratorTarget( const SelfUnregisteringAcceleratorTarget&) = delete; SelfUnregisteringAcceleratorTarget& operator=( const SelfUnregisteringAcceleratorTarget&) = delete; // ui::TestAcceleratorTarget: bool AcceleratorPressed(const ui::Accelerator& accelerator) override { focus_manager_->UnregisterAccelerator(accelerator, this); return ui::TestAcceleratorTarget::AcceleratorPressed(accelerator); } private: ui::Accelerator accelerator_; raw_ptr<FocusManager> focus_manager_; }; TEST_F(FocusManagerTest, CallsSelfDeletingAcceleratorTarget) { FocusManager* focus_manager = GetFocusManager(); ui::Accelerator return_accelerator(ui::VKEY_RETURN, ui::EF_NONE); SelfUnregisteringAcceleratorTarget target(return_accelerator, focus_manager); EXPECT_EQ(target.accelerator_count(), 0); // Register the target. focus_manager->RegisterAccelerator( return_accelerator, ui::AcceleratorManager::kNormalPriority, &target); // Hitting the return key. The target will be unregistered. EXPECT_TRUE(focus_manager->ProcessAccelerator(return_accelerator)); EXPECT_EQ(target.accelerator_count(), 1); // Hitting the return key again; nothing should happen. EXPECT_FALSE(focus_manager->ProcessAccelerator(return_accelerator)); EXPECT_EQ(target.accelerator_count(), 1); } TEST_F(FocusManagerTest, SuspendAccelerators) { const ui::KeyEvent event(ui::ET_KEY_PRESSED, ui::VKEY_RETURN, ui::EF_NONE); ui::Accelerator accelerator(event.key_code(), event.flags()); ui::TestAcceleratorTarget target(true); FocusManager* focus_manager = GetFocusManager(); focus_manager->RegisterAccelerator( accelerator, ui::AcceleratorManager::kNormalPriority, &target); focus_manager->set_shortcut_handling_suspended(true); EXPECT_TRUE(focus_manager->OnKeyEvent(event)); EXPECT_EQ(0, target.accelerator_count()); focus_manager->set_shortcut_handling_suspended(false); EXPECT_FALSE(focus_manager->OnKeyEvent(event)); EXPECT_EQ(1, target.accelerator_count()); } namespace { class FocusInAboutToRequestFocusFromTabTraversalView : public View { public: FocusInAboutToRequestFocusFromTabTraversalView() = default; FocusInAboutToRequestFocusFromTabTraversalView( const FocusInAboutToRequestFocusFromTabTraversalView&) = delete; FocusInAboutToRequestFocusFromTabTraversalView& operator=( const FocusInAboutToRequestFocusFromTabTraversalView&) = delete; void set_view_to_focus(View* view) { view_to_focus_ = view; } void AboutToRequestFocusFromTabTraversal(bool reverse) override { view_to_focus_->RequestFocus(); } private: raw_ptr<views::View> view_to_focus_ = nullptr; }; } // namespace // Verifies a focus change done during a call to // AboutToRequestFocusFromTabTraversal() is honored. TEST_F(FocusManagerTest, FocusInAboutToRequestFocusFromTabTraversal) { // Create 3 views focuses the 3 and advances to the second. The 2nd views // implementation of AboutToRequestFocusFromTabTraversal() focuses the first. views::View* v1 = new View; v1->SetFocusBehavior(View::FocusBehavior::ALWAYS); GetContentsView()->AddChildView(v1); FocusInAboutToRequestFocusFromTabTraversalView* v2 = new FocusInAboutToRequestFocusFromTabTraversalView; v2->SetFocusBehavior(View::FocusBehavior::ALWAYS); v2->set_view_to_focus(v1); GetContentsView()->AddChildView(v2); views::View* v3 = new View; v3->SetFocusBehavior(View::FocusBehavior::ALWAYS); GetContentsView()->AddChildView(v3); v3->RequestFocus(); GetWidget()->GetFocusManager()->AdvanceFocus(true); EXPECT_TRUE(v1->HasFocus()); } TEST_F(FocusManagerTest, RotatePaneFocus) { views::AccessiblePaneView* pane1 = new AccessiblePaneView(); GetContentsView()->AddChildView(pane1); views::View* v1 = new View; v1->SetFocusBehavior(View::FocusBehavior::ALWAYS); pane1->AddChildView(v1); views::View* v2 = new View; v2->SetFocusBehavior(View::FocusBehavior::ALWAYS); pane1->AddChildView(v2); views::AccessiblePaneView* pane2 = new AccessiblePaneView(); GetContentsView()->AddChildView(pane2); views::View* v3 = new View; v3->SetFocusBehavior(View::FocusBehavior::ALWAYS); pane2->AddChildView(v3); views::View* v4 = new View; v4->SetFocusBehavior(View::FocusBehavior::ALWAYS); pane2->AddChildView(v4); std::vector<views::View*> panes; panes.push_back(pane1); panes.push_back(pane2); SetAccessiblePanes(panes); FocusManager* focus_manager = GetWidget()->GetFocusManager(); // Advance forwards. Focus should stay trapped within each pane. using Direction = FocusManager::Direction; using FocusCycleWrapping = FocusManager::FocusCycleWrapping; EXPECT_TRUE(focus_manager->RotatePaneFocus(Direction::kForward, FocusCycleWrapping::kEnabled)); EXPECT_EQ(v1, focus_manager->GetFocusedView()); focus_manager->AdvanceFocus(false); EXPECT_EQ(v2, focus_manager->GetFocusedView()); focus_manager->AdvanceFocus(false); EXPECT_EQ(v1, focus_manager->GetFocusedView()); EXPECT_TRUE(focus_manager->RotatePaneFocus(Direction::kForward, FocusCycleWrapping::kEnabled)); EXPECT_EQ(v3, focus_manager->GetFocusedView()); focus_manager->AdvanceFocus(false); EXPECT_EQ(v4, focus_manager->GetFocusedView()); focus_manager->AdvanceFocus(false); EXPECT_EQ(v3, focus_manager->GetFocusedView()); EXPECT_TRUE(focus_manager->RotatePaneFocus(Direction::kForward, FocusCycleWrapping::kEnabled)); EXPECT_EQ(v1, focus_manager->GetFocusedView()); // Advance backwards. EXPECT_TRUE(focus_manager->RotatePaneFocus(Direction::kBackward, FocusCycleWrapping::kEnabled)); EXPECT_EQ(v3, focus_manager->GetFocusedView()); EXPECT_TRUE(focus_manager->RotatePaneFocus(Direction::kBackward, FocusCycleWrapping::kEnabled)); EXPECT_EQ(v1, focus_manager->GetFocusedView()); // Advance without wrap. When it gets to the end of the list of // panes, RotatePaneFocus should return false but the current // focused view shouldn't change. EXPECT_TRUE(focus_manager->RotatePaneFocus(Direction::kForward, FocusCycleWrapping::kDisabled)); EXPECT_EQ(v3, focus_manager->GetFocusedView()); EXPECT_FALSE(focus_manager->RotatePaneFocus(Direction::kForward, FocusCycleWrapping::kDisabled)); EXPECT_EQ(v3, focus_manager->GetFocusedView()); } // Verifies the stored focus view tracks the focused view. TEST_F(FocusManagerTest, ImplicitlyStoresFocus) { views::View* v1 = new View; v1->SetFocusBehavior(View::FocusBehavior::ALWAYS); GetContentsView()->AddChildView(v1); views::View* v2 = new View; v2->SetFocusBehavior(View::FocusBehavior::ALWAYS); GetContentsView()->AddChildView(v2); // Verify a focus request on |v1| implicitly updates the stored focus view. v1->RequestFocus(); EXPECT_TRUE(v1->HasFocus()); EXPECT_EQ(v1, GetWidget()->GetFocusManager()->GetStoredFocusView()); // Verify a focus request on |v2| implicitly updates the stored focus view. v2->RequestFocus(); EXPECT_TRUE(v2->HasFocus()); EXPECT_EQ(v2, GetWidget()->GetFocusManager()->GetStoredFocusView()); } namespace { class FocusManagerArrowKeyTraversalTest : public FocusManagerTest, public testing::WithParamInterface<bool> { public: FocusManagerArrowKeyTraversalTest() = default; FocusManagerArrowKeyTraversalTest(const FocusManagerArrowKeyTraversalTest&) = delete; FocusManagerArrowKeyTraversalTest& operator=( const FocusManagerArrowKeyTraversalTest&) = delete; ~FocusManagerArrowKeyTraversalTest() override = default; // FocusManagerTest overrides: void SetUp() override { if (testing::UnitTest::GetInstance()->current_test_info()->value_param()) { is_rtl_ = GetParam(); if (is_rtl_) base::i18n::SetICUDefaultLocale("he"); } FocusManagerTest::SetUp(); previous_arrow_key_traversal_enabled_ = FocusManager::arrow_key_traversal_enabled(); } void TearDown() override { FocusManager::set_arrow_key_traversal_enabled( previous_arrow_key_traversal_enabled_); FocusManagerTest::TearDown(); } bool is_rtl_ = false; private: // Restores the locale to default when the destructor is called. base::test::ScopedRestoreICUDefaultLocale restore_locale_; bool previous_arrow_key_traversal_enabled_ = false; }; // Instantiate the Boolean which is used to toggle RTL in // the parameterized tests. INSTANTIATE_TEST_SUITE_P(All, FocusManagerArrowKeyTraversalTest, testing::Bool()); } // namespace TEST_P(FocusManagerArrowKeyTraversalTest, ArrowKeyTraversal) { FocusManager* focus_manager = GetFocusManager(); const ui::KeyEvent left_key(ui::ET_KEY_PRESSED, ui::VKEY_LEFT, ui::EF_NONE); const ui::KeyEvent right_key(ui::ET_KEY_PRESSED, ui::VKEY_RIGHT, ui::EF_NONE); const ui::KeyEvent up_key(ui::ET_KEY_PRESSED, ui::VKEY_UP, ui::EF_NONE); const ui::KeyEvent down_key(ui::ET_KEY_PRESSED, ui::VKEY_DOWN, ui::EF_NONE); std::vector<views::View*> v; for (size_t i = 0; i < 2; ++i) { views::View* view = new View; view->SetFocusBehavior(View::FocusBehavior::ALWAYS); GetContentsView()->AddChildView(view); v.push_back(view); } // Arrow key traversal is off and arrow key does not change focus. FocusManager::set_arrow_key_traversal_enabled(false); v[0]->RequestFocus(); focus_manager->OnKeyEvent(right_key); EXPECT_EQ(v[0], focus_manager->GetFocusedView()); focus_manager->OnKeyEvent(left_key); EXPECT_EQ(v[0], focus_manager->GetFocusedView()); focus_manager->OnKeyEvent(down_key); EXPECT_EQ(v[0], focus_manager->GetFocusedView()); focus_manager->OnKeyEvent(up_key); EXPECT_EQ(v[0], focus_manager->GetFocusedView()); // Turn on arrow key traversal. FocusManager::set_arrow_key_traversal_enabled(true); v[0]->RequestFocus(); focus_manager->OnKeyEvent(is_rtl_ ? left_key : right_key); EXPECT_EQ(v[1], focus_manager->GetFocusedView()); focus_manager->OnKeyEvent(is_rtl_ ? right_key : left_key); EXPECT_EQ(v[0], focus_manager->GetFocusedView()); focus_manager->OnKeyEvent(down_key); EXPECT_EQ(v[1], focus_manager->GetFocusedView()); focus_manager->OnKeyEvent(up_key); EXPECT_EQ(v[0], focus_manager->GetFocusedView()); } TEST_F(FocusManagerTest, SkipViewsInArrowKeyTraversal) { FocusManager* focus_manager = GetFocusManager(); // Test the focus on the views which are under same group. std::vector<views::View*> v; for (size_t i = 0; i < 5; ++i) { auto* view = GetContentsView()->AddChildView(std::make_unique<views::View>()); view->SetGroup(12345); // Testing both kind of focuses (Always focusable and only accessibility // focusable). view->SetFocusBehavior((i == 0 || i == 4) ? View::FocusBehavior::ALWAYS : View::FocusBehavior::ACCESSIBLE_ONLY); v.push_back(view); } // Disable view at index 1, and hide view at index 3. v[1]->SetEnabled(false); v[3]->SetVisible(false); // Start with focusing on the first view which is always accessible. v[0]->RequestFocus(); EXPECT_EQ(v[0], focus_manager->GetFocusedView()); // Check that focus does not go to a disabled/hidden view. const ui::KeyEvent right_key(ui::ET_KEY_PRESSED, ui::VKEY_RIGHT, ui::EF_NONE); focus_manager->OnKeyEvent(right_key); EXPECT_EQ(v[2], focus_manager->GetFocusedView()); focus_manager->OnKeyEvent(right_key); EXPECT_EQ(v[4], focus_manager->GetFocusedView()); const ui::KeyEvent left_key(ui::ET_KEY_PRESSED, ui::VKEY_LEFT, ui::EF_NONE); focus_manager->OnKeyEvent(left_key); EXPECT_EQ(v[2], focus_manager->GetFocusedView()); focus_manager->OnKeyEvent(left_key); EXPECT_EQ(v[0], focus_manager->GetFocusedView()); // On making the views visible/enabled, the focus should start appearing. v[1]->SetEnabled(true); v[3]->SetVisible(true); focus_manager->OnKeyEvent(right_key); EXPECT_EQ(v[1], focus_manager->GetFocusedView()); focus_manager->OnKeyEvent(right_key); EXPECT_EQ(v[2], focus_manager->GetFocusedView()); focus_manager->OnKeyEvent(right_key); EXPECT_EQ(v[3], focus_manager->GetFocusedView()); } TEST_F(FocusManagerTest, StoreFocusedView) { std::vector<FocusTestEvent> event_list; const int kView1ID = 1; SimpleTestView* view = new SimpleTestView(&event_list, kView1ID); // Add view to the view hierarchy and make it focusable. GetWidget()->GetRootView()->AddChildView(view); view->SetFocusBehavior(View::FocusBehavior::ALWAYS); GetFocusManager()->SetFocusedView(view); GetFocusManager()->StoreFocusedView(false); EXPECT_EQ(nullptr, GetFocusManager()->GetFocusedView()); EXPECT_TRUE(GetFocusManager()->RestoreFocusedView()); EXPECT_EQ(view, GetFocusManager()->GetStoredFocusView()); ASSERT_EQ(3, static_cast<int>(event_list.size())); EXPECT_EQ(ON_FOCUS, event_list[0].type); EXPECT_EQ(kView1ID, event_list[0].view_id); EXPECT_EQ(FocusChangeReason::kDirectFocusChange, event_list[0].focus_change_reason); EXPECT_EQ(ON_BLUR, event_list[1].type); EXPECT_EQ(kView1ID, event_list[1].view_id); EXPECT_EQ(FocusChangeReason::kDirectFocusChange, event_list[1].focus_change_reason); EXPECT_EQ(ON_FOCUS, event_list[2].type); EXPECT_EQ(kView1ID, event_list[2].view_id); EXPECT_EQ(FocusChangeReason::kFocusRestore, event_list[2].focus_change_reason); // Repeat with |true|. event_list.clear(); GetFocusManager()->SetFocusedView(view); GetFocusManager()->StoreFocusedView(true); EXPECT_EQ(nullptr, GetFocusManager()->GetFocusedView()); EXPECT_TRUE(GetFocusManager()->RestoreFocusedView()); EXPECT_EQ(view, GetFocusManager()->GetStoredFocusView()); ASSERT_EQ(2, static_cast<int>(event_list.size())); EXPECT_EQ(ON_BLUR, event_list[0].type); EXPECT_EQ(kView1ID, event_list[0].view_id); EXPECT_EQ(FocusChangeReason::kDirectFocusChange, event_list[0].focus_change_reason); EXPECT_EQ(ON_FOCUS, event_list[1].type); EXPECT_EQ(kView1ID, event_list[1].view_id); EXPECT_EQ(FocusChangeReason::kFocusRestore, event_list[1].focus_change_reason); // Necessary for clean teardown. GetFocusManager()->ClearFocus(); } #if BUILDFLAG(IS_MAC) // Test that the correct view is restored if full keyboard access is changed. TEST_F(FocusManagerTest, StoreFocusedViewFullKeyboardAccess) { View* view1 = new View; View* view2 = new View; View* view3 = new View; // Make view1 focusable in accessibility mode, view2 not focusable and view3 // always focusable. view1->SetFocusBehavior(View::FocusBehavior::ACCESSIBLE_ONLY); view2->SetFocusBehavior(View::FocusBehavior::NEVER); view3->SetFocusBehavior(View::FocusBehavior::ALWAYS); // Add views to the view hierarchy GetWidget()->GetRootView()->AddChildView(view1); GetWidget()->GetRootView()->AddChildView(view2); GetWidget()->GetRootView()->AddChildView(view3); view1->RequestFocus(); EXPECT_EQ(view1, GetFocusManager()->GetFocusedView()); GetFocusManager()->StoreFocusedView(true); EXPECT_EQ(nullptr, GetFocusManager()->GetFocusedView()); // Turn off full keyboard access mode and restore focused view. Since view1 is // no longer focusable, view3 should have focus. GetFocusManager()->SetKeyboardAccessible(false); EXPECT_FALSE(GetFocusManager()->RestoreFocusedView()); EXPECT_EQ(view3, GetFocusManager()->GetFocusedView()); GetFocusManager()->StoreFocusedView(false); EXPECT_EQ(nullptr, GetFocusManager()->GetFocusedView()); // Turn on full keyboard access mode and restore focused view. Since view3 is // still focusable, view3 should have focus. GetFocusManager()->SetKeyboardAccessible(true); EXPECT_TRUE(GetFocusManager()->RestoreFocusedView()); EXPECT_EQ(view3, GetFocusManager()->GetFocusedView()); } // Test that View::RequestFocus() respects full keyboard access mode. TEST_F(FocusManagerTest, RequestFocus) { View* view1 = new View(); View* view2 = new View(); // Make view1 always focusable, view2 only focusable in accessibility mode. view1->SetFocusBehavior(View::FocusBehavior::ALWAYS); view2->SetFocusBehavior(View::FocusBehavior::ACCESSIBLE_ONLY); // Adds views to the view hierarchy. GetWidget()->GetRootView()->AddChildView(view1); GetWidget()->GetRootView()->AddChildView(view2); // Verify view1 can always get focus via View::RequestFocus, while view2 can // only get focus in full keyboard accessibility mode. EXPECT_TRUE(GetFocusManager()->keyboard_accessible()); view1->RequestFocus(); EXPECT_EQ(view1, GetFocusManager()->GetFocusedView()); view2->RequestFocus(); EXPECT_EQ(view2, GetFocusManager()->GetFocusedView()); // Toggle full keyboard accessibility. GetFocusManager()->SetKeyboardAccessible(false); GetFocusManager()->ClearFocus(); EXPECT_NE(view1, GetFocusManager()->GetFocusedView()); view1->RequestFocus(); EXPECT_EQ(view1, GetFocusManager()->GetFocusedView()); view2->RequestFocus(); EXPECT_EQ(view1, GetFocusManager()->GetFocusedView()); } #endif namespace { // Trivial WidgetDelegate implementation that allows setting return value of // ShouldAdvanceFocusToTopLevelWidget(). class AdvanceFocusWidgetDelegate : public WidgetDelegate { public: explicit AdvanceFocusWidgetDelegate(Widget* widget) : widget_(widget) {} AdvanceFocusWidgetDelegate(const AdvanceFocusWidgetDelegate&) = delete; AdvanceFocusWidgetDelegate& operator=(const AdvanceFocusWidgetDelegate&) = delete; ~AdvanceFocusWidgetDelegate() override = default; // WidgetDelegate: Widget* GetWidget() override { return widget_; } const Widget* GetWidget() const override { return widget_; } private: raw_ptr<Widget> widget_; }; class TestBubbleDialogDelegateView : public BubbleDialogDelegateView { public: explicit TestBubbleDialogDelegateView(View* anchor) : BubbleDialogDelegateView(anchor, BubbleBorder::NONE) { DialogDelegate::SetButtons(ui::DIALOG_BUTTON_NONE); } TestBubbleDialogDelegateView(const TestBubbleDialogDelegateView&) = delete; TestBubbleDialogDelegateView& operator=(const TestBubbleDialogDelegateView&) = delete; ~TestBubbleDialogDelegateView() override = default; static TestBubbleDialogDelegateView* CreateAndShowBubble(View* anchor) { TestBubbleDialogDelegateView* bubble = new TestBubbleDialogDelegateView(anchor); Widget* bubble_widget = BubbleDialogDelegateView::CreateBubble(bubble); bubble_widget->SetFocusTraversableParent( bubble->anchor_widget()->GetFocusTraversable()); bubble_widget->SetFocusTraversableParentView(anchor); bubble->set_close_on_deactivate(false); bubble_widget->Show(); return bubble; } // If this is called, the bubble will be forced to use a NativeWidgetAura. // If not set, it might get a DesktopNativeWidgetAura depending on the // platform and other factors. void UseNativeWidgetAura() { use_native_widget_aura_ = true; } void OnBeforeBubbleWidgetInit(Widget::InitParams* params, Widget* widget) const override { #if defined(USE_AURA) if (use_native_widget_aura_) { params->native_widget = new test::TestPlatformNativeWidget<NativeWidgetAura>(widget, false, nullptr); } #endif // USE_AURA } private: bool use_native_widget_aura_ = false; }; } // namespace // Verifies focus wrapping happens in the same widget. TEST_F(FocusManagerTest, AdvanceFocusStaysInWidget) { // Add |widget_view| as a child of the Widget. View* widget_view = new View; widget_view->SetFocusBehavior(View::FocusBehavior::ALWAYS); widget_view->SetBounds(20, 0, 20, 20); GetContentsView()->AddChildView(widget_view); // Create a widget with two views, focus the second. Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.child = true; params.bounds = gfx::Rect(10, 10, 100, 100); params.parent = GetWidget()->GetNativeView(); UniqueWidgetPtr child_widget = std::make_unique<Widget>(); std::unique_ptr<AdvanceFocusWidgetDelegate> delegate_owned = std::make_unique<AdvanceFocusWidgetDelegate>(child_widget.get()); AdvanceFocusWidgetDelegate* delegate = delegate_owned.get(); params.delegate = delegate_owned.release(); delegate->SetOwnedByWidget(true); child_widget->Init(std::move(params)); View* view1 = new View; view1->SetFocusBehavior(View::FocusBehavior::ALWAYS); view1->SetBounds(0, 0, 20, 20); View* view2 = new View; view2->SetFocusBehavior(View::FocusBehavior::ALWAYS); view2->SetBounds(20, 0, 20, 20); child_widget->client_view()->AddChildView(view1); child_widget->client_view()->AddChildView(view2); child_widget->Show(); view2->RequestFocus(); EXPECT_EQ(view2, GetFocusManager()->GetFocusedView()); // Advance focus backwards, which should focus the first. GetFocusManager()->AdvanceFocus(false); EXPECT_EQ(view1, GetFocusManager()->GetFocusedView()); // Focus forward to |view2|. GetFocusManager()->AdvanceFocus(true); EXPECT_EQ(view2, GetFocusManager()->GetFocusedView()); // And forward again, wrapping back to |view1|. GetFocusManager()->AdvanceFocus(true); EXPECT_EQ(view1, GetFocusManager()->GetFocusedView()); } TEST_F(FocusManagerTest, NavigateIntoAnchoredDialog) { // The parent Widget has four focusable views. A child widget dialog has // two focusable views, and it's anchored to the 3rd parent view. Ensure // that focus traverses into the anchored dialog after the 3rd parent // view, and then back to the 4th parent view. View* parent1 = new View(); View* parent2 = new View(); View* parent3 = new View(); View* parent4 = new View(); parent1->SetFocusBehavior(View::FocusBehavior::ALWAYS); parent2->SetFocusBehavior(View::FocusBehavior::ALWAYS); parent3->SetFocusBehavior(View::FocusBehavior::ALWAYS); parent4->SetFocusBehavior(View::FocusBehavior::ALWAYS); GetWidget()->GetRootView()->AddChildView(parent1); GetWidget()->GetRootView()->AddChildView(parent2); GetWidget()->GetRootView()->AddChildView(parent3); GetWidget()->GetRootView()->AddChildView(parent4); // Add an unfocusable child view to the dialog anchor view. This is a // regression test that makes sure focus is able to navigate past unfocusable // children and try to go into the anchored dialog. |kAnchoredDialogKey| was // previously not checked if a recursive search to find a focusable child view // was attempted (and failed), so the dialog would previously be skipped. parent3->AddChildView(new View()); BubbleDialogDelegateView* bubble_delegate = TestBubbleDialogDelegateView::CreateAndShowBubble(parent3); Widget* bubble_widget = bubble_delegate->GetWidget(); View* child1 = new View(); View* child2 = new View(); child1->SetFocusBehavior(View::FocusBehavior::ALWAYS); child2->SetFocusBehavior(View::FocusBehavior::ALWAYS); bubble_widget->GetRootView()->AddChildView(child1); bubble_widget->GetRootView()->AddChildView(child2); parent1->RequestFocus(); // Navigate forwards GetWidget()->GetFocusManager()->AdvanceFocus(false); EXPECT_TRUE(parent2->HasFocus()); GetWidget()->GetFocusManager()->AdvanceFocus(false); EXPECT_TRUE(parent3->HasFocus()); GetWidget()->GetFocusManager()->AdvanceFocus(false); EXPECT_TRUE(child1->HasFocus()); bubble_widget->GetFocusManager()->AdvanceFocus(false); EXPECT_TRUE(child2->HasFocus()); bubble_widget->GetFocusManager()->AdvanceFocus(false); EXPECT_TRUE(parent4->HasFocus()); // Navigate backwards GetWidget()->GetFocusManager()->AdvanceFocus(true); EXPECT_TRUE(child2->HasFocus()); bubble_widget->GetFocusManager()->AdvanceFocus(true); EXPECT_TRUE(child1->HasFocus()); bubble_widget->GetFocusManager()->AdvanceFocus(true); EXPECT_TRUE(parent3->HasFocus()); } TEST_F(FocusManagerTest, AnchoredDialogOnContainerView) { // The parent Widget has four focusable views, with the middle two views // inside of a non-focusable grouping View. A child widget dialog has // two focusable views, and it's anchored to the group View. Ensure // that focus traverses into the anchored dialog after the 3rd parent // view, and then back to the 4th parent view. View* parent1 = new View(); View* parent2 = new View(); View* parent3 = new View(); View* parent4 = new View(); View* parent_group = new View(); parent1->SetFocusBehavior(View::FocusBehavior::ALWAYS); parent2->SetFocusBehavior(View::FocusBehavior::ALWAYS); parent3->SetFocusBehavior(View::FocusBehavior::ALWAYS); parent4->SetFocusBehavior(View::FocusBehavior::ALWAYS); GetWidget()->GetRootView()->AddChildView(parent1); GetWidget()->GetRootView()->AddChildView(parent_group); parent_group->AddChildView(parent2); parent_group->AddChildView(parent3); GetWidget()->GetRootView()->AddChildView(parent4); BubbleDialogDelegateView* bubble_delegate = TestBubbleDialogDelegateView::CreateAndShowBubble(parent3); Widget* bubble_widget = bubble_delegate->GetWidget(); View* child1 = new View(); View* child2 = new View(); child1->SetFocusBehavior(View::FocusBehavior::ALWAYS); child2->SetFocusBehavior(View::FocusBehavior::ALWAYS); bubble_widget->GetRootView()->AddChildView(child1); bubble_widget->GetRootView()->AddChildView(child2); parent1->RequestFocus(); // Navigate forwards GetWidget()->GetFocusManager()->AdvanceFocus(false); EXPECT_TRUE(parent2->HasFocus()); GetWidget()->GetFocusManager()->AdvanceFocus(false); EXPECT_TRUE(parent3->HasFocus()); GetWidget()->GetFocusManager()->AdvanceFocus(false); EXPECT_TRUE(child1->HasFocus()); bubble_widget->GetFocusManager()->AdvanceFocus(false); EXPECT_TRUE(child2->HasFocus()); bubble_widget->GetFocusManager()->AdvanceFocus(false); EXPECT_TRUE(parent4->HasFocus()); // Navigate backwards GetWidget()->GetFocusManager()->AdvanceFocus(true); EXPECT_TRUE(child2->HasFocus()); bubble_widget->GetFocusManager()->AdvanceFocus(true); EXPECT_TRUE(child1->HasFocus()); bubble_widget->GetFocusManager()->AdvanceFocus(true); EXPECT_TRUE(parent3->HasFocus()); } // Checks that focus traverses from a View to a bubble anchored at that View // when in a pane. TEST_F(FocusManagerTest, AnchoredDialogInPane) { // Set up a focusable view (to which we will anchor our bubble) inside an // AccessiblePaneView. View* root_view = GetWidget()->GetRootView(); AccessiblePaneView* pane = root_view->AddChildView(std::make_unique<AccessiblePaneView>()); View* anchor = pane->AddChildView(std::make_unique<View>()); anchor->SetFocusBehavior(View::FocusBehavior::ALWAYS); BubbleDialogDelegateView* bubble = TestBubbleDialogDelegateView::CreateAndShowBubble(anchor); // We need a focusable view inside our bubble to check that focus traverses // in. View* bubble_child = bubble->AddChildView(std::make_unique<View>()); bubble_child->SetFocusBehavior(View::FocusBehavior::ALWAYS); // Verify that, when in pane focus mode, focus advances from the anchor view // to inside the bubble. pane->SetPaneFocus(anchor); EXPECT_TRUE(anchor->HasFocus()); GetWidget()->GetFocusManager()->AdvanceFocus(false); EXPECT_TRUE(bubble_child->HasFocus()); } #if BUILDFLAG(ENABLE_DESKTOP_AURA) // This test is specifically for the permutation where the main widget is a // DesktopNativeWidgetAura and the bubble is a NativeWidgetAura. When focus // moves back from the bubble to the parent widget, ensure that the DNWA's aura // window is focused. class DesktopWidgetFocusManagerTest : public FocusManagerTest { public: DesktopWidgetFocusManagerTest() = default; DesktopWidgetFocusManagerTest(const DesktopWidgetFocusManagerTest&) = delete; DesktopWidgetFocusManagerTest& operator=( const DesktopWidgetFocusManagerTest&) = delete; ~DesktopWidgetFocusManagerTest() override = default; // FocusManagerTest: void SetUp() override { set_native_widget_type(NativeWidgetType::kDesktop); FocusManagerTest::SetUp(); } }; TEST_F(DesktopWidgetFocusManagerTest, AnchoredDialogInDesktopNativeWidgetAura) { UniqueWidgetPtr widget = std::make_unique<Widget>(); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.bounds = gfx::Rect(0, 0, 1024, 768); widget->Init(std::move(params)); widget->Show(); widget->Activate(); View* parent1 = new View(); View* parent2 = new View(); parent1->SetFocusBehavior(View::FocusBehavior::ALWAYS); parent2->SetFocusBehavior(View::FocusBehavior::ALWAYS); widget->GetRootView()->AddChildView(parent1); widget->GetRootView()->AddChildView(parent2); TestBubbleDialogDelegateView* bubble_delegate = TestBubbleDialogDelegateView::CreateAndShowBubble(parent2); Widget* bubble_widget = bubble_delegate->GetWidget(); bubble_delegate->UseNativeWidgetAura(); View* child = new View(); child->SetFocusBehavior(View::FocusBehavior::ALWAYS); bubble_widget->GetRootView()->AddChildView(child); // In order to pass the accessibility paint checks, focusable views must have // a valid role. parent1->GetViewAccessibility().OverrideRole(ax::mojom::Role::kGroup); parent2->GetViewAccessibility().OverrideRole(ax::mojom::Role::kGroup); child->GetViewAccessibility().OverrideRole(ax::mojom::Role::kButton); // In order to pass the accessibility paint checks, focusable views must have // a non-empty accessible name, or have their name set to explicitly empty. parent1->GetViewAccessibility().OverrideName(u"Parent 1"); parent2->GetViewAccessibility().OverrideName( u"", ax::mojom::NameFrom::kAttributeExplicitlyEmpty); child->GetViewAccessibility().OverrideName("uChild"); widget->Activate(); parent1->RequestFocus(); base::RunLoop().RunUntilIdle(); // Initially the outer widget's window is focused. aura::client::FocusClient* focus_client = aura::client::GetFocusClient(widget->GetNativeView()); ASSERT_EQ(widget->GetNativeView(), focus_client->GetFocusedWindow()); // Navigate forwards widget->GetFocusManager()->AdvanceFocus(false); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(parent2->HasFocus()); widget->GetFocusManager()->AdvanceFocus(false); EXPECT_TRUE(child->HasFocus()); // Now the bubble widget's window is focused. ASSERT_NE(widget->GetNativeView(), focus_client->GetFocusedWindow()); ASSERT_EQ(bubble_widget->GetNativeView(), focus_client->GetFocusedWindow()); // Navigate backwards bubble_widget->GetFocusManager()->AdvanceFocus(true); EXPECT_TRUE(parent2->HasFocus()); // Finally, the outer widget's window should be focused again. ASSERT_EQ(widget->GetNativeView(), focus_client->GetFocusedWindow()); } #endif #if defined(USE_AURA) class RedirectToParentFocusManagerTest : public FocusManagerTest { public: RedirectToParentFocusManagerTest() = default; RedirectToParentFocusManagerTest(const RedirectToParentFocusManagerTest&) = delete; RedirectToParentFocusManagerTest& operator=( const RedirectToParentFocusManagerTest&) = delete; ~RedirectToParentFocusManagerTest() override = default; // FocusManagerTest: void SetUp() override { FocusManagerTest::SetUp(); View* anchor = GetWidget()->GetRootView()->AddChildView(std::make_unique<View>()); anchor->SetFocusBehavior(View::FocusBehavior::ALWAYS); bubble_ = TestBubbleDialogDelegateView::CreateAndShowBubble(anchor); Widget* bubble_widget = bubble_->GetWidget(); parent_focus_manager_ = anchor->GetFocusManager(); bubble_focus_manager_ = bubble_widget->GetFocusManager(); } void TearDown() override { FocusManagerFactory::Install(nullptr); FocusManagerTest::TearDown(); } protected: raw_ptr<FocusManager> parent_focus_manager_ = nullptr; raw_ptr<FocusManager> bubble_focus_manager_ = nullptr; raw_ptr<BubbleDialogDelegateView> bubble_ = nullptr; }; // Test that when an accelerator is sent to a bubble that isn't registered, // the bubble's parent handles it instead. TEST_F(RedirectToParentFocusManagerTest, ParentHandlesAcceleratorFromBubble) { ui::Accelerator return_accelerator(ui::VKEY_RETURN, ui::EF_NONE); ui::TestAcceleratorTarget parent_return_target(true); Widget* bubble_widget = bubble_->GetWidget(); EXPECT_EQ(0, parent_return_target.accelerator_count()); parent_focus_manager_->RegisterAccelerator( return_accelerator, ui::AcceleratorManager::kNormalPriority, &parent_return_target); EXPECT_TRUE( !bubble_focus_manager_->IsAcceleratorRegistered(return_accelerator)); // The bubble should be closed after parent processed accelerator only if // close_on_deactivate is true. bubble_->set_close_on_deactivate(false); // Accelerator was processed by the parent. EXPECT_TRUE(bubble_focus_manager_->ProcessAccelerator(return_accelerator)); EXPECT_EQ(parent_return_target.accelerator_count(), 1); EXPECT_FALSE(bubble_widget->IsClosed()); // Reset focus to the bubble widget. Focus was set to the the main widget // to process accelerator. bubble_focus_manager_->SetFocusedView(bubble_widget->GetRootView()); bubble_->set_close_on_deactivate(true); EXPECT_TRUE(bubble_focus_manager_->ProcessAccelerator(return_accelerator)); EXPECT_EQ(parent_return_target.accelerator_count(), 2); EXPECT_TRUE(bubble_widget->IsClosed()); } // Test that when an accelerator is sent to a bubble that is registered on both // it and its parent, the bubble handles it. TEST_F(RedirectToParentFocusManagerTest, BubbleHandlesRegisteredAccelerators) { ui::Accelerator return_accelerator(ui::VKEY_RETURN, ui::EF_NONE); ui::TestAcceleratorTarget parent_return_target(true); ui::TestAcceleratorTarget bubble_return_target(true); Widget* bubble_widget = bubble_->GetWidget(); EXPECT_EQ(0, bubble_return_target.accelerator_count()); EXPECT_EQ(0, parent_return_target.accelerator_count()); bubble_focus_manager_->RegisterAccelerator( return_accelerator, ui::AcceleratorManager::kNormalPriority, &bubble_return_target); parent_focus_manager_->RegisterAccelerator( return_accelerator, ui::AcceleratorManager::kNormalPriority, &parent_return_target); // The bubble shouldn't be closed after it processed accelerator without // passing it to the parent. bubble_->set_close_on_deactivate(true); // Accelerator was processed by the bubble and not by the parent. EXPECT_TRUE(bubble_focus_manager_->ProcessAccelerator(return_accelerator)); EXPECT_EQ(1, bubble_return_target.accelerator_count()); EXPECT_EQ(0, parent_return_target.accelerator_count()); EXPECT_FALSE(bubble_widget->IsClosed()); } // Test that when an accelerator is sent to a bubble that isn't registered // for either the bubble or the bubble's parent, the bubble isn't closed. TEST_F(RedirectToParentFocusManagerTest, NotProcessedAccelerator) { ui::Accelerator return_accelerator(ui::VKEY_RETURN, ui::EF_NONE); Widget* bubble_widget = bubble_->GetWidget(); EXPECT_TRUE( !bubble_focus_manager_->IsAcceleratorRegistered(return_accelerator)); EXPECT_TRUE( !parent_focus_manager_->IsAcceleratorRegistered(return_accelerator)); // The bubble shouldn't be closed if the accelerator was passed to the parent // but the parent didn't process it. bubble_->set_close_on_deactivate(true); EXPECT_FALSE(bubble_focus_manager_->ProcessAccelerator(return_accelerator)); EXPECT_FALSE(bubble_widget->IsClosed()); } #endif } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/focus/focus_manager_unittest.cc
C++
unknown
51,538
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/focus/focus_search.h" #include "base/logging.h" #include "build/build_config.h" #include "ui/views/focus/focus_manager.h" #include "ui/views/view.h" #include "ui/views/view_class_properties.h" #include "ui/views/widget/widget.h" #include "ui/views/window/dialog_delegate.h" namespace views { FocusSearch::FocusSearch(View* root, bool cycle, bool accessibility_mode) : root_(root), cycle_(cycle), accessibility_mode_(accessibility_mode) { #if BUILDFLAG(IS_MAC) // On Mac, only the keyboard accessibility mode defined in FocusManager is // used. No special accessibility mode should be applicable for a // FocusTraversable. accessibility_mode_ = false; #endif } View* FocusSearch::FindNextFocusableView( View* starting_view, FocusSearch::SearchDirection search_direction, FocusSearch::TraversalDirection traversal_direction, FocusSearch::StartingViewPolicy check_starting_view, FocusSearch::AnchoredDialogPolicy can_go_into_anchored_dialog, FocusTraversable** focus_traversable, View** focus_traversable_view) { DCHECK(!root_->children().empty()); *focus_traversable = nullptr; *focus_traversable_view = nullptr; View* initial_starting_view = starting_view; int starting_view_group = -1; if (starting_view) starting_view_group = starting_view->GetGroup(); if (!starting_view) { // Default to the first/last child starting_view = search_direction == SearchDirection::kBackwards ? root_->children().back() : root_->children().front(); // If there was no starting view, then the one we select is a potential // focus candidate. check_starting_view = StartingViewPolicy::kCheckStartingView; } else { // The starting view should be a direct or indirect child of the root. DCHECK(Contains(root_, starting_view)); } base::flat_set<View*> seen_views; View* v = nullptr; if (search_direction == SearchDirection::kForwards) { v = FindNextFocusableViewImpl( starting_view, check_starting_view, true, (traversal_direction == TraversalDirection::kDown), can_go_into_anchored_dialog, starting_view_group, &seen_views, focus_traversable, focus_traversable_view); } else { // If the starting view is focusable, we don't want to go down, as we are // traversing the view hierarchy tree bottom-up. bool can_go_down = (traversal_direction == TraversalDirection::kDown) && !IsFocusable(starting_view); v = FindPreviousFocusableViewImpl( starting_view, check_starting_view, true, can_go_down, can_go_into_anchored_dialog, starting_view_group, &seen_views, focus_traversable, focus_traversable_view); } // Don't set the focus to something outside of this view hierarchy. if (v && v != root_ && !Contains(root_, v)) v = nullptr; // If we should go into a sub-FocusTraversable (such as an anchored bubble), a // null View is returned and |focus_traversable| is set appropriately. Handle // this case before cycling. Note that Find{Next,Previous}FocusableViewImpl // respect |can_go_into_anchored_dialog| so we don't need to check it here. if (*focus_traversable) { DCHECK(*focus_traversable_view); DCHECK_EQ(v, nullptr); return nullptr; } // If |cycle_| is true, prefer to keep cycling rather than returning nullptr. if (cycle_ && !v && initial_starting_view) { v = FindNextFocusableView(nullptr, search_direction, traversal_direction, check_starting_view, can_go_into_anchored_dialog, focus_traversable, focus_traversable_view); } // Doing some sanity checks. if (v) { DCHECK(IsFocusable(v)); return v; } // Nothing found. return nullptr; } bool FocusSearch::IsViewFocusableCandidate(View* v, int skip_group_id) { return IsFocusable(v) && (v->IsGroupFocusTraversable() || skip_group_id == -1 || v->GetGroup() != skip_group_id); } bool FocusSearch::IsFocusable(View* v) { DCHECK(root_); // Sanity Check. Currently the FocusManager keyboard accessibility mode is // only used on Mac, for which |accessibility_mode_| is false. DCHECK(!(accessibility_mode_ && root_->GetWidget()->GetFocusManager()->keyboard_accessible())); if (accessibility_mode_ || root_->GetWidget()->GetFocusManager()->keyboard_accessible()) return v && v->IsAccessibilityFocusable(); return v && v->IsFocusable(); } View* FocusSearch::FindSelectedViewForGroup(View* view) { if (view->IsGroupFocusTraversable() || view->GetGroup() == -1) // No group for that view. return view; View* selected_view = view->GetSelectedViewForGroup(view->GetGroup()); if (selected_view) return selected_view; // No view selected for that group, default to the specified view. return view; } View* FocusSearch::GetParent(View* v) { return Contains(root_, v) ? v->parent() : nullptr; } bool FocusSearch::Contains(View* root, const View* v) { return root->Contains(v); } // Strategy for finding the next focusable view: // - keep going down the first child, stop when you find a focusable view or // a focus traversable view (in that case return it) or when you reach a view // with no children. // - go to the right sibling and start the search from there (by invoking // FindNextFocusableViewImpl on that view). // - if the view has no right sibling, go up the parents until you find a parent // with a right sibling and start the search from there. View* FocusSearch::FindNextFocusableViewImpl( View* starting_view, FocusSearch::StartingViewPolicy check_starting_view, bool can_go_up, bool can_go_down, AnchoredDialogPolicy can_go_into_anchored_dialog, int skip_group_id, base::flat_set<View*>* seen_views, FocusTraversable** focus_traversable, View** focus_traversable_view) { // Views are not supposed to have focus cycles, but just in case, fail // gracefully to avoid a crash. if (seen_views->contains(starting_view)) { LOG(ERROR) << "View focus cycle detected."; return nullptr; } seen_views->insert(starting_view); if (check_starting_view == StartingViewPolicy::kCheckStartingView) { if (IsViewFocusableCandidate(starting_view, skip_group_id)) { View* v = FindSelectedViewForGroup(starting_view); // The selected view might not be focusable (if it is disabled for // example). if (IsFocusable(v)) return v; } *focus_traversable = starting_view->GetFocusTraversable(); if (*focus_traversable) { *focus_traversable_view = starting_view; return nullptr; } } // First let's try the left child. if (can_go_down) { if (!starting_view->children().empty()) { // This view might not be `IsFocusable` but the view is still passed // down to evaluate if one of it's children `IsFocusable`. View* view = starting_view->GetChildrenFocusList().front(); View* v = FindNextFocusableViewImpl( view, StartingViewPolicy::kCheckStartingView, false, true, can_go_into_anchored_dialog, skip_group_id, seen_views, focus_traversable, focus_traversable_view); if (v || *focus_traversable) return v; } // Check to see if we should navigate into a dialog anchored at this view. if (can_go_into_anchored_dialog == AnchoredDialogPolicy::kCanGoIntoAnchoredDialog) { DialogDelegate* bubble = starting_view->GetProperty(kAnchoredDialogKey); if (bubble) { *focus_traversable = bubble->GetWidget()->GetFocusTraversable(); *focus_traversable_view = starting_view; return nullptr; } } } // Then try the right sibling. View* sibling = starting_view->GetNextFocusableView(); if (sibling) { View* v = FindNextFocusableViewImpl( sibling, FocusSearch::StartingViewPolicy::kCheckStartingView, false, true, can_go_into_anchored_dialog, skip_group_id, seen_views, focus_traversable, focus_traversable_view); if (v || *focus_traversable) return v; } // Then go up to the parent sibling. if (can_go_up) { View* parent = GetParent(starting_view); while (parent && parent != root_) { if (can_go_into_anchored_dialog == AnchoredDialogPolicy::kCanGoIntoAnchoredDialog) { DialogDelegate* bubble = parent->GetProperty(kAnchoredDialogKey); if (bubble) { *focus_traversable = bubble->GetWidget()->GetFocusTraversable(); *focus_traversable_view = starting_view; return nullptr; } } sibling = parent->GetNextFocusableView(); if (sibling) { return FindNextFocusableViewImpl( sibling, StartingViewPolicy::kCheckStartingView, true, true, can_go_into_anchored_dialog, skip_group_id, seen_views, focus_traversable, focus_traversable_view); } parent = GetParent(parent); } } // We found nothing. return nullptr; } // Strategy for finding the previous focusable view: // - keep going down on the right until you reach a view with no children, if it // it is a good candidate return it. // - start the search on the left sibling. // - if there are no left sibling, start the search on the parent (without going // down). View* FocusSearch::FindPreviousFocusableViewImpl( View* starting_view, FocusSearch::StartingViewPolicy check_starting_view, bool can_go_up, bool can_go_down, FocusSearch::AnchoredDialogPolicy can_go_into_anchored_dialog, int skip_group_id, base::flat_set<View*>* seen_views, FocusTraversable** focus_traversable, View** focus_traversable_view) { // Views are not supposed to have focus cycles, but just in case, fail // gracefully to avoid a crash. if (seen_views->contains(starting_view)) { LOG(ERROR) << "View focus cycle detected."; return nullptr; } seen_views->insert(starting_view); // Normally when we navigate to a FocusTraversableParent, can_go_down is // false so we don't navigate back in. However, if we just navigated out // of an anchored dialog, allow going down in order to navigate into // children of |starting_view| next. if (starting_view->GetProperty(kAnchoredDialogKey) && can_go_into_anchored_dialog == AnchoredDialogPolicy::kSkipAnchoredDialog && !can_go_down) { can_go_down = true; } // Let's go down and right as much as we can. if (can_go_down) { // Before we go into the direct children, we have to check if this view has // a FocusTraversable. *focus_traversable = starting_view->GetFocusTraversable(); if (*focus_traversable) { *focus_traversable_view = starting_view; return nullptr; } // Check to see if we should navigate into a dialog anchored at this view. if (can_go_into_anchored_dialog == AnchoredDialogPolicy::kCanGoIntoAnchoredDialog) { DialogDelegate* bubble = starting_view->GetProperty(kAnchoredDialogKey); if (bubble) { *focus_traversable = bubble->GetWidget()->GetFocusTraversable(); *focus_traversable_view = starting_view; return nullptr; } } can_go_into_anchored_dialog = AnchoredDialogPolicy::kCanGoIntoAnchoredDialog; if (!starting_view->children().empty()) { // This view might not be `IsFocusable` but the view is still passed // down to evaluate if one of it's children `IsFocusable`. View* view = starting_view->GetChildrenFocusList().back(); View* v = FindPreviousFocusableViewImpl( view, StartingViewPolicy::kCheckStartingView, false, true, can_go_into_anchored_dialog, skip_group_id, seen_views, focus_traversable, focus_traversable_view); if (v || *focus_traversable) return v; } } // Then look at this view. Here, we do not need to see if the view has // a FocusTraversable, since we do not want to go down any more. if (check_starting_view == StartingViewPolicy::kCheckStartingView && IsViewFocusableCandidate(starting_view, skip_group_id)) { View* v = FindSelectedViewForGroup(starting_view); // The selected view might not be focusable (if it is disabled for // example). if (IsFocusable(v)) return v; } // Then try the left sibling. View* sibling = starting_view->GetPreviousFocusableView(); if (sibling) { return FindPreviousFocusableViewImpl( sibling, StartingViewPolicy::kCheckStartingView, can_go_up, true, can_go_into_anchored_dialog, skip_group_id, seen_views, focus_traversable, focus_traversable_view); } // Then go up the parent. if (can_go_up) { View* parent = GetParent(starting_view); if (parent) return FindPreviousFocusableViewImpl( parent, StartingViewPolicy::kCheckStartingView, true, false, can_go_into_anchored_dialog, skip_group_id, seen_views, focus_traversable, focus_traversable_view); } // We found nothing. return nullptr; } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/focus/focus_search.cc
C++
unknown
13,268
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_FOCUS_FOCUS_SEARCH_H_ #define UI_VIEWS_FOCUS_FOCUS_SEARCH_H_ #include "base/containers/flat_set.h" #include "base/memory/raw_ptr.h" #include "ui/views/view.h" namespace views { class FocusTraversable; // FocusSearch is an object that implements the algorithm to find the // next view to focus. class VIEWS_EXPORT FocusSearch { public: // The direction in which the focus traversal is going. // TODO(jcampan): add support for lateral (left, right) focus traversal. The // goal is to switch to focusable views on the same level when using the arrow // keys (ala Windows: in a dialog box, arrow keys typically move between the // dialog OK, Cancel buttons). enum class TraversalDirection { kUp, kDown, }; enum class SearchDirection { kForwards, kBackwards, }; enum class StartingViewPolicy { kSkipStartingView, kCheckStartingView, }; enum class AnchoredDialogPolicy { kSkipAnchoredDialog, kCanGoIntoAnchoredDialog, }; // Constructor. // - |root| is the root of the view hierarchy to traverse. Focus will be // trapped inside. // - |cycle| should be true if you want FindNextFocusableView to cycle back // to the first view within this root when the traversal reaches // the end. If this is true, then if you pass a valid starting // view to FindNextFocusableView you will always get a valid view // out, even if it's the same view. // - |accessibility_mode| should be true if full keyboard accessibility is // needed and you want to check IsAccessibilityFocusable(), rather than // IsFocusable(). FocusSearch(View* root, bool cycle, bool accessibility_mode); FocusSearch(const FocusSearch&) = delete; FocusSearch& operator=(const FocusSearch&) = delete; virtual ~FocusSearch() = default; // Finds the next view that should be focused and returns it. If a // FocusTraversable is found while searching for the focusable view, // returns NULL and sets |focus_traversable| to the FocusTraversable // and |focus_traversable_view| to the view associated with the // FocusTraversable. // // Return NULL if the end of the focus loop is reached, unless this object // was initialized with |cycle|=true, in which case it goes back to the // beginning when it reaches the end of the traversal. // - |starting_view| is the view that should be used as the starting point // when looking for the previous/next view. It may be NULL (in which case // the first/last view should be used depending if normal/reverse). // - |search_direction| whether we should find the next (kForwards) or // previous (kReverse) view. // - |traversal_direction| specifies whether we are traversing down (meaning // we should look into child views) or traversing up (don't look at // child views). // - |check_starting_view| indicated if starting_view may obtain the next // focus. // - |can_go_into_anchored_dialog| controls if focus is allowed to jump // into a dialog anchored at one of the views being traversed. // - |focus_traversable| is set to the focus traversable that should be // traversed if one is found (in which case the call returns NULL). // - |focus_traversable_view| is set to the view associated with the // FocusTraversable set in the previous parameter (it is used as the // starting view when looking for the next focusable view). virtual View* FindNextFocusableView( View* starting_view, SearchDirection search_direction, TraversalDirection traversal_direction, StartingViewPolicy check_starting_view, AnchoredDialogPolicy can_go_into_anchored_dialog, FocusTraversable** focus_traversable, View** focus_traversable_view); protected: // Get the parent, but stay within the root. Returns NULL if asked for // the parent of |root_|. Subclasses can override this if they need custom // focus search behavior. virtual View* GetParent(View* v); // Returns true if |v| is contained within the hierarchy rooted at |root|. // Subclasses can override this if they need custom focus search behavior. virtual bool Contains(View* root, const View* v); View* root() const { return root_; } private: // Convenience method that returns true if a view is focusable and does not // belong to the specified group. bool IsViewFocusableCandidate(View* v, int skip_group_id); // Convenience method; returns true if a view is not NULL and is focusable // (checking IsAccessibilityFocusable() if |accessibility_mode_| is true or // the associated FocusManager has keyboard accessibility enabled). bool IsFocusable(View* v); // Returns the view selected for the group of the selected view. If the view // does not belong to a group or if no view is selected in the group, the // specified view is returned. View* FindSelectedViewForGroup(View* view); // Returns the next focusable view or view containing a FocusTraversable // (NULL if none was found), starting at the starting_view. // |check_starting_view|, |can_go_up| and |can_go_down| controls the // traversal of the views hierarchy. |skip_group_id| specifies a group_id, // -1 means no group. All views from a group are traversed in one pass. View* FindNextFocusableViewImpl( View* starting_view, StartingViewPolicy check_starting_view, bool can_go_up, bool can_go_down, AnchoredDialogPolicy can_go_into_anchored_dialog, int skip_group_id, base::flat_set<View*>* seen_views, FocusTraversable** focus_traversable, View** focus_traversable_view); // Same as FindNextFocusableViewImpl but returns the previous focusable view. View* FindPreviousFocusableViewImpl( View* starting_view, StartingViewPolicy check_starting_view, bool can_go_up, bool can_go_down, AnchoredDialogPolicy can_go_into_anchored_dialog, int skip_group_id, base::flat_set<View*>* seen_views, FocusTraversable** focus_traversable, View** focus_traversable_view); raw_ptr<View> root_; bool cycle_; bool accessibility_mode_; }; } // namespace views #endif // UI_VIEWS_FOCUS_FOCUS_SEARCH_H_
Zhao-PengFei35/chromium_src_4
ui/views/focus/focus_search.h
C++
unknown
6,377
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stddef.h> #include "base/memory/raw_ptr.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "ui/base/models/combobox_model.h" #include "ui/views/background.h" #include "ui/views/border.h" #include "ui/views/controls/button/checkbox.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/button/md_text_button.h" #include "ui/views/controls/button/radio_button.h" #include "ui/views/controls/combobox/combobox.h" #include "ui/views/controls/label.h" #include "ui/views/controls/link.h" #include "ui/views/controls/native/native_view_host.h" #include "ui/views/controls/scroll_view.h" #include "ui/views/controls/tabbed_pane/tabbed_pane.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/focus/focus_manager.h" #include "ui/views/test/focus_manager_test.h" #include "ui/views/widget/root_view.h" #include "ui/views/widget/widget.h" using base::ASCIIToUTF16; namespace views { namespace { enum { TOP_CHECKBOX_ID = 1, // 1 LEFT_CONTAINER_ID, APPLE_LABEL_ID, APPLE_TEXTFIELD_ID, ORANGE_LABEL_ID, // 5 ORANGE_TEXTFIELD_ID, BANANA_LABEL_ID, BANANA_TEXTFIELD_ID, KIWI_LABEL_ID, KIWI_TEXTFIELD_ID, // 10 FRUIT_BUTTON_ID, FRUIT_CHECKBOX_ID, COMBOBOX_ID, RIGHT_CONTAINER_ID, ASPARAGUS_BUTTON_ID, // 15 BROCCOLI_BUTTON_ID, CAULIFLOWER_BUTTON_ID, INNER_CONTAINER_ID, SCROLL_VIEW_ID, ROSETTA_LINK_ID, // 20 STUPEUR_ET_TREMBLEMENT_LINK_ID, DINER_GAME_LINK_ID, RIDICULE_LINK_ID, CLOSET_LINK_ID, VISITING_LINK_ID, // 25 AMELIE_LINK_ID, JOYEUX_NOEL_LINK_ID, CAMPING_LINK_ID, BRICE_DE_NICE_LINK_ID, TAXI_LINK_ID, // 30 ASTERIX_LINK_ID, OK_BUTTON_ID, CANCEL_BUTTON_ID, HELP_BUTTON_ID, STYLE_CONTAINER_ID, // 35 BOLD_CHECKBOX_ID, ITALIC_CHECKBOX_ID, UNDERLINED_CHECKBOX_ID, STYLE_HELP_LINK_ID, STYLE_TEXT_EDIT_ID, // 40 SEARCH_CONTAINER_ID, SEARCH_TEXTFIELD_ID, SEARCH_BUTTON_ID, HELP_LINK_ID, THUMBNAIL_CONTAINER_ID, // 45 THUMBNAIL_STAR_ID, THUMBNAIL_SUPER_STAR_ID, }; class DummyComboboxModel : public ui::ComboboxModel { public: // Overridden from ui::ComboboxModel: size_t GetItemCount() const override { return 10; } std::u16string GetItemAt(size_t index) const override { return u"Item " + base::NumberToString16(index); } }; // A View that can act as a pane. class PaneView : public View, public FocusTraversable { public: PaneView() = default; // If this method is called, this view will use GetPaneFocusTraversable to // have this provided FocusSearch used instead of the default one, allowing // you to trap focus within the pane. void EnablePaneFocus(FocusSearch* focus_search) { focus_search_ = focus_search; } // Overridden from View: FocusTraversable* GetPaneFocusTraversable() override { if (focus_search_) return this; else return nullptr; } // Overridden from FocusTraversable: views::FocusSearch* GetFocusSearch() override { return focus_search_; } FocusTraversable* GetFocusTraversableParent() override { return nullptr; } View* GetFocusTraversableParentView() override { return nullptr; } private: raw_ptr<FocusSearch> focus_search_ = nullptr; }; // BorderView is a view containing a native window with its own view hierarchy. // It is interesting to test focus traversal from a view hierarchy to an inner // view hierarchy. class BorderView : public NativeViewHost { public: explicit BorderView(std::unique_ptr<View> child) : child_(std::move(child)) { DCHECK(child_); SetFocusBehavior(FocusBehavior::NEVER); } BorderView(const BorderView&) = delete; BorderView& operator=(const BorderView&) = delete; virtual internal::RootView* GetContentsRootView() { return static_cast<internal::RootView*>(widget_->GetRootView()); } FocusTraversable* GetFocusTraversable() override { return static_cast<internal::RootView*>(widget_->GetRootView()); } void ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) override { NativeViewHost::ViewHierarchyChanged(details); if (details.child == this && details.is_add) { if (!widget_) { auto widget = std::make_unique<Widget>(); widget_ = widget.get(); Widget::InitParams params(Widget::InitParams::TYPE_CONTROL); params.parent = details.parent->GetWidget()->GetNativeView(); widget_->Init(std::move(params)); widget.release(); // Widget now owned by widget hierarchy. widget_->SetFocusTraversableParentView(this); widget_->SetContentsView(std::move(child_)); } // We have been added to a view hierarchy, attach the native view. Attach(widget_->GetNativeView()); // Also update the FocusTraversable parent so the focus traversal works. static_cast<internal::RootView*>(widget_->GetRootView()) ->SetFocusTraversableParent(GetWidget()->GetFocusTraversable()); } } private: std::unique_ptr<View> child_; raw_ptr<Widget> widget_ = nullptr; }; } // namespace class FocusTraversalTest : public FocusManagerTest { public: FocusTraversalTest(const FocusTraversalTest&) = delete; FocusTraversalTest& operator=(const FocusTraversalTest&) = delete; ~FocusTraversalTest() override; void InitContentView() override; protected: FocusTraversalTest(); View* FindViewByID(int id) { View* view = GetContentsView()->GetViewByID(id); if (view) return view; if (style_tab_) view = style_tab_->GetSelectedTabContentView()->GetViewByID(id); if (view) return view; view = search_border_view_->GetContentsRootView()->GetViewByID(id); if (view) return view; return nullptr; } // Helper function to advance focus multiple times in a loop. |traversal_ids| // is an array of view ids of length |N|. |reverse| denotes the direction in // which focus should be advanced. template <size_t N> void AdvanceEntireFocusLoop(const int (&traversal_ids)[N], bool reverse) { for (size_t i = 0; i < 3; ++i) { for (size_t j = 0; j < N; j++) { SCOPED_TRACE(testing::Message() << "reverse:" << reverse << " i:" << i << " j:" << j); GetFocusManager()->AdvanceFocus(reverse); View* focused_view = GetFocusManager()->GetFocusedView(); EXPECT_NE(nullptr, focused_view); if (focused_view) EXPECT_EQ(traversal_ids[reverse ? N - j - 1 : j], focused_view->GetID()); } } } // Helper function that will recursively reverse the focus order of all the // children of the provided |parent|. void ReverseChildrenFocusOrder(View* parent) { ReverseChildrenFocusOrderImpl(parent); } raw_ptr<TabbedPane> style_tab_ = nullptr; raw_ptr<BorderView> search_border_view_ = nullptr; DummyComboboxModel combobox_model_; raw_ptr<PaneView> left_container_; raw_ptr<PaneView> right_container_; private: // Implementation of `ReverseChildrenFocusOrder`. |seen_views| should not be // passed directly - it will be initialized when called and is used to make // sure there is no cycle while traversing the children views. void ReverseChildrenFocusOrderImpl(View* parent, base::flat_set<View*> seen_views = {}) { std::vector<View*> children_views = parent->children(); if (children_views.empty()) return; View* first_child = children_views[0]; std::vector<View*> children_in_focus_order; // Set each child to be before the first child in the focus list. Do this // in reverse so that the last child is the first focusable view. for (int i = children_views.size() - 1; i >= 0; i--) { views::View* child = children_views[i]; EXPECT_FALSE(seen_views.contains(child)); seen_views.insert(child); children_in_focus_order.push_back(child); if (child != first_child) child->InsertBeforeInFocusList(first_child); ReverseChildrenFocusOrderImpl(child, seen_views); } EXPECT_EQ(parent->GetChildrenFocusList(), children_in_focus_order); } }; FocusTraversalTest::FocusTraversalTest() = default; FocusTraversalTest::~FocusTraversalTest() = default; void FocusTraversalTest::InitContentView() { // Create a complicated view hierarchy with lots of control types for // use by all of the focus traversal tests. // // Class name, ID, and asterisk next to focusable views: // // View // Checkbox * TOP_CHECKBOX_ID // PaneView LEFT_CONTAINER_ID // Label APPLE_LABEL_ID // Textfield * APPLE_TEXTFIELD_ID // Label ORANGE_LABEL_ID // Textfield * ORANGE_TEXTFIELD_ID // Label BANANA_LABEL_ID // Textfield * BANANA_TEXTFIELD_ID // Label KIWI_LABEL_ID // Textfield * KIWI_TEXTFIELD_ID // NativeButton * FRUIT_BUTTON_ID // Checkbox * FRUIT_CHECKBOX_ID // Combobox * COMBOBOX_ID // PaneView RIGHT_CONTAINER_ID // RadioButton * ASPARAGUS_BUTTON_ID // RadioButton * BROCCOLI_BUTTON_ID // RadioButton * CAULIFLOWER_BUTTON_ID // View INNER_CONTAINER_ID // ScrollView SCROLL_VIEW_ID // View // Link * ROSETTA_LINK_ID // Link * STUPEUR_ET_TREMBLEMENT_LINK_ID // Link * DINER_GAME_LINK_ID // Link * RIDICULE_LINK_ID // Link * CLOSET_LINK_ID // Link * VISITING_LINK_ID // Link * AMELIE_LINK_ID // Link * JOYEUX_NOEL_LINK_ID // Link * CAMPING_LINK_ID // Link * BRICE_DE_NICE_LINK_ID // Link * TAXI_LINK_ID // Link * ASTERIX_LINK_ID // NativeButton * OK_BUTTON_ID // NativeButton * CANCEL_BUTTON_ID // NativeButton * HELP_BUTTON_ID // TabbedPane * STYLE_CONTAINER_ID // TabStrip // Tab ("Style") // Tab ("Other") // View // View // Checkbox * BOLD_CHECKBOX_ID // Checkbox * ITALIC_CHECKBOX_ID // Checkbox * UNDERLINED_CHECKBOX_ID // Link * STYLE_HELP_LINK_ID // Textfield * STYLE_TEXT_EDIT_ID // View // BorderView SEARCH_CONTAINER_ID // View // Textfield * SEARCH_TEXTFIELD_ID // NativeButton * SEARCH_BUTTON_ID // Link * HELP_LINK_ID // View * THUMBNAIL_CONTAINER_ID // NativeButton * THUMBNAIL_STAR_ID // NativeButton * THUMBNAIL_SUPER_STAR_ID GetContentsView()->SetBackground(CreateSolidBackground(SK_ColorWHITE)); auto cb = std::make_unique<Checkbox>(u"This is a checkbox"); auto* cb_ptr = GetContentsView()->AddChildView(std::move(cb)); // In this fast paced world, who really has time for non hard-coded layout? cb_ptr->SetBounds(10, 10, 200, 20); cb_ptr->SetID(TOP_CHECKBOX_ID); auto container = std::make_unique<PaneView>(); container->SetBorder(CreateSolidBorder(1, SK_ColorBLACK)); container->SetBackground(CreateSolidBackground(SkColorSetRGB(240, 240, 240))); container->SetID(LEFT_CONTAINER_ID); left_container_ = GetContentsView()->AddChildView(std::move(container)); left_container_->SetBounds(10, 35, 250, 200); int label_x = 5; int label_width = 50; int label_height = 15; int text_field_width = 150; int y = 10; int gap_between_labels = 10; auto label = std::make_unique<Label>(u"Apple:"); label->SetID(APPLE_LABEL_ID); auto* label_ptr = left_container_->AddChildView(std::move(label)); label_ptr->SetBounds(label_x, y, label_width, label_height); auto text_field = std::make_unique<Textfield>(); text_field->SetID(APPLE_TEXTFIELD_ID); auto* text_field_ptr = left_container_->AddChildView(std::move(text_field)); text_field_ptr->SetBounds(label_x + label_width + 5, y, text_field_width, label_height); y += label_height + gap_between_labels; label = std::make_unique<Label>(u"Orange:"); label->SetID(ORANGE_LABEL_ID); label_ptr = left_container_->AddChildView(std::move(label)); label_ptr->SetBounds(label_x, y, label_width, label_height); text_field = std::make_unique<Textfield>(); text_field->SetID(ORANGE_TEXTFIELD_ID); text_field_ptr = left_container_->AddChildView(std::move(text_field)); text_field_ptr->SetBounds(label_x + label_width + 5, y, text_field_width, label_height); y += label_height + gap_between_labels; label = std::make_unique<Label>(u"Banana:"); label->SetID(BANANA_LABEL_ID); label_ptr = left_container_->AddChildView(std::move(label)); label_ptr->SetBounds(label_x, y, label_width, label_height); text_field = std::make_unique<Textfield>(); text_field->SetID(BANANA_TEXTFIELD_ID); text_field_ptr = left_container_->AddChildView(std::move(text_field)); text_field_ptr->SetBounds(label_x + label_width + 5, y, text_field_width, label_height); y += label_height + gap_between_labels; label = std::make_unique<Label>(u"Kiwi:"); label->SetID(KIWI_LABEL_ID); label_ptr = left_container_->AddChildView(std::move(label)); label_ptr->SetBounds(label_x, y, label_width, label_height); text_field = std::make_unique<Textfield>(); text_field->SetID(KIWI_TEXTFIELD_ID); text_field_ptr = left_container_->AddChildView(std::move(text_field)); text_field_ptr->SetBounds(label_x + label_width + 5, y, text_field_width, label_height); y += label_height + gap_between_labels; auto button = std::make_unique<MdTextButton>(Button::PressedCallback(), u"Click me"); button->SetBounds(label_x, y + 10, 80, 30); button->SetID(FRUIT_BUTTON_ID); left_container_->AddChildView(std::move(button)); y += 40; cb = std::make_unique<Checkbox>(u"This is another check box"); cb->SetBounds(label_x + label_width + 5, y, 180, 20); cb->SetID(FRUIT_CHECKBOX_ID); left_container_->AddChildView(std::move(cb)); y += 20; auto combobox = std::make_unique<Combobox>(&combobox_model_); combobox->SetBounds(label_x + label_width + 5, y, 150, 30); combobox->SetID(COMBOBOX_ID); left_container_->AddChildView(std::move(combobox)); container = std::make_unique<PaneView>(); container->SetBorder(CreateSolidBorder(1, SK_ColorBLACK)); container->SetBackground(CreateSolidBackground(SkColorSetRGB(240, 240, 240))); container->SetID(RIGHT_CONTAINER_ID); right_container_ = GetContentsView()->AddChildView(std::move(container)); right_container_->SetBounds(270, 35, 300, 200); y = 10; int radio_button_height = 18; int gap_between_radio_buttons = 10; auto radio_button = std::make_unique<RadioButton>(u"Asparagus", 1); radio_button->SetID(ASPARAGUS_BUTTON_ID); auto* radio_button_ptr = right_container_->AddChildView(std::move(radio_button)); radio_button_ptr->SetBounds(5, y, 70, radio_button_height); radio_button_ptr->SetGroup(1); y += radio_button_height + gap_between_radio_buttons; radio_button = std::make_unique<RadioButton>(u"Broccoli", 1); radio_button->SetID(BROCCOLI_BUTTON_ID); radio_button_ptr = right_container_->AddChildView(std::move(radio_button)); radio_button_ptr->SetBounds(5, y, 70, radio_button_height); radio_button_ptr->SetGroup(1); RadioButton* radio_button_to_check = radio_button_ptr; y += radio_button_height + gap_between_radio_buttons; radio_button = std::make_unique<RadioButton>(u"Cauliflower", 1); radio_button->SetID(CAULIFLOWER_BUTTON_ID); radio_button_ptr = right_container_->AddChildView(std::move(radio_button)); radio_button_ptr->SetBounds(5, y, 70, radio_button_height); radio_button_ptr->SetGroup(1); y += radio_button_height + gap_between_radio_buttons; auto inner_container = std::make_unique<View>(); inner_container->SetBorder(CreateSolidBorder(1, SK_ColorBLACK)); inner_container->SetBackground( CreateSolidBackground(SkColorSetRGB(230, 230, 230))); inner_container->SetID(INNER_CONTAINER_ID); auto* inner_container_ptr = right_container_->AddChildView(std::move(inner_container)); inner_container_ptr->SetBounds(100, 10, 150, 180); auto scroll_view = std::make_unique<ScrollView>(); scroll_view->SetID(SCROLL_VIEW_ID); auto* scroll_view_ptr = inner_container_ptr->AddChildView(std::move(scroll_view)); scroll_view_ptr->SetBounds(1, 1, 148, 178); auto scroll_content = std::make_unique<View>(); scroll_content->SetBounds(0, 0, 200, 200); scroll_content->SetBackground( CreateSolidBackground(SkColorSetRGB(200, 200, 200))); auto* scroll_content_ptr = scroll_view_ptr->SetContents(std::move(scroll_content)); static const char* const kTitles[] = { "Rosetta", "Stupeur et tremblement", "The diner game", "Ridicule", "Le placard", "Les Visiteurs", "Amelie", "Joyeux Noel", "Camping", "Brice de Nice", "Taxi", "Asterix"}; static const int kIDs[] = {ROSETTA_LINK_ID, STUPEUR_ET_TREMBLEMENT_LINK_ID, DINER_GAME_LINK_ID, RIDICULE_LINK_ID, CLOSET_LINK_ID, VISITING_LINK_ID, AMELIE_LINK_ID, JOYEUX_NOEL_LINK_ID, CAMPING_LINK_ID, BRICE_DE_NICE_LINK_ID, TAXI_LINK_ID, ASTERIX_LINK_ID}; DCHECK(std::size(kTitles) == std::size(kIDs)); y = 5; for (size_t i = 0; i < std::size(kTitles); ++i) { auto link = std::make_unique<Link>(ASCIIToUTF16(kTitles[i])); link->SetHorizontalAlignment(gfx::ALIGN_LEFT); link->SetID(kIDs[i]); auto* link_ptr = scroll_content_ptr->AddChildView(std::move(link)); link_ptr->SetBounds(5, y, 300, 15); y += 15; } y = 250; int width = 60; button = std::make_unique<MdTextButton>(Button::PressedCallback(), u"OK"); button->SetID(OK_BUTTON_ID); button->SetIsDefault(true); button->SetBounds(150, y, width, 30); GetContentsView()->AddChildView(std::move(button)); button = std::make_unique<MdTextButton>(Button::PressedCallback(), u"Cancel"); button->SetID(CANCEL_BUTTON_ID); button->SetBounds(220, y, width, 30); GetContentsView()->AddChildView(std::move(button)); button = std::make_unique<MdTextButton>(Button::PressedCallback(), u"Help"); button->SetID(HELP_BUTTON_ID); button->SetBounds(290, y, width, 30); GetContentsView()->AddChildView(std::move(button)); y += 40; // Left bottom box with style checkboxes. auto tabbed_pane_contents = std::make_unique<View>(); tabbed_pane_contents->SetBackground(CreateSolidBackground(SK_ColorWHITE)); cb = std::make_unique<Checkbox>(u"Bold"); cb_ptr = tabbed_pane_contents->AddChildView(std::move(cb)); cb_ptr->SetBounds(10, 10, 50, 20); cb_ptr->SetID(BOLD_CHECKBOX_ID); cb = std::make_unique<Checkbox>(u"Italic"); cb_ptr = tabbed_pane_contents->AddChildView(std::move(cb)); cb_ptr->SetBounds(70, 10, 50, 20); cb_ptr->SetID(ITALIC_CHECKBOX_ID); cb = std::make_unique<Checkbox>(u"Underlined"); cb_ptr = tabbed_pane_contents->AddChildView(std::move(cb)); cb_ptr->SetBounds(130, 10, 70, 20); cb_ptr->SetID(UNDERLINED_CHECKBOX_ID); auto link = std::make_unique<Link>(u"Help"); auto* link_ptr = tabbed_pane_contents->AddChildView(std::move(link)); link_ptr->SetBounds(10, 35, 70, 10); link_ptr->SetID(STYLE_HELP_LINK_ID); text_field = std::make_unique<Textfield>(); text_field_ptr = tabbed_pane_contents->AddChildView(std::move(text_field)); text_field_ptr->SetBounds(10, 50, 100, 20); text_field_ptr->SetID(STYLE_TEXT_EDIT_ID); auto style_tab = std::make_unique<TabbedPane>(); style_tab_ = GetContentsView()->AddChildView(std::move(style_tab)); style_tab_->SetBounds(10, y, 210, 100); style_tab_->AddTab(u"Style", std::move(tabbed_pane_contents)); style_tab_->GetSelectedTab()->SetID(STYLE_CONTAINER_ID); style_tab_->AddTab(u"Other", std::make_unique<View>()); // Right bottom box with search. auto border_contents = std::make_unique<View>(); border_contents->SetBackground(CreateSolidBackground(SK_ColorWHITE)); text_field = std::make_unique<Textfield>(); text_field_ptr = border_contents->AddChildView(std::move(text_field)); text_field_ptr->SetBounds(10, 10, 100, 20); text_field_ptr->SetID(SEARCH_TEXTFIELD_ID); button = std::make_unique<MdTextButton>(Button::PressedCallback(), u"Search"); button->SetBounds(112, 5, 60, 30); button->SetID(SEARCH_BUTTON_ID); border_contents->AddChildView(std::move(button)); link = std::make_unique<Link>(u"Help"); link->SetHorizontalAlignment(gfx::ALIGN_LEFT); link->SetID(HELP_LINK_ID); link_ptr = border_contents->AddChildView(std::move(link)); link_ptr->SetBounds(175, 10, 30, 20); auto search_border_view = std::make_unique<BorderView>(std::move(border_contents)); search_border_view->SetID(SEARCH_CONTAINER_ID); search_border_view_ = GetContentsView()->AddChildView(std::move(search_border_view)); search_border_view_->SetBounds(300, y, 240, 50); y += 60; auto view_contents = std::make_unique<View>(); view_contents->SetFocusBehavior(View::FocusBehavior::ALWAYS); view_contents->SetBackground(CreateSolidBackground(SK_ColorBLUE)); view_contents->SetID(THUMBNAIL_CONTAINER_ID); button = std::make_unique<MdTextButton>(Button::PressedCallback(), u"Star"); button->SetBounds(5, 5, 50, 30); button->SetID(THUMBNAIL_STAR_ID); view_contents->AddChildView(std::move(button)); button = std::make_unique<MdTextButton>(Button::PressedCallback(), u"SuperStar"); button->SetBounds(60, 5, 100, 30); button->SetID(THUMBNAIL_SUPER_STAR_ID); view_contents->AddChildView(std::move(button)); auto* contents_ptr = GetContentsView()->AddChildView(std::move(view_contents)); contents_ptr->SetBounds(250, y, 200, 50); // We can only call RadioButton::SetChecked() on the radio-button is part of // the view hierarchy. radio_button_to_check->SetChecked(true); // Perform any pending layouts. GetWidget()->LayoutRootViewIfNecessary(); } TEST_F(FocusTraversalTest, NormalTraversal) { const int kTraversalIDs[] = {TOP_CHECKBOX_ID, APPLE_TEXTFIELD_ID, ORANGE_TEXTFIELD_ID, BANANA_TEXTFIELD_ID, KIWI_TEXTFIELD_ID, FRUIT_BUTTON_ID, FRUIT_CHECKBOX_ID, COMBOBOX_ID, BROCCOLI_BUTTON_ID, ROSETTA_LINK_ID, STUPEUR_ET_TREMBLEMENT_LINK_ID, DINER_GAME_LINK_ID, RIDICULE_LINK_ID, CLOSET_LINK_ID, VISITING_LINK_ID, AMELIE_LINK_ID, JOYEUX_NOEL_LINK_ID, CAMPING_LINK_ID, BRICE_DE_NICE_LINK_ID, TAXI_LINK_ID, ASTERIX_LINK_ID, OK_BUTTON_ID, CANCEL_BUTTON_ID, HELP_BUTTON_ID, STYLE_CONTAINER_ID, BOLD_CHECKBOX_ID, ITALIC_CHECKBOX_ID, UNDERLINED_CHECKBOX_ID, STYLE_HELP_LINK_ID, STYLE_TEXT_EDIT_ID, SEARCH_TEXTFIELD_ID, SEARCH_BUTTON_ID, HELP_LINK_ID, THUMBNAIL_CONTAINER_ID, THUMBNAIL_STAR_ID, THUMBNAIL_SUPER_STAR_ID}; SCOPED_TRACE("NormalTraversal"); // Let's traverse the whole focus hierarchy (several times, to make sure it // loops OK). GetFocusManager()->ClearFocus(); AdvanceEntireFocusLoop(kTraversalIDs, false); // Let's traverse in reverse order. GetFocusManager()->ClearFocus(); AdvanceEntireFocusLoop(kTraversalIDs, true); } #if BUILDFLAG(IS_MAC) // Test focus traversal with full keyboard access off on Mac. TEST_F(FocusTraversalTest, NormalTraversalMac) { GetFocusManager()->SetKeyboardAccessible(false); // Now only views with FocusBehavior of ALWAYS will be focusable. const int kTraversalIDs[] = {APPLE_TEXTFIELD_ID, ORANGE_TEXTFIELD_ID, BANANA_TEXTFIELD_ID, KIWI_TEXTFIELD_ID, STYLE_TEXT_EDIT_ID, SEARCH_TEXTFIELD_ID, THUMBNAIL_CONTAINER_ID}; SCOPED_TRACE("NormalTraversalMac"); // Let's traverse the whole focus hierarchy (several times, to make sure it // loops OK). GetFocusManager()->ClearFocus(); AdvanceEntireFocusLoop(kTraversalIDs, false); // Let's traverse in reverse order. GetFocusManager()->ClearFocus(); AdvanceEntireFocusLoop(kTraversalIDs, true); } // Test toggling full keyboard access correctly changes the focused view on Mac. TEST_F(FocusTraversalTest, FullKeyboardToggle) { // Give focus to TOP_CHECKBOX_ID . FindViewByID(TOP_CHECKBOX_ID)->RequestFocus(); EXPECT_EQ(TOP_CHECKBOX_ID, GetFocusManager()->GetFocusedView()->GetID()); // Turn off full keyboard access. Focus should move to next view with ALWAYS // focus behavior. GetFocusManager()->SetKeyboardAccessible(false); EXPECT_EQ(APPLE_TEXTFIELD_ID, GetFocusManager()->GetFocusedView()->GetID()); // Turning on full keyboard access should not change the focused view. GetFocusManager()->SetKeyboardAccessible(true); EXPECT_EQ(APPLE_TEXTFIELD_ID, GetFocusManager()->GetFocusedView()->GetID()); // Give focus to SEARCH_BUTTON_ID. FindViewByID(SEARCH_BUTTON_ID)->RequestFocus(); EXPECT_EQ(SEARCH_BUTTON_ID, GetFocusManager()->GetFocusedView()->GetID()); // Turn off full keyboard access. Focus should move to next view with ALWAYS // focus behavior. GetFocusManager()->SetKeyboardAccessible(false); EXPECT_EQ(THUMBNAIL_CONTAINER_ID, GetFocusManager()->GetFocusedView()->GetID()); // See focus advances correctly in both directions. GetFocusManager()->AdvanceFocus(false); EXPECT_EQ(APPLE_TEXTFIELD_ID, GetFocusManager()->GetFocusedView()->GetID()); GetFocusManager()->AdvanceFocus(true); EXPECT_EQ(THUMBNAIL_CONTAINER_ID, GetFocusManager()->GetFocusedView()->GetID()); } #endif // BUILDFLAG(IS_MAC) TEST_F(FocusTraversalTest, TraversalWithNonEnabledViews) { const int kDisabledIDs[] = { BANANA_TEXTFIELD_ID, FRUIT_CHECKBOX_ID, COMBOBOX_ID, ASPARAGUS_BUTTON_ID, CAULIFLOWER_BUTTON_ID, CLOSET_LINK_ID, VISITING_LINK_ID, BRICE_DE_NICE_LINK_ID, TAXI_LINK_ID, ASTERIX_LINK_ID, HELP_BUTTON_ID, BOLD_CHECKBOX_ID, SEARCH_TEXTFIELD_ID, HELP_LINK_ID}; const int kTraversalIDs[] = { TOP_CHECKBOX_ID, APPLE_TEXTFIELD_ID, ORANGE_TEXTFIELD_ID, KIWI_TEXTFIELD_ID, FRUIT_BUTTON_ID, BROCCOLI_BUTTON_ID, ROSETTA_LINK_ID, STUPEUR_ET_TREMBLEMENT_LINK_ID, DINER_GAME_LINK_ID, RIDICULE_LINK_ID, AMELIE_LINK_ID, JOYEUX_NOEL_LINK_ID, CAMPING_LINK_ID, OK_BUTTON_ID, CANCEL_BUTTON_ID, STYLE_CONTAINER_ID, ITALIC_CHECKBOX_ID, UNDERLINED_CHECKBOX_ID, STYLE_HELP_LINK_ID, STYLE_TEXT_EDIT_ID, SEARCH_BUTTON_ID, THUMBNAIL_CONTAINER_ID, THUMBNAIL_STAR_ID, THUMBNAIL_SUPER_STAR_ID}; SCOPED_TRACE("TraversalWithNonEnabledViews"); // Let's disable some views. for (int kDisabledID : kDisabledIDs) { View* v = FindViewByID(kDisabledID); ASSERT_TRUE(v != nullptr); v->SetEnabled(false); } // Let's do one traversal (several times, to make sure it loops ok). GetFocusManager()->ClearFocus(); AdvanceEntireFocusLoop(kTraversalIDs, false); // Same thing in reverse. GetFocusManager()->ClearFocus(); AdvanceEntireFocusLoop(kTraversalIDs, true); } TEST_F(FocusTraversalTest, TraversalWithInvisibleViews) { const int kInvisibleIDs[] = {TOP_CHECKBOX_ID, OK_BUTTON_ID, THUMBNAIL_CONTAINER_ID}; const int kTraversalIDs[] = { APPLE_TEXTFIELD_ID, ORANGE_TEXTFIELD_ID, BANANA_TEXTFIELD_ID, KIWI_TEXTFIELD_ID, FRUIT_BUTTON_ID, FRUIT_CHECKBOX_ID, COMBOBOX_ID, BROCCOLI_BUTTON_ID, ROSETTA_LINK_ID, STUPEUR_ET_TREMBLEMENT_LINK_ID, DINER_GAME_LINK_ID, RIDICULE_LINK_ID, CLOSET_LINK_ID, VISITING_LINK_ID, AMELIE_LINK_ID, JOYEUX_NOEL_LINK_ID, CAMPING_LINK_ID, BRICE_DE_NICE_LINK_ID, TAXI_LINK_ID, ASTERIX_LINK_ID, CANCEL_BUTTON_ID, HELP_BUTTON_ID, STYLE_CONTAINER_ID, BOLD_CHECKBOX_ID, ITALIC_CHECKBOX_ID, UNDERLINED_CHECKBOX_ID, STYLE_HELP_LINK_ID, STYLE_TEXT_EDIT_ID, SEARCH_TEXTFIELD_ID, SEARCH_BUTTON_ID, HELP_LINK_ID}; SCOPED_TRACE("TraversalWithInvisibleViews"); // Let's make some views invisible. for (int kInvisibleID : kInvisibleIDs) { View* v = FindViewByID(kInvisibleID); ASSERT_TRUE(v != nullptr); v->SetVisible(false); } // Let's do one traversal (several times, to make sure it loops ok). GetFocusManager()->ClearFocus(); AdvanceEntireFocusLoop(kTraversalIDs, false); // Same thing in reverse. GetFocusManager()->ClearFocus(); AdvanceEntireFocusLoop(kTraversalIDs, true); } TEST_F(FocusTraversalTest, PaneTraversal) { // Tests trapping the traversal within a pane - useful for full // keyboard accessibility for toolbars. // First test the left container. const int kLeftTraversalIDs[] = {APPLE_TEXTFIELD_ID, ORANGE_TEXTFIELD_ID, BANANA_TEXTFIELD_ID, KIWI_TEXTFIELD_ID, FRUIT_BUTTON_ID, FRUIT_CHECKBOX_ID, COMBOBOX_ID}; SCOPED_TRACE("PaneTraversal"); FocusSearch focus_search_left(left_container_, true, false); left_container_->EnablePaneFocus(&focus_search_left); FindViewByID(COMBOBOX_ID)->RequestFocus(); // Traverse the focus hierarchy within the pane several times. AdvanceEntireFocusLoop(kLeftTraversalIDs, false); // Traverse in reverse order. FindViewByID(APPLE_TEXTFIELD_ID)->RequestFocus(); AdvanceEntireFocusLoop(kLeftTraversalIDs, true); // Now test the right container, but this time with accessibility mode. // Make some links not focusable, but mark one of them as // "accessibility focusable", so it should show up in the traversal. const int kRightTraversalIDs[] = { BROCCOLI_BUTTON_ID, DINER_GAME_LINK_ID, RIDICULE_LINK_ID, CLOSET_LINK_ID, VISITING_LINK_ID, AMELIE_LINK_ID, JOYEUX_NOEL_LINK_ID, CAMPING_LINK_ID, BRICE_DE_NICE_LINK_ID, TAXI_LINK_ID, ASTERIX_LINK_ID}; FocusSearch focus_search_right(right_container_, true, true); right_container_->EnablePaneFocus(&focus_search_right); FindViewByID(ROSETTA_LINK_ID)->SetFocusBehavior(View::FocusBehavior::NEVER); FindViewByID(STUPEUR_ET_TREMBLEMENT_LINK_ID) ->SetFocusBehavior(View::FocusBehavior::NEVER); FindViewByID(DINER_GAME_LINK_ID) ->SetFocusBehavior(View::FocusBehavior::ACCESSIBLE_ONLY); FindViewByID(ASTERIX_LINK_ID)->RequestFocus(); // Traverse the focus hierarchy within the pane several times. AdvanceEntireFocusLoop(kRightTraversalIDs, false); // Traverse in reverse order. FindViewByID(BROCCOLI_BUTTON_ID)->RequestFocus(); AdvanceEntireFocusLoop(kRightTraversalIDs, true); } TEST_F(FocusTraversalTest, TraversesFocusInFocusOrder) { View* parent = GetContentsView(); ReverseChildrenFocusOrder(parent); const int kTraversalIDs[] = { THUMBNAIL_CONTAINER_ID, THUMBNAIL_SUPER_STAR_ID, THUMBNAIL_STAR_ID, // All views under SEARCH_CONTAINER_ID (SEARCH_TEXTFIELD_ID, // SEARCH_BUTTON_ID, HELP_LINK_ID) will have their original order. This is // because SEARCH_CONTAINER_ID is a NativeView and // `ReverseChildrenFocusOrder` does not reverse the order of native // children. SEARCH_TEXTFIELD_ID, SEARCH_BUTTON_ID, HELP_LINK_ID, STYLE_TEXT_EDIT_ID, STYLE_HELP_LINK_ID, UNDERLINED_CHECKBOX_ID, ITALIC_CHECKBOX_ID, BOLD_CHECKBOX_ID, STYLE_CONTAINER_ID, HELP_BUTTON_ID, CANCEL_BUTTON_ID, OK_BUTTON_ID, ASTERIX_LINK_ID, TAXI_LINK_ID, BRICE_DE_NICE_LINK_ID, CAMPING_LINK_ID, JOYEUX_NOEL_LINK_ID, AMELIE_LINK_ID, VISITING_LINK_ID, CLOSET_LINK_ID, RIDICULE_LINK_ID, DINER_GAME_LINK_ID, STUPEUR_ET_TREMBLEMENT_LINK_ID, ROSETTA_LINK_ID, BROCCOLI_BUTTON_ID, COMBOBOX_ID, FRUIT_CHECKBOX_ID, FRUIT_BUTTON_ID, KIWI_TEXTFIELD_ID, BANANA_TEXTFIELD_ID, ORANGE_TEXTFIELD_ID, APPLE_TEXTFIELD_ID, TOP_CHECKBOX_ID}; AdvanceEntireFocusLoop(kTraversalIDs, false); GetFocusManager()->ClearFocus(); AdvanceEntireFocusLoop(kTraversalIDs, true); } class FocusTraversalNonFocusableTest : public FocusManagerTest { public: FocusTraversalNonFocusableTest(const FocusTraversalNonFocusableTest&) = delete; FocusTraversalNonFocusableTest& operator=( const FocusTraversalNonFocusableTest&) = delete; ~FocusTraversalNonFocusableTest() override = default; void InitContentView() override; protected: FocusTraversalNonFocusableTest() = default; }; void FocusTraversalNonFocusableTest::InitContentView() { // Create a complex nested view hierarchy with no focusable views. This is a // regression test for http://crbug.com/453699. There was previously a bug // where advancing focus backwards through this tree resulted in an // exponential number of nodes being searched. (Each time it traverses one of // the x1-x3-x2 triangles, it will traverse the left sibling of x1, (x+1)0, // twice, which means it will visit O(2^n) nodes.) // // | 0 | // | / \ | // | / \ | // | 10 1 | // | / \ / \ | // | / \ / \ | // | 20 11 2 3 | // | / \ / \ | // | / \ / \ | // | ... 21 12 13 | // | / \ | // | / \ | // | 22 23 | View* v = GetContentsView(); // Create 30 groups of 4 nodes. |v| is the top of each group. for (int i = 0; i < 300; i += 10) { // |v|'s left child is the top of the next group. If |v| is 20, this is 30. View* v10 = new View; v10->SetID(i + 10); v->AddChildView(v10); // |v|'s right child. If |v| is 20, this is 21. View* v1 = new View; v1->SetID(i + 1); v->AddChildView(v1); // |v|'s right child has two children. If |v| is 20, these are 22 and 23. View* v2 = new View; v2->SetID(i + 2); View* v3 = new View; v3->SetID(i + 3); v1->AddChildView(v2); v1->AddChildView(v3); v = v10; } } // See explanation in InitContentView. // NOTE: The failure mode of this test (if http://crbug.com/453699 were to // regress) is a timeout, due to exponential run time. TEST_F(FocusTraversalNonFocusableTest, PathologicalSiblingTraversal) { // Advance forwards from the root node. GetFocusManager()->ClearFocus(); GetFocusManager()->AdvanceFocus(false); EXPECT_FALSE(GetFocusManager()->GetFocusedView()); // Advance backwards from the root node. GetFocusManager()->ClearFocus(); GetFocusManager()->AdvanceFocus(true); EXPECT_FALSE(GetFocusManager()->GetFocusedView()); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/focus/focus_traversal_unittest.cc
C++
unknown
36,078
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/focus/widget_focus_manager.h" #include "base/no_destructor.h" #include "base/observer_list.h" namespace views { // WidgetFocusManager ---------------------------------------------------------- // static WidgetFocusManager* WidgetFocusManager::GetInstance() { static base::NoDestructor<WidgetFocusManager> instance; return instance.get(); } WidgetFocusManager::~WidgetFocusManager() = default; void WidgetFocusManager::AddFocusChangeListener( WidgetFocusChangeListener* listener) { focus_change_listeners_.AddObserver(listener); } void WidgetFocusManager::RemoveFocusChangeListener( WidgetFocusChangeListener* listener) { focus_change_listeners_.RemoveObserver(listener); } void WidgetFocusManager::OnNativeFocusChanged(gfx::NativeView focused_now) { if (enabled_) { for (WidgetFocusChangeListener& observer : focus_change_listeners_) observer.OnNativeFocusChanged(focused_now); } } WidgetFocusManager::WidgetFocusManager() = default; // AutoNativeNotificationDisabler ---------------------------------------------- AutoNativeNotificationDisabler::AutoNativeNotificationDisabler() { WidgetFocusManager::GetInstance()->DisableNotifications(); } AutoNativeNotificationDisabler::~AutoNativeNotificationDisabler() { WidgetFocusManager::GetInstance()->EnableNotifications(); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/focus/widget_focus_manager.cc
C++
unknown
1,503
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_FOCUS_WIDGET_FOCUS_MANAGER_H_ #define UI_VIEWS_FOCUS_WIDGET_FOCUS_MANAGER_H_ #include "base/no_destructor.h" #include "base/observer_list.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/views_export.h" namespace views { // This interface should be implemented by classes that want to be notified when // the native focus is about to change. Listeners implementing this interface // will be invoked for all native focus changes across the entire Chrome // application. FocusChangeListeners are only called for changes within the // children of a single top-level native-view. class WidgetFocusChangeListener { public: virtual void OnNativeFocusChanged(gfx::NativeView focused_now) = 0; protected: virtual ~WidgetFocusChangeListener() = default; }; class VIEWS_EXPORT WidgetFocusManager { public: // Returns the singleton instance. static WidgetFocusManager* GetInstance(); WidgetFocusManager(const WidgetFocusManager&) = delete; WidgetFocusManager& operator=(const WidgetFocusManager&) = delete; ~WidgetFocusManager(); // Adds/removes a WidgetFocusChangeListener |listener| to the set of // active listeners. void AddFocusChangeListener(WidgetFocusChangeListener* listener); void RemoveFocusChangeListener(WidgetFocusChangeListener* listener); // Called when native-focus shifts within, or off, a widget. |focused_now| is // null when focus is lost. void OnNativeFocusChanged(gfx::NativeView focused_now); // Enable/Disable notification of registered listeners during calls // to OnNativeFocusChanged. Used to prevent unwanted focus changes from // propagating notifications. void EnableNotifications() { enabled_ = true; } void DisableNotifications() { enabled_ = false; } private: class Owner; friend class base::NoDestructor<WidgetFocusManager>; WidgetFocusManager(); base::ObserverList<WidgetFocusChangeListener>::Unchecked focus_change_listeners_; bool enabled_ = true; }; // A basic helper class that is used to disable native focus change // notifications within a scope. class VIEWS_EXPORT AutoNativeNotificationDisabler { public: AutoNativeNotificationDisabler(); AutoNativeNotificationDisabler(const AutoNativeNotificationDisabler&) = delete; AutoNativeNotificationDisabler& operator=( const AutoNativeNotificationDisabler&) = delete; ~AutoNativeNotificationDisabler(); }; } // namespace views #endif // UI_VIEWS_FOCUS_WIDGET_FOCUS_MANAGER_H_
Zhao-PengFei35/chromium_src_4
ui/views/focus/widget_focus_manager.h
C++
unknown
2,628
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/highlight_border.h" #include "ui/chromeos/styles/cros_tokens_color_mappings.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/dip_util.h" #include "ui/gfx/geometry/rounded_corners_f.h" #include "ui/gfx/geometry/skia_conversions.h" #include "ui/gfx/scoped_canvas.h" #include "ui/views/view.h" namespace views { // static void HighlightBorder::PaintBorderToCanvas( gfx::Canvas* canvas, SkColor highlight_color, SkColor border_color, const gfx::Rect& bounds, const gfx::RoundedCornersF& corner_radii, Type type) { cc::PaintFlags flags; flags.setStrokeWidth(kHighlightBorderThickness); flags.setColor(border_color); flags.setStyle(cc::PaintFlags::kStroke_Style); flags.setAntiAlias(true); const float half_thickness = kHighlightBorderThickness / 2.0f; // Scale bounds and corner radius with device scale factor to make sure // border bounds match content bounds but keep border stroke width the same. gfx::ScopedCanvas scoped_canvas(canvas); const float dsf = canvas->UndoDeviceScaleFactor(); const gfx::RectF pixel_bounds = gfx::ConvertRectToPixels(bounds, dsf); const SkScalar radii[8] = { corner_radii.upper_left() * dsf, corner_radii.upper_left() * dsf, corner_radii.upper_right() * dsf, corner_radii.upper_right() * dsf, corner_radii.lower_right() * dsf, corner_radii.lower_right() * dsf, corner_radii.lower_left() * dsf, corner_radii.lower_left() * dsf}; gfx::RectF outer_border_bounds(pixel_bounds); outer_border_bounds.Inset(half_thickness); SkPath outer_path; outer_path.addRoundRect(gfx::RectFToSkRect(outer_border_bounds), radii); canvas->DrawPath(outer_path, flags); gfx::RectF inner_border_bounds(pixel_bounds); inner_border_bounds.Inset(kHighlightBorderThickness); inner_border_bounds.Inset(half_thickness); flags.setColor(highlight_color); SkPath inner_path; inner_path.addRoundRect(gfx::RectFToSkRect(inner_border_bounds), radii); canvas->DrawPath(inner_path, flags); } // static void HighlightBorder::PaintBorderToCanvas( gfx::Canvas* canvas, const views::View& view, const gfx::Rect& bounds, const gfx::RoundedCornersF& corner_radii, Type type) { PaintBorderToCanvas(canvas, GetHighlightColor(view, type), GetBorderColor(view, type), bounds, corner_radii, type); } // static SkColor HighlightBorder::GetHighlightColor(const views::View& view, HighlightBorder::Type type) { ui::ColorId highlight_color_id; switch (type) { case HighlightBorder::Type::kHighlightBorderNoShadow: highlight_color_id = cros_tokens::kCrosSysSystemHighlight; break; case HighlightBorder::Type::kHighlightBorderOnShadow: highlight_color_id = cros_tokens::kCrosSysSystemHighlight1; break; case HighlightBorder::Type::kHighlightBorder1: highlight_color_id = ui::kColorHighlightBorderHighlight1; break; case HighlightBorder::Type::kHighlightBorder2: highlight_color_id = ui::kColorHighlightBorderHighlight2; break; case HighlightBorder::Type::kHighlightBorder3: highlight_color_id = ui::kColorHighlightBorderHighlight3; break; } // `view` should be embedded in a Widget to use color provider. DCHECK(view.GetWidget()); return view.GetColorProvider()->GetColor(highlight_color_id); } // static SkColor HighlightBorder::GetBorderColor(const views::View& view, HighlightBorder::Type type) { ui::ColorId border_color_id; switch (type) { case HighlightBorder::Type::kHighlightBorderNoShadow: border_color_id = cros_tokens::kCrosSysSystemBorder; break; case HighlightBorder::Type::kHighlightBorderOnShadow: border_color_id = cros_tokens::kCrosSysSystemBorder1; break; case HighlightBorder::Type::kHighlightBorder1: border_color_id = ui::kColorHighlightBorderBorder1; break; case HighlightBorder::Type::kHighlightBorder2: border_color_id = ui::kColorHighlightBorderBorder2; break; case HighlightBorder::Type::kHighlightBorder3: border_color_id = ui::kColorHighlightBorderBorder3; break; } // `view` should be embedded in a Widget to use color provider. DCHECK(view.GetWidget()); return view.GetColorProvider()->GetColor(border_color_id); } HighlightBorder::HighlightBorder(int corner_radius, Type type, InsetsType insets_type) : HighlightBorder(gfx::RoundedCornersF(corner_radius), type, insets_type) {} HighlightBorder::HighlightBorder(const gfx::RoundedCornersF& rounded_corners, Type type, InsetsType insets_type) : rounded_corners_(rounded_corners), type_(type), insets_type_(insets_type) {} void HighlightBorder::Paint(const views::View& view, gfx::Canvas* canvas) { PaintBorderToCanvas(canvas, view, view.GetLocalBounds(), rounded_corners_, type_); } void HighlightBorder::OnViewThemeChanged(views::View* view) { view->SchedulePaint(); } gfx::Insets HighlightBorder::GetInsets() const { switch (insets_type_) { case InsetsType::kNoInsets: return gfx::Insets(); case InsetsType::kHalfInsets: return gfx::Insets(kHighlightBorderThickness); case InsetsType::kFullInsets: return gfx::Insets(2 * kHighlightBorderThickness); } } gfx::Size HighlightBorder::GetMinimumSize() const { return gfx::Size(kHighlightBorderThickness * 4, kHighlightBorderThickness * 4); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/highlight_border.cc
C++
unknown
5,862
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_HIGHLIGHT_BORDER_H_ #define UI_VIEWS_HIGHLIGHT_BORDER_H_ #include "ui/gfx/geometry/rounded_corners_f.h" #include "ui/views/border.h" #include "ui/views/views_export.h" namespace gfx { class Rect; } // namespace gfx namespace views { constexpr int kHighlightBorderThickness = 1; // A rounded rectangle border that has inner (highlight) and outer color. // Useful when go/cros-launcher-spec mentions "BorderHighlight". class VIEWS_EXPORT HighlightBorder : public views::Border { public: // TODO(crbug/1319944): Change these type names to something more descriptive. enum class Type { // The highlight border for the UI without a shadow. kHighlightBorderNoShadow, // The highlight border for the UI with a shadow. kHighlightBorderOnShadow, // TODO(b/271009119): Clean up these old types after MaterialNext is fully // launched. // A higher contrast highlight border than the `kHighlightBorder2` used // for floating components that do not have a shield below. kHighlightBorder1, // A less contrast highlight border for components that float above a // shield. kHighlightBorder2, // Has same inner border color as `kHighlightBorder1`. The outer color is // same in dark and light mode with low opacity. This type is mainly used // with `HighlightBorderLayerOverlay` whose outer border is outside the // window contents. For more information, refer to the comment of // `HighlightBorderOverlay`. kHighlightBorder3, }; // The type of insets created by this highlight border. The insets shrink the // content view. enum class InsetsType { // The border does not add insets that shrink the content, so the content // around the edge of the view can be overlapped with the border. kNoInsets, // Insetting by half of the border size pushes the content inside the outer // color of the border so the content bounds is surrounded by outer color // of the border. kHalfInsets, // Insetting by full border size makes sure that contents in the view // start inside the inner color of the highlight border, so there is no // overlap between content. kFullInsets, }; // Paints the highlight border onto `canvas` with given highlight and border // border color. Note that directly using this function won't set the insets // on any view so it acts like setting kNoInsets when using HighlightBorder // class. static void PaintBorderToCanvas(gfx::Canvas* canvas, SkColor highlight_color, SkColor border_color, const gfx::Rect& bounds, const gfx::RoundedCornersF& corner_radii, Type type); // Paints the highlight border onto `canvas` for the specified `view`. The // color of the border will be determined using `view`'s color provider. Note // that directly using this function won't set the insets on any view so it // acts like setting kNoInsets when using HighlightBorder class. static void PaintBorderToCanvas(gfx::Canvas* canvas, const views::View& view, const gfx::Rect& bounds, const gfx::RoundedCornersF& corner_radii, Type type); // Returns the inner highlight color used to paint highlight border. static SkColor GetHighlightColor(const views::View& view, HighlightBorder::Type type); // Returns the outer border color used to paint highlight border. static SkColor GetBorderColor(const views::View& view, HighlightBorder::Type type); HighlightBorder(int corner_radius, Type type, InsetsType insets_type = InsetsType::kNoInsets); HighlightBorder(const gfx::RoundedCornersF& rounded_corners, Type type, InsetsType insets_type = InsetsType::kNoInsets); HighlightBorder(const HighlightBorder&) = delete; HighlightBorder& operator=(const HighlightBorder&) = delete; ~HighlightBorder() override = default; // views::Border: void Paint(const views::View& view, gfx::Canvas* canvas) override; void OnViewThemeChanged(views::View* view) override; gfx::Insets GetInsets() const override; gfx::Size GetMinimumSize() const override; private: // The rounded corners of this border. const gfx::RoundedCornersF rounded_corners_; const Type type_; // Used by `GetInsets()` to calculate the insets. const InsetsType insets_type_; }; } // namespace views #endif // UI_VIEWS_HIGHLIGHT_BORDER_H_
Zhao-PengFei35/chromium_src_4
ui/views/highlight_border.h
C++
unknown
4,887
// Copyright 2018 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/input_event_activation_protector.h" #include "base/command_line.h" #include "ui/events/event.h" #include "ui/views/metrics.h" #include "ui/views/views_switches.h" namespace views { void InputEventActivationProtector::VisibilityChanged(bool is_visible) { if (is_visible) view_shown_time_stamp_ = base::TimeTicks::Now(); } void InputEventActivationProtector::UpdateViewShownTimeStamp() { // The UI was never shown, ignore. if (view_shown_time_stamp_ == base::TimeTicks()) return; view_shown_time_stamp_ = base::TimeTicks::Now(); } bool InputEventActivationProtector::IsPossiblyUnintendedInteraction( const ui::Event& event) { if (UNLIKELY(base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableInputEventActivationProtectionForTesting))) { return false; } if (view_shown_time_stamp_ == base::TimeTicks()) { // The UI was never shown, ignore. This can happen in tests. return false; } // Don't let key repeats close the dialog, they might've been held when the // dialog pops up. if (event.IsKeyEvent() && event.AsKeyEvent()->is_repeat()) return true; if (!event.IsMouseEvent() && !event.IsTouchEvent() && !event.IsGestureEvent()) { return false; } const base::TimeDelta kShortInterval = base::Milliseconds(GetDoubleClickInterval()); const bool short_event_after_last_event = event.time_stamp() < last_event_timestamp_ + kShortInterval; last_event_timestamp_ = event.time_stamp(); // Unintended if the user has been clicking with short intervals. if (short_event_after_last_event) { repeated_event_count_++; return true; } repeated_event_count_ = 0; // Unintended if the user clicked right after the UI showed. return event.time_stamp() < view_shown_time_stamp_ + kShortInterval; } void InputEventActivationProtector::ResetForTesting() { view_shown_time_stamp_ = base::TimeTicks(); last_event_timestamp_ = base::TimeTicks(); repeated_event_count_ = 0; } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/input_event_activation_protector.cc
C++
unknown
2,182
// Copyright 2018 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_INPUT_EVENT_ACTIVATION_PROTECTOR_H_ #define UI_VIEWS_INPUT_EVENT_ACTIVATION_PROTECTOR_H_ #include "base/time/time.h" #include "ui/views/views_export.h" namespace ui { class Event; } namespace views { // The goal of this class is to prevent potentially unintentional user // interaction with a UI element. // See switch kDisableInputEventActivationProtectionForTesting for disabling it. class VIEWS_EXPORT InputEventActivationProtector { public: InputEventActivationProtector() = default; InputEventActivationProtector(const InputEventActivationProtector&) = delete; InputEventActivationProtector& operator=( const InputEventActivationProtector&) = delete; virtual ~InputEventActivationProtector() = default; // Updates the state of the protector based off of visibility changes. This // method must be called when the visibility of the view is changed. void VisibilityChanged(bool is_visible); // Updates the |view_shown_time_stamp_| if needed. This function will be // called when we want to reset back the input protector to "initial shown" // state, basically under some certain view's proprieties changed events. void UpdateViewShownTimeStamp(); // Returns true if the event is a mouse, touch, or pointer event that took // place within the double-click time interval after |view_shown_time_stamp_|. virtual bool IsPossiblyUnintendedInteraction(const ui::Event& event); // Resets the state for click tracking. void ResetForTesting(); private: // Timestamp of when the view being tracked is first shown. base::TimeTicks view_shown_time_stamp_; // Timestamp of the last event. base::TimeTicks last_event_timestamp_; // Number of repeated UI events with short intervals. size_t repeated_event_count_ = 0; }; } // namespace views #endif // UI_VIEWS_INPUT_EVENT_ACTIVATION_PROTECTOR_H_
Zhao-PengFei35/chromium_src_4
ui/views/input_event_activation_protector.h
C++
unknown
2,013
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/interaction/element_tracker_views.h" #include <list> #include <map> #include <memory> #include <string> #include "base/containers/contains.h" #include "base/debug/stack_trace.h" #include "base/logging.h" #include "base/memory/raw_ptr.h" #include "base/no_destructor.h" #include "base/ranges/algorithm.h" #include "base/scoped_multi_source_observation.h" #include "base/scoped_observation.h" #include "ui/base/interaction/element_identifier.h" #include "ui/base/interaction/element_tracker.h" #include "ui/views/view.h" #include "ui/views/view_class_properties.h" #include "ui/views/view_observer.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_observer.h" namespace views { TrackedElementViews::TrackedElementViews(View* view, ui::ElementIdentifier identifier, ui::ElementContext context) : TrackedElement(identifier, context), view_(view) {} TrackedElementViews::~TrackedElementViews() = default; gfx::Rect TrackedElementViews::GetScreenBounds() const { return view()->GetBoundsInScreen(); } std::string TrackedElementViews::ToString() const { auto result = TrackedElement::ToString(); result.append(" with view "); result.append(view()->GetClassName()); return result; } DEFINE_FRAMEWORK_SPECIFIC_METADATA(TrackedElementViews) // Tracks views associated with a specific ui::ElementIdentifier, whether or not // they are visible or attached to a widget. class ElementTrackerViews::ElementDataViews : public ViewObserver, public WidgetObserver { public: ElementDataViews(ElementTrackerViews* tracker, ui::ElementIdentifier identifier) : tracker_(tracker), id_(identifier) {} ~ElementDataViews() override = default; void AddView(View* view) { if (base::Contains(view_data_lookup_, view)) return; const auto it = view_data_.insert(view_data_.end(), ViewData(view, GetContextForView(view))); view_data_lookup_.emplace(view, it); view_observer_.AddObservation(view); tracker_->MaybeTrackWidget(view->GetWidget()); UpdateVisible(view); } void RemoveView(View* view) { const auto it = view_data_lookup_.find(view); if (it == view_data_lookup_.end()) return; if (it->second->visible()) { ui::ElementTracker::GetFrameworkDelegate()->NotifyElementHidden( it->second->element.get()); } view_observer_.RemoveObservation(view); view_data_.erase(it->second); view_data_lookup_.erase(it); if (view_data_.empty()) tracker_->element_data_.erase(id_); } TrackedElementViews* GetElementForView(View* view) { const auto it = view_data_lookup_.find(view); DCHECK(it != view_data_lookup_.end()); return it->second->element.get(); } void NotifyViewActivated(View* view) { const auto it = view_data_lookup_.find(view); DCHECK(it != view_data_lookup_.end()); if (it->second->visible()) { ui::ElementTracker::GetFrameworkDelegate()->NotifyElementActivated( it->second->element.get()); } else { DLOG(WARNING) << "View " << view->GetClassName() << " activated before it was made visible. This probably happened" " during a test; it should never happen in a live browser."; } } // When a widget we were previously watching because it had not yet been shown // becomes visible, we manually update the visibility of any view on that // widget. void UpdateViewVisibilityForWidget(Widget* widget) { for (auto& entry : view_data_) { if (!entry.visible() && entry.view->GetWidget() == widget) UpdateVisible(entry.view); } } View* FindFirstViewInContext(ui::ElementContext context) { for (const ViewData& data : view_data_) { if (data.context == context) return data.view; } return nullptr; } ViewList FindAllViewsInContext(ui::ElementContext context) { ViewList result; for (const ViewData& data : view_data_) { if (data.context == context) result.push_back(data.view); } return result; } ViewList GetAllViews() { ViewList result; base::ranges::transform(view_data_lookup_, std::back_inserter(result), &ViewDataMap::value_type::first); return result; } private: enum class UpdateReason { kGeneral, kVisbilityFromRoot, kRemoveFromWidget }; struct ViewData { explicit ViewData(View* v, ui::ElementContext initial_context) : view(v), context(initial_context) {} bool visible() const { return static_cast<bool>(element); } const raw_ptr<View> view; ui::ElementContext context; std::unique_ptr<TrackedElementViews> element; }; using ViewDataList = std::list<ViewData>; using ViewDataMap = std::map<View*, ViewDataList::iterator>; // ViewObserver: void OnViewVisibilityChanged(View* observed_view, View* starting_view) override { UpdateVisible(observed_view, starting_view->parent() ? UpdateReason::kGeneral : UpdateReason::kVisbilityFromRoot); } void OnViewAddedToWidget(View* observed_view) override { tracker_->MaybeTrackWidget(observed_view->GetWidget()); UpdateVisible(observed_view); } void OnViewRemovedFromWidget(View* observed_view) override { UpdateVisible(observed_view, UpdateReason::kRemoveFromWidget); } void OnViewIsDeleting(View* observed_view) override { RemoveView(observed_view); } // Returns whether the specified view is visible to the user. Takes the view // hierarchy and widget into account. bool IsViewVisibleToUser(View* view) { const Widget* const widget = view->GetWidget(); if (!widget || widget->IsClosed() || !tracker_->IsWidgetVisible(widget)) return false; for (; view; view = view->parent()) { if (!view->GetVisible()) return false; } return true; } void UpdateVisible(View* view, UpdateReason update_reason = UpdateReason::kGeneral) { const auto it = view_data_lookup_.find(view); DCHECK(it != view_data_lookup_.end()); ViewData& data = *it->second; const ui::ElementContext old_context = data.context; data.context = (update_reason == UpdateReason::kRemoveFromWidget) ? ui::ElementContext() : GetContextForView(view); const bool was_visible = data.visible(); const bool visible = it->second->context && IsViewVisibleToUser(view); if (visible && !was_visible) { data.element = std::make_unique<TrackedElementViews>(view, id_, data.context); ui::ElementTracker::GetFrameworkDelegate()->NotifyElementShown( data.element.get()); } else if (!visible && was_visible) { ui::ElementTracker::GetFrameworkDelegate()->NotifyElementHidden( data.element.get()); data.element.reset(); } else if (visible && old_context != data.context) { CHECK(update_reason == UpdateReason::kVisbilityFromRoot) << "We should always get a removed-from-widget notification before " "an added-to-widget notification, the context should never " "change while a view is visible."; // This can happen in some tests where a widget is closed before it // actually becomes visible, or a parent widget is closed underneath us. if (!view->GetWidget()->IsVisible()) { ui::ElementTracker::GetFrameworkDelegate()->NotifyElementHidden( data.element.get()); data.element.reset(); } } } const raw_ptr<ElementTrackerViews> tracker_; const ui::ElementIdentifier id_; ViewDataList view_data_; ViewDataMap view_data_lookup_; base::ScopedMultiSourceObservation<View, ViewObserver> view_observer_{this}; }; // Tracks Widgets which are not yet visible, or for which we have received an // OnWidgetVisibilityChanged(true) event but IsVisible() does not yet report // true for the Widget. // // Therefore, it should only be created and maintained for a Widget for which // IsVisible() does not return true. class ElementTrackerViews::WidgetTracker : public WidgetObserver { public: WidgetTracker(ElementTrackerViews* tracker, Widget* widget) : tracker_(tracker), widget_(widget) { observation_.Observe(widget); // We never want to observe a visible widget; it's unnecessary. DCHECK(!widget->IsVisible()); } bool visible() const { return visible_; } private: // WidgetObserver: void OnWidgetDestroying(Widget* widget) override { Remove(); } void OnWidgetVisibilityChanged(Widget* widget, bool visible) override { // Need to save this for later in case |this| gets deleted. auto* const tracker = tracker_.get(); if (!visible || widget->IsVisible()) { // We're in a state in which Widget::IsVisible() should accurately reflect // the state of the widget, and therefore do not need to track the Widget. Remove(); } else { // We have been told the widget is visible, but the widget is not // reporting as visible; therefore we must note this since additional // views may be added to the tracker before Widget::IsVisible() becomes // true. visible_ = true; } // We might be deleted here so don't use any local data! if (visible) { for (auto& [id, data] : tracker->element_data_) data.UpdateViewVisibilityForWidget(widget); } } void Remove() { // Side effect is that `this` is destroyed. tracker_->widget_trackers_.erase(widget_); } const base::raw_ptr<ElementTrackerViews> tracker_; const base::raw_ptr<Widget> widget_; bool visible_ = false; base::ScopedObservation<Widget, WidgetObserver> observation_{this}; }; ElementTrackerViews::ElementTrackerViews() = default; ElementTrackerViews::~ElementTrackerViews() = default; // static ElementTrackerViews* ElementTrackerViews::GetInstance() { static base::NoDestructor<ElementTrackerViews> instance; return instance.get(); } // static ui::ElementContext ElementTrackerViews::GetContextForView(View* view) { Widget* const widget = view->GetWidget(); return widget ? GetContextForWidget(widget) : ui::ElementContext(); } // static ui::ElementContext ElementTrackerViews::GetContextForWidget(Widget* widget) { return ui::ElementContext(widget->GetPrimaryWindowWidget()); } TrackedElementViews* ElementTrackerViews::GetElementForView( View* view, bool assign_temporary_id) { ui::ElementIdentifier identifier = view->GetProperty(kElementIdentifierKey); if (!identifier) { if (!assign_temporary_id) return nullptr; // We shouldn't be assigning temporary IDs to views which are not yet on // widgets (how did we even get a reference to the view?) DCHECK(view->GetWidget()); identifier = ui::ElementTracker::kTemporaryIdentifier; view->SetProperty(kElementIdentifierKey, identifier); } const auto it = element_data_.find(identifier); if (it == element_data_.end()) { DCHECK(!assign_temporary_id); return nullptr; } return it->second.GetElementForView(view); } const TrackedElementViews* ElementTrackerViews::GetElementForView( const View* view) const { // Const casts are justified as `assign_temporary_id` = false will not result // in any modification to existing data. return const_cast<ElementTrackerViews*>(this)->GetElementForView( const_cast<View*>(view), false); } View* ElementTrackerViews::GetUniqueView(ui::ElementIdentifier id, ui::ElementContext context) { ui::TrackedElement* const element = ui::ElementTracker::GetElementTracker()->GetUniqueElement(id, context); // Note: this will crash if element is not a TrackedElementViews, but this // method *should* crash if the element is present but of the wrong type. return element ? element->AsA<TrackedElementViews>()->view() : nullptr; } View* ElementTrackerViews::GetFirstMatchingView(ui::ElementIdentifier id, ui::ElementContext context) { const auto it = element_data_.find(id); if (it == element_data_.end()) return nullptr; return it->second.FindFirstViewInContext(context); } ElementTrackerViews::ViewList ElementTrackerViews::GetAllMatchingViews( ui::ElementIdentifier id, ui::ElementContext context) { const auto it = element_data_.find(id); if (it == element_data_.end()) return ViewList(); return it->second.FindAllViewsInContext(context); } ElementTrackerViews::ViewList ElementTrackerViews::GetAllMatchingViewsInAnyContext(ui::ElementIdentifier id) { const auto it = element_data_.find(id); if (it == element_data_.end()) return ViewList(); return it->second.GetAllViews(); } Widget* ElementTrackerViews::GetWidgetForContext(ui::ElementContext context) { for (auto& [id, data] : element_data_) { auto* const view = data.FindFirstViewInContext(context); if (view) return view->GetWidget(); } return nullptr; } bool ElementTrackerViews::NotifyCustomEvent( ui::CustomElementEventType event_type, View* view) { auto* const element = GetElementForView(view, /* assign_temporary_id =*/true); if (!element) return false; ui::ElementTracker::GetFrameworkDelegate()->NotifyCustomEvent(element, event_type); return true; } void ElementTrackerViews::RegisterView(ui::ElementIdentifier element_id, View* view) { const auto [it, added] = element_data_.try_emplace(element_id, this, element_id); it->second.AddView(view); } void ElementTrackerViews::UnregisterView(ui::ElementIdentifier element_id, View* view) { DCHECK(view); const auto it = element_data_.find(element_id); DCHECK(it != element_data_.end()); it->second.RemoveView(view); } void ElementTrackerViews::NotifyViewActivated(ui::ElementIdentifier element_id, View* view) { DCHECK(view); const auto it = element_data_.find(element_id); DCHECK(it != element_data_.end()); it->second.NotifyViewActivated(view); } void ElementTrackerViews::MaybeTrackWidget(Widget* widget) { if (!widget || widget->IsVisible()) return; widget_trackers_.try_emplace(widget, this, widget); } bool ElementTrackerViews::IsWidgetVisible(const Widget* widget) const { if (widget->IsVisible()) return true; const auto it = widget_trackers_.find(widget); return it != widget_trackers_.end() && it->second.visible(); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/interaction/element_tracker_views.cc
C++
unknown
14,947
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_INTERACTION_ELEMENT_TRACKER_VIEWS_H_ #define UI_VIEWS_INTERACTION_ELEMENT_TRACKER_VIEWS_H_ #include <map> #include <string> #include <vector> #include "base/gtest_prod_util.h" #include "base/memory/raw_ptr.h" #include "base/no_destructor.h" #include "base/scoped_multi_source_observation.h" #include "base/strings/string_piece_forward.h" #include "ui/base/interaction/element_identifier.h" #include "ui/base/interaction/element_tracker.h" #include "ui/views/view_utils.h" #include "ui/views/views_export.h" namespace views { class View; class Widget; // Wraps a View in an ui::TrackedElement. class VIEWS_EXPORT TrackedElementViews : public ui::TrackedElement { public: TrackedElementViews(View* view, ui::ElementIdentifier identifier, ui::ElementContext context); ~TrackedElementViews() override; View* view() { return view_; } const View* view() const { return view_; } // TrackedElement: gfx::Rect GetScreenBounds() const override; std::string ToString() const override; DECLARE_FRAMEWORK_SPECIFIC_METADATA() private: const raw_ptr<View> view_; }; // Manages TrackedElements associated with View objects. class VIEWS_EXPORT ElementTrackerViews { public: using ViewList = std::vector<View*>; // Gets the global instance of the tracker for Views. static ElementTrackerViews* GetInstance(); // Returns the context associated with a particular View. The context will be // the same across all Views associated with a root Widget (such as an // application window). static ui::ElementContext GetContextForView(View* view); // Returns the context associated with a particular Widget. The context will // be the same across all Widgets associated with a root Widget (such as an // application window). static ui::ElementContext GetContextForWidget(Widget* widget); // ---------- // The following methods retrieve Views directly without having to retrieve a // TrackedElement from ElementTracker, call, AsA<>, etc. Use if you know that // the element(s) in question are guaranteed to be Views. // Returns the corresponding TrackedElementViews for the given view, or // null if none exists. Note that views which are not visible or not added to // a Widget may not have associated elements, and that the returned object // may be transient. // // For the non-const version, if `assign_temporary_id` is set and `view` does // not have an identifier, ui::ElementTracker::kTemporaryIdentifier will be // assigned. TrackedElementViews* GetElementForView(View* view, bool assign_temporary_id = false); const TrackedElementViews* GetElementForView(const View* view) const; // Returns either the unique View matching the given `id` in the given // `context`, or null if there is none. // // Use if you are sure there's at most one matching element in the context // and that (if present) the element is a View; will DCHECK/crash otherwise. View* GetUniqueView(ui::ElementIdentifier id, ui::ElementContext context); // Convenience method that calls GetUniqueView() and then safely converts the // result to `T`, which must be a View subclass with metadata. Fails if a View // is found but is not of the expected subtype. template <class T> T* GetUniqueViewAs(ui::ElementIdentifier id, ui::ElementContext context); // Returns the first View with the given `id` in the given `context`; null if // none is found. Ignores all other Views and any matching elements that are // not Views. // // Use when you just need *a* View in the given context, and don't care if // there's more than one. View* GetFirstMatchingView(ui::ElementIdentifier id, ui::ElementContext context); // Convenience method that calls GetFirstMatchingView() and then safely // converts the result to `T`, which must be a view subclass with metadata. // Fails if a View is found but is not of the expected subtype. template <class T> T* GetFirstMatchingViewAs(ui::ElementIdentifier id, ui::ElementContext context); // Returns a list of all visible Views with identifier `id` in `context`. // The list may be empty. Ignores any non-Views elements which might match. ViewList GetAllMatchingViews(ui::ElementIdentifier id, ui::ElementContext context); // Returns a list of all visible Views with identifier `id` in any context. // Order is not guaranteed. Ignores any non-Views elements with the same // identifier. ViewList GetAllMatchingViewsInAnyContext(ui::ElementIdentifier id); // Returns a widget that matches the given context. A valid // TrackedElementViews must exist within the widget. Widget* GetWidgetForContext(ui::ElementContext context); // ---------- // Notifies listeners that a specific custom event has occurred for the given // view. Calls GetElementForView(view, true) under the hood; returns false if // an element cannot be found or created for the view (e.g. in the case where // it is not visible or associated with a widget). bool NotifyCustomEvent(ui::CustomElementEventType event_type, View* view); // ---------- // The following methods are used by View and derived classes to send events // to ElementTracker. ElementTrackerViews maintains additional observers and // states that make sure shown and hidden events get sent at the correct // times. // Called by View after the kUniqueElementKey property is set. void RegisterView(ui::ElementIdentifier element_id, View* view); // Called by View if the kUniqueElementKey property is changed from a non-null // value. void UnregisterView(ui::ElementIdentifier element_id, View* view); // Called by a View when the user activates it (clicks a button, selects a // menu item, etc.) void NotifyViewActivated(ui::ElementIdentifier element_id, View* view); private: friend class base::NoDestructor<ElementTrackerViews>; FRIEND_TEST_ALL_PREFIXES(ElementTrackerViewsTest, CleansUpWidgetTrackers); class ElementDataViews; class WidgetTracker; ElementTrackerViews(); ~ElementTrackerViews(); // We do not get notified at the View level if a view's widget has not yet // been shown. We need this notification to know when the view is actually // visible to the user. So if a view is added to the trakcer or is added to // a widget, and its widget is not visible, we watch it until it is (or it is // destroyed). void MaybeTrackWidget(Widget* widget); // Keep track of widgets for which we've received an // OnWidgetVisibilityChanged(true) event for but which are still reporting // IsVisible() = false. This happens because visibility of native window in // Aura is not exactly synced with our event reporting. bool IsWidgetVisible(const Widget* widget) const; std::map<ui::ElementIdentifier, ElementDataViews> element_data_; std::map<const Widget*, WidgetTracker> widget_trackers_; }; // Template implementations. template <class T> T* ElementTrackerViews::GetUniqueViewAs(ui::ElementIdentifier id, ui::ElementContext context) { views::View* const view = GetUniqueView(id, context); if (!view) return nullptr; T* const result = views::AsViewClass<T>(view); DCHECK(result); return result; } template <class T> T* ElementTrackerViews::GetFirstMatchingViewAs(ui::ElementIdentifier id, ui::ElementContext context) { views::View* const view = GetFirstMatchingView(id, context); if (!view) return nullptr; T* const result = views::AsViewClass<T>(view); DCHECK(result); return result; } } // namespace views #endif // UI_VIEWS_INTERACTION_ELEMENT_TRACKER_VIEWS_H_
Zhao-PengFei35/chromium_src_4
ui/views/interaction/element_tracker_views.h
C++
unknown
7,976
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/interaction/element_tracker_views.h" #include <iterator> #include <memory> #include <utility> #include "base/functional/bind.h" #include "base/memory/raw_ptr.h" #include "base/ranges/algorithm.h" #include "base/test/bind.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/interaction/element_identifier.h" #include "ui/base/interaction/element_test_util.h" #include "ui/base/interaction/element_tracker.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/events/base_event_utils.h" #include "ui/events/event.h" #include "ui/events/keycodes/dom/dom_code.h" #include "ui/events/types/event_type.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/button/menu_button.h" #include "ui/views/interaction/interaction_test_util_views.h" #include "ui/views/test/views_test_base.h" #include "ui/views/test/widget_test.h" #include "ui/views/view_class_properties.h" #include "ui/views/widget/widget.h" namespace views { DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kTestElementID); DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kTestElementID2); DECLARE_CUSTOM_ELEMENT_EVENT_TYPE(kCustomEventType); DEFINE_CUSTOM_ELEMENT_EVENT_TYPE(kCustomEventType); namespace { enum ElementEventType { kShown, kActivated, kHidden, kCustom }; View* ElementToView(ui::TrackedElement* element) { auto* const view_element = element->AsA<TrackedElementViews>(); return view_element ? view_element->view() : nullptr; } // A subclass of View that has metadata. class TypedView : public View { public: METADATA_HEADER(TypedView); }; BEGIN_METADATA(TypedView, View) END_METADATA // Watches events on the ElementTracker and converts the resulting values back // into Views from the original ui::TrackedElement objects. Monitoring // callbacks in this way could be done with gmock but the boilerplate would be // unfortunately complicated (for some events, the correct parameters are not // known until after the call is made, since the call itself might create the // element in question). So instead we use this helper class. class ElementEventWatcher { public: // Watches the specified `event_type` on Views with identifier `id` in // `context`. ElementEventWatcher(ui::ElementIdentifier id, ui::ElementContext context, ElementEventType event_type) : id_(id), event_type_(event_type) { auto callback = base::BindRepeating(&ElementEventWatcher::OnEvent, base::Unretained(this)); ui::ElementTracker* const tracker = ui::ElementTracker::GetElementTracker(); switch (event_type_) { case ElementEventType::kShown: subscription_ = tracker->AddElementShownCallback(id, context, callback); break; case ElementEventType::kActivated: subscription_ = tracker->AddElementActivatedCallback(id, context, callback); break; case ElementEventType::kHidden: subscription_ = tracker->AddElementHiddenCallback(id, context, callback); break; case ElementEventType::kCustom: subscription_ = tracker->AddCustomEventCallback(id, context, callback); break; } } int event_count() const { return event_count_; } View* last_view() { return last_view_; } private: void OnEvent(ui::TrackedElement* element) { if (event_type_ != ElementEventType::kCustom) EXPECT_EQ(id_, element->identifier()); last_view_ = ElementToView(element); ++event_count_; } const ui::ElementIdentifier id_; const ElementEventType event_type_; ui::ElementTracker::Subscription subscription_; int event_count_ = 0; raw_ptr<View> last_view_ = nullptr; }; ElementTrackerViews::ViewList ElementsToViews( ui::ElementTracker::ElementList elements) { ElementTrackerViews::ViewList result; base::ranges::transform(elements, std::back_inserter(result), [](ui::TrackedElement* element) { return element->AsA<TrackedElementViews>()->view(); }); return result; } } // namespace class ElementTrackerViewsTest : public ViewsTestBase { public: ElementTrackerViewsTest() = default; ~ElementTrackerViewsTest() override = default; void SetUp() override { ViewsTestBase::SetUp(); widget_ = CreateWidget(); widget_->Show(); } void TearDown() override { widget_.reset(); ViewsTestBase::TearDown(); } ui::ElementContext context() const { return ui::ElementContext(widget_.get()); } std::unique_ptr<Widget> CreateWidget() { auto widget = std::make_unique<Widget>(); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(0, 0, 650, 650); widget->Init(std::move(params)); return widget; } protected: std::unique_ptr<Widget> widget_; }; TEST_F(ElementTrackerViewsTest, ViewShownByAddingToWidgetSendsNotification) { ElementEventWatcher watcher(kTestElementID, context(), ElementEventType::kShown); auto button_ptr = std::make_unique<LabelButton>(); button_ptr->SetProperty(kElementIdentifierKey, kTestElementID); EXPECT_EQ(0, watcher.event_count()); auto* const button = widget_->SetContentsView(std::move(button_ptr)); EXPECT_EQ(1, watcher.event_count()); EXPECT_EQ(button, watcher.last_view()); } TEST_F(ElementTrackerViewsTest, ViewHiddenByRemovingFromWidgetSendsNotification) { ElementEventWatcher watcher(kTestElementID, context(), ElementEventType::kHidden); auto button_ptr = std::make_unique<LabelButton>(); button_ptr->SetProperty(kElementIdentifierKey, kTestElementID); EXPECT_EQ(0, watcher.event_count()); auto* const view = widget_->SetContentsView(std::make_unique<View>()); auto* const button = view->AddChildView(std::move(button_ptr)); EXPECT_EQ(0, watcher.event_count()); view->RemoveChildViewT(button); EXPECT_EQ(1, watcher.event_count()); EXPECT_EQ(button, watcher.last_view()); } TEST_F(ElementTrackerViewsTest, ViewShownAfterAddingToWidgetSendsNotification) { ElementEventWatcher watcher(kTestElementID, context(), ElementEventType::kShown); auto button_ptr = std::make_unique<LabelButton>(); button_ptr->SetVisible(false); button_ptr->SetProperty(kElementIdentifierKey, kTestElementID); auto* const button = widget_->SetContentsView(std::move(button_ptr)); EXPECT_EQ(0, watcher.event_count()); button->SetVisible(true); EXPECT_EQ(1, watcher.event_count()); EXPECT_EQ(button, watcher.last_view()); } TEST_F(ElementTrackerViewsTest, ViewHiddenAfterAddingToWidgetSendsNotification) { ElementEventWatcher watcher(kTestElementID, context(), ElementEventType::kHidden); auto button_ptr = std::make_unique<LabelButton>(); button_ptr->SetProperty(kElementIdentifierKey, kTestElementID); auto* const button = widget_->SetContentsView(std::move(button_ptr)); EXPECT_EQ(0, watcher.event_count()); button->SetVisible(false); EXPECT_EQ(1, watcher.event_count()); EXPECT_EQ(button, watcher.last_view()); } TEST_F(ElementTrackerViewsTest, SettingIDOnVisibleViewSendsNotification) { ElementEventWatcher watcher(kTestElementID, context(), ElementEventType::kShown); auto button_ptr = std::make_unique<LabelButton>(); auto* const button = widget_->SetContentsView(std::move(button_ptr)); EXPECT_EQ(0, watcher.event_count()); button->SetProperty(kElementIdentifierKey, kTestElementID); EXPECT_EQ(1, watcher.event_count()); EXPECT_EQ(button, watcher.last_view()); } TEST_F(ElementTrackerViewsTest, ClearingIDOnVisibleViewSendsNotification) { ElementEventWatcher watcher(kTestElementID, context(), ElementEventType::kHidden); auto button_ptr = std::make_unique<LabelButton>(); button_ptr->SetProperty(kElementIdentifierKey, kTestElementID); auto* const button = widget_->SetContentsView(std::move(button_ptr)); EXPECT_EQ(0, watcher.event_count()); button->ClearProperty(kElementIdentifierKey); EXPECT_EQ(1, watcher.event_count()); EXPECT_EQ(button, watcher.last_view()); } TEST_F(ElementTrackerViewsTest, ChangingIDOnVisibleViewSendsNotification) { ElementEventWatcher shown(kTestElementID, context(), ElementEventType::kShown); ElementEventWatcher hidden(kTestElementID, context(), ElementEventType::kHidden); ElementEventWatcher shown2(kTestElementID2, context(), ElementEventType::kShown); ElementEventWatcher hidden2(kTestElementID2, context(), ElementEventType::kHidden); auto button_ptr = std::make_unique<LabelButton>(); button_ptr->SetProperty(kElementIdentifierKey, kTestElementID); auto* const button = widget_->SetContentsView(std::move(button_ptr)); EXPECT_EQ(1, shown.event_count()); EXPECT_EQ(0, hidden.event_count()); EXPECT_EQ(0, shown2.event_count()); EXPECT_EQ(0, hidden2.event_count()); button->SetProperty(kElementIdentifierKey, kTestElementID2); EXPECT_EQ(1, shown.event_count()); EXPECT_EQ(1, hidden.event_count()); EXPECT_EQ(1, shown2.event_count()); EXPECT_EQ(0, hidden2.event_count()); button->SetVisible(false); EXPECT_EQ(1, shown.event_count()); EXPECT_EQ(1, hidden.event_count()); EXPECT_EQ(1, shown2.event_count()); EXPECT_EQ(1, hidden2.event_count()); } TEST_F(ElementTrackerViewsTest, ButtonPressedSendsActivatedSignal) { ElementEventWatcher watcher(kTestElementID, context(), ElementEventType::kActivated); auto button_ptr = std::make_unique<LabelButton>(); button_ptr->SetProperty(kElementIdentifierKey, kTestElementID); EXPECT_EQ(0, watcher.event_count()); auto* const button = widget_->SetContentsView(std::move(button_ptr)); EXPECT_EQ(0, watcher.event_count()); // Test mouse click. constexpr gfx::Point kPressPoint(10, 10); button->OnMousePressed(ui::MouseEvent( ui::ET_MOUSE_PRESSED, kPressPoint, kPressPoint, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); button->OnMouseReleased(ui::MouseEvent( ui::ET_MOUSE_PRESSED, kPressPoint, kPressPoint, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); EXPECT_EQ(1, watcher.event_count()); EXPECT_EQ(button, watcher.last_view()); // Test accessible keypress. views::test::InteractionTestUtilSimulatorViews::PressButton(button); EXPECT_EQ(2, watcher.event_count()); EXPECT_EQ(button, watcher.last_view()); } TEST_F(ElementTrackerViewsTest, MenuButtonPressedSendsActivatedSignal) { ElementEventWatcher watcher(kTestElementID, context(), ElementEventType::kActivated); size_t pressed_count = 0; auto button_ptr = std::make_unique<MenuButton>( base::BindLambdaForTesting([&](const ui::Event&) { ++pressed_count; })); button_ptr->SetProperty(kElementIdentifierKey, kTestElementID); EXPECT_EQ(0, watcher.event_count()); auto* const button = widget_->SetContentsView(std::move(button_ptr)); EXPECT_EQ(0, watcher.event_count()); // Test mouse click. constexpr gfx::Point kPressPoint(10, 10); button->OnMousePressed(ui::MouseEvent( ui::ET_MOUSE_PRESSED, kPressPoint, kPressPoint, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); EXPECT_EQ(1U, pressed_count); EXPECT_EQ(1, watcher.event_count()); EXPECT_EQ(button, watcher.last_view()); // Test accessible keypress. views::test::InteractionTestUtilSimulatorViews::PressButton(button); EXPECT_EQ(2U, pressed_count); EXPECT_EQ(2, watcher.event_count()); EXPECT_EQ(button, watcher.last_view()); } TEST_F(ElementTrackerViewsTest, SendCustomEventWithNamedElement) { ElementEventWatcher watcher(kCustomEventType, context(), ElementEventType::kCustom); auto* const target = widget_->SetContentsView(std::make_unique<View>()); target->SetProperty(kElementIdentifierKey, kTestElementID); EXPECT_EQ(0, watcher.event_count()); ElementTrackerViews::GetInstance()->NotifyCustomEvent(kCustomEventType, target); EXPECT_EQ(1, watcher.event_count()); EXPECT_EQ(target, watcher.last_view()); // Send an event with a different ID (which happens to be the element's ID; // this shouldn't happen but we should handle it gracefully). ElementTrackerViews::GetInstance()->NotifyCustomEvent(kTestElementID, target); EXPECT_EQ(1, watcher.event_count()); // Send another event. ElementTrackerViews::GetInstance()->NotifyCustomEvent(kCustomEventType, target); EXPECT_EQ(2, watcher.event_count()); EXPECT_EQ(target, watcher.last_view()); } TEST_F(ElementTrackerViewsTest, SendCustomEventWithUnnamedElement) { ElementEventWatcher watcher(kCustomEventType, context(), ElementEventType::kCustom); auto* const target = widget_->SetContentsView(std::make_unique<View>()); // View has no pre-set identifier, but this should still work. EXPECT_EQ(0, watcher.event_count()); ElementTrackerViews::GetInstance()->NotifyCustomEvent(kCustomEventType, target); EXPECT_EQ(1, watcher.event_count()); EXPECT_EQ(target, watcher.last_view()); // Send an extraneous event. ElementTrackerViews::GetInstance()->NotifyCustomEvent(kTestElementID, target); EXPECT_EQ(1, watcher.event_count()); // Send another event. ElementTrackerViews::GetInstance()->NotifyCustomEvent(kCustomEventType, target); EXPECT_EQ(2, watcher.event_count()); EXPECT_EQ(target, watcher.last_view()); } TEST_F(ElementTrackerViewsTest, HandlesCreateWithTheSameIDMultipleTimes) { ElementEventWatcher watcher(kTestElementID, context(), ElementEventType::kShown); auto button_ptr = std::make_unique<LabelButton>(); button_ptr->SetProperty(kElementIdentifierKey, kTestElementID); auto* const button = widget_->SetContentsView(std::move(button_ptr)); EXPECT_EQ(1, watcher.event_count()); EXPECT_EQ(button, watcher.last_view()); widget_->GetRootView()->RemoveChildViewT(button); button_ptr = std::make_unique<LabelButton>(); button_ptr->SetProperty(kElementIdentifierKey, kTestElementID); auto* const button2 = widget_->SetContentsView(std::move(button_ptr)); EXPECT_EQ(2, watcher.event_count()); EXPECT_EQ(button2, watcher.last_view()); } TEST_F(ElementTrackerViewsTest, HandlesReshowingTheSameView) { ElementEventWatcher watcher(kTestElementID, context(), ElementEventType::kShown); auto button_ptr = std::make_unique<LabelButton>(); button_ptr->SetProperty(kElementIdentifierKey, kTestElementID); auto* const button = widget_->SetContentsView(std::move(button_ptr)); EXPECT_EQ(1, watcher.event_count()); EXPECT_EQ(button, watcher.last_view()); button->SetVisible(false); EXPECT_EQ(1, watcher.event_count()); button->SetVisible(true); EXPECT_EQ(2, watcher.event_count()); EXPECT_EQ(button, watcher.last_view()); } TEST_F(ElementTrackerViewsTest, CanLookupViewByIdentifier) { // Should initially be null. EXPECT_EQ(nullptr, ui::ElementTracker::GetElementTracker()->GetUniqueElement( kTestElementID, context())); auto button_ptr = std::make_unique<LabelButton>(); button_ptr->SetProperty(kElementIdentifierKey, kTestElementID); // Because the button is not attached to a widget, it will not be returned for // the current context (which is associated with a widget). EXPECT_EQ(nullptr, ui::ElementTracker::GetElementTracker()->GetUniqueElement( kTestElementID, context())); // Adding the view to a widget will cause it to be returned in the current // context. auto* button = widget_->SetContentsView(std::move(button_ptr)); EXPECT_EQ( button, ElementToView(ui::ElementTracker::GetElementTracker()->GetUniqueElement( kTestElementID, context()))); // Once the view is destroyed, however, the result should be null again. widget_->GetRootView()->RemoveChildViewT(button); EXPECT_EQ(nullptr, ui::ElementTracker::GetElementTracker()->GetUniqueElement( kTestElementID, context())); // Create a second view with the same ID and verify that the new pointer is // returned. button = widget_->SetContentsView(std::make_unique<LabelButton>()); button->SetProperty(kElementIdentifierKey, kTestElementID); EXPECT_EQ( button, ElementToView(ui::ElementTracker::GetElementTracker()->GetUniqueElement( kTestElementID, context()))); // When the view is deleted, the result once again becomes null. widget_->GetRootView()->RemoveChildViewT(button); EXPECT_EQ(nullptr, ui::ElementTracker::GetElementTracker()->GetUniqueElement( kTestElementID, context())); } TEST_F(ElementTrackerViewsTest, CanLookUpElementByIdentifier) { // Should initially be null. EXPECT_EQ(nullptr, ui::ElementTracker::GetElementTracker()->GetUniqueElement( kTestElementID, context())); auto button_ptr = std::make_unique<LabelButton>(); button_ptr->SetProperty(kElementIdentifierKey, kTestElementID); // Because the button is not attached to a widget, it will not be returned for // the current context (which is associated with a widget). EXPECT_EQ(nullptr, ui::ElementTracker::GetElementTracker()->GetUniqueElement( kTestElementID, context())); // Adding the view to a widget will cause it to be returned in the current // context. auto* button = widget_->SetContentsView(std::move(button_ptr)); EXPECT_EQ(button, ui::ElementTracker::GetElementTracker() ->GetUniqueElement(kTestElementID, context()) ->AsA<TrackedElementViews>() ->view()); // Hiding the view will make the view not findable through the base element // tracker. button->SetVisible(false); EXPECT_EQ(nullptr, ui::ElementTracker::GetElementTracker()->GetUniqueElement( kTestElementID, context())); // Showing the view will bring it back. button->SetVisible(true); EXPECT_EQ(button, ui::ElementTracker::GetElementTracker() ->GetUniqueElement(kTestElementID, context()) ->AsA<TrackedElementViews>() ->view()); // Once the view is destroyed, however, the result should be null again. widget_->GetRootView()->RemoveChildViewT(button); EXPECT_EQ(nullptr, ui::ElementTracker::GetElementTracker()->GetUniqueElement( kTestElementID, context())); // Create a second view with the same ID and verify that the new pointer is // returned. button = widget_->SetContentsView(std::make_unique<LabelButton>()); button->SetProperty(kElementIdentifierKey, kTestElementID); EXPECT_EQ(button, ui::ElementTracker::GetElementTracker() ->GetUniqueElement(kTestElementID, context()) ->AsA<TrackedElementViews>() ->view()); // When the view is deleted, the result once again becomes null. widget_->GetRootView()->RemoveChildViewT(button); EXPECT_EQ(nullptr, ui::ElementTracker::GetElementTracker()->GetUniqueElement( kTestElementID, context())); } TEST_F(ElementTrackerViewsTest, CanGetFirstViewByIdentifier) { // Should initially be null. EXPECT_EQ(nullptr, ui::ElementTracker::GetElementTracker()->GetFirstMatchingElement( kTestElementID, context())); // Add two buttons with the same identifier. auto* contents = widget_->SetContentsView(std::make_unique<View>()); auto* button = contents->AddChildView(std::make_unique<LabelButton>()); button->SetProperty(kElementIdentifierKey, kTestElementID); auto* button2 = contents->AddChildView(std::make_unique<LabelButton>()); button2->SetProperty(kElementIdentifierKey, kTestElementID); // The first button should be returned. EXPECT_EQ( button, ElementToView( ui::ElementTracker::GetElementTracker()->GetFirstMatchingElement( kTestElementID, context()))); // Remove the first button. The second should now be returned. contents->RemoveChildViewT(button); EXPECT_EQ( button2, ElementToView( ui::ElementTracker::GetElementTracker()->GetFirstMatchingElement( kTestElementID, context()))); // Remove the second button. There will be no matching views. contents->RemoveChildViewT(button2); EXPECT_EQ(nullptr, ui::ElementTracker::GetElementTracker()->GetFirstMatchingElement( kTestElementID, context())); } TEST_F(ElementTrackerViewsTest, CanGetFirstElementByIdentifier) { // Should initially be null. EXPECT_EQ(nullptr, ui::ElementTracker::GetElementTracker()->GetFirstMatchingElement( kTestElementID, context())); // Add two buttons with the same identifier. auto* contents = widget_->SetContentsView(std::make_unique<View>()); auto* button = contents->AddChildView(std::make_unique<LabelButton>()); button->SetProperty(kElementIdentifierKey, kTestElementID); auto* button2 = contents->AddChildView(std::make_unique<LabelButton>()); button2->SetProperty(kElementIdentifierKey, kTestElementID); // The first button should be returned. EXPECT_EQ(button, ui::ElementTracker::GetElementTracker() ->GetFirstMatchingElement(kTestElementID, context()) ->AsA<TrackedElementViews>() ->view()); // Set the buttons' visibility; this should change whether the element tracker // sees them. button->SetVisible(false); EXPECT_EQ(button2, ui::ElementTracker::GetElementTracker() ->GetFirstMatchingElement(kTestElementID, context()) ->AsA<TrackedElementViews>() ->view()); button2->SetVisible(false); EXPECT_EQ(nullptr, ui::ElementTracker::GetElementTracker()->GetFirstMatchingElement( kTestElementID, context())); // The second button is now the first to become visible in the base tracker. button2->SetVisible(true); button->SetVisible(true); EXPECT_EQ(button2, ui::ElementTracker::GetElementTracker() ->GetFirstMatchingElement(kTestElementID, context()) ->AsA<TrackedElementViews>() ->view()); // Remove the second button. The first should now be returned. contents->RemoveChildViewT(button2); EXPECT_EQ(button, ui::ElementTracker::GetElementTracker() ->GetFirstMatchingElement(kTestElementID, context()) ->AsA<TrackedElementViews>() ->view()); // Remove the first button. There will be no matching views. contents->RemoveChildViewT(button); EXPECT_EQ(nullptr, ui::ElementTracker::GetElementTracker()->GetFirstMatchingElement( kTestElementID, context())); } TEST_F(ElementTrackerViewsTest, CanGetAllViewsByIdentifier) { // Should initially be empty. ElementTrackerViews::ViewList expected; EXPECT_EQ(expected, ElementsToViews( ui::ElementTracker::GetElementTracker()->GetAllMatchingElements( kTestElementID, context()))); // Add two buttons with the same identifier. auto* contents = widget_->SetContentsView(std::make_unique<View>()); auto* button = contents->AddChildView(std::make_unique<LabelButton>()); button->SetProperty(kElementIdentifierKey, kTestElementID); auto* button2 = contents->AddChildView(std::make_unique<LabelButton>()); button2->SetProperty(kElementIdentifierKey, kTestElementID); // All buttons should be returned. expected = ElementTrackerViews::ViewList{button, button2}; EXPECT_EQ(expected, ElementsToViews( ui::ElementTracker::GetElementTracker()->GetAllMatchingElements( kTestElementID, context()))); // Remove the first button. The second should now be returned. contents->RemoveChildViewT(button); expected = ElementTrackerViews::ViewList{button2}; EXPECT_EQ(expected, ElementsToViews( ui::ElementTracker::GetElementTracker()->GetAllMatchingElements( kTestElementID, context()))); // Remove the second button. There will be no matching views. contents->RemoveChildViewT(button2); expected.clear(); EXPECT_EQ(expected, ElementsToViews( ui::ElementTracker::GetElementTracker()->GetAllMatchingElements( kTestElementID, context()))); } TEST_F(ElementTrackerViewsTest, CanGetAllElementsByIdentifier) { // Should initially be empty. ElementTrackerViews::ViewList expected; EXPECT_EQ(expected, ElementsToViews( ui::ElementTracker::GetElementTracker()->GetAllMatchingElements( kTestElementID, context()))); // Add two buttons with the same identifier. auto* contents = widget_->SetContentsView(std::make_unique<View>()); auto* button = contents->AddChildView(std::make_unique<LabelButton>()); button->SetProperty(kElementIdentifierKey, kTestElementID); auto* button2 = contents->AddChildView(std::make_unique<LabelButton>()); button2->SetProperty(kElementIdentifierKey, kTestElementID); // Both buttons should be returned. expected = ElementTrackerViews::ViewList{button, button2}; EXPECT_EQ(expected, ElementsToViews( ui::ElementTracker::GetElementTracker()->GetAllMatchingElements( kTestElementID, context()))); // Set the buttons' visibility; this should change whether the element tracker // sees them. button->SetVisible(false); expected = ElementTrackerViews::ViewList{button2}; EXPECT_EQ(expected, ElementsToViews( ui::ElementTracker::GetElementTracker()->GetAllMatchingElements( kTestElementID, context()))); button2->SetVisible(false); expected.clear(); EXPECT_EQ(expected, ElementsToViews( ui::ElementTracker::GetElementTracker()->GetAllMatchingElements( kTestElementID, context()))); // The second button is now the first to become visible in the base tracker. button2->SetVisible(true); button->SetVisible(true); expected = ElementTrackerViews::ViewList{button2, button}; EXPECT_EQ(expected, ElementsToViews( ui::ElementTracker::GetElementTracker()->GetAllMatchingElements( kTestElementID, context()))); // Remove the second button. Only the first should now be returned. contents->RemoveChildViewT(button2); expected = ElementTrackerViews::ViewList{button}; EXPECT_EQ(expected, ElementsToViews( ui::ElementTracker::GetElementTracker()->GetAllMatchingElements( kTestElementID, context()))); // Remove the first button. There will be no matching views. contents->RemoveChildViewT(button); expected.clear(); EXPECT_EQ(expected, ElementsToViews( ui::ElementTracker::GetElementTracker()->GetAllMatchingElements( kTestElementID, context()))); } TEST_F(ElementTrackerViewsTest, CanGetVisibilityByIdentifier) { // Should initially be false. EXPECT_FALSE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context())); auto button_ptr = std::make_unique<LabelButton>(); button_ptr->SetProperty(kElementIdentifierKey, kTestElementID); // Because the button is not attached to a widget, it will not be counted as // visible. EXPECT_FALSE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context())); // Adding the view to a widget will cause it to be counted as visible. auto* button = widget_->SetContentsView(std::move(button_ptr)); EXPECT_TRUE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context())); // Once the view is destroyed, however, the result should be false again. widget_->GetRootView()->RemoveChildViewT(button); EXPECT_FALSE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context())); // Create a second view with the same ID but start it as not visible. button = widget_->SetContentsView(std::make_unique<LabelButton>()); button->SetVisible(false); button->SetProperty(kElementIdentifierKey, kTestElementID); EXPECT_FALSE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context())); // Now set the visibility to true. button->SetVisible(true); EXPECT_TRUE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context())); // Set visibility to false again. button->SetVisible(false); EXPECT_FALSE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context())); } TEST_F(ElementTrackerViewsTest, CanLookupElementByView) { // Should initially be false. EXPECT_FALSE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context())); auto button_ptr = std::make_unique<LabelButton>(); button_ptr->SetProperty(kElementIdentifierKey, kTestElementID); // The button is not attached to a widget so there is no associated element // object. EXPECT_EQ(nullptr, ElementTrackerViews::GetInstance()->GetElementForView( button_ptr.get())); // Adding the (visible) view to a widget will cause an element to be // generated. auto* button = widget_->SetContentsView(std::move(button_ptr)); EXPECT_NE(nullptr, ElementTrackerViews::GetInstance()->GetElementForView(button)); // Once the view is destroyed, however, the result should be false again. widget_->GetRootView()->RemoveChildView(button); EXPECT_EQ(nullptr, ElementTrackerViews::GetInstance()->GetElementForView(button)); delete button; // Create a second view with the same ID but start it as not visible. button = widget_->SetContentsView(std::make_unique<LabelButton>()); button->SetVisible(false); button->SetProperty(kElementIdentifierKey, kTestElementID); EXPECT_EQ(nullptr, ElementTrackerViews::GetInstance()->GetElementForView(button)); // Now set the visibility to true. button->SetVisible(true); EXPECT_NE(nullptr, ElementTrackerViews::GetInstance()->GetElementForView(button)); // Set visibility to false again. button->SetVisible(false); EXPECT_EQ(nullptr, ElementTrackerViews::GetInstance()->GetElementForView(button)); } TEST_F(ElementTrackerViewsTest, AssignTemporaryId) { auto* button = widget_->SetContentsView(std::make_unique<LabelButton>()); DCHECK(!button->GetProperty(kElementIdentifierKey)); TrackedElementViews* element = ElementTrackerViews::GetInstance()->GetElementForView(button); EXPECT_EQ(nullptr, element); element = ElementTrackerViews::GetInstance()->GetElementForView(button, true); EXPECT_NE(nullptr, element); EXPECT_EQ(ui::ElementTracker::kTemporaryIdentifier, button->GetProperty(kElementIdentifierKey)); EXPECT_EQ(element, ui::ElementTracker::GetElementTracker()->GetUniqueElement( ui::ElementTracker::kTemporaryIdentifier, context())); } // The following tests ensure conformity with the different platforms' Views // implementation to ensure that Views are reported as visible to the user at // the correct times, including during Widget close/delete. TEST_F(ElementTrackerViewsTest, ParentNotVisibleWhenAddedToWidget) { View* const contents = widget_->SetContentsView(std::make_unique<View>()); contents->SetVisible(false); auto child_ptr = std::make_unique<View>(); child_ptr->SetProperty(kElementIdentifierKey, kTestElementID); EXPECT_FALSE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context())); contents->AddChildView(std::move(child_ptr)); EXPECT_FALSE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context())); contents->SetVisible(true); EXPECT_TRUE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context())); } TEST_F(ElementTrackerViewsTest, WidgetNotVisibleWhenAddedToWidget) { View* const contents = widget_->SetContentsView(std::make_unique<View>()); widget_->Hide(); auto child_ptr = std::make_unique<View>(); child_ptr->SetProperty(kElementIdentifierKey, kTestElementID); EXPECT_FALSE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context())); contents->AddChildView(std::move(child_ptr)); EXPECT_FALSE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context())); widget_->Show(); EXPECT_TRUE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context())); } TEST_F(ElementTrackerViewsTest, ParentHidden) { View* const contents = widget_->SetContentsView(std::make_unique<View>()); auto child_ptr = std::make_unique<View>(); child_ptr->SetProperty(kElementIdentifierKey, kTestElementID); EXPECT_FALSE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context())); contents->AddChildView(std::move(child_ptr)); EXPECT_TRUE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context())); contents->SetVisible(false); EXPECT_FALSE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context())); } TEST_F(ElementTrackerViewsTest, WidgetHidden) { View* const contents = widget_->SetContentsView(std::make_unique<View>()); auto child_ptr = std::make_unique<View>(); child_ptr->SetProperty(kElementIdentifierKey, kTestElementID); EXPECT_FALSE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context())); contents->AddChildView(std::move(child_ptr)); EXPECT_TRUE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context())); widget_->Hide(); EXPECT_FALSE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context())); } TEST_F(ElementTrackerViewsTest, WidgetClosed) { View* const contents = widget_->SetContentsView(std::make_unique<View>()); auto child_ptr = std::make_unique<View>(); child_ptr->SetProperty(kElementIdentifierKey, kTestElementID); EXPECT_FALSE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context())); contents->AddChildView(std::move(child_ptr)); EXPECT_TRUE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context())); widget_->Close(); EXPECT_FALSE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context())); } TEST_F(ElementTrackerViewsTest, WidgetDestroyed) { View* const contents = widget_->SetContentsView(std::make_unique<View>()); auto child_ptr = std::make_unique<View>(); child_ptr->SetProperty(kElementIdentifierKey, kTestElementID); EXPECT_FALSE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context())); contents->AddChildView(std::move(child_ptr)); EXPECT_TRUE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context())); widget_.reset(); EXPECT_FALSE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context())); } TEST_F(ElementTrackerViewsTest, WidgetShownAfterAdd) { auto widget = CreateWidget(); View* const contents = widget->SetContentsView(std::make_unique<View>()); const ui::ElementContext context = ElementTrackerViews::GetContextForView(contents); auto child_ptr = std::make_unique<View>(); child_ptr->SetProperty(kElementIdentifierKey, kTestElementID); EXPECT_FALSE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context)); contents->AddChildView(std::move(child_ptr)); EXPECT_FALSE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context)); widget->Show(); EXPECT_TRUE(ui::ElementTracker::GetElementTracker()->IsElementVisible( kTestElementID, context)); } // This is a gross corner case where a Widget might not report IsVisible() // during show, but we're still showing views and could conceivably add another // view as part of a callback. TEST_F(ElementTrackerViewsTest, AddedDuringWidgetShow) { auto widget = CreateWidget(); View* const contents = widget->SetContentsView(std::make_unique<View>()); View* const child1 = contents->AddChildView(std::make_unique<View>()); View* const child2 = contents->AddChildView(std::make_unique<View>()); child1->SetProperty(kElementIdentifierKey, kTestElementID); auto subscription = ui::ElementTracker::GetElementTracker()->AddElementShownCallback( kTestElementID, ElementTrackerViews::GetContextForWidget(widget.get()), base::BindLambdaForTesting([&](ui::TrackedElement*) { child2->SetProperty(kElementIdentifierKey, kTestElementID2); })); bool called = false; auto subscription2 = ui::ElementTracker::GetElementTracker()->AddElementShownCallback( kTestElementID2, ElementTrackerViews::GetContextForWidget(widget.get()), base::BindLambdaForTesting([&](ui::TrackedElement* element) { EXPECT_EQ(child2, element->AsA<TrackedElementViews>()->view()); called = true; })); test::WidgetVisibleWaiter visible_waiter(widget.get()); widget->Show(); visible_waiter.Wait(); EXPECT_TRUE(called); // Now verify that hiding a widget which we engaged during initial Show(), // without destroying the views, causes the elements to be hidden. subscription2 = ui::ElementTracker::GetElementTracker()->AddElementHiddenCallback( kTestElementID2, ElementTrackerViews::GetContextForWidget(widget.get()), base::BindLambdaForTesting([&](ui::TrackedElement* element) { EXPECT_EQ(child2, element->AsA<TrackedElementViews>()->view()); called = true; })); called = false; widget->Hide(); EXPECT_TRUE(called); } TEST_F(ElementTrackerViewsTest, CleansUpWidgetTrackers) { auto widget1 = CreateWidget(); View* const contents1 = widget1->SetContentsView(std::make_unique<View>()); contents1->SetProperty(kElementIdentifierKey, kTestElementID); auto widget2 = CreateWidget(); View* const contents2 = widget1->SetContentsView(std::make_unique<View>()); contents2->SetProperty(kElementIdentifierKey, kTestElementID); test::WidgetVisibleWaiter waiter1(widget1.get()); test::WidgetVisibleWaiter waiter2(widget2.get()); widget1->Show(); widget2->Show(); waiter1.Wait(); waiter2.Wait(); widget1->Hide(); test::WidgetDestroyedWaiter destroyed_waiter(widget2.get()); widget2->Close(); destroyed_waiter.Wait(); EXPECT_TRUE(ElementTrackerViews::GetInstance()->widget_trackers_.empty()); } TEST_F(ElementTrackerViewsTest, GetUniqueView) { auto widget = CreateWidget(); View* const contents = widget->SetContentsView(std::make_unique<View>()); widget->Show(); const ui::ElementContext context = ElementTrackerViews::GetContextForView(contents); EXPECT_EQ(nullptr, ElementTrackerViews::GetInstance()->GetUniqueView( kTestElementID, context)); contents->SetProperty(kElementIdentifierKey, kTestElementID); EXPECT_EQ(contents, ElementTrackerViews::GetInstance()->GetUniqueView( kTestElementID, context)); contents->ClearProperty(kElementIdentifierKey); EXPECT_EQ(nullptr, ElementTrackerViews::GetInstance()->GetUniqueView( kTestElementID, context)); } TEST_F(ElementTrackerViewsTest, GetUniqueViewAs) { auto widget = CreateWidget(); TypedView* const contents = widget->SetContentsView(std::make_unique<TypedView>()); widget->Show(); const ui::ElementContext context = ElementTrackerViews::GetContextForView(contents); EXPECT_EQ(nullptr, ElementTrackerViews::GetInstance()->GetUniqueViewAs<TypedView>( kTestElementID, context)); contents->SetProperty(kElementIdentifierKey, kTestElementID); EXPECT_EQ(contents, ElementTrackerViews::GetInstance()->GetUniqueViewAs<TypedView>( kTestElementID, context)); contents->ClearProperty(kElementIdentifierKey); EXPECT_EQ(nullptr, ElementTrackerViews::GetInstance()->GetUniqueViewAs<TypedView>( kTestElementID, context)); } TEST_F(ElementTrackerViewsTest, GetFirstMatchingViewWithSingleView) { auto widget = CreateWidget(); View* const contents = widget->SetContentsView(std::make_unique<View>()); widget->Show(); const ui::ElementContext context = ElementTrackerViews::GetContextForView(contents); EXPECT_EQ(nullptr, ElementTrackerViews::GetInstance()->GetFirstMatchingView( kTestElementID, context)); contents->SetProperty(kElementIdentifierKey, kTestElementID); EXPECT_EQ(contents, ElementTrackerViews::GetInstance()->GetFirstMatchingView( kTestElementID, context)); contents->ClearProperty(kElementIdentifierKey); EXPECT_EQ(nullptr, ElementTrackerViews::GetInstance()->GetFirstMatchingView( kTestElementID, context)); } TEST_F(ElementTrackerViewsTest, GetFirstMatchingViewAs) { auto widget = CreateWidget(); TypedView* const contents = widget->SetContentsView(std::make_unique<TypedView>()); widget->Show(); const ui::ElementContext context = ElementTrackerViews::GetContextForView(contents); EXPECT_EQ( nullptr, ElementTrackerViews::GetInstance()->GetFirstMatchingViewAs<TypedView>( kTestElementID, context)); contents->SetProperty(kElementIdentifierKey, kTestElementID); EXPECT_EQ( contents, ElementTrackerViews::GetInstance()->GetFirstMatchingViewAs<TypedView>( kTestElementID, context)); contents->ClearProperty(kElementIdentifierKey); EXPECT_EQ( nullptr, ElementTrackerViews::GetInstance()->GetFirstMatchingViewAs<TypedView>( kTestElementID, context)); } TEST_F(ElementTrackerViewsTest, GetFirstMatchingViewWithMultipleViews) { auto widget = CreateWidget(); View* const contents = widget->SetContentsView(std::make_unique<View>()); View* const v1 = contents->AddChildView(std::make_unique<View>()); View* const v2 = contents->AddChildView(std::make_unique<View>()); widget->Show(); const ui::ElementContext context = ElementTrackerViews::GetContextForView(contents); v1->SetProperty(kElementIdentifierKey, kTestElementID); v2->SetProperty(kElementIdentifierKey, kTestElementID); EXPECT_EQ(v1, ElementTrackerViews::GetInstance()->GetFirstMatchingView( kTestElementID, context)); v1->ClearProperty(kElementIdentifierKey); EXPECT_EQ(v2, ElementTrackerViews::GetInstance()->GetFirstMatchingView( kTestElementID, context)); v2->ClearProperty(kElementIdentifierKey); EXPECT_EQ(nullptr, ElementTrackerViews::GetInstance()->GetFirstMatchingView( kTestElementID, context)); } TEST_F(ElementTrackerViewsTest, GetFirstMatchingViewWithNonViewsElements) { auto widget = CreateWidget(); View* const contents = widget->SetContentsView(std::make_unique<View>()); widget->Show(); const ui::ElementContext context = ElementTrackerViews::GetContextForView(contents); ui::test::TestElementPtr test_element1 = std::make_unique<ui::test::TestElement>(kTestElementID, context); ui::test::TestElementPtr test_element2 = std::make_unique<ui::test::TestElement>(kTestElementID, context); test_element1->Show(); contents->SetProperty(kElementIdentifierKey, kTestElementID); test_element2->Show(); EXPECT_EQ(contents, ElementTrackerViews::GetInstance()->GetFirstMatchingView( kTestElementID, context)); contents->ClearProperty(kElementIdentifierKey); EXPECT_EQ(nullptr, ElementTrackerViews::GetInstance()->GetFirstMatchingView( kTestElementID, context)); } TEST_F(ElementTrackerViewsTest, GetAllMatchingViewsWithSingleView) { auto widget = CreateWidget(); View* const contents = widget->SetContentsView(std::make_unique<View>()); widget->Show(); const ui::ElementContext context = ElementTrackerViews::GetContextForView(contents); EXPECT_EQ(ElementTrackerViews::ViewList(), ElementTrackerViews::GetInstance()->GetAllMatchingViews( kTestElementID, context)); contents->SetProperty(kElementIdentifierKey, kTestElementID); const ElementTrackerViews::ViewList expected = {contents}; EXPECT_EQ(expected, ElementTrackerViews::GetInstance()->GetAllMatchingViews( kTestElementID, context)); contents->ClearProperty(kElementIdentifierKey); EXPECT_EQ(ElementTrackerViews::ViewList(), ElementTrackerViews::GetInstance()->GetAllMatchingViews( kTestElementID, context)); } TEST_F(ElementTrackerViewsTest, GetAllMatchingViewsWithMultipleViews) { auto widget = CreateWidget(); View* const contents = widget->SetContentsView(std::make_unique<View>()); View* const v1 = contents->AddChildView(std::make_unique<View>()); View* const v2 = contents->AddChildView(std::make_unique<View>()); widget->Show(); const ui::ElementContext context = ElementTrackerViews::GetContextForView(contents); v1->SetProperty(kElementIdentifierKey, kTestElementID); v2->SetProperty(kElementIdentifierKey, kTestElementID); ElementTrackerViews::ViewList expected = {v1, v2}; EXPECT_EQ(expected, ElementTrackerViews::GetInstance()->GetAllMatchingViews( kTestElementID, context)); v1->ClearProperty(kElementIdentifierKey); expected = {v2}; EXPECT_EQ(expected, ElementTrackerViews::GetInstance()->GetAllMatchingViews( kTestElementID, context)); v2->ClearProperty(kElementIdentifierKey); EXPECT_EQ(ElementTrackerViews::ViewList(), ElementTrackerViews::GetInstance()->GetAllMatchingViews( kTestElementID, context)); } TEST_F(ElementTrackerViewsTest, GetAllMatchingViewsWithNonViewsElements) { auto widget = CreateWidget(); View* const contents = widget->SetContentsView(std::make_unique<View>()); widget->Show(); const ui::ElementContext context = ElementTrackerViews::GetContextForView(contents); ui::test::TestElementPtr test_element1 = std::make_unique<ui::test::TestElement>(kTestElementID, context); ui::test::TestElementPtr test_element2 = std::make_unique<ui::test::TestElement>(kTestElementID, context); test_element1->Show(); contents->SetProperty(kElementIdentifierKey, kTestElementID); test_element2->Show(); const ElementTrackerViews::ViewList expected = {contents}; EXPECT_EQ(expected, ElementTrackerViews::GetInstance()->GetAllMatchingViews( kTestElementID, context)); contents->ClearProperty(kElementIdentifierKey); EXPECT_EQ(ElementTrackerViews::ViewList(), ElementTrackerViews::GetInstance()->GetAllMatchingViews( kTestElementID, context)); } TEST_F(ElementTrackerViewsTest, GetAllViewsInAnyContextWithSingleView) { auto widget = CreateWidget(); View* const contents = widget->SetContentsView(std::make_unique<View>()); widget->Show(); EXPECT_THAT( ElementTrackerViews::GetInstance()->GetAllMatchingViewsInAnyContext( kTestElementID), testing::IsEmpty()); contents->SetProperty(kElementIdentifierKey, kTestElementID); EXPECT_THAT( ElementTrackerViews::GetInstance()->GetAllMatchingViewsInAnyContext( kTestElementID), testing::UnorderedElementsAre(contents)); contents->ClearProperty(kElementIdentifierKey); EXPECT_THAT( ElementTrackerViews::GetInstance()->GetAllMatchingViewsInAnyContext( kTestElementID), testing::IsEmpty()); } TEST_F(ElementTrackerViewsTest, GetAllViewsInAnyContextWithMultipleViews) { auto widget = CreateWidget(); auto widget2 = CreateWidget(); View* const contents = widget->SetContentsView(std::make_unique<View>()); View* const v1 = contents->AddChildView(std::make_unique<View>()); View* const v2 = contents->AddChildView(std::make_unique<View>()); View* const contents2 = widget2->SetContentsView(std::make_unique<View>()); View* const v3 = contents2->AddChildView(std::make_unique<View>()); View* const v4 = contents2->AddChildView(std::make_unique<View>()); widget->Show(); widget2->Show(); v1->SetProperty(kElementIdentifierKey, kTestElementID); v2->SetProperty(kElementIdentifierKey, kTestElementID); v3->SetProperty(kElementIdentifierKey, kTestElementID); v4->SetProperty(kElementIdentifierKey, kTestElementID2); EXPECT_THAT( ElementTrackerViews::GetInstance()->GetAllMatchingViewsInAnyContext( kTestElementID), testing::UnorderedElementsAre(v1, v2, v3)); v1->ClearProperty(kElementIdentifierKey); EXPECT_THAT( ElementTrackerViews::GetInstance()->GetAllMatchingViewsInAnyContext( kTestElementID), testing::UnorderedElementsAre(v2, v3)); v2->ClearProperty(kElementIdentifierKey); EXPECT_THAT( ElementTrackerViews::GetInstance()->GetAllMatchingViewsInAnyContext( kTestElementID), testing::UnorderedElementsAre(v3)); } TEST_F(ElementTrackerViewsTest, GetAllViewsInAnyContextWithNonViewsElements) { auto widget = CreateWidget(); View* const contents = widget->SetContentsView(std::make_unique<View>()); widget->Show(); const ui::ElementContext context = ElementTrackerViews::GetContextForView(contents); ui::test::TestElementPtr test_element1 = std::make_unique<ui::test::TestElement>(kTestElementID, context); ui::test::TestElementPtr test_element2 = std::make_unique<ui::test::TestElement>(kTestElementID, context); test_element1->Show(); contents->SetProperty(kElementIdentifierKey, kTestElementID); test_element2->Show(); EXPECT_THAT( ElementTrackerViews::GetInstance()->GetAllMatchingViewsInAnyContext( kTestElementID), testing::UnorderedElementsAre(contents)); contents->ClearProperty(kElementIdentifierKey); EXPECT_THAT( ElementTrackerViews::GetInstance()->GetAllMatchingViewsInAnyContext( kTestElementID), testing::IsEmpty()); } // Verifies that Views on different Widgets are differentiated by the system. class ElementTrackerTwoWidgetTest : public ElementTrackerViewsTest { public: ElementTrackerTwoWidgetTest() = default; ~ElementTrackerTwoWidgetTest() override = default; void SetUp() override { ElementTrackerViewsTest::SetUp(); widget2_ = CreateWidget(); widget2_->Show(); } void TearDown() override { widget2_.reset(); ElementTrackerViewsTest::TearDown(); } ui::ElementContext context2() const { return ui::ElementContext(widget2_.get()); } protected: std::unique_ptr<Widget> widget2_; }; TEST_F(ElementTrackerTwoWidgetTest, ViewMovedToDifferentWidgetGeneratesEvents) { ElementEventWatcher shown(kTestElementID, context(), ElementEventType::kShown); ElementEventWatcher hidden(kTestElementID, context(), ElementEventType::kHidden); ElementEventWatcher shown2(kTestElementID, context2(), ElementEventType::kShown); ElementEventWatcher hidden2(kTestElementID, context2(), ElementEventType::kHidden); auto* const view = widget_->SetContentsView(std::make_unique<View>()); auto* const view2 = widget2_->SetContentsView(std::make_unique<View>()); auto button_ptr = std::make_unique<LabelButton>(); button_ptr->SetProperty(kElementIdentifierKey, kTestElementID); // Add to first widget. auto* const button = view->AddChildView(std::move(button_ptr)); EXPECT_EQ(1, shown.event_count()); EXPECT_EQ(0, hidden.event_count()); EXPECT_EQ(0, shown2.event_count()); EXPECT_EQ(0, hidden2.event_count()); // Move to second widget. view2->AddChildView(button); EXPECT_EQ(1, shown.event_count()); EXPECT_EQ(1, hidden.event_count()); EXPECT_EQ(1, shown2.event_count()); EXPECT_EQ(0, hidden2.event_count()); // Destroy the second widget. widget2_.reset(); EXPECT_EQ(1, shown.event_count()); EXPECT_EQ(1, hidden.event_count()); EXPECT_EQ(1, shown2.event_count()); EXPECT_EQ(1, hidden2.event_count()); } TEST_F(ElementTrackerTwoWidgetTest, CanLookUpViewsOnMultipleWidgets) { auto* button = widget_->SetContentsView(std::make_unique<LabelButton>()); button->SetProperty(kElementIdentifierKey, kTestElementID); auto* button2 = widget2_->SetContentsView(std::make_unique<LabelButton>()); button2->SetProperty(kElementIdentifierKey, kTestElementID); EXPECT_EQ( button, ElementToView(ui::ElementTracker::GetElementTracker()->GetUniqueElement( kTestElementID, context()))); EXPECT_EQ( button2, ElementToView(ui::ElementTracker::GetElementTracker()->GetUniqueElement( kTestElementID, context2()))); widget_->GetRootView()->RemoveChildViewT(button); widget2_->GetRootView()->RemoveChildViewT(button2); EXPECT_EQ(nullptr, ui::ElementTracker::GetElementTracker()->GetUniqueElement( kTestElementID, context())); EXPECT_EQ(nullptr, ui::ElementTracker::GetElementTracker()->GetUniqueElement( kTestElementID, context2())); } TEST_F(ElementTrackerTwoWidgetTest, MakingViewsVisibleSendsNotificationsToCorrectListeners) { ElementEventWatcher watcher(kTestElementID, context(), ElementEventType::kShown); ElementEventWatcher watcher2(kTestElementID, context2(), ElementEventType::kShown); auto* const button = widget_->SetContentsView(std::make_unique<LabelButton>()); auto* const button2 = widget2_->SetContentsView(std::make_unique<LabelButton>()); EXPECT_EQ(0, watcher.event_count()); EXPECT_EQ(0, watcher2.event_count()); // Each listener should be notified when the appropriate button is shown. button->SetProperty(kElementIdentifierKey, kTestElementID); EXPECT_EQ(1, watcher.event_count()); EXPECT_EQ(button, watcher.last_view()); EXPECT_EQ(0, watcher2.event_count()); button2->SetProperty(kElementIdentifierKey, kTestElementID); EXPECT_EQ(1, watcher.event_count()); EXPECT_EQ(button, watcher.last_view()); EXPECT_EQ(1, watcher2.event_count()); EXPECT_EQ(button2, watcher2.last_view()); // Each listener should be notified when the appropriate button is shown. button->SetVisible(false); button->SetVisible(true); EXPECT_EQ(2, watcher.event_count()); EXPECT_EQ(1, watcher2.event_count()); // Hide and show several times to verify events are still set. button->SetVisible(false); button2->SetVisible(false); EXPECT_EQ(2, watcher.event_count()); EXPECT_EQ(1, watcher2.event_count()); button2->SetVisible(true); EXPECT_EQ(2, watcher.event_count()); EXPECT_EQ(2, watcher2.event_count()); button->SetVisible(true); EXPECT_EQ(3, watcher.event_count()); EXPECT_EQ(2, watcher2.event_count()); } TEST_F(ElementTrackerTwoWidgetTest, ButtonPressedSendsNotificationsToCorrectListeners) { ElementEventWatcher watcher(kTestElementID, context(), ElementEventType::kActivated); ElementEventWatcher watcher2(kTestElementID, context2(), ElementEventType::kActivated); auto* const button = widget_->SetContentsView(std::make_unique<LabelButton>()); auto* const button2 = widget2_->SetContentsView(std::make_unique<LabelButton>()); button->SetProperty(kElementIdentifierKey, kTestElementID); button2->SetProperty(kElementIdentifierKey, kTestElementID); EXPECT_EQ(0, watcher.event_count()); EXPECT_EQ(0, watcher2.event_count()); // Test mouse click. constexpr gfx::Point kPressPoint(10, 10); button->OnMousePressed(ui::MouseEvent( ui::ET_MOUSE_PRESSED, kPressPoint, kPressPoint, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); button->OnMouseReleased(ui::MouseEvent( ui::ET_MOUSE_PRESSED, kPressPoint, kPressPoint, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); EXPECT_EQ(1, watcher.event_count()); EXPECT_EQ(button, watcher.last_view()); EXPECT_EQ(0, watcher2.event_count()); // Click other button. button2->OnMousePressed(ui::MouseEvent( ui::ET_MOUSE_PRESSED, kPressPoint, kPressPoint, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); button2->OnMouseReleased(ui::MouseEvent( ui::ET_MOUSE_PRESSED, kPressPoint, kPressPoint, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); EXPECT_EQ(1, watcher.event_count()); EXPECT_EQ(button, watcher.last_view()); EXPECT_EQ(1, watcher2.event_count()); EXPECT_EQ(button2, watcher2.last_view()); // Test accessible keypress. views::test::InteractionTestUtilSimulatorViews::PressButton(button2); EXPECT_EQ(1, watcher.event_count()); EXPECT_EQ(2, watcher2.event_count()); views::test::InteractionTestUtilSimulatorViews::PressButton(button); EXPECT_EQ(2, watcher.event_count()); EXPECT_EQ(2, watcher2.event_count()); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/interaction/element_tracker_views_unittest.cc
C++
unknown
58,209
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/interaction/interaction_sequence_views.h" #include <utility> #include "ui/base/interaction/element_identifier.h" #include "ui/base/interaction/element_tracker.h" #include "ui/base/interaction/interaction_sequence.h" #include "ui/views/interaction/element_tracker_views.h" #include "ui/views/view.h" #include "ui/views/view_class_properties.h" namespace views { // static std::unique_ptr<ui::InteractionSequence::Step> InteractionSequenceViews::WithInitialView( View* view, ui::InteractionSequence::StepStartCallback start_callback, ui::InteractionSequence::StepEndCallback end_callback) { // If there's already an element associated with this view, then explicitly // key off of that element. auto* const element = ElementTrackerViews::GetInstance()->GetElementForView(view); if (element) return ui::InteractionSequence::WithInitialElement( element, std::move(start_callback), std::move(end_callback)); // Otherwise, use the element's identifier and context. ui::ElementContext context = ElementTrackerViews::GetContextForView(view); ui::ElementIdentifier identifier = view->GetProperty(kElementIdentifierKey); return ui::InteractionSequence::StepBuilder() .SetContext(context) .SetElementID(identifier) .SetType(ui::InteractionSequence::StepType::kShown) .SetMustBeVisibleAtStart(true) .SetMustRemainVisible(true) .SetStartCallback(std::move(start_callback)) .SetEndCallback(std::move(end_callback)) .Build(); } // static void InteractionSequenceViews::NameView(ui::InteractionSequence* sequence, View* view, const base::StringPiece& name) { ui::TrackedElement* element = nullptr; if (view) { element = ElementTrackerViews::GetInstance()->GetElementForView( view, /* assign_temporary_id =*/true); DCHECK(element); } sequence->NameElement(element, name); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/interaction/interaction_sequence_views.cc
C++
unknown
2,147
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_INTERACTION_INTERACTION_SEQUENCE_VIEWS_H_ #define UI_VIEWS_INTERACTION_INTERACTION_SEQUENCE_VIEWS_H_ #include <memory> #include "base/strings/string_piece.h" #include "ui/base/interaction/interaction_sequence.h" #include "ui/views/views_export.h" namespace views { class View; // Provides utility methods for using ui::InteractionsSequence with Views. class VIEWS_EXPORT InteractionSequenceViews { public: // Not constructible. InteractionSequenceViews() = delete; // Returns an InteractionSequence initial step with the specified `view`. static std::unique_ptr<ui::InteractionSequence::Step> WithInitialView( View* view, ui::InteractionSequence::StepStartCallback start_callback = ui::InteractionSequence::StepStartCallback(), ui::InteractionSequence::StepEndCallback end_callback = ui::InteractionSequence::StepEndCallback()); // Given an InteractionSequence and a View, names the view in the sequence. // If the view doesn't already have an element identifier, assigns // ui::ElementTracker::kTemporaryIdentifier. If `view` is null, calls // sequence->NameElement(nullptr, name). // // It is an error to call this method on a non-null View which is not visible // or which is not attached to a Widget. static void NameView(ui::InteractionSequence* sequence, View* view, const base::StringPiece& name); }; } // namespace views #endif // UI_VIEWS_INTERACTION_INTERACTION_SEQUENCE_VIEWS_H_
Zhao-PengFei35/chromium_src_4
ui/views/interaction/interaction_sequence_views.h
C++
unknown
1,671
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/interaction/interaction_sequence_views.h" // This suite contains tests which integrate the functionality of // ui::InteractionSequence with Views elements like Widgets and menus. // Similar suites should be created for other platforms. #include <memory> #include <utility> #include "base/functional/bind.h" #include "base/memory/raw_ptr.h" #include "base/test/bind.h" #include "base/test/mock_callback.h" #include "build/build_config.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/interaction/element_tracker.h" #include "ui/base/interaction/expect_call_in_scope.h" #include "ui/base/interaction/interaction_sequence.h" #include "ui/base/interaction/interaction_test_util.h" #include "ui/base/models/simple_menu_model.h" #include "ui/base/ui_base_types.h" #include "ui/events/base_event_utils.h" #include "ui/events/event.h" #include "ui/events/test/event_generator.h" #include "ui/events/types/event_type.h" #include "ui/views/bubble/bubble_dialog_delegate_view.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/button/menu_button.h" #include "ui/views/controls/menu/menu_item_view.h" #include "ui/views/controls/menu/menu_runner.h" #include "ui/views/interaction/element_tracker_views.h" #include "ui/views/interaction/interaction_test_util_views.h" #include "ui/views/layout/flex_layout.h" #include "ui/views/layout/flex_layout_types.h" #include "ui/views/layout/layout_types.h" #include "ui/views/test/views_test_base.h" #include "ui/views/test/widget_test.h" #include "ui/views/view.h" #include "ui/views/view_class_properties.h" #include "ui/views/widget/widget.h" namespace views { namespace { DECLARE_ELEMENT_IDENTIFIER_VALUE(kContentsElementID); DECLARE_ELEMENT_IDENTIFIER_VALUE(kTestElementID); DECLARE_ELEMENT_IDENTIFIER_VALUE(kTestElementID2); DECLARE_ELEMENT_IDENTIFIER_VALUE(kTestElementID3); DEFINE_ELEMENT_IDENTIFIER_VALUE(kContentsElementID); DEFINE_ELEMENT_IDENTIFIER_VALUE(kTestElementID); DEFINE_ELEMENT_IDENTIFIER_VALUE(kTestElementID2); DEFINE_ELEMENT_IDENTIFIER_VALUE(kTestElementID3); const char16_t kMenuItem1[] = u"Menu item"; const char16_t kMenuItem2[] = u"Menu item 2"; constexpr int kMenuID1 = 1; constexpr int kMenuID2 = 2; const char kElementName[] = "ElementName"; } // namespace class InteractionSequenceViewsTest : public ViewsTestBase { public: InteractionSequenceViewsTest() = default; ~InteractionSequenceViewsTest() override = default; static View* ElementToView(ui::TrackedElement* element) { return element ? element->AsA<TrackedElementViews>()->view() : nullptr; } static ui::TrackedElement* ViewToElement(View* view) { return view ? ElementTrackerViews::GetInstance()->GetElementForView(view) : nullptr; } std::unique_ptr<Widget> CreateWidget() { auto widget = std::make_unique<Widget>(); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(0, 0, 650, 650); widget->Init(std::move(params)); auto* contents = widget->SetContentsView(std::make_unique<View>()); auto* layout = contents->SetLayoutManager(std::make_unique<FlexLayout>()); layout->SetOrientation(LayoutOrientation::kHorizontal); layout->SetDefault(kFlexBehaviorKey, FlexSpecification(MinimumFlexSizeRule::kPreferred, MaximumFlexSizeRule::kUnbounded)); test::WidgetVisibleWaiter visible_waiter(widget.get()); widget->Show(); visible_waiter.Wait(); return widget; } void ShowMenu(ui::ElementIdentifier id) { CreateAndRunMenu(id); menu_element_ = ui::SafeElementReference( ui::ElementTracker::GetElementTracker()->GetFirstMatchingElement( id, ElementTrackerViews::GetContextForView(contents_))); Widget* const menu_widget = ElementToView(menu_element_.get())->GetWidget(); test::WidgetVisibleWaiter visible_waiter(menu_widget); visible_waiter.Wait(); } void CloseMenu() { menu_runner_.reset(); menu_model_.reset(); menu_element_ = ui::SafeElementReference(); } void ShowBubble(ui::ElementIdentifier id) { auto delegate = std::make_unique<BubbleDialogDelegateView>( contents_, BubbleBorder::Arrow::TOP_LEFT); label_button_ = delegate->AddChildView(std::make_unique<LabelButton>()); label_button_->SetProperty(kElementIdentifierKey, id); no_id_view_ = delegate->AddChildView(std::make_unique<LabelButton>()); bubble_widget_ = BubbleDialogDelegateView::CreateBubble(std::move(delegate)); test::WidgetVisibleWaiter visible_waiter(bubble_widget_); bubble_widget_->Show(); visible_waiter.Wait(); } void CloseBubble() { DCHECK(bubble_widget_); bubble_widget_->CloseNow(); bubble_widget_ = nullptr; label_button_ = nullptr; } void Activate(View* view) { ui::ElementTracker::GetFrameworkDelegate()->NotifyElementActivated( ElementTrackerViews::GetInstance()->GetElementForView(view)); } void SetUp() override { ViewsTestBase::SetUp(); widget_ = CreateWidget(); contents_ = widget_->GetContentsView(); contents_->SetProperty(kElementIdentifierKey, kContentsElementID); } void TearDown() override { if (bubble_widget_) CloseBubble(); if (menu_runner_) CloseMenu(); widget_.reset(); contents_ = nullptr; ViewsTestBase::TearDown(); } protected: ui::ElementContext context() const { return ui::ElementContext(widget_.get()); } virtual void CreateAndRunMenu(ui::ElementIdentifier id) { menu_model_ = std::make_unique<ui::SimpleMenuModel>(nullptr); menu_model_->AddItem(kMenuID1, kMenuItem1); menu_model_->AddItem(kMenuID2, kMenuItem2); menu_model_->SetElementIdentifierAt( menu_model_->GetIndexOfCommandId(kMenuID2).value(), id); menu_runner_ = std::make_unique<MenuRunner>(menu_model_.get(), MenuRunner::NO_FLAGS); menu_runner_->RunMenuAt( widget_.get(), nullptr, gfx::Rect(gfx::Point(), gfx::Size(200, 200)), MenuAnchorPosition::kTopLeft, ui::MENU_SOURCE_MOUSE); } std::unique_ptr<Widget> widget_; raw_ptr<View> contents_ = nullptr; raw_ptr<Widget> bubble_widget_ = nullptr; raw_ptr<LabelButton> label_button_ = nullptr; raw_ptr<LabelButton> no_id_view_ = nullptr; std::unique_ptr<ui::SimpleMenuModel> menu_model_; std::unique_ptr<MenuRunner> menu_runner_; ui::SafeElementReference menu_element_; }; TEST_F(InteractionSequenceViewsTest, DestructWithInitialViewAborts) { UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::AbortedCallback, aborted); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::CompletedCallback, completed); auto* const starting_view = contents_->AddChildView(std::make_unique<View>()); starting_view->SetProperty(kElementIdentifierKey, kTestElementID); auto sequence = ui::InteractionSequence::Builder() .SetAbortedCallback(aborted.Get()) .SetCompletedCallback(completed.Get()) .AddStep(InteractionSequenceViews::WithInitialView(starting_view)) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID) .SetType(ui::InteractionSequence::StepType::kActivated) .Build()) .Build(); sequence->Start(); EXPECT_CALL_IN_SCOPE(aborted, Run, contents_->RemoveChildViewT(starting_view)); } TEST_F(InteractionSequenceViewsTest, DestructWithInitialViewBeforeStartAborts) { UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::AbortedCallback, aborted); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::CompletedCallback, completed); auto* const starting_view = contents_->AddChildView(std::make_unique<View>()); starting_view->SetProperty(kElementIdentifierKey, kTestElementID); auto sequence = ui::InteractionSequence::Builder() .SetAbortedCallback(aborted.Get()) .SetCompletedCallback(completed.Get()) .AddStep(InteractionSequenceViews::WithInitialView(starting_view)) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID) .SetType(ui::InteractionSequence::StepType::kActivated) .Build()) .Build(); contents_->RemoveChildViewT(starting_view); EXPECT_CALL_IN_SCOPE(aborted, Run, sequence->Start()); } TEST_F(InteractionSequenceViewsTest, WrongWithInitialViewDoesNotStartSequence) { UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::AbortedCallback, aborted); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::CompletedCallback, completed); auto* const starting_view = contents_->AddChildView(std::make_unique<View>()); starting_view->SetProperty(kElementIdentifierKey, kTestElementID); auto* const other_view = contents_->AddChildView(std::make_unique<View>()); other_view->SetProperty(kElementIdentifierKey, kTestElementID); auto sequence = ui::InteractionSequence::Builder() .SetAbortedCallback(aborted.Get()) .SetCompletedCallback(completed.Get()) .AddStep(InteractionSequenceViews::WithInitialView(starting_view)) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID) .SetType(ui::InteractionSequence::StepType::kActivated) .Build()) .Build(); starting_view->SetVisible(false); EXPECT_CALL_IN_SCOPE(aborted, Run, sequence->Start()); } TEST_F(InteractionSequenceViewsTest, SequenceNotCanceledDueToViewDestroyedIfRequirementChanged) { UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::AbortedCallback, aborted); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::CompletedCallback, completed); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::StepStartCallback, step2_start); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::StepEndCallback, step2_end); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::StepStartCallback, step3_start); auto* const starting_view = contents_->AddChildView(std::make_unique<View>()); starting_view->SetProperty(kElementIdentifierKey, kTestElementID); auto sequence = ui::InteractionSequence::Builder() .SetAbortedCallback(aborted.Get()) .SetCompletedCallback(completed.Get()) .AddStep(InteractionSequenceViews::WithInitialView(starting_view)) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID2) .SetType(ui::InteractionSequence::StepType::kShown) .Build()) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID2) .SetType(ui::InteractionSequence::StepType::kActivated) // Specify that this step doesn't abort on the view // becoming hidden. .SetMustRemainVisible(false) .SetStartCallback(step2_start.Get()) .SetEndCallback(step2_end.Get()) .Build()) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID3) .SetType(ui::InteractionSequence::StepType::kShown) .SetStartCallback(step3_start.Get()) .Build()) .Build(); sequence->Start(); auto* const second_view = contents_->AddChildView(std::make_unique<View>()); second_view->SetProperty(kElementIdentifierKey, kTestElementID2); auto* const third_view = contents_->AddChildView(std::make_unique<View>()); third_view->SetProperty(kElementIdentifierKey, kTestElementID3); third_view->SetVisible(false); // Simulate the view being activated to do the second step. EXPECT_CALL_IN_SCOPE(step2_start, Run(sequence.get(), ViewToElement(second_view)), Activate(second_view)); // Destroying the second view should NOT break the sequence. contents_->RemoveChildViewT(second_view); // Showing the third view at this point continues the sequence. EXPECT_CALLS_IN_SCOPE_3(step2_end, Run, step3_start, Run, completed, Run, third_view->SetVisible(true)); } TEST_F(InteractionSequenceViewsTest, TransitionToBubble) { UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::AbortedCallback, aborted); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::CompletedCallback, completed); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::StepStartCallback, step); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::StepStartCallback, step2); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::StepStartCallback, step3); auto sequence = ui::InteractionSequence::Builder() .SetAbortedCallback(aborted.Get()) .SetCompletedCallback(completed.Get()) .AddStep(InteractionSequenceViews::WithInitialView(contents_)) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID) .SetType(ui::InteractionSequence::StepType::kActivated) .SetStartCallback(step.Get()) .Build()) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID2) .SetType(ui::InteractionSequence::StepType::kShown) .SetStartCallback(step2.Get()) .Build()) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID2) .SetType(ui::InteractionSequence::StepType::kActivated) .SetStartCallback(step3.Get()) .Build()) .Build(); auto* const button = contents_->AddChildView( std::make_unique<LabelButton>(Button::PressedCallback( base::BindRepeating(&InteractionSequenceViewsTest::ShowBubble, base::Unretained(this), kTestElementID2)))); button->SetProperty(kElementIdentifierKey, kTestElementID); sequence->Start(); EXPECT_CALLS_IN_SCOPE_2( step, Run, step2, Run, views::test::InteractionTestUtilSimulatorViews::PressButton(button)); EXPECT_CALLS_IN_SCOPE_2( step3, Run, completed, Run, views::test::InteractionTestUtilSimulatorViews::PressButton( label_button_)); } TEST_F(InteractionSequenceViewsTest, TransitionToBubbleThenAbort) { UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::AbortedCallback, aborted); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::CompletedCallback, completed); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::StepStartCallback, step); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::StepStartCallback, step2); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::StepStartCallback, step3); auto sequence = ui::InteractionSequence::Builder() .SetAbortedCallback(aborted.Get()) .SetCompletedCallback(completed.Get()) .AddStep(InteractionSequenceViews::WithInitialView(contents_)) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID) .SetType(ui::InteractionSequence::StepType::kActivated) .SetStartCallback(step.Get()) .Build()) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID2) .SetType(ui::InteractionSequence::StepType::kShown) .SetStartCallback(step2.Get()) .Build()) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID2) .SetType(ui::InteractionSequence::StepType::kActivated) .SetStartCallback(step3.Get()) .Build()) .Build(); auto* const button = contents_->AddChildView( std::make_unique<LabelButton>(Button::PressedCallback( base::BindRepeating(&InteractionSequenceViewsTest::ShowBubble, base::Unretained(this), kTestElementID2)))); button->SetProperty(kElementIdentifierKey, kTestElementID); sequence->Start(); EXPECT_CALLS_IN_SCOPE_2( step, Run, step2, Run, views::test::InteractionTestUtilSimulatorViews::PressButton(button)); EXPECT_CALL_IN_SCOPE(aborted, Run, CloseBubble()); } TEST_F(InteractionSequenceViewsTest, TransitionToMenuAndViewMenuItem) { UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::AbortedCallback, aborted); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::CompletedCallback, completed); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::StepStartCallback, step); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::StepStartCallback, step2); auto sequence = ui::InteractionSequence::Builder() .SetAbortedCallback(aborted.Get()) .SetCompletedCallback(completed.Get()) .AddStep(InteractionSequenceViews::WithInitialView(contents_)) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID) .SetType(ui::InteractionSequence::StepType::kActivated) .SetStartCallback(step.Get()) .Build()) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID2) .SetType(ui::InteractionSequence::StepType::kShown) .SetStartCallback(step2.Get()) .Build()) .Build(); auto* const button = contents_->AddChildView( std::make_unique<LabelButton>(Button::PressedCallback( base::BindRepeating(&InteractionSequenceViewsTest::ShowMenu, base::Unretained(this), kTestElementID2)))); button->SetProperty(kElementIdentifierKey, kTestElementID); sequence->Start(); EXPECT_CALLS_IN_SCOPE_3( step, Run, step2, Run, completed, Run, views::test::InteractionTestUtilSimulatorViews::PressButton(button)); } TEST_F(InteractionSequenceViewsTest, TransitionToMenuThenCloseMenuToCancel) { UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::AbortedCallback, aborted); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::CompletedCallback, completed); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::StepStartCallback, step); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::StepStartCallback, step2); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::StepStartCallback, step3); auto sequence = ui::InteractionSequence::Builder() .SetAbortedCallback(aborted.Get()) .SetCompletedCallback(completed.Get()) .AddStep(InteractionSequenceViews::WithInitialView(contents_)) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID) .SetType(ui::InteractionSequence::StepType::kActivated) .SetStartCallback(step.Get()) .Build()) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID2) .SetType(ui::InteractionSequence::StepType::kShown) .SetStartCallback(step2.Get()) .Build()) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID2) .SetType(ui::InteractionSequence::StepType::kActivated) .SetStartCallback(step3.Get()) .Build()) .Build(); auto* const button = contents_->AddChildView( std::make_unique<LabelButton>(Button::PressedCallback( base::BindRepeating(&InteractionSequenceViewsTest::ShowMenu, base::Unretained(this), kTestElementID2)))); button->SetProperty(kElementIdentifierKey, kTestElementID); sequence->Start(); EXPECT_CALLS_IN_SCOPE_2( step, Run, step2, Run, views::test::InteractionTestUtilSimulatorViews::PressButton(button)); EXPECT_CALL_IN_SCOPE(aborted, Run, CloseMenu()); } // Menu button uses different event-handling architecture than standard Button, // so test it separately here. TEST_F(InteractionSequenceViewsTest, TransitionToMenuWithMenuButton) { UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::AbortedCallback, aborted); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::CompletedCallback, completed); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::StepStartCallback, step); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::StepStartCallback, step2); auto sequence = ui::InteractionSequence::Builder() .SetAbortedCallback(aborted.Get()) .SetCompletedCallback(completed.Get()) .AddStep(InteractionSequenceViews::WithInitialView(contents_)) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID) .SetType(ui::InteractionSequence::StepType::kActivated) .SetStartCallback(step.Get()) .Build()) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID2) .SetType(ui::InteractionSequence::StepType::kShown) .SetStartCallback(step2.Get()) .Build()) .Build(); auto* const button = contents_->AddChildView( std::make_unique<MenuButton>(Button::PressedCallback( base::BindRepeating(&InteractionSequenceViewsTest::ShowMenu, base::Unretained(this), kTestElementID2)))); button->SetProperty(kElementIdentifierKey, kTestElementID); sequence->Start(); EXPECT_CALLS_IN_SCOPE_3( step, Run, step2, Run, completed, Run, views::test::InteractionTestUtilSimulatorViews::PressButton(button)); } TEST_F(InteractionSequenceViewsTest, TransitionToMenuAndActivateMenuItem) { UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::AbortedCallback, aborted); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::CompletedCallback, completed); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::StepStartCallback, step); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::StepStartCallback, step2); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::StepStartCallback, step3); auto sequence = ui::InteractionSequence::Builder() .SetAbortedCallback(aborted.Get()) .SetCompletedCallback(completed.Get()) .AddStep(InteractionSequenceViews::WithInitialView(contents_)) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID) .SetType(ui::InteractionSequence::StepType::kActivated) .SetStartCallback(step.Get()) .Build()) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID2) .SetType(ui::InteractionSequence::StepType::kShown) .SetStartCallback(step2.Get()) .Build()) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID2) .SetType(ui::InteractionSequence::StepType::kActivated) .SetStartCallback(step3.Get()) .Build()) .Build(); auto* const button = contents_->AddChildView( std::make_unique<LabelButton>(Button::PressedCallback( base::BindRepeating(&InteractionSequenceViewsTest::ShowMenu, base::Unretained(this), kTestElementID2)))); button->SetProperty(kElementIdentifierKey, kTestElementID); sequence->Start(); EXPECT_CALLS_IN_SCOPE_2( step, Run, step2, Run, test::InteractionTestUtilSimulatorViews::PressButton(button)); EXPECT_CALLS_IN_SCOPE_2(step3, Run, completed, Run, { ui::test::InteractionTestUtil test_util; test_util.AddSimulator( std::make_unique<test::InteractionTestUtilSimulatorViews>()); EXPECT_EQ(ui::test::ActionResult::kSucceeded, test_util.SelectMenuItem(menu_element_.get())); }); } TEST_F(InteractionSequenceViewsTest, TransitionOnKeyboardMenuActivation) { UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::AbortedCallback, aborted); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::CompletedCallback, completed); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::StepStartCallback, step); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::StepStartCallback, step2); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::StepStartCallback, step3); auto sequence = ui::InteractionSequence::Builder() .SetAbortedCallback(aborted.Get()) .SetCompletedCallback(completed.Get()) .AddStep(InteractionSequenceViews::WithInitialView(contents_)) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID) .SetType(ui::InteractionSequence::StepType::kActivated) .SetStartCallback(step.Get()) .Build()) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID2) .SetType(ui::InteractionSequence::StepType::kShown) .SetStartCallback(step2.Get()) .Build()) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID2) .SetType(ui::InteractionSequence::StepType::kActivated) .SetStartCallback(step3.Get()) .Build()) .Build(); auto* const button = contents_->AddChildView( std::make_unique<LabelButton>(Button::PressedCallback( base::BindRepeating(&InteractionSequenceViewsTest::ShowMenu, base::Unretained(this), kTestElementID2)))); button->SetProperty(kElementIdentifierKey, kTestElementID); sequence->Start(); EXPECT_CALLS_IN_SCOPE_2( step, Run, step2, Run, views::test::InteractionTestUtilSimulatorViews::PressButton(button)); EXPECT_CALLS_IN_SCOPE_2(step3, Run, completed, Run, { ui::test::EventGenerator generator(GetContext(), widget_->GetNativeWindow()); generator.PressKey(ui::VKEY_DOWN, 0); generator.PressKey(ui::VKEY_DOWN, 0); generator.PressKey(ui::VKEY_RETURN, 0); }); } // NameView tests: TEST_F(InteractionSequenceViewsTest, NameView_NameViewWithIdentifier) { UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::AbortedCallback, aborted); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::CompletedCallback, completed); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::StepStartCallback, step); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::StepStartCallback, step3); auto step2 = base::BindLambdaForTesting([&](ui::InteractionSequence* sequence, ui::TrackedElement* element) { EXPECT_EQ(label_button_, element->AsA<TrackedElementViews>()->view()); InteractionSequenceViews::NameView(sequence, label_button_, kElementName); }); auto sequence = ui::InteractionSequence::Builder() .SetAbortedCallback(aborted.Get()) .SetCompletedCallback(completed.Get()) .AddStep(InteractionSequenceViews::WithInitialView(contents_)) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID) .SetType(ui::InteractionSequence::StepType::kActivated) .SetStartCallback(step.Get()) .Build()) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID2) .SetType(ui::InteractionSequence::StepType::kShown) .SetStartCallback(std::move(step2)) .Build()) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementName(kElementName) .SetType(ui::InteractionSequence::StepType::kActivated) .SetStartCallback(step3.Get()) .Build()) .Build(); auto* const button = contents_->AddChildView( std::make_unique<LabelButton>(Button::PressedCallback( base::BindRepeating(&InteractionSequenceViewsTest::ShowBubble, base::Unretained(this), kTestElementID2)))); button->SetProperty(kElementIdentifierKey, kTestElementID); sequence->Start(); EXPECT_CALL_IN_SCOPE( step, Run, views::test::InteractionTestUtilSimulatorViews::PressButton(button)); EXPECT_CALLS_IN_SCOPE_2( step3, Run, completed, Run, views::test::InteractionTestUtilSimulatorViews::PressButton( label_button_)); } TEST_F(InteractionSequenceViewsTest, NameView_NameViewWithNoIdentifier) { UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::AbortedCallback, aborted); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::CompletedCallback, completed); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::StepStartCallback, step); UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::StepStartCallback, step3); auto step2 = base::BindLambdaForTesting( [&](ui::InteractionSequence* sequence, ui::TrackedElement* element) { EXPECT_EQ(label_button_, element->AsA<TrackedElementViews>()->view()); InteractionSequenceViews::NameView(sequence, no_id_view_, kElementName); }); auto sequence = ui::InteractionSequence::Builder() .SetAbortedCallback(aborted.Get()) .SetCompletedCallback(completed.Get()) .AddStep(InteractionSequenceViews::WithInitialView(contents_)) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID) .SetType(ui::InteractionSequence::StepType::kActivated) .SetStartCallback(step.Get()) .Build()) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementID(kTestElementID2) .SetType(ui::InteractionSequence::StepType::kShown) .SetStartCallback(std::move(step2)) .Build()) .AddStep(ui::InteractionSequence::StepBuilder() .SetElementName(kElementName) .SetType(ui::InteractionSequence::StepType::kActivated) .SetStartCallback(step3.Get()) .Build()) .Build(); auto* const button = contents_->AddChildView( std::make_unique<LabelButton>(Button::PressedCallback( base::BindRepeating(&InteractionSequenceViewsTest::ShowBubble, base::Unretained(this), kTestElementID2)))); button->SetProperty(kElementIdentifierKey, kTestElementID); sequence->Start(); EXPECT_CALL_IN_SCOPE( step, Run, views::test::InteractionTestUtilSimulatorViews::PressButton(button)); EXPECT_CALLS_IN_SCOPE_2( step3, Run, completed, Run, views::test::InteractionTestUtilSimulatorViews::PressButton(no_id_view_)); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/interaction/interaction_sequence_views_unittest.cc
C++
unknown
31,816
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/interaction/interaction_test_util_mouse.h" #include <memory> #include <utility> #include "base/auto_reset.h" #include "base/check.h" #include "base/containers/contains.h" #include "base/functional/callback_forward.h" #include "base/functional/callback_helpers.h" #include "base/location.h" #include "base/logging.h" #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/run_loop.h" #include "base/scoped_observation.h" #include "base/task/single_thread_task_runner.h" #include "base/threading/thread.h" #include "build/build_config.h" #include "ui/base/test/ui_controls.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/widget/widget.h" #if defined(USE_AURA) #include "ui/aura/client/drag_drop_client.h" #include "ui/aura/client/drag_drop_client_observer.h" #include "ui/aura/window.h" #include "ui/aura/window_observer.h" #endif // defined(USE_AURA) // Currently, touch is only supported on ChromeOS Ash. #if BUILDFLAG(IS_CHROMEOS_ASH) #define TOUCH_INPUT_SUPPORTED 1 #else #define TOUCH_INPUT_SUPPORTED 0 #endif namespace views::test { namespace { base::raw_ptr<InteractionTestUtilMouse> g_current_mouse_util = nullptr; void PostTask(base::OnceClosure task) { base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(FROM_HERE, std::move(task)); } #if TOUCH_INPUT_SUPPORTED ui_controls::TouchType GetTouchAction(ui_controls::MouseButtonState state) { switch (state) { case ui_controls::DOWN: return ui_controls::kTouchPress; case ui_controls::UP: return ui_controls::kTouchRelease; } } int GetTouchCount(ui_controls::MouseButton button) { switch (button) { case ui_controls::LEFT: return 1; case ui_controls::MIDDLE: return 3; case ui_controls::RIGHT: return 2; } } #endif // TOUCH_INPUT_SUPPORTED } // namespace #if defined(USE_AURA) // Ends any drag currently in progress or that starts during this object's // lifetime. This is needed because the drag controller can get out of sync with // mouse event handling - especially when running ChromeOS-on-Linux. This can // result in weird test hangs/timeouts during mouse-up after a drag, or (more // insidiously) during test shutdown. // // Once started, the DragEnder will kill any drags that start until: // - Stop() is called. // - The Aura window it is watching goes away. // - The DragEnder is destroyed (which should happen no earlier than the end of // ShutDownOnMainThread()). class InteractionTestUtilMouse::DragEnder : public aura::client::DragDropClientObserver, public aura::WindowObserver { public: explicit DragEnder(aura::Window* window) : window_(window) { window_observation_.Observe(window); } ~DragEnder() override = default; // Either cancels a current drag, or starts observing for a future drag start // event (at which point the drag will be canceled). void Start() { if (CancelDragNow() || drag_client_observation_.IsObserving()) { return; } // Only Ash actually supports observing the drag-drop client. Therefore, on // other platforms, only direct cancel is possible. #if BUILDFLAG(IS_CHROMEOS_ASH) if (auto* const client = GetClient()) { drag_client_observation_.Observe(client); } #endif } // Stops any ongoing observation of drag start events. void Stop() { drag_client_observation_.Reset(); } // Cancels any drag that is currently happening, but does not watch for future // drag start events. bool CancelDragNow() { if (auto* const client = GetClient()) { if (client->IsDragDropInProgress()) { LOG(WARNING) << "InteractionTestUtilMouse: Force-canceling spurious drag " "operation.\n" << "This can happen when the drag controller gets out of sync with " "mouse events being sent by the test, and is especially likely " "on ChromeOS-on-Linux.\n" << "This is not necessarily a serious error if the test functions " "normally; however, if you see this too often or your test " "flakes as a result of the cancel you may need to insert " "additional FlushEvents() steps into your test, or restructure " "it so that you can be sure the drag has started before " "attempting to invoke ReleaseMouse()."; client->DragCancel(); return true; } } return false; } base::WeakPtr<DragEnder> GetWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); } private: // aura::client::DragDropClientObserver: void OnDragStarted() override { drag_client_observation_.Reset(); PostTask(base::BindOnce(base::IgnoreResult(&DragEnder::CancelDragNow), weak_ptr_factory_.GetWeakPtr())); } // aura::WindowObserver: void OnWindowDestroying(aura::Window* window) override { DCHECK_EQ(window_, window); drag_client_observation_.Reset(); window_observation_.Reset(); window_ = nullptr; } aura::client::DragDropClient* GetClient() { return window_ ? aura::client::GetDragDropClient(window_->GetRootWindow()) : nullptr; } // Since there is no "DragDropClientDestroying" event, use the aura::Window as // a proxy for the existence of the DragDropClient, and unregister listeners // when the window goes away. If this is not done, UAFs may happen when the // scoped observation of the drag client goes away. base::raw_ptr<aura::Window> window_; base::ScopedObservation<aura::Window, aura::WindowObserver> window_observation_{this}; base::ScopedObservation<aura::client::DragDropClient, aura::client::DragDropClientObserver> drag_client_observation_{this}; base::WeakPtrFactory<DragEnder> weak_ptr_factory_{this}; }; #endif // defined(USE_AURA) InteractionTestUtilMouse::InteractionTestUtilMouse(views::Widget* widget) : InteractionTestUtilMouse(widget->GetNativeWindow()) {} InteractionTestUtilMouse::~InteractionTestUtilMouse() { CHECK(!performing_gestures_) << "InteractionTestUtilMouse destroyed with pending actions."; LOG_IF(ERROR, g_current_mouse_util != this) << "Expected |this| to be current InteractionTestUtilMouse."; g_current_mouse_util = nullptr; } // static InteractionTestUtilMouse::MouseGesture InteractionTestUtilMouse::MoveTo( gfx::Point point) { return MouseGesture(point); } // static InteractionTestUtilMouse::MouseGesture InteractionTestUtilMouse::MouseDown( ui_controls::MouseButton button) { return MouseGesture(std::make_pair(button, ui_controls::DOWN)); } // static InteractionTestUtilMouse::MouseGesture InteractionTestUtilMouse::MouseUp( ui_controls::MouseButton button) { return MouseGesture(std::make_pair(button, ui_controls::UP)); } // static InteractionTestUtilMouse::MouseGestures InteractionTestUtilMouse::Click( ui_controls::MouseButton button) { return MouseGestures{MouseDown(button), MouseUp(button)}; } // static InteractionTestUtilMouse::MouseGestures InteractionTestUtilMouse::DragAndHold( gfx::Point destination) { return MouseGestures{MouseDown(ui_controls::LEFT), MoveTo(destination)}; } // static InteractionTestUtilMouse::MouseGestures InteractionTestUtilMouse::DragAndRelease(gfx::Point destination) { return MouseGestures{MouseDown(ui_controls::LEFT), MoveTo(destination), MouseUp(ui_controls::LEFT)}; } bool InteractionTestUtilMouse::ShouldCancelDrag() const { #if defined(USE_AURA) return dragging_; #else return false; #endif } void InteractionTestUtilMouse::CancelFutureDrag() { #if defined(USE_AURA) // Allow the system to finish processing any mouse input before force- // canceling any ongoing drag. It's possible that a drag that was queued to // complete simply hasn't yet. PostTask(base::BindOnce(&DragEnder::Start, drag_ender_->GetWeakPtr())); #endif } void InteractionTestUtilMouse::CancelDragNow() { #if defined(USE_AURA) CHECK(!dragging_); drag_ender_->Stop(); drag_ender_->CancelDragNow(); #endif } bool InteractionTestUtilMouse::SendButtonPress( const MouseButtonGesture& gesture, gfx::NativeWindow window_hint, bool sync, base::OnceClosure on_complete) { if (sync) { #if TOUCH_INPUT_SUPPORTED if (touch_mode_) { return ui_controls::SendTouchEventsNotifyWhenDone( GetTouchAction(gesture.second), GetTouchCount(gesture.first), touch_hover_point_.x(), touch_hover_point_.y(), std::move(on_complete)); } #endif // TOUCH_INPUT_SUPPORTED return ui_controls::SendMouseEventsNotifyWhenDone( gesture.first, gesture.second, std::move(on_complete), ui_controls::kNoAccelerator, window_hint); } #if TOUCH_INPUT_SUPPORTED if (touch_mode_) { PostTask(base::BindOnce( [](base::WeakPtr<InteractionTestUtilMouse> util, base::OnceClosure on_complete, MouseButtonGesture gesture, gfx::Point target) { if (!util) { return; } CHECK(ui_controls::SendTouchEventsNotifyWhenDone( GetTouchAction(gesture.second), GetTouchCount(gesture.first), target.x(), target.y(), std::move(on_complete))); }, weak_ptr_factory_.GetWeakPtr(), std::move(on_complete), gesture, touch_hover_point_)); return true; } #endif // TOUCH_INPUT_SUPPORTED PostTask(base::BindOnce( [](base::WeakPtr<InteractionTestUtilMouse> util, base::OnceClosure on_complete, MouseButtonGesture gesture, gfx::NativeWindow window_hint) { if (!util) { return; } CHECK(ui_controls::SendMouseEventsNotifyWhenDone( gesture.first, gesture.second, std::move(on_complete), ui_controls::kNoAccelerator, window_hint)); }, weak_ptr_factory_.GetWeakPtr(), std::move(on_complete), gesture, window_hint)); return true; } bool InteractionTestUtilMouse::SendMove(const MouseMoveGesture& gesture, gfx::NativeWindow window_hint, bool sync, base::OnceClosure on_complete) { #if TOUCH_INPUT_SUPPORTED if (touch_mode_) { // Need to remember where our finger is. touch_hover_point_ = gesture; // If no fingers are down, there's nothing to do. if (buttons_down_.empty()) { std::move(on_complete).Run(); return true; } // Should never have two different sets of fingers down at once. CHECK_EQ(1U, buttons_down_.size()); } #endif // TOUCH_INPUT_SUPPORTED if (sync) { #if TOUCH_INPUT_SUPPORTED if (touch_mode_) { return ui_controls::SendTouchEventsNotifyWhenDone( ui_controls::kTouchMove, GetTouchCount(*buttons_down_.begin()), gesture.x(), gesture.y(), std::move(on_complete)); } #endif // TOUCH_INPUT_SUPPORTED return ui_controls::SendMouseMoveNotifyWhenDone( gesture.x(), gesture.y(), std::move(on_complete), window_hint); } #if TOUCH_INPUT_SUPPORTED if (touch_mode_) { PostTask(base::BindOnce( [](base::WeakPtr<InteractionTestUtilMouse> util, base::OnceClosure on_complete, MouseMoveGesture gesture) { if (!util) { return; } const int touch_count = GetTouchCount(*util->buttons_down_.begin()); CHECK(ui_controls::SendTouchEventsNotifyWhenDone( ui_controls::kTouchMove, touch_count, gesture.x(), gesture.y(), std::move(on_complete))); }, weak_ptr_factory_.GetWeakPtr(), std::move(on_complete), gesture)); return true; } #endif // TOUCH_INPUT_SUPPORTED PostTask(base::BindOnce( [](base::WeakPtr<InteractionTestUtilMouse> util, base::OnceClosure on_complete, MouseMoveGesture gesture, gfx::NativeWindow window_hint) { if (!util) { return; } CHECK(ui_controls::SendMouseMoveNotifyWhenDone( gesture.x(), gesture.y(), std::move(on_complete), window_hint)); }, weak_ptr_factory_.GetWeakPtr(), std::move(on_complete), gesture, window_hint)); return true; } bool InteractionTestUtilMouse::SetTouchMode(bool touch_mode) { if (touch_mode == touch_mode_) { return true; } CHECK(buttons_down_.empty()) << "Cannot toggle touch mode when buttons or fingers are down."; #if TOUCH_INPUT_SUPPORTED touch_mode_ = touch_mode; return true; #else LOG(WARNING) << "Touch mode not supported on this platform."; return false; #endif } bool InteractionTestUtilMouse::GetTouchMode() const { return touch_mode_; } bool InteractionTestUtilMouse::PerformGesturesImpl( MouseGestures gestures, gfx::NativeWindow window_hint) { CHECK(!gestures.empty()); CHECK(!performing_gestures_); base::AutoReset<bool> performing_gestures(&performing_gestures_, true); canceled_ = false; for (auto& gesture : gestures) { if (canceled_) break; bool force_async = false; #if BUILDFLAG(IS_MAC) force_async = base::Contains(buttons_down_, ui_controls::RIGHT); #endif base::RunLoop run_loop{base::RunLoop::Type::kNestableTasksAllowed}; if (MouseButtonGesture* const button = absl::get_if<MouseButtonGesture>(&gesture)) { switch (button->second) { case ui_controls::UP: { CHECK(buttons_down_.erase(button->first)); base::OnceClosure on_complete = force_async ? base::DoNothing() : run_loop.QuitClosure(); if (ShouldCancelDrag()) { // This will bail out of any nested drag-drop run loop, allowing // the code to proceed even if the drag somehow starts while the // mouse-up is being processed. on_complete = std::move(on_complete) .Then(base::BindOnce( &InteractionTestUtilMouse::CancelFutureDrag, weak_ptr_factory_.GetWeakPtr())); } #if defined(USE_AURA) dragging_ = false; #endif if (!SendButtonPress(*button, window_hint, !force_async, std::move(on_complete))) { LOG(ERROR) << "Mouse button " << button->first << " up failed."; return false; } if (!force_async) { run_loop.Run(); } break; } case ui_controls::DOWN: #if TOUCH_INPUT_SUPPORTED CHECK(!touch_mode_ || buttons_down_.empty()) << "In touch mode, only one set of fingers may be down at any " "given time."; #endif CHECK(buttons_down_.insert(button->first).second); #if BUILDFLAG(IS_MAC) if (!force_async && button->first == ui_controls::RIGHT) { force_async = true; LOG(WARNING) << "InteractionTestUtilMouse::PerformGestures(): " "Important note:\n" << "Because right-clicking on Mac typically results in a " "context menu, and because context menus on Mac are native " "and take over the main message loop, mouse events from " "here until release of the right mouse button will be sent " "asynchronously to avoid a hang.\n" << "Furthermore, your test will likely still hang unless you " "explicitly find and close the context menu. There is (as " "of the time this warning was written) no general way to do " "this because it requires access to the menu runner, which " "is not always publicly exposed."; } #endif CancelDragNow(); if (!SendButtonPress( *button, window_hint, !force_async, force_async ? base::DoNothing() : run_loop.QuitClosure())) { LOG(ERROR) << "Mouse button " << button->first << " down failed."; return false; } if (!force_async) { run_loop.Run(); } break; } } else { const auto& move = absl::get<MouseMoveGesture>(gesture); #if defined(USE_AURA) if (!buttons_down_.empty()) { CHECK(base::Contains(buttons_down_, ui_controls::LEFT)); dragging_ = true; } #endif if (!SendMove(move, window_hint, !force_async, force_async ? base::DoNothing() : run_loop.QuitClosure())) { LOG(ERROR) << "Mouse move to " << move.ToString() << " failed."; return false; } if (!force_async) { run_loop.Run(); } } } return !canceled_; } void InteractionTestUtilMouse::CancelAllGestures() { weak_ptr_factory_.InvalidateWeakPtrs(); canceled_ = true; #if TOUCH_INPUT_SUPPORTED if (touch_mode_ && !buttons_down_.empty()) { // Should never get in a state where multiple finger combinations are down // at the same time. CHECK_EQ(1U, buttons_down_.size()); const auto& button = *buttons_down_.begin(); if (!ui_controls::SendTouchEvents( ui_controls::kTouchRelease, GetTouchCount(button), touch_hover_point_.x(), touch_hover_point_.y())) { LOG(WARNING) << "Unable to send touch up."; } buttons_down_.clear(); } #endif // TOUCH_INPUT_SUPPORTED // Now that no additional actions will happen, release all mouse buttons. for (ui_controls::MouseButton button : buttons_down_) { if (!ui_controls::SendMouseEvents(button, ui_controls::UP)) { LOG(WARNING) << "Unable to release mouse button " << button; } } buttons_down_.clear(); // Maybe handle dragging stopped. if (ShouldCancelDrag()) { CancelFutureDrag(); } } InteractionTestUtilMouse::InteractionTestUtilMouse(gfx::NativeWindow window) #if defined(USE_AURA) : drag_ender_(std::make_unique<DragEnder>(window)) #endif { CHECK(window); CHECK(!g_current_mouse_util) << "Cannot have multiple overlapping InteractionTestUtilMouse instances"; g_current_mouse_util = this; } // static void InteractionTestUtilMouse::AddGestures(MouseGestures& gestures, MouseGesture to_add) { gestures.emplace_back(std::move(to_add)); } // static void InteractionTestUtilMouse::AddGestures(MouseGestures& gestures, MouseGestures to_add) { for (auto& gesture : to_add) gestures.emplace_back(std::move(gesture)); } } // namespace views::test
Zhao-PengFei35/chromium_src_4
ui/views/interaction/interaction_test_util_mouse.cc
C++
unknown
18,786
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_INTERACTION_INTERACTION_TEST_UTIL_MOUSE_H_ #define UI_VIEWS_INTERACTION_INTERACTION_TEST_UTIL_MOUSE_H_ #include <list> #include <memory> #include <set> #include <utility> #include "base/functional/callback_forward.h" #include "base/functional/callback_helpers.h" #include "base/memory/weak_ptr.h" #include "build/build_config.h" #include "third_party/abseil-cpp/absl/types/variant.h" #include "ui/base/test/ui_controls.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/native_widget_types.h" namespace views { class Widget; namespace test { // Class which provides useful primitives for controlling the mouse and then // cleaning up mouse state (even if a test fails). As this object does control // the mouse, do not create multiple simultaneous instances, and strongly prefer // to use it only in test suites such as interactive_ui_tests where a single // test can control the mouse at a time. class InteractionTestUtilMouse { public: // Construct for a particular window or browser. This is required because the // util object may need access to a drag controller, which is most easily // accessed via the window. explicit InteractionTestUtilMouse(Widget* widget); ~InteractionTestUtilMouse(); InteractionTestUtilMouse(const InteractionTestUtilMouse&) = delete; void operator=(const InteractionTestUtilMouse&) = delete; // These represent mouse gestures of different types. They are implementation // details; prefer to use the static factory methods below. using MouseButtonGesture = std::pair<ui_controls::MouseButton, ui_controls::MouseButtonState>; using MouseMoveGesture = gfx::Point; using MouseGesture = absl::variant<MouseMoveGesture, MouseButtonGesture>; using MouseGestures = std::list<MouseGesture>; // These factory methods create individual or compound gestures. They can be // chained together. Prefer these to directly constructing a MouseGesture. static MouseGesture MoveTo(gfx::Point point); static MouseGesture MouseDown(ui_controls::MouseButton button); static MouseGesture MouseUp(ui_controls::MouseButton button); static MouseGestures Click(ui_controls::MouseButton button); static MouseGestures DragAndHold(gfx::Point destination); static MouseGestures DragAndRelease(gfx::Point destination); // Set or get touch mode. // // `SetTouchMode(true)` returns false if touch is not supported. If it // succeeds, subsequent mouse inputs will be converted to equivalent touch // inputs. // // Notes: // - This is an experimental feature and the API is subject to change. // - See tracking bug at crbug.com/1428292 for current status. // - Currently only Ash Chrome is supported. // - Hover is not yet supported, only tap [up/down] and drag. // - Moves without a finger down affect the next tap input but do not send // events. // // To use this in an InteractiveViewsTest or InteractiveBrowserTest, use the // following syntax: // // Check([this](){ return test_impl().mouse_util().SetTouchMode(true); }) // // Afterwards, you can use mouse verbs as normal and they will convert to // equivalent touch inputs. We suggest using `Check()` so that the test will // fail if it's accidentally run on a system that doesn't yet support it. // // Alternatively, you can write a parameterized test which selectively tries // the test in touch-on and touch-off modes for platforms that support it, but // only in touch-off mode for those that don't. In these cases, the `Check()` // above changes to something like `...SetTouchMode(GetParam())`. bool SetTouchMode(bool touch_mode); bool GetTouchMode() const; // Perform the gesture or gestures specified, returns true on success. template <typename... Args> bool PerformGestures(gfx::NativeWindow window_hint, Args... gestures); // Cancels any pending actions and cleans up any resulting mouse state (i.e. // releases any buttons which were pressed). void CancelAllGestures(); private: explicit InteractionTestUtilMouse(gfx::NativeWindow window); // Helper methods for adding gestures to a gesture list. static void AddGestures(MouseGestures& gestures, MouseGesture to_add); static void AddGestures(MouseGestures& gestures, MouseGestures to_add); bool PerformGesturesImpl(MouseGestures gestures, gfx::NativeWindow window_hint); bool ShouldCancelDrag() const; void CancelFutureDrag(); void CancelDragNow(); bool SendButtonPress(const MouseButtonGesture& gesture, gfx::NativeWindow window_hint, bool sync, base::OnceClosure on_complete); bool SendMove(const MouseMoveGesture& gesture, gfx::NativeWindow window_hint, bool sync, base::OnceClosure on_complete); // The set of mouse buttons currently depressed. Used to clean up on abort. std::set<ui_controls::MouseButton> buttons_down_; // Whether gestures are being executed. bool performing_gestures_ = false; // Whether the current sequence is canceled. bool canceled_ = false; // Whether we're in touch mode. In touch mode, touch events are sent instead // of mouse events. Moves without fingers down will not send events (but see // `touch_hover_point_` below). bool touch_mode_ = false; // Tracks the next place touch input should take place. It is affected by all // moves, regardless of whether any fingers are down, and you can use MoveTo // with no fingers to reposition the point. gfx::Point touch_hover_point_; #if defined(USE_AURA) // Whether the mouse is currently being dragged. bool dragging_ = false; // These are used in order to clean up extraneous drags on Aura platforms; // without this it is possible for a drag loop to start and not exit, // preventing a test from completing. class DragEnder; const std::unique_ptr<DragEnder> drag_ender_; #endif base::WeakPtrFactory<InteractionTestUtilMouse> weak_ptr_factory_{this}; }; template <typename... Args> bool InteractionTestUtilMouse::PerformGestures(gfx::NativeWindow window_hint, Args... gestures) { MouseGestures gesture_list; (AddGestures(gesture_list, std::move(gestures)), ...); return PerformGesturesImpl(std::move(gesture_list), window_hint); } } // namespace test } // namespace views #endif // UI_VIEWS_INTERACTION_INTERACTION_TEST_UTIL_MOUSE_H_
Zhao-PengFei35/chromium_src_4
ui/views/interaction/interaction_test_util_mouse.h
C++
unknown
6,624